@workflow/world-testing 5.1.3 → 5.1.5

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.
@@ -13681,7 +13681,7 @@ var init_locales2 = __esm({
13681
13681
  });
13682
13682
 
13683
13683
  // ../../node_modules/.pnpm/zod@4.6.7/node_modules/zod/v4/core/registries.js
13684
- function registry2() {
13684
+ function registry3() {
13685
13685
  return new $ZodRegistry2();
13686
13686
  }
13687
13687
  var _a5, $output2, $input2, $ZodRegistry2, globalRegistry2;
@@ -13732,8 +13732,8 @@ var init_registries2 = __esm({
13732
13732
  return this._map.has(schema);
13733
13733
  }
13734
13734
  };
13735
- __name(registry2, "registry");
13736
- (_a5 = globalThis).__zod_globalRegistry ?? (_a5.__zod_globalRegistry = registry2());
13735
+ __name(registry3, "registry");
13736
+ (_a5 = globalThis).__zod_globalRegistry ?? (_a5.__zod_globalRegistry = registry3());
13737
13737
  globalRegistry2 = globalThis.__zod_globalRegistry;
13738
13738
  }
13739
13739
  });
@@ -17291,21 +17291,21 @@ function serializeDefaultValue2(value, schema, ctx, json3, params) {
17291
17291
  }
17292
17292
  function toJSONSchema2(input3, params) {
17293
17293
  if ("_idmap" in input3) {
17294
- const registry3 = input3;
17294
+ const registry5 = input3;
17295
17295
  const ctx2 = initializeContext2({ ...params, processors: allProcessors2 });
17296
17296
  const defs = {};
17297
- for (const entry of registry3._idmap.entries()) {
17297
+ for (const entry of registry5._idmap.entries()) {
17298
17298
  const [_, schema] = entry;
17299
17299
  processSchema2(schema, ctx2);
17300
17300
  }
17301
17301
  const schemas = {};
17302
17302
  const external = {
17303
- registry: registry3,
17303
+ registry: registry5,
17304
17304
  uri: params?.uri,
17305
17305
  defs
17306
17306
  };
17307
17307
  ctx2.external = external;
17308
- for (const entry of registry3._idmap.entries()) {
17308
+ for (const entry of registry5._idmap.entries()) {
17309
17309
  const [key, schema] = entry;
17310
17310
  extractDefs2(ctx2, schema);
17311
17311
  assignProp2(schemas, key, finalize2(ctx2, schema));
@@ -18327,7 +18327,7 @@ __export(core_exports3, {
18327
18327
  process: () => processSchema2,
18328
18328
  processSchema: () => processSchema2,
18329
18329
  regexes: () => regexes_exports2,
18330
- registry: () => registry2,
18330
+ registry: () => registry3,
18331
18331
  safeDecode: () => safeDecode3,
18332
18332
  safeDecodeAsync: () => safeDecodeAsync3,
18333
18333
  safeEncode: () => safeEncode3,
@@ -21545,7 +21545,7 @@ __export(external_exports2, {
21545
21545
  refine: () => refine2,
21546
21546
  regex: () => _regex2,
21547
21547
  regexes: () => regexes_exports2,
21548
- registry: () => registry2,
21548
+ registry: () => registry3,
21549
21549
  safeDecode: () => safeDecode4,
21550
21550
  safeDecodeAsync: () => safeDecodeAsync4,
21551
21551
  safeEncode: () => safeEncode4,
@@ -21781,7 +21781,7 @@ var init_attributes2 = __esm({
21781
21781
  function getOwnProperty2(object3, key) {
21782
21782
  return Object.hasOwn(object3, key) ? object3[key] : void 0;
21783
21783
  }
21784
- function isSealedNoopEvent(event) {
21784
+ function isSealedNoopEvent2(event) {
21785
21785
  return event.eventType === "noop";
21786
21786
  }
21787
21787
  function entityEventClass(eventType) {
@@ -21808,7 +21808,7 @@ var init_event_metadata2 = __esm({
21808
21808
  "../world/dist/event-metadata.js"() {
21809
21809
  "use strict";
21810
21810
  __name(getOwnProperty2, "getOwnProperty");
21811
- __name(isSealedNoopEvent, "isSealedNoopEvent");
21811
+ __name(isSealedNoopEvent2, "isSealedNoopEvent");
21812
21812
  ENTITY_EVENT_CLASS_BY_TYPE = {
21813
21813
  attr_set: "attr_set",
21814
21814
  step_created: "step_created",
@@ -24204,6 +24204,235 @@ var init_ulid2 = __esm({
24204
24204
  }
24205
24205
  });
24206
24206
 
24207
+ // ../world/dist/usage.js
24208
+ function spanOf2(eventType, workflowName) {
24209
+ if (eventType.startsWith("hook_"))
24210
+ return { kind: "hook", name: "hook" };
24211
+ if (eventType.startsWith("wait_"))
24212
+ return { kind: "wait", name: "sleep" };
24213
+ if (eventType.startsWith("run_"))
24214
+ return { kind: "run", name: workflowName };
24215
+ if (eventType === "attr_set") {
24216
+ return { kind: "attributes", name: "attributes" };
24217
+ }
24218
+ return { kind: "other", name: "other" };
24219
+ }
24220
+ function compareCodeUnits2(a, b) {
24221
+ return a < b ? -1 : a > b ? 1 : 0;
24222
+ }
24223
+ function toCount2(value) {
24224
+ const n = Number(value);
24225
+ return Number.isFinite(n) && n > 0 ? n : 0;
24226
+ }
24227
+ function usageEntityOfEventType2(eventType) {
24228
+ if (isSealedNoopEvent2({ eventType }))
24229
+ return null;
24230
+ if (eventType.startsWith("step_"))
24231
+ return "step";
24232
+ if (eventType.startsWith("hook_"))
24233
+ return "hook";
24234
+ return "run";
24235
+ }
24236
+ function buildRunUsage2(input3) {
24237
+ const spans = /* @__PURE__ */ new Map();
24238
+ const byEntity = {
24239
+ run: 0,
24240
+ step: 0,
24241
+ hook: 0,
24242
+ stream: toCount2(input3.streamBytes)
24243
+ };
24244
+ let events = 0;
24245
+ let retries = 0;
24246
+ const add3 = /* @__PURE__ */ __name((kind, name, entity, count2, retryCount, bytes) => {
24247
+ if (count2 <= 0)
24248
+ return;
24249
+ const key = `${kind}\0${name}`;
24250
+ let span = spans.get(key);
24251
+ if (!span) {
24252
+ span = { kind, name, events: 0, share: 0, retries: 0, calls: 0 };
24253
+ spans.set(key, span);
24254
+ }
24255
+ span.events += count2;
24256
+ span.retries += retryCount;
24257
+ events += count2;
24258
+ retries += retryCount;
24259
+ byEntity[entity] += bytes;
24260
+ }, "add");
24261
+ const created = { hook: 0, wait: 0 };
24262
+ const hookGroups = input3.hookGroups;
24263
+ let hookEvents = 0;
24264
+ const runEvents = {
24265
+ events: 0,
24266
+ byType: { created: 0, started: 0, completed: 0, failed: 0, cancelled: 0 }
24267
+ };
24268
+ for (const group of input3.eventGroups) {
24269
+ const entity = usageEntityOfEventType2(group.eventType);
24270
+ if (!entity)
24271
+ continue;
24272
+ const runType = group.eventType.slice("run_".length);
24273
+ if (group.eventType.startsWith("run_") && RUN_USAGE_RUN_EVENT_TYPES2.includes(runType)) {
24274
+ runEvents.byType[runType] += toCount2(group.events);
24275
+ }
24276
+ if (group.eventType.startsWith("run_")) {
24277
+ runEvents.events += toCount2(group.events);
24278
+ }
24279
+ if (group.eventType === "hook_created")
24280
+ created.hook += toCount2(group.events);
24281
+ if (group.eventType === "wait_created")
24282
+ created.wait += toCount2(group.events);
24283
+ const { kind, name } = spanOf2(group.eventType, input3.workflowName);
24284
+ if (kind === "hook" && hookGroups) {
24285
+ hookEvents += toCount2(group.events);
24286
+ events += toCount2(group.events);
24287
+ byEntity[entity] += toCount2(group.bytes);
24288
+ continue;
24289
+ }
24290
+ add3(kind, name, entity, toCount2(group.events), 0, toCount2(group.bytes));
24291
+ }
24292
+ if (hookGroups) {
24293
+ let grouped = 0;
24294
+ for (const group of hookGroups) {
24295
+ const count2 = toCount2(group.events);
24296
+ if (count2 <= 0 || !group.hookId)
24297
+ continue;
24298
+ grouped += count2;
24299
+ spans.set(`hook\0${group.hookId}`, {
24300
+ kind: "hook",
24301
+ name: group.token || group.hookId,
24302
+ id: group.hookId,
24303
+ events: count2,
24304
+ share: 0,
24305
+ retries: 0,
24306
+ calls: 1
24307
+ });
24308
+ }
24309
+ if (hookEvents > grouped) {
24310
+ spans.set("hook\0", {
24311
+ kind: "hook",
24312
+ name: "hook",
24313
+ events: hookEvents - grouped,
24314
+ share: 0,
24315
+ retries: 0,
24316
+ calls: 0
24317
+ });
24318
+ }
24319
+ }
24320
+ const calls = {
24321
+ hook: toCount2(created.hook),
24322
+ wait: toCount2(input3.calls?.wait ?? created.wait)
24323
+ };
24324
+ const stepEvents = {
24325
+ steps: 0,
24326
+ events: 0,
24327
+ byType: {
24328
+ created: 0,
24329
+ started: 0,
24330
+ completed: 0,
24331
+ failed: 0,
24332
+ retrying: 0,
24333
+ other: 0
24334
+ }
24335
+ };
24336
+ let restarts = 0;
24337
+ for (const group of input3.stepGroups) {
24338
+ restarts += toCount2(group.restarts);
24339
+ const counts = {
24340
+ created: toCount2(group.created),
24341
+ started: toCount2(group.started),
24342
+ completed: toCount2(group.completed),
24343
+ failed: toCount2(group.failed),
24344
+ retrying: toCount2(group.retries)
24345
+ };
24346
+ const total = toCount2(group.events);
24347
+ if (total <= 0)
24348
+ continue;
24349
+ stepEvents.steps += toCount2(group.steps);
24350
+ stepEvents.events += total;
24351
+ let known = 0;
24352
+ for (const type of RUN_USAGE_STEP_EVENT_TYPES2) {
24353
+ stepEvents.byType[type] += counts[type];
24354
+ known += counts[type];
24355
+ }
24356
+ stepEvents.byType.other += Math.max(0, total - known);
24357
+ const name = group.stepName || UNKNOWN_STEP_NAME2;
24358
+ add3("step", name, "step", toCount2(group.events), toCount2(group.retries), toCount2(group.bytes));
24359
+ const span = spans.get(`step\0${name}`);
24360
+ if (span)
24361
+ span.calls += toCount2(group.steps);
24362
+ }
24363
+ for (const span of spans.values()) {
24364
+ if (span.kind === "run")
24365
+ span.calls = 1;
24366
+ if (span.kind === "hook" && !hookGroups)
24367
+ span.calls = calls.hook;
24368
+ if (span.kind === "wait")
24369
+ span.calls = calls.wait;
24370
+ if (span.kind === "attributes" || span.kind === "other") {
24371
+ span.calls = span.events;
24372
+ }
24373
+ }
24374
+ const eventsBySpan = [...spans.values()].map((span) => ({ ...span, share: events > 0 ? span.events / events : 0 })).sort((a, b) => b.events - a.events || compareCodeUnits2(a.name, b.name) || compareCodeUnits2(a.kind, b.kind) || compareCodeUnits2(a.id ?? "", b.id ?? ""));
24375
+ return {
24376
+ runId: input3.runId,
24377
+ status: input3.status,
24378
+ workflowName: input3.workflowName,
24379
+ billed: input3.billed === true,
24380
+ inProgress: !isTerminalWorkflowRunStatus2(input3.status),
24381
+ events,
24382
+ billableEvents: events,
24383
+ retries: { count: retries, events: retries + restarts },
24384
+ runEvents,
24385
+ stepEvents,
24386
+ eventsBySpan,
24387
+ dataWritten: dataWrittenOf2(input3, byEntity),
24388
+ dataPurged: input3.dataPurged === true,
24389
+ dataRetained: input3.dataRetained ?? null
24390
+ };
24391
+ }
24392
+ function dataWrittenOf2(input3, measured) {
24393
+ const saved = input3.dataPurged ? input3.savedDataWritten : void 0;
24394
+ const byEntity = saved ? {
24395
+ run: toCount2(saved.run),
24396
+ step: toCount2(saved.step),
24397
+ hook: toCount2(saved.hook),
24398
+ stream: toCount2(saved.stream)
24399
+ } : measured;
24400
+ return {
24401
+ bytes: byEntity.run + byEntity.step + byEntity.hook + byEntity.stream,
24402
+ byEntity,
24403
+ source: !input3.dataPurged ? "log" : saved ? "saved-at-purge" : "left-after-purge"
24404
+ };
24405
+ }
24406
+ var RUN_USAGE_RUN_EVENT_TYPES2, RUN_USAGE_STEP_EVENT_TYPES2, UNKNOWN_STEP_NAME2;
24407
+ var init_usage2 = __esm({
24408
+ "../world/dist/usage.js"() {
24409
+ "use strict";
24410
+ init_event_metadata2();
24411
+ init_runs3();
24412
+ RUN_USAGE_RUN_EVENT_TYPES2 = [
24413
+ "created",
24414
+ "started",
24415
+ "completed",
24416
+ "failed",
24417
+ "cancelled"
24418
+ ];
24419
+ RUN_USAGE_STEP_EVENT_TYPES2 = [
24420
+ "created",
24421
+ "started",
24422
+ "completed",
24423
+ "failed",
24424
+ "retrying"
24425
+ ];
24426
+ UNKNOWN_STEP_NAME2 = "(unknown step)";
24427
+ __name(spanOf2, "spanOf");
24428
+ __name(compareCodeUnits2, "compareCodeUnits");
24429
+ __name(toCount2, "toCount");
24430
+ __name(usageEntityOfEventType2, "usageEntityOfEventType");
24431
+ __name(buildRunUsage2, "buildRunUsage");
24432
+ __name(dataWrittenOf2, "dataWrittenOf");
24433
+ }
24434
+ });
24435
+
24207
24436
  // ../world/dist/index.js
24208
24437
  var init_dist10 = __esm({
24209
24438
  "../world/dist/index.js"() {
@@ -24226,6 +24455,7 @@ var init_dist10 = __esm({
24226
24455
  init_start_hook3();
24227
24456
  init_steps3();
24228
24457
  init_ulid2();
24458
+ init_usage2();
24229
24459
  init_waits2();
24230
24460
  }
24231
24461
  });
@@ -24299,7 +24529,7 @@ function formatErrorMessageWithDetails(title, details) {
24299
24529
  function isRunAlreadyStartedError(error123) {
24300
24530
  return EntityConflictError2.is(error123) && error123.code === RUN_ALREADY_STARTED_CODE;
24301
24531
  }
24302
- var BASE_URL2, QUICKJS_SNAPSHOT_REMEDIATION, ERROR_SLUGS2, WorkflowError2, WorkflowWorldError2, START_HOOK_ADMISSION_REJECTED2, START_HOOK_ADMISSION_DISABLED2, START_HOOK_CANDIDATE_CANCELLED2, WorkflowStartError2, WorkflowRunFailedError2, WorkflowRunNotCompletedError2, WorkflowRuntimeError2, CorruptedEventLogError2, ReplayDivergenceError, MaxEventsExceededError, RuntimeDecryptionError2, EncryptionKeyLookupError2, SerializationError2, StepNotRegisteredError2, WorkflowNotRegisteredError, WorkflowDeploymentMismatchError, WorkflowRunNotFoundError2, HookConflictError2, HookForceClaimedError2, HookNotFoundError2, EntityConflictError2, RUN_ALREADY_STARTED_CODE, RunExpiredError2, StreamError2, StreamExpiredError2, TooEarlyError2, ThrottleError2, PreconditionFailedError2, IN_BAND_SUPERSEDED_CODE2, InBandSupersededError2, WorkflowRunCancelledError2, RunNotSupportedError2, FatalError2, RetryableError2, FATAL_ERROR_KEY2, RETRYABLE_ERROR_KEY2, HOOK_CONFLICT_ERROR_KEY2, HOOK_FORCE_CLAIMED_ERROR_KEY2, RUNTIME_DECRYPTION_ERROR_KEY2, STREAM_ERROR_KEY2, WORKFLOW_START_ERROR_KEY2;
24532
+ var BASE_URL2, QUICKJS_SNAPSHOT_REMEDIATION, ERROR_SLUGS2, WorkflowError2, WorkflowWorldError2, START_HOOK_ADMISSION_REJECTED2, START_HOOK_ADMISSION_DISABLED2, START_HOOK_CANDIDATE_CANCELLED2, WorkflowStartError2, DYNAMIC_WORKFLOWS_ENV_VAR2, DYNAMIC_WORKFLOWS_DOCS_URL2, DYNAMIC_WORKFLOWS_NOT_ENABLED_HINT2, DynamicWorkflowsNotEnabledError2, WorkflowRunFailedError2, WorkflowRunNotCompletedError2, WorkflowRuntimeError2, CorruptedEventLogError2, ReplayDivergenceError, MaxEventsExceededError, RuntimeDecryptionError2, EncryptionKeyLookupError2, SerializationError2, StepNotRegisteredError2, WorkflowNotRegisteredError, WorkflowDeploymentMismatchError, WorkflowRunNotFoundError2, HookConflictError2, HookForceClaimedError2, HookNotFoundError2, EntityConflictError2, RUN_ALREADY_STARTED_CODE, RunExpiredError2, StreamError2, StreamExpiredError2, TooEarlyError2, ThrottleError2, PreconditionFailedError2, IN_BAND_SUPERSEDED_CODE2, InBandSupersededError2, WorkflowRunCancelledError2, RunNotSupportedError2, FatalError2, RetryableError2, FATAL_ERROR_KEY2, RETRYABLE_ERROR_KEY2, HOOK_CONFLICT_ERROR_KEY2, HOOK_FORCE_CLAIMED_ERROR_KEY2, RUNTIME_DECRYPTION_ERROR_KEY2, STREAM_ERROR_KEY2, WORKFLOW_START_ERROR_KEY2;
24303
24533
  var init_dist11 = __esm({
24304
24534
  "../errors/dist/index.js"() {
24305
24535
  "use strict";
@@ -24411,6 +24641,29 @@ Caused by: ${options.cause.stack}`;
24411
24641
  return isError2(value) && value.name === "WorkflowStartError";
24412
24642
  }
24413
24643
  };
24644
+ DYNAMIC_WORKFLOWS_ENV_VAR2 = "WORKFLOW_EXPERIMENTAL_DYNAMIC_WORKFLOWS";
24645
+ DYNAMIC_WORKFLOWS_DOCS_URL2 = "https://workflow-sdk.dev/docs/advanced/dynamic-workflows#enabling-dynamic-workflows";
24646
+ DYNAMIC_WORKFLOWS_NOT_ENABLED_HINT2 = `Set the ${DYNAMIC_WORKFLOWS_ENV_VAR2}=1 environment variable on your project, then redeploy (or restart your dev server) so the new value takes effect.`;
24647
+ DynamicWorkflowsNotEnabledError2 = class extends WorkflowError2 {
24648
+ static {
24649
+ __name(this, "DynamicWorkflowsNotEnabledError");
24650
+ }
24651
+ fatal = true;
24652
+ /**
24653
+ * @param message - What was refused, e.g. that `start()` created no run.
24654
+ * The fix-it hint and a docs link are appended to it.
24655
+ */
24656
+ constructor(message, options) {
24657
+ super(appendFramedDetails2(message, [
24658
+ { label: "hint", value: DYNAMIC_WORKFLOWS_NOT_ENABLED_HINT2 },
24659
+ { label: "docs", value: DYNAMIC_WORKFLOWS_DOCS_URL2 }
24660
+ ]), { cause: options?.cause });
24661
+ this.name = "DynamicWorkflowsNotEnabledError";
24662
+ }
24663
+ static is(value) {
24664
+ return isError2(value) && value.name === "DynamicWorkflowsNotEnabledError";
24665
+ }
24666
+ };
24414
24667
  WorkflowRunFailedError2 = class extends WorkflowError2 {
24415
24668
  static {
24416
24669
  __name(this, "WorkflowRunFailedError");
@@ -57190,6 +57443,121 @@ var init_recovery_wake2 = __esm({
57190
57443
  }
57191
57444
  });
57192
57445
 
57446
+ // ../world-local/dist/storage/purged-usage.js
57447
+ function valueBytesSql2(path15) {
57448
+ const data3 = `CAST(json_extract(doc, '${path15}.data') AS BLOB)`;
57449
+ return `CASE WHEN json_extract(doc, '${path15}.__type') = 'Uint8Array'
57450
+ THEN length(${data3}) / 4 * 3 - (CASE WHEN substr(${data3}, -2) = X'3D3D' THEN 2 WHEN substr(${data3}, -1) = X'3D' THEN 1 ELSE 0 END)
57451
+ ELSE coalesce(length(CAST(doc -> '${path15}' AS BLOB)), 0) END`;
57452
+ }
57453
+ function measureStreamBytes2(db, runId) {
57454
+ return Number(db.get(STREAM_BYTES_SQL2, runId)?.bytes ?? 0);
57455
+ }
57456
+ function tableExists2(db) {
57457
+ return db.get("SELECT 1 AS one FROM sqlite_master WHERE type = 'table' AND name = ?", TABLE2) !== void 0;
57458
+ }
57459
+ function savePurgedUsage2(db, runId, usage) {
57460
+ db.run(CREATE_TABLE_SQL2);
57461
+ db.run(`INSERT INTO ${TABLE2}
57462
+ (run_id, seq, run_bytes, step_bytes, hook_bytes, stream_bytes)
57463
+ VALUES (?, ?, ?, ?, ?, ?)
57464
+ ON CONFLICT (run_id) DO UPDATE SET
57465
+ seq = excluded.seq,
57466
+ run_bytes = excluded.run_bytes,
57467
+ step_bytes = excluded.step_bytes,
57468
+ hook_bytes = excluded.hook_bytes,
57469
+ stream_bytes = excluded.stream_bytes`, runId, usage.seq, usage.byEntity.run, usage.byEntity.step, usage.byEntity.hook, usage.byEntity.stream);
57470
+ }
57471
+ function readPurgedUsage2(db, runId) {
57472
+ if (!tableExists2(db))
57473
+ return null;
57474
+ const row = db.get(`SELECT seq, run_bytes, step_bytes, hook_bytes, stream_bytes
57475
+ FROM ${TABLE2} WHERE run_id = ?`, runId);
57476
+ if (!row)
57477
+ return null;
57478
+ return {
57479
+ seq: Number(row.seq),
57480
+ byEntity: {
57481
+ run: Number(row.run_bytes),
57482
+ step: Number(row.step_bytes),
57483
+ hook: Number(row.hook_bytes),
57484
+ stream: Number(row.stream_bytes)
57485
+ }
57486
+ };
57487
+ }
57488
+ function deletePurgedUsage2(db, where) {
57489
+ if (!tableExists2(db))
57490
+ return;
57491
+ if (!where) {
57492
+ db.run(`DELETE FROM ${TABLE2}`);
57493
+ return;
57494
+ }
57495
+ db.run(`DELETE FROM ${TABLE2} WHERE run_id IN (${where.runIdsSql})`, ...where.params);
57496
+ }
57497
+ var PAYLOAD_PATHS2, PAYLOAD_EVENT_TYPES2, PAYLOAD_BYTES_SQL2, STREAM_BYTES_SQL2, TABLE2, CREATE_TABLE_SQL2, EntityBytes2;
57498
+ var init_purged_usage2 = __esm({
57499
+ "../world-local/dist/storage/purged-usage.js"() {
57500
+ "use strict";
57501
+ init_dist10();
57502
+ PAYLOAD_PATHS2 = {
57503
+ // A dynamic run's code is kept on the run, not on its events, so it is
57504
+ // not here.
57505
+ run_created: ["$.eventData.input", "$.eventData.startHook.metadata"],
57506
+ run_started: ["$.eventData.input", "$.eventData.startHook.metadata"],
57507
+ run_completed: ["$.eventData.output"],
57508
+ run_failed: ["$.eventData.error"],
57509
+ step_created: ["$.eventData.input"],
57510
+ step_started: ["$.eventData.input"],
57511
+ step_completed: ["$.eventData.result"],
57512
+ step_failed: ["$.eventData.error"],
57513
+ step_retrying: ["$.eventData.error"],
57514
+ hook_created: ["$.eventData.metadata"],
57515
+ hook_received: ["$.eventData.payload"]
57516
+ };
57517
+ PAYLOAD_EVENT_TYPES2 = Object.keys(PAYLOAD_PATHS2);
57518
+ __name(valueBytesSql2, "valueBytesSql");
57519
+ PAYLOAD_BYTES_SQL2 = `(CASE event_type ${Object.entries(PAYLOAD_PATHS2).map(([eventType, paths]) => `WHEN '${eventType}' THEN ${paths.map((path15) => `(${valueBytesSql2(path15)})`).join(" + ")}`).join(" ")} ELSE 0 END)`;
57520
+ STREAM_BYTES_SQL2 = `
57521
+ SELECT COALESCE(SUM(length(data)), 0) AS bytes
57522
+ FROM stream_chunks
57523
+ WHERE run_id = ?
57524
+ `;
57525
+ __name(measureStreamBytes2, "measureStreamBytes");
57526
+ TABLE2 = "run_usage_purged";
57527
+ CREATE_TABLE_SQL2 = `
57528
+ CREATE TABLE IF NOT EXISTS ${TABLE2} (
57529
+ run_id TEXT PRIMARY KEY,
57530
+ -- The last log position the sizes below cover.
57531
+ seq INTEGER NOT NULL,
57532
+ run_bytes INTEGER NOT NULL,
57533
+ step_bytes INTEGER NOT NULL,
57534
+ hook_bytes INTEGER NOT NULL,
57535
+ stream_bytes INTEGER NOT NULL
57536
+ )
57537
+ `;
57538
+ EntityBytes2 = class {
57539
+ static {
57540
+ __name(this, "EntityBytes");
57541
+ }
57542
+ byEntity = {
57543
+ run: 0,
57544
+ step: 0,
57545
+ hook: 0,
57546
+ stream: 0
57547
+ };
57548
+ add(eventType, bytes) {
57549
+ const entity = usageEntityOfEventType2(eventType);
57550
+ if (entity)
57551
+ this.byEntity[entity] += Number(bytes) || 0;
57552
+ }
57553
+ };
57554
+ __name(tableExists2, "tableExists");
57555
+ __name(savePurgedUsage2, "savePurgedUsage");
57556
+ __name(readPurgedUsage2, "readPurgedUsage");
57557
+ __name(deletePurgedUsage2, "deletePurgedUsage");
57558
+ }
57559
+ });
57560
+
57193
57561
  // ../world-local/dist/ids.js
57194
57562
  function truncateForError2(value) {
57195
57563
  const s = typeof value === "string" ? value : String(value);
@@ -57239,11 +57607,31 @@ function ranPurge2(run3) {
57239
57607
  return true;
57240
57608
  return run3.expiredAt !== void 0 && new Date(run3.expiredAt).getTime() <= Date.now();
57241
57609
  }
57242
- function purgeRunData2(db, runId) {
57610
+ function purgeRunData2(db, runId, { purgedBefore = false } = {}) {
57243
57611
  for (const row of db.all("SELECT step_id, doc FROM steps WHERE run_id = ?", runId)) {
57244
57612
  writeScrubbedStep2(db, runId, row.step_id, row.doc);
57245
57613
  }
57246
- for (const row of db.all("SELECT seq, doc FROM events WHERE run_id = ?", runId)) {
57614
+ const saved = readPurgedUsage2(db, runId);
57615
+ const written = new EntityBytes2();
57616
+ let lastSeq = 0;
57617
+ const events = db.all(`SELECT seq, event_type, doc, ${PAYLOAD_BYTES_SQL2} AS bytes
57618
+ FROM events WHERE run_id = ?`, runId);
57619
+ for (const row of events) {
57620
+ lastSeq = Math.max(lastSeq, Number(row.seq));
57621
+ if (saved && Number(row.seq) <= saved.seq)
57622
+ continue;
57623
+ written.add(row.event_type, row.bytes);
57624
+ }
57625
+ written.byEntity.stream = measureStreamBytes2(db, runId);
57626
+ if (saved) {
57627
+ savePurgedUsage2(db, runId, {
57628
+ seq: lastSeq,
57629
+ byEntity: addBytes2(saved.byEntity, written.byEntity)
57630
+ });
57631
+ } else if (!purgedBefore) {
57632
+ savePurgedUsage2(db, runId, { seq: lastSeq, byEntity: written.byEntity });
57633
+ }
57634
+ for (const row of events) {
57247
57635
  writeScrubbedEvent2(db, runId, row.seq, row.doc);
57248
57636
  }
57249
57637
  for (const row of db.all("SELECT hook_id, doc FROM hooks WHERE run_id = ?", runId)) {
@@ -57263,8 +57651,29 @@ function purgeLateStepWrite2(db, runId, stepId, seq) {
57263
57651
  db.run("UPDATE steps SET doc = ? WHERE run_id = ? AND step_id = ?", encode8(step), runId, stepId);
57264
57652
  }
57265
57653
  const event = db.get("SELECT doc FROM events WHERE run_id = ? AND seq = ?", runId, seq);
57266
- if (event)
57267
- writeScrubbedEvent2(db, runId, seq, event.doc);
57654
+ if (!event)
57655
+ return;
57656
+ const saved = readPurgedUsage2(db, runId);
57657
+ if (saved && seq > saved.seq) {
57658
+ const written = new EntityBytes2();
57659
+ for (const row of db.all(`SELECT event_type, ${PAYLOAD_BYTES_SQL2} AS bytes
57660
+ FROM events WHERE run_id = ? AND seq > ? AND seq <= ?`, runId, saved.seq, seq)) {
57661
+ written.add(row.event_type, row.bytes);
57662
+ }
57663
+ savePurgedUsage2(db, runId, {
57664
+ seq,
57665
+ byEntity: addBytes2(saved.byEntity, written.byEntity)
57666
+ });
57667
+ }
57668
+ writeScrubbedEvent2(db, runId, seq, event.doc);
57669
+ }
57670
+ function addBytes2(a, b) {
57671
+ return {
57672
+ run: a.run + b.run,
57673
+ step: a.step + b.step,
57674
+ hook: a.hook + b.hook,
57675
+ stream: a.stream + b.stream
57676
+ };
57268
57677
  }
57269
57678
  function writeScrubbedStep2(db, runId, stepId, doc) {
57270
57679
  const step = decode8(doc);
@@ -57302,10 +57711,12 @@ var init_run_retention2 = __esm({
57302
57711
  "use strict";
57303
57712
  init_dist10();
57304
57713
  init_codec3();
57714
+ init_purged_usage2();
57305
57715
  __name(purgesUserDataOnFinish3, "purgesUserDataOnFinish");
57306
57716
  __name(ranPurge2, "ranPurge");
57307
57717
  __name(purgeRunData2, "purgeRunData");
57308
57718
  __name(purgeLateStepWrite2, "purgeLateStepWrite");
57719
+ __name(addBytes2, "addBytes");
57309
57720
  __name(writeScrubbedStep2, "writeScrubbedStep");
57310
57721
  __name(writeScrubbedEvent2, "writeScrubbedEvent");
57311
57722
  __name(purgeRunStreams2, "purgeRunStreams");
@@ -57588,6 +57999,7 @@ var init_store2 = __esm({
57588
57999
  eventsBetween(runId, afterSeq, beforeSeq) {
57589
58000
  return this.db.all("SELECT doc FROM events WHERE run_id = ? AND seq > ? AND seq < ? ORDER BY seq", runId, afterSeq, beforeSeq).map((row) => decode8(row.doc));
57590
58001
  }
58002
+ // A caller that rewrites a live run's events makes the usage cache stale (see usage-storage.ts).
57591
58003
  rewriteEvent(event) {
57592
58004
  const seq = eventIdToSlot2(event.eventId);
57593
58005
  if (seq === null)
@@ -58793,7 +59205,7 @@ function createRunsStorage2(db, tag) {
58793
59205
  const alreadyDeleted = run3.expiredAt !== void 0 && run3.expiredAt.getTime() <= now3.getTime();
58794
59206
  if (!alreadyDeleted)
58795
59207
  store.updateRun(withRunPayloadsPurged2(run3, now3));
58796
- purgeRunData2(db, runId);
59208
+ purgeRunData2(db, runId, { purgedBefore: alreadyDeleted });
58797
59209
  return { runId, outcome: alreadyDeleted ? "already_deleted" : "deleted" };
58798
59210
  }
58799
59211
  __name(deleteRunData, "deleteRunData");
@@ -59024,6 +59436,339 @@ var init_steps_storage2 = __esm({
59024
59436
  }
59025
59437
  });
59026
59438
 
59439
+ // ../world-local/dist/storage/usage-storage.js
59440
+ function countRange2(db, runId, counts, from, to) {
59441
+ if (to <= from)
59442
+ return;
59443
+ for (const row of db.all(EVENT_GROUPS_SQL2, runId, from, to)) {
59444
+ const entry = counts.eventTypes.get(row.event_type) ?? {
59445
+ events: 0,
59446
+ bytes: 0
59447
+ };
59448
+ entry.events += Number(row.events);
59449
+ entry.bytes += Number(row.bytes ?? 0);
59450
+ counts.eventTypes.set(row.event_type, entry);
59451
+ }
59452
+ for (const row of db.all(STEP_GROUPS_SQL2, runId, from, to)) {
59453
+ const stepId = row.correlation_id ?? "";
59454
+ let step = counts.steps.get(stepId);
59455
+ if (!step) {
59456
+ const name = row.correlation_id === null ? null : db.get(STEP_NAME_SQL2, runId, row.correlation_id)?.step_name ?? null;
59457
+ step = {
59458
+ name,
59459
+ events: 0,
59460
+ created: 0,
59461
+ started: 0,
59462
+ completed: 0,
59463
+ failed: 0,
59464
+ retries: 0,
59465
+ bytes: 0
59466
+ };
59467
+ counts.steps.set(stepId, step);
59468
+ }
59469
+ step.events += Number(row.events);
59470
+ step.created += Number(row.created);
59471
+ step.started += Number(row.started);
59472
+ step.completed += Number(row.completed);
59473
+ step.failed += Number(row.failed);
59474
+ step.retries += Number(row.retries);
59475
+ step.bytes += Number(row.bytes ?? 0);
59476
+ }
59477
+ for (const row of db.all(HOOK_GROUPS_SQL2, runId, from, to)) {
59478
+ let hook = counts.hooks.get(row.correlation_id);
59479
+ if (!hook) {
59480
+ hook = { token: hookToken2(db, runId, row.correlation_id), events: 0 };
59481
+ counts.hooks.set(row.correlation_id, hook);
59482
+ }
59483
+ hook.events += Number(row.events);
59484
+ }
59485
+ for (const row of db.all(WAIT_IDS_SQL2, runId, from, to)) {
59486
+ counts.waitIds.add(row.correlation_id);
59487
+ }
59488
+ counts.countedSeq = to;
59489
+ }
59490
+ function hookToken2(db, runId, hookId) {
59491
+ const created = db.get(HOOK_TOKEN_SQL2, runId, hookId);
59492
+ if (typeof created?.token === "string" && created.token)
59493
+ return created.token;
59494
+ const row = db.get(HOOK_ROW_TOKEN_SQL2, hookId);
59495
+ if (typeof row?.token === "string" && row.token)
59496
+ return row.token;
59497
+ let startHook;
59498
+ try {
59499
+ startHook = startHookId2(runId);
59500
+ } catch {
59501
+ return null;
59502
+ }
59503
+ if (hookId !== startHook)
59504
+ return null;
59505
+ const start3 = db.get(START_HOOK_TOKEN_SQL2, runId);
59506
+ return typeof start3?.token === "string" && start3.token ? start3.token : null;
59507
+ }
59508
+ function hookGroupsOf2(counts) {
59509
+ return [...counts.hooks].map(([hookId, hook]) => ({
59510
+ hookId,
59511
+ token: hook.token,
59512
+ events: hook.events
59513
+ }));
59514
+ }
59515
+ function eventGroupsOf2(counts) {
59516
+ return [...counts.eventTypes].map(([eventType, entry]) => ({
59517
+ eventType,
59518
+ events: entry.events,
59519
+ bytes: entry.bytes
59520
+ }));
59521
+ }
59522
+ function stepGroupsOf2(counts) {
59523
+ const byName = /* @__PURE__ */ new Map();
59524
+ for (const step of counts.steps.values()) {
59525
+ let group = byName.get(step.name);
59526
+ if (!group) {
59527
+ group = {
59528
+ stepName: step.name,
59529
+ steps: 0,
59530
+ events: 0,
59531
+ created: 0,
59532
+ started: 0,
59533
+ completed: 0,
59534
+ failed: 0,
59535
+ retries: 0,
59536
+ restarts: 0,
59537
+ bytes: 0
59538
+ };
59539
+ byName.set(step.name, group);
59540
+ }
59541
+ group.steps += 1;
59542
+ group.events += step.events;
59543
+ group.created += step.created;
59544
+ group.started += step.started;
59545
+ group.completed += step.completed;
59546
+ group.failed += step.failed;
59547
+ group.retries += step.retries;
59548
+ group.restarts += Math.min(step.retries, Math.max(0, step.started - 1));
59549
+ group.bytes += step.bytes;
59550
+ }
59551
+ return [...byName.values()];
59552
+ }
59553
+ function purgedDataWritten2(db, runId, streamBytes) {
59554
+ const saved = readPurgedUsage2(db, runId);
59555
+ if (!saved)
59556
+ return null;
59557
+ const late = new EntityBytes2();
59558
+ for (const row of db.all(EVENTS_AFTER_SQL2, runId, saved.seq)) {
59559
+ late.add(row.event_type, Number(row.bytes ?? 0));
59560
+ }
59561
+ return {
59562
+ run: saved.byEntity.run + late.byEntity.run,
59563
+ step: saved.byEntity.step + late.byEntity.step,
59564
+ hook: saved.byEntity.hook + late.byEntity.hook,
59565
+ stream: saved.byEntity.stream + streamBytes
59566
+ };
59567
+ }
59568
+ function createUsageStorage2(db, tag, options = {}) {
59569
+ const maxRuns = options.maxRuns ?? 64;
59570
+ const batchTargetMs = options.batchTargetMs ?? 10;
59571
+ const maxBatchRows = options.maxBatchRows ?? 4096;
59572
+ const initialBatchRows = options.initialBatchRows ?? 4;
59573
+ const cache = /* @__PURE__ */ new Map();
59574
+ const inFlight = /* @__PURE__ */ new Map();
59575
+ const remember = /* @__PURE__ */ __name((runId, counts) => {
59576
+ cache.delete(runId);
59577
+ cache.set(runId, counts);
59578
+ while (cache.size > maxRuns) {
59579
+ cache.delete(cache.keys().next().value);
59580
+ }
59581
+ }, "remember");
59582
+ const runRow = /* @__PURE__ */ __name((runId) => db.get(`SELECT status, workflow_name, seq FROM runs WHERE run_id = ? AND ${tagClause2("tag", tag)}`, runId, ...tagParams2(tag)), "runRow");
59583
+ async function countInBatches(runId, counts, target3) {
59584
+ let batchRows = initialBatchRows;
59585
+ while (counts.countedSeq < target3) {
59586
+ const end = Number(db.get(BATCH_END_SQL2, runId, counts.countedSeq, batchRows)?.seq ?? target3);
59587
+ const started = performance.now();
59588
+ countRange2(db, runId, counts, counts.countedSeq, Math.min(end, target3));
59589
+ const took = performance.now() - started;
59590
+ batchRows = Math.max(1, Math.min(maxBatchRows, batchRows * 2, Math.round(batchRows * batchTargetMs / Math.max(took, 0.1))));
59591
+ if (counts.countedSeq < target3) {
59592
+ await options.onBatch?.(runId, counts.countedSeq);
59593
+ await yieldToEventLoop2();
59594
+ }
59595
+ }
59596
+ }
59597
+ __name(countInBatches, "countInBatches");
59598
+ async function read5(runId) {
59599
+ const first = runRow(runId);
59600
+ if (!first) {
59601
+ cache.delete(runId);
59602
+ throw new WorkflowRunNotFoundError2(runId);
59603
+ }
59604
+ let counts = cache.get(runId) ?? newCounts2();
59605
+ if (Number(first.seq) < counts.countedSeq)
59606
+ counts = newCounts2();
59607
+ let readBeforeFinish = !isTerminalWorkflowRunStatus2(first.status) || counts.countedSeq > 0 && !counts.finished;
59608
+ await countInBatches(runId, counts, Number(first.seq));
59609
+ const snapshot = db.snapshot(() => {
59610
+ const run3 = runRow(runId);
59611
+ if (!run3)
59612
+ return null;
59613
+ const seq = Number(run3.seq);
59614
+ const finished = isTerminalWorkflowRunStatus2(run3.status);
59615
+ if (seq < counts.countedSeq) {
59616
+ counts = newCounts2();
59617
+ readBeforeFinish = !finished;
59618
+ }
59619
+ countRange2(db, runId, counts, counts.countedSeq, seq);
59620
+ const streamBytes = measureStreamBytes2(db, runId);
59621
+ const savedDataWritten = purgedDataWritten2(db, runId, streamBytes) ?? void 0;
59622
+ const dataPurged = savedDataWritten !== void 0 || finished && Number(db.get(PURGED_RUN_SQL2, runId)?.purged) === 1;
59623
+ if (dataPurged && readBeforeFinish && counts.countedSeq > 0) {
59624
+ options.onRecount?.(runId);
59625
+ counts = newCounts2();
59626
+ countRange2(db, runId, counts, 0, seq);
59627
+ }
59628
+ counts.finished = finished;
59629
+ return {
59630
+ run: run3,
59631
+ streamBytes,
59632
+ dataPurged,
59633
+ savedDataWritten
59634
+ };
59635
+ });
59636
+ if (!snapshot) {
59637
+ cache.delete(runId);
59638
+ throw new WorkflowRunNotFoundError2(runId);
59639
+ }
59640
+ remember(runId, counts);
59641
+ return buildRunUsage2({
59642
+ runId,
59643
+ status: snapshot.run.status,
59644
+ workflowName: snapshot.run.workflow_name,
59645
+ eventGroups: eventGroupsOf2(counts),
59646
+ stepGroups: stepGroupsOf2(counts),
59647
+ streamBytes: snapshot.streamBytes,
59648
+ dataPurged: snapshot.dataPurged,
59649
+ savedDataWritten: snapshot.savedDataWritten,
59650
+ hookGroups: hookGroupsOf2(counts),
59651
+ calls: { wait: counts.waitIds.size },
59652
+ // Local runs are not billed.
59653
+ billed: false,
59654
+ // world-local has no plan retention, so there is no Data Retained to
59655
+ // report: the UI and CLI hide it.
59656
+ dataRetained: null
59657
+ });
59658
+ }
59659
+ __name(read5, "read");
59660
+ return {
59661
+ async getRun(runId) {
59662
+ assertSafeEntityId2("runId", runId);
59663
+ const previous = inFlight.get(runId) ?? Promise.resolve();
59664
+ const current3 = previous.catch(() => {
59665
+ }).then(() => read5(runId));
59666
+ inFlight.set(runId, current3);
59667
+ try {
59668
+ return await current3;
59669
+ } finally {
59670
+ if (inFlight.get(runId) === current3)
59671
+ inFlight.delete(runId);
59672
+ }
59673
+ }
59674
+ };
59675
+ }
59676
+ var IS_STEP_EVENT2, EVENT_GROUPS_SQL2, STEP_GROUPS_SQL2, WAIT_IDS_SQL2, HOOK_GROUPS_SQL2, HOOK_TOKEN_SQL2, HOOK_ROW_TOKEN_SQL2, START_HOOK_TOKEN_SQL2, STEP_NAME_SQL2, BATCH_END_SQL2, EVENTS_AFTER_SQL2, PURGED_RUN_SQL2, newCounts2, yieldToEventLoop2;
59677
+ var init_usage_storage2 = __esm({
59678
+ "../world-local/dist/storage/usage-storage.js"() {
59679
+ "use strict";
59680
+ init_dist11();
59681
+ init_dist10();
59682
+ init_ids2();
59683
+ init_purged_usage2();
59684
+ init_store2();
59685
+ IS_STEP_EVENT2 = `event_type LIKE 'step\\_%' ESCAPE '\\'`;
59686
+ EVENT_GROUPS_SQL2 = `
59687
+ SELECT event_type,
59688
+ COUNT(*) AS events,
59689
+ SUM(${PAYLOAD_BYTES_SQL2}) AS bytes
59690
+ FROM events
59691
+ WHERE run_id = ?1 AND seq > ?2 AND seq <= ?3 AND NOT (${IS_STEP_EVENT2})
59692
+ GROUP BY event_type
59693
+ `;
59694
+ STEP_GROUPS_SQL2 = `
59695
+ SELECT correlation_id,
59696
+ COUNT(*) AS events,
59697
+ SUM(event_type = 'step_created') AS created,
59698
+ SUM(event_type = 'step_started') AS started,
59699
+ SUM(event_type = 'step_completed') AS completed,
59700
+ SUM(event_type = 'step_failed') AS failed,
59701
+ SUM(event_type = 'step_retrying') AS retries,
59702
+ SUM(${PAYLOAD_BYTES_SQL2}) AS bytes
59703
+ FROM events
59704
+ WHERE run_id = ?1 AND seq > ?2 AND seq <= ?3 AND ${IS_STEP_EVENT2}
59705
+ GROUP BY correlation_id
59706
+ `;
59707
+ WAIT_IDS_SQL2 = `
59708
+ SELECT DISTINCT correlation_id
59709
+ FROM events
59710
+ WHERE run_id = ?1 AND seq > ?2 AND seq <= ?3
59711
+ AND correlation_id IS NOT NULL AND substr(event_type, 1, 5) = 'wait_'
59712
+ `;
59713
+ HOOK_GROUPS_SQL2 = `
59714
+ SELECT correlation_id, COUNT(*) AS events
59715
+ FROM events
59716
+ WHERE run_id = ?1 AND seq > ?2 AND seq <= ?3
59717
+ AND correlation_id IS NOT NULL AND substr(event_type, 1, 5) = 'hook_'
59718
+ GROUP BY correlation_id
59719
+ `;
59720
+ HOOK_TOKEN_SQL2 = `
59721
+ SELECT json_extract(doc, '$.eventData.token') AS token
59722
+ FROM ${EVENTS_BY_CORRELATION2}
59723
+ WHERE run_id = ? AND correlation_id = ?
59724
+ AND event_type IN ('hook_created', 'hook_conflict')
59725
+ ORDER BY seq LIMIT 1
59726
+ `;
59727
+ HOOK_ROW_TOKEN_SQL2 = "SELECT token FROM hooks WHERE hook_id = ?";
59728
+ START_HOOK_TOKEN_SQL2 = `
59729
+ SELECT json_extract(doc, '$.eventData.startHook.token') AS token
59730
+ FROM events
59731
+ WHERE run_id = ? AND event_type = 'run_created'
59732
+ LIMIT 1
59733
+ `;
59734
+ STEP_NAME_SQL2 = `
59735
+ SELECT json_extract(doc, '$.stepName') AS step_name
59736
+ FROM steps WHERE run_id = ? AND step_id = ?
59737
+ `;
59738
+ BATCH_END_SQL2 = `
59739
+ SELECT MAX(seq) AS seq FROM (
59740
+ SELECT seq FROM events WHERE run_id = ? AND seq > ? ORDER BY seq LIMIT ?
59741
+ )
59742
+ `;
59743
+ EVENTS_AFTER_SQL2 = `
59744
+ SELECT event_type, SUM(${PAYLOAD_BYTES_SQL2}) AS bytes
59745
+ FROM events
59746
+ WHERE run_id = ? AND seq > ?
59747
+ GROUP BY event_type
59748
+ `;
59749
+ PURGED_RUN_SQL2 = `
59750
+ SELECT json_extract(doc, '$.expiredAt') IS NOT NULL AS purged
59751
+ FROM runs WHERE run_id = ?
59752
+ `;
59753
+ newCounts2 = /* @__PURE__ */ __name(() => ({
59754
+ countedSeq: 0,
59755
+ finished: false,
59756
+ eventTypes: /* @__PURE__ */ new Map(),
59757
+ steps: /* @__PURE__ */ new Map(),
59758
+ hooks: /* @__PURE__ */ new Map(),
59759
+ waitIds: /* @__PURE__ */ new Set()
59760
+ }), "newCounts");
59761
+ __name(countRange2, "countRange");
59762
+ __name(hookToken2, "hookToken");
59763
+ __name(hookGroupsOf2, "hookGroupsOf");
59764
+ __name(eventGroupsOf2, "eventGroupsOf");
59765
+ __name(stepGroupsOf2, "stepGroupsOf");
59766
+ __name(purgedDataWritten2, "purgedDataWritten");
59767
+ yieldToEventLoop2 = /* @__PURE__ */ __name(() => new Promise((resolve4) => setImmediate(resolve4)), "yieldToEventLoop");
59768
+ __name(createUsageStorage2, "createUsageStorage");
59769
+ }
59770
+ });
59771
+
59027
59772
  // ../world-local/dist/storage/index.js
59028
59773
  function createStorage3(basedir, tag) {
59029
59774
  const db = databaseFor2(basedir);
@@ -59032,12 +59777,14 @@ function createStorage3(basedir, tag) {
59032
59777
  const events = createEventsStorage2(db, tag);
59033
59778
  const hooks = createHooksStorage2(db, tag);
59034
59779
  const snapshots = createSnapshotsStorage3(db);
59780
+ const usage = createUsageStorage2(db, tag);
59035
59781
  return {
59036
59782
  runs: instrumentObject3("world.runs", runs),
59037
59783
  steps: instrumentObject3("world.steps", steps),
59038
59784
  events: instrumentObject3("world.events", events),
59039
59785
  hooks: instrumentObject3("world.hooks", hooks),
59040
59786
  experimental_snapshots: instrumentObject3("world.experimental_snapshots", snapshots),
59787
+ experimental_usage: instrumentObject3("world.experimental_usage", usage),
59041
59788
  clearCache: /* @__PURE__ */ __name(() => {
59042
59789
  }, "clearCache")
59043
59790
  };
@@ -59052,6 +59799,7 @@ var init_storage4 = __esm({
59052
59799
  init_runs_storage2();
59053
59800
  init_snapshots_storage2();
59054
59801
  init_steps_storage2();
59802
+ init_usage_storage2();
59055
59803
  __name(createStorage3, "createStorage");
59056
59804
  }
59057
59805
  });
@@ -59458,9 +60206,11 @@ function createWorld4(args) {
59458
60206
  ]) {
59459
60207
  db.run(`DELETE FROM ${table}`);
59460
60208
  }
60209
+ deletePurgedUsage2(db);
59461
60210
  return;
59462
60211
  }
59463
60212
  const runs = "SELECT run_id FROM runs WHERE tag = ?";
60213
+ deletePurgedUsage2(db, { runIdsSql: runs, params: [tag] });
59464
60214
  for (const table of [
59465
60215
  "events",
59466
60216
  "steps",
@@ -59500,6 +60250,7 @@ var init_dist12 = __esm({
59500
60250
  init_queue5();
59501
60251
  init_queue_auth_key2();
59502
60252
  init_recovery_wake2();
60253
+ init_purged_usage2();
59503
60254
  init_storage5();
59504
60255
  init_streamer3();
59505
60256
  init_build_target_mismatch2();
@@ -63353,7 +64104,7 @@ var version6;
63353
64104
  var init_version4 = __esm({
63354
64105
  "../world-vercel/dist/version.js"() {
63355
64106
  "use strict";
63356
- version6 = "5.7.0";
64107
+ version6 = "5.7.2";
63357
64108
  }
63358
64109
  });
63359
64110
 
@@ -72186,17 +72937,17 @@ var require_exec2 = __commonJS({
72186
72937
  var import_node_path11 = __toESM3(__require("node:path"));
72187
72938
  var import_execa = __toESM3(require_execa2());
72188
72939
  var import_envpath = require_envpath2();
72189
- var import_errors89 = require_errors5();
72940
+ var import_errors90 = require_errors5();
72190
72941
  var import_lookup = require_lookup2();
72191
72942
  async function execVercelCli2(args, options = {}) {
72192
72943
  const cwd = import_node_path11.default.resolve(options.cwd ?? process.cwd());
72193
- await (0, import_errors89.assertValidCwd)(cwd);
72944
+ await (0, import_errors90.assertValidCwd)(cwd);
72194
72945
  const env = mergeExecEnv(options.env);
72195
72946
  const pathValue = (0, import_envpath.getEnvPath)(env);
72196
72947
  try {
72197
72948
  return await execResolvedVercelCli(args, options, cwd, env, pathValue);
72198
72949
  } catch (error123) {
72199
- if (error123 instanceof import_errors89.VercelCliError && error123.code === "VERCEL_CLI_NOT_FOUND") {
72950
+ if (error123 instanceof import_errors90.VercelCliError && error123.code === "VERCEL_CLI_NOT_FOUND") {
72200
72951
  (0, import_lookup.clearCachedCliInvocation)(cwd, pathValue);
72201
72952
  return await execResolvedVercelCli(args, options, cwd, env, pathValue);
72202
72953
  }
@@ -72228,16 +72979,16 @@ var require_exec2 = __commonJS({
72228
72979
  );
72229
72980
  return { stdout, stderr, invocation };
72230
72981
  } catch (error123) {
72231
- throw (0, import_errors89.toVercelCliError)(invocation, error123);
72982
+ throw (0, import_errors90.toVercelCliError)(invocation, error123);
72232
72983
  }
72233
72984
  }
72234
72985
  __name(execResolvedVercelCli, "execResolvedVercelCli");
72235
72986
  async function resolveInvocationOrThrow(cwd, pathValue) {
72236
72987
  const resolution = await (0, import_lookup.resolveCachedCliInvocation)(cwd, pathValue);
72237
72988
  if (!resolution.found) {
72238
- throw new import_errors89.VercelCliError({
72989
+ throw new import_errors90.VercelCliError({
72239
72990
  code: "VERCEL_CLI_NOT_FOUND",
72240
- message: (0, import_errors89.getCliNotFoundMessage)(resolution.diagnostics)
72991
+ message: (0, import_errors90.getCliNotFoundMessage)(resolution.diagnostics)
72241
72992
  });
72242
72993
  }
72243
72994
  return (0, import_lookup.toVercelCliInvocation)(resolution);
@@ -72291,13 +73042,13 @@ var require_dist6 = __commonJS({
72291
73042
  var __toCommonJS = /* @__PURE__ */ __name((mod) => __copyProps3(__defProp3({}, "__esModule", { value: true }), mod), "__toCommonJS");
72292
73043
  var src_exports = {};
72293
73044
  __export3(src_exports, {
72294
- VercelCliError: /* @__PURE__ */ __name(() => import_errors89.VercelCliError, "VercelCliError"),
73045
+ VercelCliError: /* @__PURE__ */ __name(() => import_errors90.VercelCliError, "VercelCliError"),
72295
73046
  clearVercelCliLookupCache: /* @__PURE__ */ __name(() => import_lookup.clearVercelCliLookupCache, "clearVercelCliLookupCache"),
72296
73047
  execVercelCli: /* @__PURE__ */ __name(() => import_exec.execVercelCli, "execVercelCli"),
72297
73048
  findVercelCli: /* @__PURE__ */ __name(() => import_lookup.findVercelCli, "findVercelCli")
72298
73049
  });
72299
73050
  module.exports = __toCommonJS(src_exports);
72300
- var import_errors89 = require_errors5();
73051
+ var import_errors90 = require_errors5();
72301
73052
  var import_exec = require_exec2();
72302
73053
  var import_lookup = require_lookup2();
72303
73054
  }
@@ -74455,11 +75206,11 @@ ${content.join(`
74455
75206
  return this._map.has(schema);
74456
75207
  }
74457
75208
  };
74458
- function registry3() {
75209
+ function registry5() {
74459
75210
  return new $ZodRegistry3();
74460
75211
  }
74461
- __name(registry3, "registry");
74462
- (_a22 = globalThis).__zod_globalRegistry ?? (_a22.__zod_globalRegistry = registry3());
75212
+ __name(registry5, "registry");
75213
+ (_a22 = globalThis).__zod_globalRegistry ?? (_a22.__zod_globalRegistry = registry5());
74463
75214
  var globalRegistry3 = globalThis.__zod_globalRegistry;
74464
75215
  function snapshotChecks3(def) {
74465
75216
  return def.checks && (def.checks = [...def.checks]), def;
@@ -86602,10 +87353,10 @@ function registerHandlerForFile2(filePath, handler, client, options) {
86602
87353
  const absolutePath = path14.isAbsolute(filePath) ? filePath : path14.resolve(process.cwd(), filePath);
86603
87354
  const fileMappings = findMappingsForFile2(absolutePath);
86604
87355
  if (fileMappings.length === 0) return false;
86605
- const registry3 = getHandlerRegistry2();
87356
+ const registry5 = getHandlerRegistry2();
86606
87357
  for (const mapping of fileMappings) {
86607
87358
  const key = mapping.topic;
86608
- const existing = registry3.get(key) ?? [];
87359
+ const existing = registry5.get(key) ?? [];
86609
87360
  const nextEntry = {
86610
87361
  consumerGroup: mapping.consumer,
86611
87362
  handler,
@@ -86620,7 +87371,7 @@ function registerHandlerForFile2(filePath, handler, client, options) {
86620
87371
  } else {
86621
87372
  existing.push(nextEntry);
86622
87373
  }
86623
- registry3.set(key, existing);
87374
+ registry5.set(key, existing);
86624
87375
  }
86625
87376
  return true;
86626
87377
  }
@@ -86662,9 +87413,9 @@ Add a trigger to vercel.json:
86662
87413
  }
86663
87414
  }
86664
87415
  function lookupHandlers2(topicName) {
86665
- const registry3 = getHandlerRegistry2();
87416
+ const registry5 = getHandlerRegistry2();
86666
87417
  const result2 = [];
86667
- for (const [pattern, handlers] of registry3) {
87418
+ for (const [pattern, handlers] of registry5) {
86668
87419
  const matches = pattern.includes("*") ? matchesWildcardPattern2(topicName, pattern) : pattern === topicName;
86669
87420
  if (matches) {
86670
87421
  result2.push(...handlers);
@@ -95790,6 +96541,9 @@ function isRetryableWorldError2(err) {
95790
96541
  return err.code !== void 0 && RETRYABLE_WORLD_ERROR_CODES2.has(err.code);
95791
96542
  }
95792
96543
  function classifyRunError(err) {
96544
+ if (DynamicWorkflowsNotEnabledError2.is(err)) {
96545
+ return RUN_ERROR_CODES2.USER_ERROR;
96546
+ }
95793
96547
  if (ReplayDivergenceError.is(err)) {
95794
96548
  return RUN_ERROR_CODES2.REPLAY_DIVERGENCE;
95795
96549
  }
@@ -96166,6 +96920,13 @@ function describeError3(err, errorCode) {
96166
96920
  hint: CONTEXT_ERROR_HINT
96167
96921
  };
96168
96922
  }
96923
+ if (DynamicWorkflowsNotEnabledError2.is(err)) {
96924
+ return {
96925
+ attribution: "user",
96926
+ errorCode: effectiveCode,
96927
+ hint: DYNAMIC_WORKFLOWS_NOT_ENABLED_DESCRIPTION_HINT
96928
+ };
96929
+ }
96169
96930
  if (CorruptedEventLogError2.is(err)) {
96170
96931
  return {
96171
96932
  attribution: "sdk",
@@ -96238,7 +96999,7 @@ function describeError3(err, errorCode) {
96238
96999
  }
96239
97000
  return { attribution: "user", errorCode: effectiveCode };
96240
97001
  }
96241
- var SERIALIZATION_ERROR_HINT, CONTEXT_ERROR_HINT, RUNTIME_ERROR_HINT, CORRUPTED_EVENT_LOG_HINT, REPLAY_TIMEOUT_HINT, MAX_DELIVERIES_HINT, MAX_EVENTS_HINT, STREAM_ERROR_HINT, WORLD_CONTRACT_HINT, DEPLOYMENT_MISMATCH_HINT, WORKFLOW_NOT_REGISTERED_HINT, CODE_DESCRIPTIONS;
97002
+ var SERIALIZATION_ERROR_HINT, CONTEXT_ERROR_HINT, RUNTIME_ERROR_HINT, CORRUPTED_EVENT_LOG_HINT, REPLAY_TIMEOUT_HINT, MAX_DELIVERIES_HINT, MAX_EVENTS_HINT, STREAM_ERROR_HINT, WORLD_CONTRACT_HINT, DEPLOYMENT_MISMATCH_HINT, DYNAMIC_WORKFLOWS_NOT_ENABLED_DESCRIPTION_HINT, WORKFLOW_NOT_REGISTERED_HINT, CODE_DESCRIPTIONS;
96242
97003
  var init_describe_error = __esm({
96243
97004
  "../core/dist/describe-error.js"() {
96244
97005
  "use strict";
@@ -96256,6 +97017,7 @@ var init_describe_error = __esm({
96256
97017
  STREAM_ERROR_HINT = "Workflow stream infrastructure failed while reading or writing data. This is an SDK or backend failure, not an error in your workflow code; please retry the run and report persistent failures with the runId.";
96257
97018
  WORLD_CONTRACT_HINT = "The workflow backend returned data that violated the SDK contract. This is not retryable; please report it with the stack trace and runId.";
96258
97019
  DEPLOYMENT_MISMATCH_HINT = "The run was delivered to a deployment other than the deployment it is pinned to, and was stopped to protect against code-skew errors after the runtime failed to re-route it there. Verify that the run's deployment is still available and that queue callbacks route to it.";
97020
+ DYNAMIC_WORKFLOWS_NOT_ENABLED_DESCRIPTION_HINT = `Dynamic workflows are not enabled for this project. ${DYNAMIC_WORKFLOWS_NOT_ENABLED_HINT2}`;
96259
97021
  WORKFLOW_NOT_REGISTERED_HINT = "The deployment that executed this run does not have its workflow registered. Usually the run was started or replayed against a deployment where the workflow was renamed, moved, or removed, or the build did not bundle it. Check the workflowId and the deployment the run is pinned to.";
96260
97022
  CODE_DESCRIPTIONS = {
96261
97023
  [RUN_ERROR_CODES2.REPLAY_TIMEOUT]: {
@@ -101568,6 +102330,76 @@ var init_sealed_box2 = __esm({
101568
102330
  }
101569
102331
  });
101570
102332
 
102333
+ // ../core/dist/serialization/abort-local.js
102334
+ function registry4() {
102335
+ const holder = globalThis;
102336
+ holder[REGISTRY_KEY2] ??= { listeners: /* @__PURE__ */ new Map(), published: /* @__PURE__ */ new Map() };
102337
+ return holder[REGISTRY_KEY2];
102338
+ }
102339
+ function keyOf2(runId, streamName) {
102340
+ return `${runId}\0${streamName}`;
102341
+ }
102342
+ function prune2(published, now3) {
102343
+ for (const [key, entry] of published) {
102344
+ if (now3 - entry.at < PUBLISHED_TTL_MS2 && published.size <= MAX_PUBLISHED2)
102345
+ break;
102346
+ published.delete(key);
102347
+ }
102348
+ }
102349
+ function publishLocalAbort2(runId, streamName, packet) {
102350
+ const { listeners, published } = registry4();
102351
+ const key = keyOf2(runId, streamName);
102352
+ const now3 = Date.now();
102353
+ published.delete(key);
102354
+ published.set(key, { packet, at: now3 });
102355
+ prune2(published, now3);
102356
+ for (const listener of listeners.get(key) ?? []) {
102357
+ try {
102358
+ listener(packet);
102359
+ } catch {
102360
+ }
102361
+ }
102362
+ }
102363
+ function onLocalAbort2(runId, streamName, listener) {
102364
+ const { listeners, published } = registry4();
102365
+ const key = keyOf2(runId, streamName);
102366
+ prune2(published, Date.now());
102367
+ const recent = published.get(key);
102368
+ if (recent) {
102369
+ listener(recent.packet);
102370
+ return () => {
102371
+ };
102372
+ }
102373
+ let set3 = listeners.get(key);
102374
+ if (!set3) {
102375
+ set3 = /* @__PURE__ */ new Set();
102376
+ listeners.set(key, set3);
102377
+ }
102378
+ set3.add(listener);
102379
+ return () => {
102380
+ const current3 = listeners.get(key);
102381
+ if (!current3)
102382
+ return;
102383
+ current3.delete(listener);
102384
+ if (current3.size === 0)
102385
+ listeners.delete(key);
102386
+ };
102387
+ }
102388
+ var REGISTRY_KEY2, PUBLISHED_TTL_MS2, MAX_PUBLISHED2;
102389
+ var init_abort_local2 = __esm({
102390
+ "../core/dist/serialization/abort-local.js"() {
102391
+ "use strict";
102392
+ REGISTRY_KEY2 = /* @__PURE__ */ Symbol.for("@workflow/core//localAbortDelivery");
102393
+ PUBLISHED_TTL_MS2 = 6e4;
102394
+ MAX_PUBLISHED2 = 256;
102395
+ __name(registry4, "registry");
102396
+ __name(keyOf2, "keyOf");
102397
+ __name(prune2, "prune");
102398
+ __name(publishLocalAbort2, "publishLocalAbort");
102399
+ __name(onLocalAbort2, "onLocalAbort");
102400
+ }
102401
+ });
102402
+
101571
102403
  // ../core/dist/serialization/types.js
101572
102404
  function isFormatPrefix2(value) {
101573
102405
  return value.length === 4 && /^[a-z0-9]{4}$/.test(value);
@@ -102124,12 +102956,12 @@ var init_dist16 = __esm({
102124
102956
  // ../core/dist/class-serialization.js
102125
102957
  function getRegistry2(global2 = globalThis) {
102126
102958
  const g = global2;
102127
- let registry3 = g[WORKFLOW_CLASS_REGISTRY2];
102128
- if (!registry3) {
102129
- registry3 = /* @__PURE__ */ new Map();
102130
- g[WORKFLOW_CLASS_REGISTRY2] = registry3;
102959
+ let registry5 = g[WORKFLOW_CLASS_REGISTRY2];
102960
+ if (!registry5) {
102961
+ registry5 = /* @__PURE__ */ new Map();
102962
+ g[WORKFLOW_CLASS_REGISTRY2] = registry5;
102131
102963
  }
102132
- return registry3;
102964
+ return registry5;
102133
102965
  }
102134
102966
  function getSerializationClass2(classId, global2) {
102135
102967
  return getRegistry2(global2).get(classId);
@@ -104657,11 +105489,11 @@ function getWorkflowRunStreamId2(runId, namespace) {
104657
105489
  function getAbortStreamId2(id) {
104658
105490
  return `strm_${id}_system_abort`;
104659
105491
  }
104660
- function getAbortStreamIdFromToken(hookToken) {
104661
- if (!hookToken.startsWith(ABORT_TOKEN_PREFIX)) {
104662
- throw new Error(`Invalid abort hook token format: expected "abrt_" prefix, got "${hookToken}"`);
105492
+ function getAbortStreamIdFromToken(hookToken3) {
105493
+ if (!hookToken3.startsWith(ABORT_TOKEN_PREFIX)) {
105494
+ throw new Error(`Invalid abort hook token format: expected "abrt_" prefix, got "${hookToken3}"`);
104663
105495
  }
104664
- return getAbortStreamId2(hookToken.slice(ABORT_TOKEN_PREFIX.length));
105496
+ return getAbortStreamId2(hookToken3.slice(ABORT_TOKEN_PREFIX.length));
104665
105497
  }
104666
105498
  var ABORT_TOKEN_PREFIX;
104667
105499
  var init_util6 = __esm({
@@ -104973,7 +105805,7 @@ var init_events_consumer2 = __esm({
104973
105805
  while (true) {
104974
105806
  this.drainParked();
104975
105807
  const currentEvent = this.events[this.eventIndex] ?? null;
104976
- if (currentEvent !== null && isSealedNoopEvent(currentEvent)) {
105808
+ if (currentEvent !== null && isSealedNoopEvent2(currentEvent)) {
104977
105809
  this.skipSealedNoop(currentEvent);
104978
105810
  continue;
104979
105811
  }
@@ -105662,15 +106494,15 @@ function createCreateAbortController(ctx) {
105662
106494
  constructor() {
105663
106495
  const id = ctx.generateUlid();
105664
106496
  const streamName = getAbortStreamId2(id);
105665
- const hookToken = `abrt_${id}`;
106497
+ const hookToken3 = `abrt_${id}`;
105666
106498
  this[ABORT_STREAM_NAME2] = streamName;
105667
- this[ABORT_HOOK_TOKEN2] = hookToken;
105668
- this.signal = new WorkflowAbortSignal2(streamName, hookToken);
106499
+ this[ABORT_HOOK_TOKEN2] = hookToken3;
106500
+ this.signal = new WorkflowAbortSignal2(streamName, hookToken3);
105669
106501
  const correlationId = mintHookCorrelationId(ctx.generateUlid, ctx.startHook);
105670
106502
  ctx.invocationsQueue.set(correlationId, {
105671
106503
  type: "hook",
105672
106504
  correlationId,
105673
- token: hookToken,
106505
+ token: hookToken3,
105674
106506
  isWebhook: false,
105675
106507
  isSystem: true
105676
106508
  });
@@ -105823,9 +106655,9 @@ var init_abort_controller2 = __esm({
105823
106655
  handler.call(this);
105824
106656
  }
105825
106657
  }
105826
- constructor(streamName, hookToken) {
106658
+ constructor(streamName, hookToken3) {
105827
106659
  this[ABORT_STREAM_NAME2] = streamName;
105828
- this[ABORT_HOOK_TOKEN2] = hookToken;
106660
+ this[ABORT_HOOK_TOKEN2] = hookToken3;
105829
106661
  }
105830
106662
  /**
105831
106663
  * @internal Sets aborted state and fires listeners.
@@ -106534,35 +107366,35 @@ function getAllBaseReducers2(global2 = globalThis) {
106534
107366
  }
106535
107367
  function reduceAbortWithListener2(signal, holder, global2, ops, runId, cryptoKey, framedAbortStreams) {
106536
107368
  let streamName = holder[ABORT_STREAM_NAME2];
106537
- let hookToken = holder[ABORT_HOOK_TOKEN2];
107369
+ let hookToken3 = holder[ABORT_HOOK_TOKEN2];
106538
107370
  if (!streamName) {
106539
107371
  const id = (global2[STABLE_ULID2] || defaultUlid2)();
106540
107372
  streamName = getAbortStreamId2(id);
106541
- hookToken = `abrt_${id}`;
107373
+ hookToken3 = `abrt_${id}`;
106542
107374
  holder[ABORT_STREAM_NAME2] = streamName;
106543
- holder[ABORT_HOOK_TOKEN2] = hookToken;
107375
+ holder[ABORT_HOOK_TOKEN2] = hookToken3;
106544
107376
  if (holder.signal) {
106545
107377
  holder.signal[ABORT_STREAM_NAME2] = streamName;
106546
- holder.signal[ABORT_HOOK_TOKEN2] = hookToken;
107378
+ holder.signal[ABORT_HOOK_TOKEN2] = hookToken3;
106547
107379
  }
106548
107380
  }
106549
107381
  attachAbortListenerOnce2(signal, streamName, runId, cryptoKey, ops, framedAbortStreams);
106550
107382
  return {
106551
107383
  streamName,
106552
- hookToken,
107384
+ hookToken: hookToken3,
106553
107385
  aborted: signal.aborted,
106554
107386
  reason: signal.aborted ? signal.reason : void 0
106555
107387
  };
106556
107388
  }
106557
107389
  function reduceAbortBySymbol2(signal, holder) {
106558
107390
  const streamName = holder[ABORT_STREAM_NAME2] ?? holder.signal?.[ABORT_STREAM_NAME2];
106559
- const hookToken = holder[ABORT_HOOK_TOKEN2] ?? holder.signal?.[ABORT_HOOK_TOKEN2];
107391
+ const hookToken3 = holder[ABORT_HOOK_TOKEN2] ?? holder.signal?.[ABORT_HOOK_TOKEN2];
106560
107392
  if (!streamName) {
106561
107393
  throw new Error("AbortController/AbortSignal stream name is not set");
106562
107394
  }
106563
107395
  return {
106564
107396
  streamName,
106565
- hookToken,
107397
+ hookToken: hookToken3,
106566
107398
  aborted: signal.aborted,
106567
107399
  reason: signal.aborted ? signal.reason : void 0
106568
107400
  };
@@ -106578,6 +107410,7 @@ function attachAbortListenerOnce2(signal, streamName, runId, cryptoKey, ops, fra
106578
107410
  try {
106579
107411
  const key = await resolveEncryptionKey2(cryptoKey);
106580
107412
  const payload = await dehydrateStepArguments2({ aborted: true, reason: signal.reason }, runId, key);
107413
+ publishLocalAbort2(runId, streamName, payload);
106581
107414
  const writable = new WorkflowServerWritableStream2(runId, streamName);
106582
107415
  const writer = writable.getWriter();
106583
107416
  await writer.write(framedAbortStreams ? frameAbortStreamPayload2(payload) : payload);
@@ -106881,40 +107714,76 @@ function cancelAbortReaders2(...values) {
106881
107714
  for (const v of values)
106882
107715
  walk(v);
106883
107716
  }
106884
- function setupAbortStreamReader2(controller, runId, streamName, ops, cryptoKey) {
107717
+ function setupAbortStreamReader2(controller, runId, streamName, ops, cryptoKey, untilCancelled) {
106885
107718
  const readerCancel = new AbortController();
107719
+ let resolveLocal;
107720
+ const localPacket = new Promise((resolve4) => {
107721
+ resolveLocal = resolve4;
107722
+ });
107723
+ const stopLocal = onLocalAbort2(runId, streamName, (packet) => resolveLocal?.(packet));
106886
107724
  ops.push((async () => {
106887
107725
  let reader;
107726
+ let keepListening = false;
106888
107727
  try {
106889
- const readable = new WorkflowServerReadableStream2(runId, streamName);
106890
- reader = readable.getReader();
106891
107728
  let keyPromise;
106892
107729
  let decoded;
106893
107730
  const decodePacket = /* @__PURE__ */ __name(async (packet) => {
106894
107731
  keyPromise ??= resolveEncryptionKey2(cryptoKey);
106895
107732
  decoded = await hydrateStepArguments2(packet, runId, await keyPromise);
106896
107733
  }, "decodePacket");
106897
- const result2 = await Promise.race([
106898
- readAbortStreamPacket2(reader, decodePacket),
106899
- new Promise((resolve4) => {
106900
- if (readerCancel.signal.aborted) {
106901
- resolve4(void 0);
106902
- return;
106903
- }
106904
- readerCancel.signal.addEventListener("abort", () => resolve4(void 0), { once: true });
106905
- })
106906
- ]);
106907
- if (result2) {
107734
+ const abortWith = /* @__PURE__ */ __name(async (packet, already) => {
106908
107735
  try {
107736
+ decoded = already;
106909
107737
  if (decoded === void 0)
106910
- await decodePacket(result2);
107738
+ await decodePacket(packet);
106911
107739
  controller.abort(decoded?.reason);
106912
107740
  } catch {
106913
107741
  controller.abort();
106914
107742
  }
107743
+ }, "abortWith");
107744
+ const cancelled = new Promise((resolve4) => {
107745
+ if (readerCancel.signal.aborted) {
107746
+ resolve4(void 0);
107747
+ return;
107748
+ }
107749
+ readerCancel.signal.addEventListener("abort", () => resolve4(void 0), { once: true });
107750
+ });
107751
+ let streamPacket;
107752
+ try {
107753
+ const readable = new WorkflowServerReadableStream2(runId, streamName);
107754
+ reader = readable.getReader();
107755
+ streamPacket = readAbortStreamPacket2(reader, decodePacket);
107756
+ } catch {
107757
+ streamPacket = new Promise(() => {
107758
+ });
107759
+ }
107760
+ const local = localPacket.then((packet) => ({ packet, local: true }));
107761
+ const winner = await Promise.race([
107762
+ local,
107763
+ untilCancelled ? (
107764
+ // An empty or failed stream is not the end of the abort.
107765
+ streamPacket.then((packet) => packet ? { packet, local: false } : void 0, () => void 0)
107766
+ ) : streamPacket.then((packet) => packet ? { packet, local: false } : void 0),
107767
+ cancelled
107768
+ ]);
107769
+ if (winner) {
107770
+ await abortWith(winner.packet, winner.local ? void 0 : decoded);
107771
+ } else if (untilCancelled && !readerCancel.signal.aborted) {
107772
+ keepListening = true;
107773
+ const expiry = setTimeout(stopLocal, LOCAL_ABORT_LISTEN_AFTER_STREAM_END_MS2);
107774
+ expiry.unref?.();
107775
+ void Promise.race([local, cancelled]).then(async (late) => {
107776
+ clearTimeout(expiry);
107777
+ stopLocal();
107778
+ if (late)
107779
+ await abortWith(late.packet, void 0);
107780
+ }).catch(() => {
107781
+ });
106915
107782
  }
106916
107783
  } catch {
106917
107784
  } finally {
107785
+ if (!keepListening)
107786
+ stopLocal();
106918
107787
  void reader?.cancel().catch(() => {
106919
107788
  });
106920
107789
  }
@@ -106946,13 +107815,13 @@ function copyAbortInternals2(src3, dest) {
106946
107815
  d[ABORT_READER_CANCEL2] = s[ABORT_READER_CANCEL2];
106947
107816
  }
106948
107817
  }
106949
- function reviveAbortController2(value, ops, runId, cryptoKey) {
107818
+ function reviveAbortController2(value, ops, runId, cryptoKey, untilCancelled = false) {
106950
107819
  const controller = new AbortController();
106951
107820
  if (value.aborted) {
106952
107821
  tagAbortPair2(controller, value);
106953
107822
  controller.abort(value.reason);
106954
107823
  } else if (value.streamName) {
106955
- const readerCancel = setupAbortStreamReader2(controller, runId, value.streamName, ops, cryptoKey);
107824
+ const readerCancel = setupAbortStreamReader2(controller, runId, value.streamName, ops, cryptoKey, untilCancelled);
106956
107825
  tagAbortPair2(controller, value, readerCancel);
106957
107826
  } else {
106958
107827
  tagAbortPair2(controller, value);
@@ -106967,6 +107836,7 @@ function reviveAbortController2(value, ops, runId, cryptoKey) {
106967
107836
  ctx.ops.push((async () => {
106968
107837
  try {
106969
107838
  const payload = await dehydrateStepArguments2({ aborted: true, reason }, ctx.workflowMetadata.workflowRunId, ctx.encryptionKey);
107839
+ publishLocalAbort2(ctx.workflowMetadata.workflowRunId, value.streamName, payload);
106970
107840
  const writable = new WorkflowServerWritableStream2(ctx.workflowMetadata.workflowRunId, value.streamName);
106971
107841
  const writer = writable.getWriter();
106972
107842
  await writer.write(frameAbortStreamPayload2(payload));
@@ -106991,13 +107861,13 @@ function reviveAbortController2(value, ops, runId, cryptoKey) {
106991
107861
  };
106992
107862
  return controller;
106993
107863
  }
106994
- function reviveAbortSignal2(value, ops, runId, cryptoKey) {
107864
+ function reviveAbortSignal2(value, ops, runId, cryptoKey, untilCancelled = false) {
106995
107865
  const controller = new AbortController();
106996
107866
  if (value.aborted) {
106997
107867
  tagAbortPair2(controller, value);
106998
107868
  controller.abort(value.reason);
106999
107869
  } else if (value.streamName) {
107000
- const readerCancel = setupAbortStreamReader2(controller, runId, value.streamName, ops, cryptoKey);
107870
+ const readerCancel = setupAbortStreamReader2(controller, runId, value.streamName, ops, cryptoKey, untilCancelled);
107001
107871
  tagAbortPair2(controller, value, readerCancel);
107002
107872
  } else {
107003
107873
  tagAbortPair2(controller, value);
@@ -107497,8 +108367,10 @@ function getStepRevivers2(global2 = globalThis, ops, runId, cryptoKey, deploymen
107497
108367
  }
107498
108368
  return writable;
107499
108369
  }, "WritableStream"),
107500
- AbortController: /* @__PURE__ */ __name((value) => reviveAbortController2(value, ops, runId, cryptoKey), "AbortController"),
107501
- AbortSignal: /* @__PURE__ */ __name((value) => reviveAbortSignal2(value, ops, runId, cryptoKey), "AbortSignal")
108370
+ // A step's readers are cancelled when the step returns
108371
+ // (`cancelAbortReaders`), so they may outlive an empty stream.
108372
+ AbortController: /* @__PURE__ */ __name((value) => reviveAbortController2(value, ops, runId, cryptoKey, true), "AbortController"),
108373
+ AbortSignal: /* @__PURE__ */ __name((value) => reviveAbortSignal2(value, ops, runId, cryptoKey, true), "AbortSignal")
107502
108374
  };
107503
108375
  }
107504
108376
  async function maybeEncrypt2(data3, key) {
@@ -107813,7 +108685,7 @@ function getStreamAndRequestRevivers2(allRevivers) {
107813
108685
  }
107814
108686
  return extra;
107815
108687
  }
107816
- var defaultUlid2, FRAME_HEADER_SIZE2, MAX_FRAME_SIZE2, WorkflowServerReadableStream2, FRAMED_STREAM_MAX_RECONNECTS2, getFramedStreamMaxReconnects2, FRAMED_STREAM_MAX_TOTAL_RECONNECTS2, getFramedStreamMaxTotalReconnects2, FRAMED_STREAM_MAX_STALLS_BELOW_TAIL2, FRAMED_STREAM_MIN_STALL_SESSION_MS2, STREAM_FLUSH_INTERVAL_MS2, getEnvStreamFlushIntervalMs2, WorkflowServerWritableStream2, prepareReplayPayload2, STREAM_AND_REQUEST_KEYS2;
108688
+ var defaultUlid2, FRAME_HEADER_SIZE2, MAX_FRAME_SIZE2, WorkflowServerReadableStream2, FRAMED_STREAM_MAX_RECONNECTS2, getFramedStreamMaxReconnects2, FRAMED_STREAM_MAX_TOTAL_RECONNECTS2, getFramedStreamMaxTotalReconnects2, FRAMED_STREAM_MAX_STALLS_BELOW_TAIL2, FRAMED_STREAM_MIN_STALL_SESSION_MS2, STREAM_FLUSH_INTERVAL_MS2, getEnvStreamFlushIntervalMs2, WorkflowServerWritableStream2, LOCAL_ABORT_LISTEN_AFTER_STREAM_END_MS2, prepareReplayPayload2, STREAM_AND_REQUEST_KEYS2;
107817
108689
  var init_serialization4 = __esm({
107818
108690
  "../core/dist/serialization.js"() {
107819
108691
  "use strict";
@@ -107829,6 +108701,7 @@ var init_serialization4 = __esm({
107829
108701
  init_private2();
107830
108702
  init_get_world_lazy2();
107831
108703
  init_sealed_box2();
108704
+ init_abort_local2();
107832
108705
  init_abort_stream2();
107833
108706
  init_client2();
107834
108707
  init_compression2();
@@ -108214,6 +109087,7 @@ var init_serialization4 = __esm({
108214
109087
  __name(getWorkflowReducers2, "getWorkflowReducers");
108215
109088
  __name(getStepReducers2, "getStepReducers");
108216
109089
  __name(cancelAbortReaders2, "cancelAbortReaders");
109090
+ LOCAL_ABORT_LISTEN_AFTER_STREAM_END_MS2 = 60 * 60 * 1e3;
108217
109091
  __name(setupAbortStreamReader2, "setupAbortStreamReader");
108218
109092
  __name(tagAbortPair2, "tagAbortPair");
108219
109093
  __name(copyAbortInternals2, "copyAbortInternals");
@@ -108386,7 +109260,7 @@ var version7;
108386
109260
  var init_version5 = __esm({
108387
109261
  "../core/dist/version.js"() {
108388
109262
  "use strict";
108389
- version7 = "5.7.0";
109263
+ version7 = "5.7.2";
108390
109264
  }
108391
109265
  });
108392
109266
 
@@ -108814,7 +109688,7 @@ async function loadWorkflowRunEvents(runId, afterCursor, options) {
108814
109688
  appendUniqueEvents(loadedEvents, response.data, loadedEventIds);
108815
109689
  if (eventLimit) {
108816
109690
  for (let i3 = before; i3 < loadedEvents.length; i3++) {
108817
- if (!isSealedNoopEvent(loadedEvents[i3]))
109691
+ if (!isSealedNoopEvent2(loadedEvents[i3]))
108818
109692
  workflowEventCount++;
108819
109693
  }
108820
109694
  }
@@ -116948,15 +117822,15 @@ var init_run = __esm({
116948
117822
 
116949
117823
  // ../core/dist/runtime/lifecycle-hooks.js
116950
117824
  function getRegistry3() {
116951
- if (!Object.hasOwn(globalThis, REGISTRY_KEY)) {
116952
- Object.defineProperty(globalThis, REGISTRY_KEY, {
117825
+ if (!Object.hasOwn(globalThis, REGISTRY_KEY3)) {
117826
+ Object.defineProperty(globalThis, REGISTRY_KEY3, {
116953
117827
  value: [],
116954
117828
  writable: false,
116955
117829
  enumerable: false,
116956
117830
  configurable: false
116957
117831
  });
116958
117832
  }
116959
- return globalThis[REGISTRY_KEY];
117833
+ return globalThis[REGISTRY_KEY3];
116960
117834
  }
116961
117835
  function dispatch3(runId, workflowName, event, prepare, invoke) {
116962
117836
  let lifecycleSpan;
@@ -117058,7 +117932,7 @@ function dispatchRunFailedHooks(runId, workflowName, error123, encryptionKey, er
117058
117932
  error: new WorkflowRunFailedError2(runId, await hydrateForHandlers(error123, runId, encryptionKey, ops, onHydrationError), { errorCode })
117059
117933
  }), (hooks, params) => hooks.onRunFailed?.(params));
117060
117934
  }
117061
- var REGISTRY_KEY;
117935
+ var REGISTRY_KEY3;
117062
117936
  var init_lifecycle_hooks = __esm({
117063
117937
  "../core/dist/runtime/lifecycle-hooks.js"() {
117064
117938
  "use strict";
@@ -117071,7 +117945,7 @@ var init_lifecycle_hooks = __esm({
117071
117945
  init_types4();
117072
117946
  init_run();
117073
117947
  init_wait_until2();
117074
- REGISTRY_KEY = /* @__PURE__ */ Symbol.for("@workflow/core//lifecycleHooks");
117948
+ REGISTRY_KEY3 = /* @__PURE__ */ Symbol.for("@workflow/core//lifecycleHooks");
117075
117949
  __name(getRegistry3, "getRegistry");
117076
117950
  __name(dispatch3, "dispatch");
117077
117951
  __name(dispatchRunCompletedHooks, "dispatchRunCompletedHooks");
@@ -121246,6 +122120,9 @@ async function getMaxInlineDurationMs(world, invocationStartTime) {
121246
122120
  return (0, import_ms4.default)("2m");
121247
122121
  }
121248
122122
  function getWorkflowSetupErrorCode(err) {
122123
+ if (DynamicWorkflowsNotEnabledError2.is(err)) {
122124
+ return RUN_ERROR_CODES2.USER_ERROR;
122125
+ }
121249
122126
  if (WorkflowRuntimeError2.is(err)) {
121250
122127
  return RUN_ERROR_CODES2.RUNTIME_ERROR;
121251
122128
  }
@@ -121304,7 +122181,7 @@ async function resolveWorkflowCodeForRun(staticWorkflowCode, workflowRun, getEnc
121304
122181
  return { code: staticWorkflowCode };
121305
122182
  const runLabel = `Workflow run "${workflowRun.runId}" is a dynamic workflow run (source ${dynamicWorkflow.sourceHash.slice(0, 12)})`;
121306
122183
  if (!isDynamicWorkflowsEnabled2()) {
121307
- throw new WorkflowRuntimeError2(`${runLabel}, but this deployment has not enabled dynamic workflows, so its stored code was not executed. Set ${DYNAMIC_WORKFLOWS_ENV2}=1 on the deployment to enable them.`);
122184
+ throw new DynamicWorkflowsNotEnabledError2(`${runLabel}, but dynamic workflows are not enabled for this project on the deployment that received it, so its stored code was not executed.`);
121308
122185
  }
121309
122186
  const expectedWorkflowName = dynamicWorkflowName2(dynamicWorkflow);
121310
122187
  if (workflowRun.workflowName !== expectedWorkflowName) {
@@ -123081,6 +123958,7 @@ async function startSuspensionHookWrites({ suspension, world, run: run3, runId,
123081
123958
  });
123082
123959
  try {
123083
123960
  const streamName = getAbortStreamIdFromToken(queueItem.token);
123961
+ publishLocalAbort2(runId, streamName, abortPayload);
123084
123962
  await world.streams.write(runId, streamName, frameAbortStreamPayload2(abortPayload));
123085
123963
  await world.streams.close(runId, streamName);
123086
123964
  } catch {
@@ -123136,6 +124014,7 @@ var init_suspension_hooks = __esm({
123136
124014
  init_dist10();
123137
124015
  init_encryption5();
123138
124016
  init_logger2();
124017
+ init_abort_local2();
123139
124018
  init_abort_stream2();
123140
124019
  init_hardened2();
123141
124020
  init_serialization4();
@@ -124051,6 +124930,7 @@ async function dispatchPendingOps(params) {
124051
124930
  }
124052
124931
  if (hook.token.startsWith("abrt_") && abortPayload) {
124053
124932
  const streamName = `strm_${hook.token.slice("abrt_".length)}_system_abort`;
124933
+ publishLocalAbort2(runId, streamName, abortPayload);
124054
124934
  try {
124055
124935
  await world.streams.write(runId, streamName, frameAbortStreamPayload2(abortPayload));
124056
124936
  await world.streams.close(runId, streamName);
@@ -124377,6 +125257,7 @@ var init_quickjs_pending_ops = __esm({
124377
125257
  init_dist11();
124378
125258
  init_dist10();
124379
125259
  init_logger2();
125260
+ init_abort_local2();
124380
125261
  init_abort_stream2();
124381
125262
  init_encryption6();
124382
125263
  init_serialization4();
@@ -128023,7 +128904,7 @@ function createQuickJSSerde(vm, capturedRoot) {
128023
128904
  const signal = ownSignal(value);
128024
128905
  const holder = signal ?? value;
128025
128906
  const streamName = ownSymbolString(value, "WORKFLOW_ABORT_STREAM_NAME") ?? ownSymbolString(holder, "WORKFLOW_ABORT_STREAM_NAME");
128026
- const hookToken = ownSymbolString(value, "WORKFLOW_ABORT_HOOK_TOKEN") ?? ownSymbolString(holder, "WORKFLOW_ABORT_HOOK_TOKEN");
128907
+ const hookToken3 = ownSymbolString(value, "WORKFLOW_ABORT_HOOK_TOKEN") ?? ownSymbolString(holder, "WORKFLOW_ABORT_HOOK_TOKEN");
128027
128908
  if (!streamName) {
128028
128909
  signal?.dispose();
128029
128910
  throw new Error("AbortController/AbortSignal stream name is not set");
@@ -128034,7 +128915,7 @@ function createQuickJSSerde(vm, capturedRoot) {
128034
128915
  signal.dispose();
128035
128916
  return {
128036
128917
  streamName,
128037
- hookToken,
128918
+ hookToken: hookToken3,
128038
128919
  aborted: aborted3,
128039
128920
  reason: aborted3 ? reason : void 0
128040
128921
  };
@@ -128602,12 +129483,12 @@ function createQuickJSSerde(vm, capturedRoot) {
128602
129483
  }
128603
129484
  try {
128604
129485
  const streamName = own3(value, "streamName") ?? vm.undefined;
128605
- const hookToken = own3(value, "hookToken") ?? vm.undefined;
128606
- const signal = vm.construct(cls, streamName, hookToken);
129486
+ const hookToken3 = own3(value, "hookToken") ?? vm.undefined;
129487
+ const signal = vm.construct(cls, streamName, hookToken3);
128607
129488
  if (streamName !== vm.undefined)
128608
129489
  streamName.dispose();
128609
- if (hookToken !== vm.undefined)
128610
- hookToken.dispose();
129490
+ if (hookToken3 !== vm.undefined)
129491
+ hookToken3.dispose();
128611
129492
  const aborted3 = own3(value, "aborted");
128612
129493
  if (aborted3?.toBoolean()) {
128613
129494
  const setAborted = chained(signal, "_setAborted");
@@ -128632,10 +129513,10 @@ function createQuickJSSerde(vm, capturedRoot) {
128632
129513
  define2(controller, sym("WORKFLOW_ABORT_STREAM_NAME"), streamName);
128633
129514
  if (streamName !== vm.undefined)
128634
129515
  streamName.dispose();
128635
- const hookToken = own3(value, "hookToken") ?? vm.undefined;
128636
- define2(controller, sym("WORKFLOW_ABORT_HOOK_TOKEN"), hookToken);
128637
- if (hookToken !== vm.undefined)
128638
- hookToken.dispose();
129516
+ const hookToken3 = own3(value, "hookToken") ?? vm.undefined;
129517
+ define2(controller, sym("WORKFLOW_ABORT_HOOK_TOKEN"), hookToken3);
129518
+ if (hookToken3 !== vm.undefined)
129519
+ hookToken3.dispose();
128639
129520
  const signal = reviveAbortSignal3(value);
128640
129521
  define2(controller, "signal", signal);
128641
129522
  signal.dispose();
@@ -129230,18 +130111,18 @@ function createQuickJSSerde(vm, capturedRoot) {
129230
130111
  function lookupRegisteredClass(classId) {
129231
130112
  if (classId === void 0)
129232
130113
  return void 0;
129233
- const registry3 = own3(vm.global, sym("workflow-class-registry"));
129234
- if (!registry3 || registry3.isUndefined) {
129235
- registry3?.dispose();
130114
+ const registry5 = own3(vm.global, sym("workflow-class-registry"));
130115
+ if (!registry5 || registry5.isUndefined) {
130116
+ registry5?.dispose();
129236
130117
  return void 0;
129237
130118
  }
129238
130119
  try {
129239
- const getMethod = chained(registry3, "get");
130120
+ const getMethod = chained(registry5, "get");
129240
130121
  if (!getMethod)
129241
130122
  return void 0;
129242
130123
  try {
129243
130124
  const key = vm.newString(classId);
129244
- const cls = call(getMethod, registry3, key);
130125
+ const cls = call(getMethod, registry5, key);
129245
130126
  key.dispose();
129246
130127
  if (cls.isUndefined || cls.typeof !== "function") {
129247
130128
  cls.dispose();
@@ -129252,7 +130133,7 @@ function createQuickJSSerde(vm, capturedRoot) {
129252
130133
  getMethod.dispose();
129253
130134
  }
129254
130135
  } finally {
129255
- registry3.dispose();
130136
+ registry5.dispose();
129256
130137
  }
129257
130138
  }
129258
130139
  __name(lookupRegisteredClass, "lookupRegisteredClass");
@@ -130169,7 +131050,7 @@ async function processEvents(vm, serde, events, advanceClock, getLastUlid, inert
130169
131050
  let resolved = false;
130170
131051
  for (let index = 0; index < events.length; index++) {
130171
131052
  const event = events[index];
130172
- if (isSealedNoopEvent(event))
131053
+ if (isSealedNoopEvent2(event))
130173
131054
  continue;
130174
131055
  advanceClock(+event.createdAt);
130175
131056
  const cid = event.correlationId;
@@ -130601,7 +131482,7 @@ function beginTerminalInertBatch(vm, events, lastUlid) {
130601
131482
  for (let index = 0; index < events.length; index++) {
130602
131483
  const event = events[index];
130603
131484
  const cid = event.correlationId;
130604
- if (!cid || isSealedNoopEvent(event))
131485
+ if (!cid || isSealedNoopEvent2(event))
130605
131486
  continue;
130606
131487
  cids.add(cid);
130607
131488
  if (firstTerminalIndex.has(cid))
@@ -133984,15 +134865,73 @@ var init_in_band_writer = __esm({
133984
134865
  * The slot the next write would take if no other writer appends first:
133985
134866
  * one past every position this writer knows is allocated, including the
133986
134867
  * writes still queued in it. Run-ahead places a speculative event there.
134868
+ *
134869
+ * Each position is counted once. The write being sent is in
134870
+ * `pendingPositions` until it settles, while `knownMaxSlot` can already
134871
+ * cover its positions: the live feed echoes a write before its answer
134872
+ * arrives ({@link observeEvent}), and the answer raises `knownMaxSlot` a
134873
+ * few microtasks before the write settles. Those positions are taken off
134874
+ * ({@link sending}), or the prediction would run past the slot the next
134875
+ * write takes, and a speculative event placed there shares its id with a
134876
+ * later event.
133987
134877
  */
133988
134878
  predictNextSlot() {
133989
- return this.knownMaxSlot + this.pendingPositions + 1;
134879
+ return this.knownMaxSlot + this.pendingPositions - (this.sending?.covered ?? 0) + 1;
133990
134880
  }
133991
- /** A position another writer took, seen in a load, a report or the feed. */
134881
+ /** A position another writer took, seen in a load or a report. */
133992
134882
  observeSlot(slot) {
133993
134883
  if (slot > this.knownMaxSlot)
133994
134884
  this.knownMaxSlot = slot;
133995
134885
  }
134886
+ /**
134887
+ * An event seen outside this writer's own answers (the live feed, an
134888
+ * incremental load): its position is allocated. When it is an event of the
134889
+ * write being sent (the feed's echo, ahead of the answer), that write's
134890
+ * position is now covered by `knownMaxSlot` and is not counted again by
134891
+ * {@link predictNextSlot}.
134892
+ */
134893
+ observeEvent(event) {
134894
+ const slot = eventIdToSlot2(event.eventId);
134895
+ if (slot === null || slot <= this.knownMaxSlot)
134896
+ return;
134897
+ this.knownMaxSlot = slot;
134898
+ const sending = this.sending;
134899
+ if (!sending || sending.covered >= sending.positions)
134900
+ return;
134901
+ const at3 = sending.unechoed.findIndex((sent) => sent.eventType === event.eventType && sent.correlationId === event.correlationId);
134902
+ if (at3 === -1)
134903
+ return;
134904
+ sending.unechoed.splice(at3, 1);
134905
+ sending.covered++;
134906
+ }
134907
+ /**
134908
+ * The write being sent: how many positions it asks for, how many of them
134909
+ * `knownMaxSlot` already covers, and its events the live feed has not
134910
+ * echoed yet. Cleared where the write leaves `pendingPositions`.
134911
+ */
134912
+ sending;
134913
+ beginSend(events) {
134914
+ this.sending = {
134915
+ positions: events.length,
134916
+ covered: 0,
134917
+ unechoed: events.map((event) => ({
134918
+ eventType: event.eventType,
134919
+ correlationId: event.correlationId
134920
+ }))
134921
+ };
134922
+ }
134923
+ /**
134924
+ * The write being sent was answered, or failed: whatever it allocated is
134925
+ * in `knownMaxSlot` (the caller noted the answer's slots just before), so
134926
+ * none of its positions is predicted on top of that.
134927
+ */
134928
+ answerSend() {
134929
+ const sending = this.sending;
134930
+ if (!sending)
134931
+ return;
134932
+ sending.covered = sending.positions;
134933
+ sending.unechoed = [];
134934
+ }
133996
134935
  /**
133997
134936
  * Stops the writer for good with `error`, as a failed write would: every
133998
134937
  * later write and {@link assertActive} throw it.
@@ -134034,13 +134973,16 @@ var init_in_band_writer = __esm({
134034
134973
  let result2;
134035
134974
  try {
134036
134975
  const position5 = this.sendPosition(params?.eventCount);
134976
+ const fence = this.fenceParams();
134977
+ this.beginSend([data3]);
134037
134978
  const written = await this.world.events.create(this.runId, data3, {
134038
134979
  ...params,
134039
134980
  ...position5,
134040
- ...this.fenceParams()
134981
+ ...fence
134041
134982
  });
134042
134983
  this.noteComplete(position5, written, [written.event]);
134043
134984
  const inferred = this.allocatedBy([written.event], knownAtSend);
134985
+ this.answerSend();
134044
134986
  const allocated = written.allocated ?? inferred;
134045
134987
  this.advance(allocated);
134046
134988
  result2 = written.event ? {
@@ -134048,6 +134990,7 @@ var init_in_band_writer = __esm({
134048
134990
  event: withWrittenEventData(written.event, data3, allocated > 0)
134049
134991
  } : written;
134050
134992
  } catch (error123) {
134993
+ this.answerSend();
134051
134994
  throw this.stop(error123, required3);
134052
134995
  }
134053
134996
  this.accepted(result2.event);
@@ -134157,6 +135100,7 @@ var init_in_band_writer = __esm({
134157
135100
  const knownAtSend = this.knownMaxSlot;
134158
135101
  const position5 = this.sendPosition(first.params.eventCount);
134159
135102
  let result2;
135103
+ this.beginSend(events.map(({ event }) => event));
134160
135104
  try {
134161
135105
  result2 = await this.world.events.createBatch.call(this.world.events, this.runId, events, {
134162
135106
  ...position5,
@@ -134165,6 +135109,7 @@ var init_in_band_writer = __esm({
134165
135109
  ...this.fenceParams()
134166
135110
  });
134167
135111
  } catch (error123) {
135112
+ this.answerSend();
134168
135113
  const stopped = this.stop(error123, true);
134169
135114
  for (const write of group)
134170
135115
  write.reject(stopped);
@@ -134177,6 +135122,7 @@ var init_in_band_writer = __esm({
134177
135122
  if (item.error === void 0)
134178
135123
  this.noteSlot(item.event.eventId);
134179
135124
  }
135125
+ this.answerSend();
134180
135126
  this.advance(result2.allocated ?? events.length - replayed);
134181
135127
  let offset3 = 0;
134182
135128
  let failed;
@@ -134226,6 +135172,7 @@ var init_in_band_writer = __esm({
134226
135172
  }
134227
135173
  } finally {
134228
135174
  this.pendingPositions -= total;
135175
+ this.sending = void 0;
134229
135176
  }
134230
135177
  }
134231
135178
  /**
@@ -134284,6 +135231,7 @@ var init_in_band_writer = __esm({
134284
135231
  const knownAtSend = this.knownMaxSlot;
134285
135232
  const position5 = this.sendPosition(params?.eventCount);
134286
135233
  try {
135234
+ this.beginSend(events.map(({ event }) => event));
134287
135235
  const result2 = await createBatch.call(this.world.events, this.runId, events, {
134288
135236
  ...params,
134289
135237
  ...position5,
@@ -134296,6 +135244,7 @@ var init_in_band_writer = __esm({
134296
135244
  if (item.error === void 0)
134297
135245
  this.noteSlot(item.event.eventId);
134298
135246
  }
135247
+ this.answerSend();
134299
135248
  this.advance(result2.allocated ?? events.length - replayed);
134300
135249
  const answered = {
134301
135250
  ...result2,
@@ -134320,6 +135269,7 @@ var init_in_band_writer = __esm({
134320
135269
  }
134321
135270
  return answered;
134322
135271
  } catch (error123) {
135272
+ this.answerSend();
134323
135273
  throw this.stop(error123, required3);
134324
135274
  }
134325
135275
  });
@@ -134408,6 +135358,8 @@ var init_in_band_writer = __esm({
134408
135358
  this.pendingPositions += positions;
134409
135359
  const settle3 = /* @__PURE__ */ __name(() => {
134410
135360
  this.pendingPositions -= positions;
135361
+ if (positions > 0)
135362
+ this.sending = void 0;
134411
135363
  }, "settle");
134412
135364
  const guarded = /* @__PURE__ */ __name(async () => {
134413
135365
  try {
@@ -135074,6 +136026,66 @@ var init_run_ahead = __esm({
135074
136026
  }
135075
136027
  });
135076
136028
 
136029
+ // ../core/dist/runtime/spec9/speculative-placement.js
136030
+ function isSameWrite(speculative, committed) {
136031
+ return speculative.eventType === committed.eventType && speculative.correlationId === committed.correlationId;
136032
+ }
136033
+ function speculativeSlotFor(input3) {
136034
+ let floor = input3.heldMaxSlot ?? 0;
136035
+ for (const slot of input3.unconfirmedSlots) {
136036
+ if (slot > floor)
136037
+ floor = slot;
136038
+ }
136039
+ return Math.max(input3.predicted, floor + 1);
136040
+ }
136041
+ function displacesSpeculation(event, speculativeAt) {
136042
+ const speculative = speculativeAt(event.eventId);
136043
+ return speculative !== void 0 && !isSameWrite(speculative, event);
136044
+ }
136045
+ function foldReadEvents(events, speculativeAt) {
136046
+ const fold = [];
136047
+ let displaced = false;
136048
+ for (const event of events) {
136049
+ const speculative = speculativeAt(event.eventId);
136050
+ if (speculative !== void 0) {
136051
+ if (!isSameWrite(speculative, event))
136052
+ displaced = true;
136053
+ } else if (!displaced) {
136054
+ fold.push(event);
136055
+ }
136056
+ }
136057
+ return { fold, displaced, complete: fold.length === events.length };
136058
+ }
136059
+ function settledOutcomeFold(input3) {
136060
+ if (!input3.writtenAhead)
136061
+ return "fold";
136062
+ if (!input3.unconfirmed)
136063
+ return "committed";
136064
+ return input3.slotHeld ? "displaced" : "fold";
136065
+ }
136066
+ function committedBelowPrediction(aliases) {
136067
+ for (const [predicted, committed] of aliases) {
136068
+ const predictedSlot = eventIdToSlot2(predicted);
136069
+ const committedSlot = eventIdToSlot2(committed);
136070
+ if (predictedSlot !== null && committedSlot !== null && committedSlot < predictedSlot) {
136071
+ return true;
136072
+ }
136073
+ }
136074
+ return false;
136075
+ }
136076
+ var init_speculative_placement = __esm({
136077
+ "../core/dist/runtime/spec9/speculative-placement.js"() {
136078
+ "use strict";
136079
+ init_dist10();
136080
+ __name(isSameWrite, "isSameWrite");
136081
+ __name(speculativeSlotFor, "speculativeSlotFor");
136082
+ __name(displacesSpeculation, "displacesSpeculation");
136083
+ __name(foldReadEvents, "foldReadEvents");
136084
+ __name(settledOutcomeFold, "settledOutcomeFold");
136085
+ __name(committedBelowPrediction, "committedBelowPrediction");
136086
+ }
136087
+ });
136088
+
135077
136089
  // ../core/dist/runtime/spec9/step-executor.js
135078
136090
  import { types as types13 } from "node:util";
135079
136091
  function mayRunBeforeItsStart(stepName) {
@@ -136939,7 +137951,7 @@ async function runQuickJSDelivery(params, afterTerminal) {
136939
137951
  return written;
136940
137952
  } : void 0;
136941
137953
  let restoredEventCount = existingSnapshot?.metadata.eventCount ?? 0;
136942
- const workflowEventCount = events.filter((event) => !isSealedNoopEvent(event)).length;
137954
+ const workflowEventCount = events.filter((event) => !isSealedNoopEvent2(event)).length;
136943
137955
  if (maxEventsLimit !== void 0 && restoredEventCount + workflowEventCount >= maxEventsLimit) {
136944
137956
  throw new MaxEventsExceededError(restoredEventCount + workflowEventCount, maxEventsLimit);
136945
137957
  }
@@ -137092,7 +138104,7 @@ async function runQuickJSDelivery(params, afterTerminal) {
137092
138104
  if (!event.eventId)
137093
138105
  return;
137094
138106
  seenEventIds.add(event.eventId);
137095
- if (isSealedNoopEvent(event))
138107
+ if (isSealedNoopEvent2(event))
137096
138108
  seenNoopIds.add(event.eventId);
137097
138109
  }, "noteSeenEvent");
137098
138110
  for (const e of events) {
@@ -138748,7 +139760,7 @@ async function runSpec9Delivery(delivery) {
138748
139760
  return continuation.handoff && result2 === void 0 ? { timeoutSeconds: 0 } : result2;
138749
139761
  }
138750
139762
  function countWorkflowEvents(events) {
138751
- return events.reduce((n, e) => isSealedNoopEvent(e) ? n : n + 1, 0);
139763
+ return events.reduce((n, e) => isSealedNoopEvent2(e) ? n : n + 1, 0);
138752
139764
  }
138753
139765
  async function runDelivery2(delivery, continuation) {
138754
139766
  const { workflowCode: workflowCode2, namespace, metadata, world, span, runLogger, workflowName, requestId, nextTraceCarrier, replayBudget, prefetchedRun, runSpecVersion } = delivery;
@@ -138960,6 +139972,27 @@ async function runDelivery2(delivery, continuation) {
138960
139972
  const repairWrites = [];
138961
139973
  const speculativeSlots = /* @__PURE__ */ new Set();
138962
139974
  let runAheadRepair = false;
139975
+ const everSpeculative = /* @__PURE__ */ new WeakSet();
139976
+ const speculativeEventAt = /* @__PURE__ */ __name((eventId) => {
139977
+ for (const event of speculativeEvents) {
139978
+ if (event.eventId === eventId)
139979
+ return event;
139980
+ }
139981
+ return void 0;
139982
+ }, "speculativeEventAt");
139983
+ let noteDisplacedSpeculation = /* @__PURE__ */ __name((_cause) => {
139984
+ runAheadRepair = true;
139985
+ }, "noteDisplacedSpeculation");
139986
+ const foldReadIntoLog = /* @__PURE__ */ __name((events, cause) => {
139987
+ assert9(log, "The event log is loaded to fold read events");
139988
+ const { fold, displaced, complete } = foldReadEvents(events, speculativeEventAt);
139989
+ if (displaced)
139990
+ noteDisplacedSpeculation(cause);
139991
+ for (const event of fold)
139992
+ prepareReplayEvent(event);
139993
+ indexOf(log.events).merge(fold);
139994
+ return complete;
139995
+ }, "foldReadIntoLog");
138963
139996
  let logBehind = false;
138964
139997
  const ownSlots = /* @__PURE__ */ new Set();
138965
139998
  let passConsumedSlot = 0;
@@ -138983,6 +140016,11 @@ async function runDelivery2(delivery, continuation) {
138983
140016
  }
138984
140017
  const own3 = result2.event;
138985
140018
  const report = (result2.events ?? []).filter((event) => event.eventId !== own3.eventId);
140019
+ if ([own3, ...report].some((event) => displacesSpeculation(event, speculativeEventAt))) {
140020
+ noteDisplacedSpeculation("response");
140021
+ repairWrites.push(result2);
140022
+ return;
140023
+ }
138986
140024
  const below = Math.max(indexOf(log.events).maxSlot() ?? 0, maxEventSlot(report) ?? 0);
138987
140025
  const ownSlot = eventIdToSlot2(own3.eventId);
138988
140026
  if (ownSlot !== null && ownSlot > below + 1) {
@@ -139034,6 +140072,7 @@ async function runDelivery2(delivery, continuation) {
139034
140072
  }
139035
140073
  logBehind = false;
139036
140074
  log = { events: loaded.events, cursor: loaded.cursor };
140075
+ writer.observeSlot(indexOf(log.events).maxSlot() ?? 0);
139037
140076
  return log;
139038
140077
  }, "fullLoad");
139039
140078
  const loadAfter = /* @__PURE__ */ __name(async () => {
@@ -139050,11 +140089,11 @@ async function runDelivery2(delivery, continuation) {
139050
140089
  label: "Incremental event log read",
139051
140090
  runId
139052
140091
  });
139053
- for (const event of page.events) {
139054
- prepareReplayEvent(event);
140092
+ for (const event of page.events)
140093
+ writer.observeEvent(event);
140094
+ if (foldReadIntoLog(page.events, "read")) {
140095
+ log.cursor = page.cursor ?? log.cursor;
139055
140096
  }
139056
- indexOf(log.events).merge(page.events);
139057
- log.cursor = page.cursor ?? log.cursor;
139058
140097
  return log;
139059
140098
  }, "loadAfter");
139060
140099
  let workflowRun;
@@ -139647,7 +140686,7 @@ async function runDelivery2(delivery, continuation) {
139647
140686
  }
139648
140687
  assert9(run3, "Workflow run must be loaded before replay");
139649
140688
  assert9(log, "The event log is loaded before replay");
139650
- invocationStartedClean = log.events.every((e) => e.eventType === "run_created" || e.eventType === "run_started" || e.eventType === "attr_set" || isSealedNoopEvent(e));
140689
+ invocationStartedClean = log.events.every((e) => e.eventType === "run_created" || e.eventType === "run_started" || e.eventType === "attr_set" || isSealedNoopEvent2(e));
139651
140690
  const runCreated = log.events.find(isRunCreationEvent2);
139652
140691
  const createdInput = runCreated && "eventData" in runCreated ? runCreated.eventData?.input : void 0;
139653
140692
  let runInputValue;
@@ -139816,6 +140855,7 @@ async function runDelivery2(delivery, continuation) {
139816
140855
  return log?.events.some((e) => e.eventId === event.eventId) ?? false;
139817
140856
  }, "isOwnEvent");
139818
140857
  const settledInline = [];
140858
+ let awaitedOutcomeWrites = 0;
139819
140859
  const creationsInFlight = /* @__PURE__ */ new Set();
139820
140860
  const creationBatchesQueuing = /* @__PURE__ */ new Set();
139821
140861
  let trailingCreationFailure;
@@ -139842,30 +140882,23 @@ async function runDelivery2(delivery, continuation) {
139842
140882
  progressWaiter = void 0;
139843
140883
  waiter?.();
139844
140884
  }, "notifyProgress");
140885
+ const flushFeedEvents = /* @__PURE__ */ __name(() => {
140886
+ if (pendingFeedEvents.length === 0)
140887
+ return;
140888
+ const events = pendingFeedEvents.splice(0);
140889
+ for (const event of events) {
140890
+ writer.observeEvent(event);
140891
+ checkRunAheadHazard(event, "live feed");
140892
+ }
140893
+ if (!runAheadRepair)
140894
+ foldReadIntoLog(events, "feed");
140895
+ }, "flushFeedEvents");
139845
140896
  const flushPending = /* @__PURE__ */ __name(() => {
139846
140897
  if (!log)
139847
140898
  return;
139848
140899
  if (turboStartLanded)
139849
140900
  absorbWrite(turboStartLanded);
139850
- if (pendingFeedEvents.length > 0) {
139851
- const events = pendingFeedEvents.splice(0).filter((event) => {
139852
- const slot = eventIdToSlot2(event.eventId);
139853
- if (slot !== null)
139854
- writer.observeSlot(slot);
139855
- checkRunAheadHazard(event, "live feed");
139856
- if (slot !== null && speculativeSlots.has(slot)) {
139857
- const own3 = speculationsBySlot.get(slot);
139858
- if (own3 && (own3.event.eventType !== event.eventType || own3.event.correlationId !== event.correlationId)) {
139859
- markRunAheadRepair("feed");
139860
- }
139861
- return false;
139862
- }
139863
- return !runAheadRepair;
139864
- });
139865
- for (const event of events)
139866
- prepareReplayEvent(event);
139867
- indexOf(log.events).merge(events);
139868
- }
140901
+ flushFeedEvents();
139869
140902
  if (pendingAbsorbs.length > 0) {
139870
140903
  const results = pendingAbsorbs.splice(0);
139871
140904
  results.sort((a, b) => (eventIdToSlot2(a.event?.eventId ?? "") ?? 0) - (eventIdToSlot2(b.event?.eventId ?? "") ?? 0));
@@ -139896,7 +140929,11 @@ async function runDelivery2(delivery, continuation) {
139896
140929
  if (liveFeed || !log)
139897
140930
  return;
139898
140931
  liveFeed = new LiveLogFeed(world, runId, {
139899
- afterSlot: indexOf(log.events).maxSlot() ?? 0,
140932
+ // From the highest confirmed position: a speculative
140933
+ // event sits at a predicted slot, and another
140934
+ // writer's event that takes that slot must still be
140935
+ // offered.
140936
+ afterSlot: slotSnapshot().eventCount ?? 0,
139900
140937
  cursor: log.cursor,
139901
140938
  pollIntervalMs: getOrchestratorPollIntervalMs(),
139902
140939
  feedPollIntervalMs: getOrchestratorFeedPollIntervalMs(),
@@ -139978,7 +141015,13 @@ async function runDelivery2(delivery, continuation) {
139978
141015
  * Counted once per repair, by what found it first.
139979
141016
  */
139980
141017
  repairs: 0,
139981
- repairsByCause: { feed: 0, outcome: 0, creation: 0 },
141018
+ repairsByCause: {
141019
+ feed: 0,
141020
+ outcome: 0,
141021
+ creation: 0,
141022
+ response: 0,
141023
+ read: 0
141024
+ },
139982
141025
  /** Wall time spent repairing, in milliseconds. */
139983
141026
  repairMs: 0,
139984
141027
  /** Repairs whose retained session survived them. */
@@ -140001,6 +141044,12 @@ async function runDelivery2(delivery, continuation) {
140001
141044
  runAheadStats.repairsByCause[cause]++;
140002
141045
  recordRunAheadSpan();
140003
141046
  }, "markRunAheadRepair");
141047
+ noteDisplacedSpeculation = markRunAheadRepair;
141048
+ const nextSpeculativeSlot = /* @__PURE__ */ __name(() => speculativeSlotFor({
141049
+ predicted: writer.predictNextSlot(),
141050
+ heldMaxSlot: log ? indexOf(log.events).maxSlot() : void 0,
141051
+ unconfirmedSlots: speculativeSlots
141052
+ }), "nextSpeculativeSlot");
140004
141053
  const outOfBandBoundaries = {
140005
141054
  inert: 0,
140006
141055
  observedHook: 0,
@@ -140029,6 +141078,8 @@ async function runDelivery2(delivery, continuation) {
140029
141078
  "workflow.run_ahead.repairs.feed": runAheadStats.repairsByCause.feed,
140030
141079
  "workflow.run_ahead.repairs.outcome": runAheadStats.repairsByCause.outcome,
140031
141080
  "workflow.run_ahead.repairs.creation": runAheadStats.repairsByCause.creation,
141081
+ "workflow.run_ahead.repairs.response": runAheadStats.repairsByCause.response,
141082
+ "workflow.run_ahead.repairs.read": runAheadStats.repairsByCause.read,
140032
141083
  "workflow.run_ahead.repair_ms": runAheadStats.repairMs,
140033
141084
  "workflow.run_ahead.repairs_retained": runAheadStats.repairsRetained,
140034
141085
  "workflow.run_ahead.repair_reads": runAheadStats.repairReads,
@@ -140107,6 +141158,15 @@ async function runDelivery2(delivery, continuation) {
140107
141158
  return runAheadRepair ? "repair" : "clean";
140108
141159
  }
140109
141160
  __name(drainRunAhead, "drainRunAhead");
141161
+ async function repairRunAheadIfDue() {
141162
+ if (!runAheadRepair)
141163
+ return;
141164
+ await settleRunAhead();
141165
+ if (runAheadFailure !== void 0)
141166
+ throw runAheadFailure;
141167
+ await repairRunAhead();
141168
+ }
141169
+ __name(repairRunAheadIfDue, "repairRunAheadIfDue");
140110
141170
  async function repairRunAhead() {
140111
141171
  const startedAt = Date.now();
140112
141172
  await writer.idle();
@@ -140147,6 +141207,8 @@ async function runDelivery2(delivery, continuation) {
140147
141207
  runAheadStats.repairReads++;
140148
141208
  await loadAfter();
140149
141209
  }
141210
+ if (committedBelowPrediction(repairAliases))
141211
+ session = null;
140150
141212
  if (session) {
140151
141213
  const sensitive = new Set(runAheadSensitiveHookIds);
140152
141214
  pendingRebase = {
@@ -140168,7 +141230,7 @@ async function runDelivery2(delivery, continuation) {
140168
141230
  __name(repairRunAhead, "repairRunAhead");
140169
141231
  function writeOutcomeAhead(data3, params, context2) {
140170
141232
  const occurredAt = /* @__PURE__ */ new Date();
140171
- const slot = writer.predictNextSlot();
141233
+ const slot = nextSpeculativeSlot();
140172
141234
  const event = {
140173
141235
  ...data3,
140174
141236
  runId,
@@ -140177,6 +141239,7 @@ async function runDelivery2(delivery, continuation) {
140177
141239
  };
140178
141240
  speculativeSlots.add(slot);
140179
141241
  speculativeEvents.add(event);
141242
+ everSpeculative.add(event);
140180
141243
  const releaseContext = noteRunAheadContext(context2);
140181
141244
  const commit = writer.createAhead(data3, {
140182
141245
  ...params,
@@ -140225,7 +141288,7 @@ async function runDelivery2(delivery, continuation) {
140225
141288
  function writeCreationAhead(events, context2) {
140226
141289
  assert9(log, "The event log is loaded to run ahead");
140227
141290
  const occurredAt = /* @__PURE__ */ new Date();
140228
- const first = writer.predictNextSlot();
141291
+ const first = nextSpeculativeSlot();
140229
141292
  const speculative = events.map((data3, index) => ({
140230
141293
  ...data3,
140231
141294
  runId,
@@ -140313,6 +141376,7 @@ async function runDelivery2(delivery, continuation) {
140313
141376
  speculative.forEach((event, index) => {
140314
141377
  speculativeSlots.add(first + index);
140315
141378
  speculativeEvents.add(event);
141379
+ everSpeculative.add(event);
140316
141380
  speculationsBySlot.set(first + index, {
140317
141381
  event,
140318
141382
  settled: settled3
@@ -140450,16 +141514,13 @@ async function runDelivery2(delivery, continuation) {
140450
141514
  }
140451
141515
  let replayStart = 0;
140452
141516
  try {
140453
- if (runAheadRepair) {
140454
- await settleRunAhead();
140455
- if (runAheadFailure !== void 0) {
140456
- throw runAheadFailure;
140457
- }
140458
- await repairRunAhead();
140459
- }
141517
+ await repairRunAheadIfDue();
140460
141518
  flushPending();
140461
- if (logBehind)
141519
+ await repairRunAheadIfDue();
141520
+ if (logBehind) {
140462
141521
  await loadAfter();
141522
+ await repairRunAheadIfDue();
141523
+ }
140463
141524
  assert9(log, "The event log is loaded in the loop");
140464
141525
  if (hasRecordedTerminalRunEvent(log.events, runId)) {
140465
141526
  recordTerminalRun(world, runId);
@@ -140492,12 +141553,13 @@ async function runDelivery2(delivery, continuation) {
140492
141553
  assert9(log, "The event log is loaded in the loop");
140493
141554
  if (due.length > 0)
140494
141555
  await armTimers(log.events, "other-chains");
140495
- if (speculationsBySlot.size > 0 && indexOf(log.events).slotGap() !== void 0) {
141556
+ if (speculationsBySlot.size > 0 && (awaitedOutcomeWrites > 0 || indexOf(log.events).slotGap() !== void 0)) {
140496
141557
  if (await drainRunAhead() === "repair") {
140497
141558
  await repairRunAhead();
140498
141559
  }
140499
141560
  await writer.idle();
140500
141561
  flushPending();
141562
+ await repairRunAheadIfDue();
140501
141563
  }
140502
141564
  if (indexOf(log.events).slotGap() !== void 0) {
140503
141565
  const settled3 = await settleEventSlotGap(runId, { events: log.events, cursor: log.cursor }, { specVersion: SPEC_VERSION_SINGLE_ORCHESTRATOR2 });
@@ -141136,11 +142198,17 @@ async function runDelivery2(delivery, continuation) {
141136
142198
  return writeOutcomeAhead(data3, params, runAhead);
141137
142199
  }
141138
142200
  }
141139
- const result2 = await writer.create(withRetryCreator(data3, creatorMessageId), {
141140
- ...params,
141141
- ...slotSnapshot(),
141142
- resolveData: REPLAY_RESOLVE_DATA
141143
- });
142201
+ awaitedOutcomeWrites++;
142202
+ let result2;
142203
+ try {
142204
+ result2 = await writer.create(withRetryCreator(data3, creatorMessageId), {
142205
+ ...params,
142206
+ ...slotSnapshot(),
142207
+ resolveData: REPLAY_RESOLVE_DATA
142208
+ });
142209
+ } finally {
142210
+ awaitedOutcomeWrites--;
142211
+ }
141144
142212
  pendingAbsorbs.push(result2);
141145
142213
  return result2;
141146
142214
  }, "createEvent"),
@@ -141270,8 +142338,18 @@ async function runDelivery2(delivery, continuation) {
141270
142338
  pendingStreamOps = true;
141271
142339
  }
141272
142340
  assert9(log, "The event log is loaded after inline steps");
142341
+ const outcomeEvent = result2.result.event;
142342
+ const outcomeFold = settledOutcomeFold({
142343
+ writtenAhead: outcomeEvent !== void 0 && everSpeculative.has(outcomeEvent),
142344
+ unconfirmed: outcomeEvent !== void 0 && speculativeEvents.has(outcomeEvent),
142345
+ slotHeld: outcomeEvent !== void 0 && indexOf(log.events).has(outcomeEvent.eventId)
142346
+ });
141273
142347
  if (runAheadRepair) {
141274
142348
  reload = true;
142349
+ } else if (outcomeFold === "committed") {
142350
+ } else if (outcomeFold === "displaced") {
142351
+ markRunAheadRepair("outcome");
142352
+ reload = true;
141275
142353
  } else if (consumeOwnResolvingWrite(indexOf(log.events), preparedResult(result2.result)).type === "reload") {
141276
142354
  reload = true;
141277
142355
  }
@@ -141651,6 +142729,7 @@ var init_delivery2 = __esm({
141651
142729
  init_log_state();
141652
142730
  init_read_deadline();
141653
142731
  init_run_ahead();
142732
+ init_speculative_placement();
141654
142733
  init_step_executor2();
141655
142734
  init_step_handler();
141656
142735
  init_step_message();
@@ -142349,6 +143428,10 @@ var START_HOOK_ADMISSION_REJECTED;
142349
143428
  var START_HOOK_ADMISSION_DISABLED;
142350
143429
  var START_HOOK_CANDIDATE_CANCELLED;
142351
143430
  var WorkflowStartError;
143431
+ var DYNAMIC_WORKFLOWS_ENV_VAR;
143432
+ var DYNAMIC_WORKFLOWS_DOCS_URL;
143433
+ var DYNAMIC_WORKFLOWS_NOT_ENABLED_HINT;
143434
+ var DynamicWorkflowsNotEnabledError;
142352
143435
  var WorkflowRunFailedError;
142353
143436
  var WorkflowRunNotCompletedError;
142354
143437
  var WorkflowRuntimeError;
@@ -142503,6 +143586,40 @@ Caused by: ${options.cause.stack}`;
142503
143586
  return isError(value) && value.name === "WorkflowStartError";
142504
143587
  }
142505
143588
  };
143589
+ DYNAMIC_WORKFLOWS_ENV_VAR = "WORKFLOW_EXPERIMENTAL_DYNAMIC_WORKFLOWS";
143590
+ DYNAMIC_WORKFLOWS_DOCS_URL = "https://workflow-sdk.dev/docs/advanced/dynamic-workflows#enabling-dynamic-workflows";
143591
+ 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.`;
143592
+ DynamicWorkflowsNotEnabledError = class extends WorkflowError {
143593
+ static {
143594
+ __name(this, "DynamicWorkflowsNotEnabledError");
143595
+ }
143596
+ static {
143597
+ __name2(this, "DynamicWorkflowsNotEnabledError");
143598
+ }
143599
+ fatal = true;
143600
+ /**
143601
+ * @param message - What was refused, e.g. that `start()` created no run.
143602
+ * The fix-it hint and a docs link are appended to it.
143603
+ */
143604
+ constructor(message, options) {
143605
+ super(appendFramedDetails(message, [
143606
+ {
143607
+ label: "hint",
143608
+ value: DYNAMIC_WORKFLOWS_NOT_ENABLED_HINT
143609
+ },
143610
+ {
143611
+ label: "docs",
143612
+ value: DYNAMIC_WORKFLOWS_DOCS_URL
143613
+ }
143614
+ ]), {
143615
+ cause: options?.cause
143616
+ });
143617
+ this.name = "DynamicWorkflowsNotEnabledError";
143618
+ }
143619
+ static is(value) {
143620
+ return isError(value) && value.name === "DynamicWorkflowsNotEnabledError";
143621
+ }
143622
+ };
142506
143623
  WorkflowRunFailedError = class extends WorkflowError {
142507
143624
  static {
142508
143625
  __name(this, "WorkflowRunFailedError");
@@ -161675,24 +162792,24 @@ function serializeDefaultValue(value, schema, ctx, json22, params) {
161675
162792
  __name(serializeDefaultValue, "serializeDefaultValue");
161676
162793
  function toJSONSchema(input22, params) {
161677
162794
  if ("_idmap" in input22) {
161678
- const registry22 = input22;
162795
+ const registry32 = input22;
161679
162796
  const ctx2 = initializeContext({
161680
162797
  ...params,
161681
162798
  processors: allProcessors
161682
162799
  });
161683
162800
  const defs = {};
161684
- for (const entry of registry22._idmap.entries()) {
162801
+ for (const entry of registry32._idmap.entries()) {
161685
162802
  const [_, schema] = entry;
161686
162803
  processSchema(schema, ctx2);
161687
162804
  }
161688
162805
  const schemas = {};
161689
162806
  const external = {
161690
- registry: registry22,
162807
+ registry: registry32,
161691
162808
  uri: params?.uri,
161692
162809
  defs
161693
162810
  };
161694
162811
  ctx2.external = external;
161695
- for (const entry of registry22._idmap.entries()) {
162812
+ for (const entry of registry32._idmap.entries()) {
161696
162813
  const [key, schema] = entry;
161697
162814
  extractDefs(ctx2, schema);
161698
162815
  assignProp(schemas, key, finalize(ctx2, schema));
@@ -166621,6 +167738,10 @@ function getOwnProperty(object22, key) {
166621
167738
  return Object.hasOwn(object22, key) ? object22[key] : void 0;
166622
167739
  }
166623
167740
  __name(getOwnProperty, "getOwnProperty");
167741
+ function isSealedNoopEvent(event) {
167742
+ return event.eventType === "noop";
167743
+ }
167744
+ __name(isSealedNoopEvent, "isSealedNoopEvent");
166624
167745
  function getEventDataRefFields(eventType) {
166625
167746
  return getOwnProperty(EVENT_DATA_REF_FIELDS_BY_EVENT_TYPE, eventType) ?? NO_EVENT_DATA_REF_FIELDS;
166626
167747
  }
@@ -166635,6 +167756,7 @@ var init_event_metadata = __esm2({
166635
167756
  "../world/dist/event-metadata.js"() {
166636
167757
  "use strict";
166637
167758
  __name2(getOwnProperty, "getOwnProperty");
167759
+ __name2(isSealedNoopEvent, "isSealedNoopEvent");
166638
167760
  EVENT_DATA_REF_FIELDS_BY_EVENT_TYPE = {
166639
167761
  run_created: [
166640
167762
  "input"
@@ -169202,6 +170324,266 @@ var init_ulid = __esm2({
169202
170324
  __name2(validateUlidTimestamp, "validateUlidTimestamp");
169203
170325
  }
169204
170326
  });
170327
+ function spanOf(eventType, workflowName) {
170328
+ if (eventType.startsWith("hook_")) return {
170329
+ kind: "hook",
170330
+ name: "hook"
170331
+ };
170332
+ if (eventType.startsWith("wait_")) return {
170333
+ kind: "wait",
170334
+ name: "sleep"
170335
+ };
170336
+ if (eventType.startsWith("run_")) return {
170337
+ kind: "run",
170338
+ name: workflowName
170339
+ };
170340
+ if (eventType === "attr_set") {
170341
+ return {
170342
+ kind: "attributes",
170343
+ name: "attributes"
170344
+ };
170345
+ }
170346
+ return {
170347
+ kind: "other",
170348
+ name: "other"
170349
+ };
170350
+ }
170351
+ __name(spanOf, "spanOf");
170352
+ function compareCodeUnits(a, b) {
170353
+ return a < b ? -1 : a > b ? 1 : 0;
170354
+ }
170355
+ __name(compareCodeUnits, "compareCodeUnits");
170356
+ function toCount(value) {
170357
+ const n = Number(value);
170358
+ return Number.isFinite(n) && n > 0 ? n : 0;
170359
+ }
170360
+ __name(toCount, "toCount");
170361
+ function usageEntityOfEventType(eventType) {
170362
+ if (isSealedNoopEvent({
170363
+ eventType
170364
+ })) return null;
170365
+ if (eventType.startsWith("step_")) return "step";
170366
+ if (eventType.startsWith("hook_")) return "hook";
170367
+ return "run";
170368
+ }
170369
+ __name(usageEntityOfEventType, "usageEntityOfEventType");
170370
+ function buildRunUsage(input22) {
170371
+ const spans = /* @__PURE__ */ new Map();
170372
+ const byEntity = {
170373
+ run: 0,
170374
+ step: 0,
170375
+ hook: 0,
170376
+ stream: toCount(input22.streamBytes)
170377
+ };
170378
+ let events = 0;
170379
+ let retries = 0;
170380
+ const add3 = /* @__PURE__ */ __name2((kind, name, entity, count2, retryCount, bytes) => {
170381
+ if (count2 <= 0) return;
170382
+ const key = `${kind}\0${name}`;
170383
+ let span = spans.get(key);
170384
+ if (!span) {
170385
+ span = {
170386
+ kind,
170387
+ name,
170388
+ events: 0,
170389
+ share: 0,
170390
+ retries: 0,
170391
+ calls: 0
170392
+ };
170393
+ spans.set(key, span);
170394
+ }
170395
+ span.events += count2;
170396
+ span.retries += retryCount;
170397
+ events += count2;
170398
+ retries += retryCount;
170399
+ byEntity[entity] += bytes;
170400
+ }, "add");
170401
+ const created = {
170402
+ hook: 0,
170403
+ wait: 0
170404
+ };
170405
+ const hookGroups = input22.hookGroups;
170406
+ let hookEvents = 0;
170407
+ const runEvents = {
170408
+ events: 0,
170409
+ byType: {
170410
+ created: 0,
170411
+ started: 0,
170412
+ completed: 0,
170413
+ failed: 0,
170414
+ cancelled: 0
170415
+ }
170416
+ };
170417
+ for (const group of input22.eventGroups) {
170418
+ const entity = usageEntityOfEventType(group.eventType);
170419
+ if (!entity) continue;
170420
+ const runType = group.eventType.slice("run_".length);
170421
+ if (group.eventType.startsWith("run_") && RUN_USAGE_RUN_EVENT_TYPES.includes(runType)) {
170422
+ runEvents.byType[runType] += toCount(group.events);
170423
+ }
170424
+ if (group.eventType.startsWith("run_")) {
170425
+ runEvents.events += toCount(group.events);
170426
+ }
170427
+ if (group.eventType === "hook_created") created.hook += toCount(group.events);
170428
+ if (group.eventType === "wait_created") created.wait += toCount(group.events);
170429
+ const { kind, name } = spanOf(group.eventType, input22.workflowName);
170430
+ if (kind === "hook" && hookGroups) {
170431
+ hookEvents += toCount(group.events);
170432
+ events += toCount(group.events);
170433
+ byEntity[entity] += toCount(group.bytes);
170434
+ continue;
170435
+ }
170436
+ add3(kind, name, entity, toCount(group.events), 0, toCount(group.bytes));
170437
+ }
170438
+ if (hookGroups) {
170439
+ let grouped = 0;
170440
+ for (const group of hookGroups) {
170441
+ const count2 = toCount(group.events);
170442
+ if (count2 <= 0 || !group.hookId) continue;
170443
+ grouped += count2;
170444
+ spans.set(`hook\0${group.hookId}`, {
170445
+ kind: "hook",
170446
+ name: group.token || group.hookId,
170447
+ id: group.hookId,
170448
+ events: count2,
170449
+ share: 0,
170450
+ retries: 0,
170451
+ calls: 1
170452
+ });
170453
+ }
170454
+ if (hookEvents > grouped) {
170455
+ spans.set("hook\0", {
170456
+ kind: "hook",
170457
+ name: "hook",
170458
+ events: hookEvents - grouped,
170459
+ share: 0,
170460
+ retries: 0,
170461
+ calls: 0
170462
+ });
170463
+ }
170464
+ }
170465
+ const calls = {
170466
+ hook: toCount(created.hook),
170467
+ wait: toCount(input22.calls?.wait ?? created.wait)
170468
+ };
170469
+ const stepEvents = {
170470
+ steps: 0,
170471
+ events: 0,
170472
+ byType: {
170473
+ created: 0,
170474
+ started: 0,
170475
+ completed: 0,
170476
+ failed: 0,
170477
+ retrying: 0,
170478
+ other: 0
170479
+ }
170480
+ };
170481
+ let restarts = 0;
170482
+ for (const group of input22.stepGroups) {
170483
+ restarts += toCount(group.restarts);
170484
+ const counts = {
170485
+ created: toCount(group.created),
170486
+ started: toCount(group.started),
170487
+ completed: toCount(group.completed),
170488
+ failed: toCount(group.failed),
170489
+ retrying: toCount(group.retries)
170490
+ };
170491
+ const total = toCount(group.events);
170492
+ if (total <= 0) continue;
170493
+ stepEvents.steps += toCount(group.steps);
170494
+ stepEvents.events += total;
170495
+ let known = 0;
170496
+ for (const type of RUN_USAGE_STEP_EVENT_TYPES) {
170497
+ stepEvents.byType[type] += counts[type];
170498
+ known += counts[type];
170499
+ }
170500
+ stepEvents.byType.other += Math.max(0, total - known);
170501
+ const name = group.stepName || UNKNOWN_STEP_NAME;
170502
+ add3("step", name, "step", toCount(group.events), toCount(group.retries), toCount(group.bytes));
170503
+ const span = spans.get(`step\0${name}`);
170504
+ if (span) span.calls += toCount(group.steps);
170505
+ }
170506
+ for (const span of spans.values()) {
170507
+ if (span.kind === "run") span.calls = 1;
170508
+ if (span.kind === "hook" && !hookGroups) span.calls = calls.hook;
170509
+ if (span.kind === "wait") span.calls = calls.wait;
170510
+ if (span.kind === "attributes" || span.kind === "other") {
170511
+ span.calls = span.events;
170512
+ }
170513
+ }
170514
+ const eventsBySpan = [
170515
+ ...spans.values()
170516
+ ].map((span) => ({
170517
+ ...span,
170518
+ share: events > 0 ? span.events / events : 0
170519
+ })).sort((a, b) => b.events - a.events || compareCodeUnits(a.name, b.name) || compareCodeUnits(a.kind, b.kind) || compareCodeUnits(a.id ?? "", b.id ?? ""));
170520
+ return {
170521
+ runId: input22.runId,
170522
+ status: input22.status,
170523
+ workflowName: input22.workflowName,
170524
+ billed: input22.billed === true,
170525
+ inProgress: !isTerminalWorkflowRunStatus(input22.status),
170526
+ events,
170527
+ billableEvents: events,
170528
+ retries: {
170529
+ count: retries,
170530
+ events: retries + restarts
170531
+ },
170532
+ runEvents,
170533
+ stepEvents,
170534
+ eventsBySpan,
170535
+ dataWritten: dataWrittenOf(input22, byEntity),
170536
+ dataPurged: input22.dataPurged === true,
170537
+ dataRetained: input22.dataRetained ?? null
170538
+ };
170539
+ }
170540
+ __name(buildRunUsage, "buildRunUsage");
170541
+ function dataWrittenOf(input22, measured) {
170542
+ const saved = input22.dataPurged ? input22.savedDataWritten : void 0;
170543
+ const byEntity = saved ? {
170544
+ run: toCount(saved.run),
170545
+ step: toCount(saved.step),
170546
+ hook: toCount(saved.hook),
170547
+ stream: toCount(saved.stream)
170548
+ } : measured;
170549
+ return {
170550
+ bytes: byEntity.run + byEntity.step + byEntity.hook + byEntity.stream,
170551
+ byEntity,
170552
+ source: !input22.dataPurged ? "log" : saved ? "saved-at-purge" : "left-after-purge"
170553
+ };
170554
+ }
170555
+ __name(dataWrittenOf, "dataWrittenOf");
170556
+ var RUN_USAGE_RUN_EVENT_TYPES;
170557
+ var RUN_USAGE_STEP_EVENT_TYPES;
170558
+ var UNKNOWN_STEP_NAME;
170559
+ var init_usage = __esm2({
170560
+ "../world/dist/usage.js"() {
170561
+ "use strict";
170562
+ init_event_metadata();
170563
+ init_runs();
170564
+ RUN_USAGE_RUN_EVENT_TYPES = [
170565
+ "created",
170566
+ "started",
170567
+ "completed",
170568
+ "failed",
170569
+ "cancelled"
170570
+ ];
170571
+ RUN_USAGE_STEP_EVENT_TYPES = [
170572
+ "created",
170573
+ "started",
170574
+ "completed",
170575
+ "failed",
170576
+ "retrying"
170577
+ ];
170578
+ UNKNOWN_STEP_NAME = "(unknown step)";
170579
+ __name2(spanOf, "spanOf");
170580
+ __name2(compareCodeUnits, "compareCodeUnits");
170581
+ __name2(toCount, "toCount");
170582
+ __name2(usageEntityOfEventType, "usageEntityOfEventType");
170583
+ __name2(buildRunUsage, "buildRunUsage");
170584
+ __name2(dataWrittenOf, "dataWrittenOf");
170585
+ }
170586
+ });
169205
170587
  var init_dist4 = __esm2({
169206
170588
  "../world/dist/index.js"() {
169207
170589
  "use strict";
@@ -169223,6 +170605,7 @@ var init_dist4 = __esm2({
169223
170605
  init_start_hook();
169224
170606
  init_steps();
169225
170607
  init_ulid();
170608
+ init_usage();
169226
170609
  init_waits();
169227
170610
  }
169228
170611
  });
@@ -174519,6 +175902,84 @@ var init_get_world_lazy = __esm2({
174519
175902
  __name2(getWorldLazy, "getWorldLazy");
174520
175903
  }
174521
175904
  });
175905
+ function registry2() {
175906
+ const holder = globalThis;
175907
+ holder[REGISTRY_KEY] ??= {
175908
+ listeners: /* @__PURE__ */ new Map(),
175909
+ published: /* @__PURE__ */ new Map()
175910
+ };
175911
+ return holder[REGISTRY_KEY];
175912
+ }
175913
+ __name(registry2, "registry2");
175914
+ function keyOf(runId, streamName) {
175915
+ return `${runId}\0${streamName}`;
175916
+ }
175917
+ __name(keyOf, "keyOf");
175918
+ function prune(published, now22) {
175919
+ for (const [key, entry] of published) {
175920
+ if (now22 - entry.at < PUBLISHED_TTL_MS && published.size <= MAX_PUBLISHED) break;
175921
+ published.delete(key);
175922
+ }
175923
+ }
175924
+ __name(prune, "prune");
175925
+ function publishLocalAbort(runId, streamName, packet) {
175926
+ const { listeners, published } = registry2();
175927
+ const key = keyOf(runId, streamName);
175928
+ const now22 = Date.now();
175929
+ published.delete(key);
175930
+ published.set(key, {
175931
+ packet,
175932
+ at: now22
175933
+ });
175934
+ prune(published, now22);
175935
+ for (const listener of listeners.get(key) ?? []) {
175936
+ try {
175937
+ listener(packet);
175938
+ } catch {
175939
+ }
175940
+ }
175941
+ }
175942
+ __name(publishLocalAbort, "publishLocalAbort");
175943
+ function onLocalAbort(runId, streamName, listener) {
175944
+ const { listeners, published } = registry2();
175945
+ const key = keyOf(runId, streamName);
175946
+ prune(published, Date.now());
175947
+ const recent = published.get(key);
175948
+ if (recent) {
175949
+ listener(recent.packet);
175950
+ return () => {
175951
+ };
175952
+ }
175953
+ let set22 = listeners.get(key);
175954
+ if (!set22) {
175955
+ set22 = /* @__PURE__ */ new Set();
175956
+ listeners.set(key, set22);
175957
+ }
175958
+ set22.add(listener);
175959
+ return () => {
175960
+ const current22 = listeners.get(key);
175961
+ if (!current22) return;
175962
+ current22.delete(listener);
175963
+ if (current22.size === 0) listeners.delete(key);
175964
+ };
175965
+ }
175966
+ __name(onLocalAbort, "onLocalAbort");
175967
+ var REGISTRY_KEY;
175968
+ var PUBLISHED_TTL_MS;
175969
+ var MAX_PUBLISHED;
175970
+ var init_abort_local = __esm2({
175971
+ "../core/dist/serialization/abort-local.js"() {
175972
+ "use strict";
175973
+ REGISTRY_KEY = /* @__PURE__ */ Symbol.for("@workflow/core//localAbortDelivery");
175974
+ PUBLISHED_TTL_MS = 6e4;
175975
+ MAX_PUBLISHED = 256;
175976
+ __name2(registry2, "registry");
175977
+ __name2(keyOf, "keyOf");
175978
+ __name2(prune, "prune");
175979
+ __name2(publishLocalAbort, "publishLocalAbort");
175980
+ __name2(onLocalAbort, "onLocalAbort");
175981
+ }
175982
+ });
174522
175983
  function frameAbortStreamPayload(payload) {
174523
175984
  if (payload.length < HEADER_SIZE || payload.length > MAX_PACKET_SIZE) {
174524
175985
  throw new StreamError("Invalid abort stream packet length");
@@ -175001,12 +176462,12 @@ var init_hardened = __esm2({
175001
176462
  });
175002
176463
  function getRegistry(global2 = globalThis) {
175003
176464
  const g = global2;
175004
- let registry22 = g[WORKFLOW_CLASS_REGISTRY];
175005
- if (!registry22) {
175006
- registry22 = /* @__PURE__ */ new Map();
175007
- g[WORKFLOW_CLASS_REGISTRY] = registry22;
176465
+ let registry32 = g[WORKFLOW_CLASS_REGISTRY];
176466
+ if (!registry32) {
176467
+ registry32 = /* @__PURE__ */ new Map();
176468
+ g[WORKFLOW_CLASS_REGISTRY] = registry32;
175008
176469
  }
175009
- return registry22;
176470
+ return registry32;
175010
176471
  }
175011
176472
  __name(getRegistry, "getRegistry");
175012
176473
  function getSerializationClass(classId, global2) {
@@ -177458,9 +178919,9 @@ var init_abort_controller = __esm2({
177458
178919
  handler.call(this);
177459
178920
  }
177460
178921
  }
177461
- constructor(streamName, hookToken) {
178922
+ constructor(streamName, hookToken22) {
177462
178923
  this[ABORT_STREAM_NAME] = streamName;
177463
- this[ABORT_HOOK_TOKEN] = hookToken;
178924
+ this[ABORT_HOOK_TOKEN] = hookToken22;
177464
178925
  }
177465
178926
  /**
177466
178927
  * @internal Sets aborted state and fires listeners.
@@ -179794,7 +181255,7 @@ var version2;
179794
181255
  var init_version = __esm2({
179795
181256
  "../core/dist/version.js"() {
179796
181257
  "use strict";
179797
- version2 = "5.7.0";
181258
+ version2 = "5.7.2";
179798
181259
  }
179799
181260
  });
179800
181261
  function safetyCheckDelayMs(index) {
@@ -211307,6 +212768,154 @@ var init_recovery_wake = __esm2({
211307
212768
  __name2(backstopWakeDelaySeconds, "backstopWakeDelaySeconds");
211308
212769
  }
211309
212770
  });
212771
+ function valueBytesSql(path82) {
212772
+ const data22 = `CAST(json_extract(doc, '${path82}.data') AS BLOB)`;
212773
+ return `CASE WHEN json_extract(doc, '${path82}.__type') = 'Uint8Array'
212774
+ THEN length(${data22}) / 4 * 3 - (CASE WHEN substr(${data22}, -2) = X'3D3D' THEN 2 WHEN substr(${data22}, -1) = X'3D' THEN 1 ELSE 0 END)
212775
+ ELSE coalesce(length(CAST(doc -> '${path82}' AS BLOB)), 0) END`;
212776
+ }
212777
+ __name(valueBytesSql, "valueBytesSql");
212778
+ function measureStreamBytes(db, runId) {
212779
+ return Number(db.get(STREAM_BYTES_SQL, runId)?.bytes ?? 0);
212780
+ }
212781
+ __name(measureStreamBytes, "measureStreamBytes");
212782
+ function tableExists(db) {
212783
+ return db.get("SELECT 1 AS one FROM sqlite_master WHERE type = 'table' AND name = ?", TABLE) !== void 0;
212784
+ }
212785
+ __name(tableExists, "tableExists");
212786
+ function savePurgedUsage(db, runId, usage) {
212787
+ db.run(CREATE_TABLE_SQL);
212788
+ db.run(`INSERT INTO ${TABLE}
212789
+ (run_id, seq, run_bytes, step_bytes, hook_bytes, stream_bytes)
212790
+ VALUES (?, ?, ?, ?, ?, ?)
212791
+ ON CONFLICT (run_id) DO UPDATE SET
212792
+ seq = excluded.seq,
212793
+ run_bytes = excluded.run_bytes,
212794
+ step_bytes = excluded.step_bytes,
212795
+ hook_bytes = excluded.hook_bytes,
212796
+ stream_bytes = excluded.stream_bytes`, runId, usage.seq, usage.byEntity.run, usage.byEntity.step, usage.byEntity.hook, usage.byEntity.stream);
212797
+ }
212798
+ __name(savePurgedUsage, "savePurgedUsage");
212799
+ function readPurgedUsage(db, runId) {
212800
+ if (!tableExists(db)) return null;
212801
+ const row = db.get(`SELECT seq, run_bytes, step_bytes, hook_bytes, stream_bytes
212802
+ FROM ${TABLE} WHERE run_id = ?`, runId);
212803
+ if (!row) return null;
212804
+ return {
212805
+ seq: Number(row.seq),
212806
+ byEntity: {
212807
+ run: Number(row.run_bytes),
212808
+ step: Number(row.step_bytes),
212809
+ hook: Number(row.hook_bytes),
212810
+ stream: Number(row.stream_bytes)
212811
+ }
212812
+ };
212813
+ }
212814
+ __name(readPurgedUsage, "readPurgedUsage");
212815
+ function deletePurgedUsage(db, where) {
212816
+ if (!tableExists(db)) return;
212817
+ if (!where) {
212818
+ db.run(`DELETE FROM ${TABLE}`);
212819
+ return;
212820
+ }
212821
+ db.run(`DELETE FROM ${TABLE} WHERE run_id IN (${where.runIdsSql})`, ...where.params);
212822
+ }
212823
+ __name(deletePurgedUsage, "deletePurgedUsage");
212824
+ var PAYLOAD_PATHS;
212825
+ var PAYLOAD_EVENT_TYPES;
212826
+ var PAYLOAD_BYTES_SQL;
212827
+ var STREAM_BYTES_SQL;
212828
+ var TABLE;
212829
+ var CREATE_TABLE_SQL;
212830
+ var EntityBytes;
212831
+ var init_purged_usage = __esm2({
212832
+ "../world-local/dist/storage/purged-usage.js"() {
212833
+ "use strict";
212834
+ init_dist4();
212835
+ PAYLOAD_PATHS = {
212836
+ // A dynamic run's code is kept on the run, not on its events, so it is
212837
+ // not here.
212838
+ run_created: [
212839
+ "$.eventData.input",
212840
+ "$.eventData.startHook.metadata"
212841
+ ],
212842
+ run_started: [
212843
+ "$.eventData.input",
212844
+ "$.eventData.startHook.metadata"
212845
+ ],
212846
+ run_completed: [
212847
+ "$.eventData.output"
212848
+ ],
212849
+ run_failed: [
212850
+ "$.eventData.error"
212851
+ ],
212852
+ step_created: [
212853
+ "$.eventData.input"
212854
+ ],
212855
+ step_started: [
212856
+ "$.eventData.input"
212857
+ ],
212858
+ step_completed: [
212859
+ "$.eventData.result"
212860
+ ],
212861
+ step_failed: [
212862
+ "$.eventData.error"
212863
+ ],
212864
+ step_retrying: [
212865
+ "$.eventData.error"
212866
+ ],
212867
+ hook_created: [
212868
+ "$.eventData.metadata"
212869
+ ],
212870
+ hook_received: [
212871
+ "$.eventData.payload"
212872
+ ]
212873
+ };
212874
+ PAYLOAD_EVENT_TYPES = Object.keys(PAYLOAD_PATHS);
212875
+ __name2(valueBytesSql, "valueBytesSql");
212876
+ PAYLOAD_BYTES_SQL = `(CASE event_type ${Object.entries(PAYLOAD_PATHS).map(([eventType, paths]) => `WHEN '${eventType}' THEN ${paths.map((path82) => `(${valueBytesSql(path82)})`).join(" + ")}`).join(" ")} ELSE 0 END)`;
212877
+ STREAM_BYTES_SQL = `
212878
+ SELECT COALESCE(SUM(length(data)), 0) AS bytes
212879
+ FROM stream_chunks
212880
+ WHERE run_id = ?
212881
+ `;
212882
+ __name2(measureStreamBytes, "measureStreamBytes");
212883
+ TABLE = "run_usage_purged";
212884
+ CREATE_TABLE_SQL = `
212885
+ CREATE TABLE IF NOT EXISTS ${TABLE} (
212886
+ run_id TEXT PRIMARY KEY,
212887
+ -- The last log position the sizes below cover.
212888
+ seq INTEGER NOT NULL,
212889
+ run_bytes INTEGER NOT NULL,
212890
+ step_bytes INTEGER NOT NULL,
212891
+ hook_bytes INTEGER NOT NULL,
212892
+ stream_bytes INTEGER NOT NULL
212893
+ )
212894
+ `;
212895
+ EntityBytes = class {
212896
+ static {
212897
+ __name(this, "EntityBytes");
212898
+ }
212899
+ static {
212900
+ __name2(this, "EntityBytes");
212901
+ }
212902
+ byEntity = {
212903
+ run: 0,
212904
+ step: 0,
212905
+ hook: 0,
212906
+ stream: 0
212907
+ };
212908
+ add(eventType, bytes) {
212909
+ const entity = usageEntityOfEventType(eventType);
212910
+ if (entity) this.byEntity[entity] += Number(bytes) || 0;
212911
+ }
212912
+ };
212913
+ __name2(tableExists, "tableExists");
212914
+ __name2(savePurgedUsage, "savePurgedUsage");
212915
+ __name2(readPurgedUsage, "readPurgedUsage");
212916
+ __name2(deletePurgedUsage, "deletePurgedUsage");
212917
+ }
212918
+ });
211310
212919
  function truncateForError(value) {
211311
212920
  const s = typeof value === "string" ? value : String(value);
211312
212921
  const MAX = 48;
@@ -211359,11 +212968,33 @@ function ranPurge(run22) {
211359
212968
  return run22.expiredAt !== void 0 && new Date(run22.expiredAt).getTime() <= Date.now();
211360
212969
  }
211361
212970
  __name(ranPurge, "ranPurge");
211362
- function purgeRunData(db, runId) {
212971
+ function purgeRunData(db, runId, { purgedBefore = false } = {}) {
211363
212972
  for (const row of db.all("SELECT step_id, doc FROM steps WHERE run_id = ?", runId)) {
211364
212973
  writeScrubbedStep(db, runId, row.step_id, row.doc);
211365
212974
  }
211366
- for (const row of db.all("SELECT seq, doc FROM events WHERE run_id = ?", runId)) {
212975
+ const saved = readPurgedUsage(db, runId);
212976
+ const written = new EntityBytes();
212977
+ let lastSeq = 0;
212978
+ const events = db.all(`SELECT seq, event_type, doc, ${PAYLOAD_BYTES_SQL} AS bytes
212979
+ FROM events WHERE run_id = ?`, runId);
212980
+ for (const row of events) {
212981
+ lastSeq = Math.max(lastSeq, Number(row.seq));
212982
+ if (saved && Number(row.seq) <= saved.seq) continue;
212983
+ written.add(row.event_type, row.bytes);
212984
+ }
212985
+ written.byEntity.stream = measureStreamBytes(db, runId);
212986
+ if (saved) {
212987
+ savePurgedUsage(db, runId, {
212988
+ seq: lastSeq,
212989
+ byEntity: addBytes(saved.byEntity, written.byEntity)
212990
+ });
212991
+ } else if (!purgedBefore) {
212992
+ savePurgedUsage(db, runId, {
212993
+ seq: lastSeq,
212994
+ byEntity: written.byEntity
212995
+ });
212996
+ }
212997
+ for (const row of events) {
211367
212998
  writeScrubbedEvent(db, runId, row.seq, row.doc);
211368
212999
  }
211369
213000
  for (const row of db.all("SELECT hook_id, doc FROM hooks WHERE run_id = ?", runId)) {
@@ -211384,9 +213015,31 @@ function purgeLateStepWrite(db, runId, stepId, seq) {
211384
213015
  db.run("UPDATE steps SET doc = ? WHERE run_id = ? AND step_id = ?", encode3(step), runId, stepId);
211385
213016
  }
211386
213017
  const event = db.get("SELECT doc FROM events WHERE run_id = ? AND seq = ?", runId, seq);
211387
- if (event) writeScrubbedEvent(db, runId, seq, event.doc);
213018
+ if (!event) return;
213019
+ const saved = readPurgedUsage(db, runId);
213020
+ if (saved && seq > saved.seq) {
213021
+ const written = new EntityBytes();
213022
+ for (const row of db.all(`SELECT event_type, ${PAYLOAD_BYTES_SQL} AS bytes
213023
+ FROM events WHERE run_id = ? AND seq > ? AND seq <= ?`, runId, saved.seq, seq)) {
213024
+ written.add(row.event_type, row.bytes);
213025
+ }
213026
+ savePurgedUsage(db, runId, {
213027
+ seq,
213028
+ byEntity: addBytes(saved.byEntity, written.byEntity)
213029
+ });
213030
+ }
213031
+ writeScrubbedEvent(db, runId, seq, event.doc);
211388
213032
  }
211389
213033
  __name(purgeLateStepWrite, "purgeLateStepWrite");
213034
+ function addBytes(a, b) {
213035
+ return {
213036
+ run: a.run + b.run,
213037
+ step: a.step + b.step,
213038
+ hook: a.hook + b.hook,
213039
+ stream: a.stream + b.stream
213040
+ };
213041
+ }
213042
+ __name(addBytes, "addBytes");
211390
213043
  function writeScrubbedStep(db, runId, stepId, doc) {
211391
213044
  const step = decode3(doc);
211392
213045
  step.input = void 0;
@@ -211424,10 +213077,12 @@ var init_run_retention = __esm2({
211424
213077
  "use strict";
211425
213078
  init_dist4();
211426
213079
  init_codec();
213080
+ init_purged_usage();
211427
213081
  __name2(purgesUserDataOnFinish2, "purgesUserDataOnFinish");
211428
213082
  __name2(ranPurge, "ranPurge");
211429
213083
  __name2(purgeRunData, "purgeRunData");
211430
213084
  __name2(purgeLateStepWrite, "purgeLateStepWrite");
213085
+ __name2(addBytes, "addBytes");
211431
213086
  __name2(writeScrubbedStep, "writeScrubbedStep");
211432
213087
  __name2(writeScrubbedEvent, "writeScrubbedEvent");
211433
213088
  __name2(purgeRunStreams, "purgeRunStreams");
@@ -211733,6 +213388,7 @@ var init_store = __esm2({
211733
213388
  eventsBetween(runId, afterSeq, beforeSeq) {
211734
213389
  return this.db.all("SELECT doc FROM events WHERE run_id = ? AND seq > ? AND seq < ? ORDER BY seq", runId, afterSeq, beforeSeq).map((row) => decode3(row.doc));
211735
213390
  }
213391
+ // A caller that rewrites a live run's events makes the usage cache stale (see usage-storage.ts).
211736
213392
  rewriteEvent(event) {
211737
213393
  const seq = eventIdToSlot(event.eventId);
211738
213394
  if (seq === null) return;
@@ -213035,7 +214691,9 @@ function createRunsStorage(db, tag) {
213035
214691
  const now22 = /* @__PURE__ */ new Date();
213036
214692
  const alreadyDeleted = run22.expiredAt !== void 0 && run22.expiredAt.getTime() <= now22.getTime();
213037
214693
  if (!alreadyDeleted) store.updateRun(withRunPayloadsPurged(run22, now22));
213038
- purgeRunData(db, runId);
214694
+ purgeRunData(db, runId, {
214695
+ purgedBefore: alreadyDeleted
214696
+ });
213039
214697
  return {
213040
214698
  runId,
213041
214699
  outcome: alreadyDeleted ? "already_deleted" : "deleted"
@@ -213283,6 +214941,362 @@ var init_steps_storage = __esm2({
213283
214941
  __name2(createStepsStorage, "createStepsStorage");
213284
214942
  }
213285
214943
  });
214944
+ function countRange(db, runId, counts, from, to) {
214945
+ if (to <= from) return;
214946
+ for (const row of db.all(EVENT_GROUPS_SQL, runId, from, to)) {
214947
+ const entry = counts.eventTypes.get(row.event_type) ?? {
214948
+ events: 0,
214949
+ bytes: 0
214950
+ };
214951
+ entry.events += Number(row.events);
214952
+ entry.bytes += Number(row.bytes ?? 0);
214953
+ counts.eventTypes.set(row.event_type, entry);
214954
+ }
214955
+ for (const row of db.all(STEP_GROUPS_SQL, runId, from, to)) {
214956
+ const stepId = row.correlation_id ?? "";
214957
+ let step = counts.steps.get(stepId);
214958
+ if (!step) {
214959
+ const name = row.correlation_id === null ? null : db.get(STEP_NAME_SQL, runId, row.correlation_id)?.step_name ?? null;
214960
+ step = {
214961
+ name,
214962
+ events: 0,
214963
+ created: 0,
214964
+ started: 0,
214965
+ completed: 0,
214966
+ failed: 0,
214967
+ retries: 0,
214968
+ bytes: 0
214969
+ };
214970
+ counts.steps.set(stepId, step);
214971
+ }
214972
+ step.events += Number(row.events);
214973
+ step.created += Number(row.created);
214974
+ step.started += Number(row.started);
214975
+ step.completed += Number(row.completed);
214976
+ step.failed += Number(row.failed);
214977
+ step.retries += Number(row.retries);
214978
+ step.bytes += Number(row.bytes ?? 0);
214979
+ }
214980
+ for (const row of db.all(HOOK_GROUPS_SQL, runId, from, to)) {
214981
+ let hook = counts.hooks.get(row.correlation_id);
214982
+ if (!hook) {
214983
+ hook = {
214984
+ token: hookToken(db, runId, row.correlation_id),
214985
+ events: 0
214986
+ };
214987
+ counts.hooks.set(row.correlation_id, hook);
214988
+ }
214989
+ hook.events += Number(row.events);
214990
+ }
214991
+ for (const row of db.all(WAIT_IDS_SQL, runId, from, to)) {
214992
+ counts.waitIds.add(row.correlation_id);
214993
+ }
214994
+ counts.countedSeq = to;
214995
+ }
214996
+ __name(countRange, "countRange");
214997
+ function hookToken(db, runId, hookId) {
214998
+ const created = db.get(HOOK_TOKEN_SQL, runId, hookId);
214999
+ if (typeof created?.token === "string" && created.token) return created.token;
215000
+ const row = db.get(HOOK_ROW_TOKEN_SQL, hookId);
215001
+ if (typeof row?.token === "string" && row.token) return row.token;
215002
+ let startHook;
215003
+ try {
215004
+ startHook = startHookId(runId);
215005
+ } catch {
215006
+ return null;
215007
+ }
215008
+ if (hookId !== startHook) return null;
215009
+ const start22 = db.get(START_HOOK_TOKEN_SQL, runId);
215010
+ return typeof start22?.token === "string" && start22.token ? start22.token : null;
215011
+ }
215012
+ __name(hookToken, "hookToken");
215013
+ function hookGroupsOf(counts) {
215014
+ return [
215015
+ ...counts.hooks
215016
+ ].map(([hookId, hook]) => ({
215017
+ hookId,
215018
+ token: hook.token,
215019
+ events: hook.events
215020
+ }));
215021
+ }
215022
+ __name(hookGroupsOf, "hookGroupsOf");
215023
+ function eventGroupsOf(counts) {
215024
+ return [
215025
+ ...counts.eventTypes
215026
+ ].map(([eventType, entry]) => ({
215027
+ eventType,
215028
+ events: entry.events,
215029
+ bytes: entry.bytes
215030
+ }));
215031
+ }
215032
+ __name(eventGroupsOf, "eventGroupsOf");
215033
+ function stepGroupsOf(counts) {
215034
+ const byName = /* @__PURE__ */ new Map();
215035
+ for (const step of counts.steps.values()) {
215036
+ let group = byName.get(step.name);
215037
+ if (!group) {
215038
+ group = {
215039
+ stepName: step.name,
215040
+ steps: 0,
215041
+ events: 0,
215042
+ created: 0,
215043
+ started: 0,
215044
+ completed: 0,
215045
+ failed: 0,
215046
+ retries: 0,
215047
+ restarts: 0,
215048
+ bytes: 0
215049
+ };
215050
+ byName.set(step.name, group);
215051
+ }
215052
+ group.steps += 1;
215053
+ group.events += step.events;
215054
+ group.created += step.created;
215055
+ group.started += step.started;
215056
+ group.completed += step.completed;
215057
+ group.failed += step.failed;
215058
+ group.retries += step.retries;
215059
+ group.restarts += Math.min(step.retries, Math.max(0, step.started - 1));
215060
+ group.bytes += step.bytes;
215061
+ }
215062
+ return [
215063
+ ...byName.values()
215064
+ ];
215065
+ }
215066
+ __name(stepGroupsOf, "stepGroupsOf");
215067
+ function purgedDataWritten(db, runId, streamBytes) {
215068
+ const saved = readPurgedUsage(db, runId);
215069
+ if (!saved) return null;
215070
+ const late = new EntityBytes();
215071
+ for (const row of db.all(EVENTS_AFTER_SQL, runId, saved.seq)) {
215072
+ late.add(row.event_type, Number(row.bytes ?? 0));
215073
+ }
215074
+ return {
215075
+ run: saved.byEntity.run + late.byEntity.run,
215076
+ step: saved.byEntity.step + late.byEntity.step,
215077
+ hook: saved.byEntity.hook + late.byEntity.hook,
215078
+ stream: saved.byEntity.stream + streamBytes
215079
+ };
215080
+ }
215081
+ __name(purgedDataWritten, "purgedDataWritten");
215082
+ function createUsageStorage(db, tag, options = {}) {
215083
+ const maxRuns = options.maxRuns ?? 64;
215084
+ const batchTargetMs = options.batchTargetMs ?? 10;
215085
+ const maxBatchRows = options.maxBatchRows ?? 4096;
215086
+ const initialBatchRows = options.initialBatchRows ?? 4;
215087
+ const cache = /* @__PURE__ */ new Map();
215088
+ const inFlight = /* @__PURE__ */ new Map();
215089
+ const remember = /* @__PURE__ */ __name2((runId, counts) => {
215090
+ cache.delete(runId);
215091
+ cache.set(runId, counts);
215092
+ while (cache.size > maxRuns) {
215093
+ cache.delete(cache.keys().next().value);
215094
+ }
215095
+ }, "remember");
215096
+ const runRow = /* @__PURE__ */ __name2((runId) => db.get(`SELECT status, workflow_name, seq FROM runs WHERE run_id = ? AND ${tagClause("tag", tag)}`, runId, ...tagParams(tag)), "runRow");
215097
+ async function countInBatches(runId, counts, target22) {
215098
+ let batchRows = initialBatchRows;
215099
+ while (counts.countedSeq < target22) {
215100
+ const end = Number(db.get(BATCH_END_SQL, runId, counts.countedSeq, batchRows)?.seq ?? target22);
215101
+ const started = performance.now();
215102
+ countRange(db, runId, counts, counts.countedSeq, Math.min(end, target22));
215103
+ const took = performance.now() - started;
215104
+ batchRows = Math.max(1, Math.min(maxBatchRows, batchRows * 2, Math.round(batchRows * batchTargetMs / Math.max(took, 0.1))));
215105
+ if (counts.countedSeq < target22) {
215106
+ await options.onBatch?.(runId, counts.countedSeq);
215107
+ await yieldToEventLoop();
215108
+ }
215109
+ }
215110
+ }
215111
+ __name(countInBatches, "countInBatches");
215112
+ __name2(countInBatches, "countInBatches");
215113
+ async function read32(runId) {
215114
+ const first = runRow(runId);
215115
+ if (!first) {
215116
+ cache.delete(runId);
215117
+ throw new WorkflowRunNotFoundError(runId);
215118
+ }
215119
+ let counts = cache.get(runId) ?? newCounts();
215120
+ if (Number(first.seq) < counts.countedSeq) counts = newCounts();
215121
+ let readBeforeFinish = !isTerminalWorkflowRunStatus(first.status) || counts.countedSeq > 0 && !counts.finished;
215122
+ await countInBatches(runId, counts, Number(first.seq));
215123
+ const snapshot = db.snapshot(() => {
215124
+ const run22 = runRow(runId);
215125
+ if (!run22) return null;
215126
+ const seq = Number(run22.seq);
215127
+ const finished = isTerminalWorkflowRunStatus(run22.status);
215128
+ if (seq < counts.countedSeq) {
215129
+ counts = newCounts();
215130
+ readBeforeFinish = !finished;
215131
+ }
215132
+ countRange(db, runId, counts, counts.countedSeq, seq);
215133
+ const streamBytes = measureStreamBytes(db, runId);
215134
+ const savedDataWritten = purgedDataWritten(db, runId, streamBytes) ?? void 0;
215135
+ const dataPurged = savedDataWritten !== void 0 || finished && Number(db.get(PURGED_RUN_SQL, runId)?.purged) === 1;
215136
+ if (dataPurged && readBeforeFinish && counts.countedSeq > 0) {
215137
+ options.onRecount?.(runId);
215138
+ counts = newCounts();
215139
+ countRange(db, runId, counts, 0, seq);
215140
+ }
215141
+ counts.finished = finished;
215142
+ return {
215143
+ run: run22,
215144
+ streamBytes,
215145
+ dataPurged,
215146
+ savedDataWritten
215147
+ };
215148
+ });
215149
+ if (!snapshot) {
215150
+ cache.delete(runId);
215151
+ throw new WorkflowRunNotFoundError(runId);
215152
+ }
215153
+ remember(runId, counts);
215154
+ return buildRunUsage({
215155
+ runId,
215156
+ status: snapshot.run.status,
215157
+ workflowName: snapshot.run.workflow_name,
215158
+ eventGroups: eventGroupsOf(counts),
215159
+ stepGroups: stepGroupsOf(counts),
215160
+ streamBytes: snapshot.streamBytes,
215161
+ dataPurged: snapshot.dataPurged,
215162
+ savedDataWritten: snapshot.savedDataWritten,
215163
+ hookGroups: hookGroupsOf(counts),
215164
+ calls: {
215165
+ wait: counts.waitIds.size
215166
+ },
215167
+ // Local runs are not billed.
215168
+ billed: false,
215169
+ // world-local has no plan retention, so there is no Data Retained to
215170
+ // report: the UI and CLI hide it.
215171
+ dataRetained: null
215172
+ });
215173
+ }
215174
+ __name(read32, "read3");
215175
+ __name2(read32, "read");
215176
+ return {
215177
+ async getRun(runId) {
215178
+ assertSafeEntityId("runId", runId);
215179
+ const previous = inFlight.get(runId) ?? Promise.resolve();
215180
+ const current22 = previous.catch(() => {
215181
+ }).then(() => read32(runId));
215182
+ inFlight.set(runId, current22);
215183
+ try {
215184
+ return await current22;
215185
+ } finally {
215186
+ if (inFlight.get(runId) === current22) inFlight.delete(runId);
215187
+ }
215188
+ }
215189
+ };
215190
+ }
215191
+ __name(createUsageStorage, "createUsageStorage");
215192
+ var IS_STEP_EVENT;
215193
+ var EVENT_GROUPS_SQL;
215194
+ var STEP_GROUPS_SQL;
215195
+ var WAIT_IDS_SQL;
215196
+ var HOOK_GROUPS_SQL;
215197
+ var HOOK_TOKEN_SQL;
215198
+ var HOOK_ROW_TOKEN_SQL;
215199
+ var START_HOOK_TOKEN_SQL;
215200
+ var STEP_NAME_SQL;
215201
+ var BATCH_END_SQL;
215202
+ var EVENTS_AFTER_SQL;
215203
+ var PURGED_RUN_SQL;
215204
+ var newCounts;
215205
+ var yieldToEventLoop;
215206
+ var init_usage_storage = __esm2({
215207
+ "../world-local/dist/storage/usage-storage.js"() {
215208
+ "use strict";
215209
+ init_dist2();
215210
+ init_dist4();
215211
+ init_ids();
215212
+ init_purged_usage();
215213
+ init_store();
215214
+ IS_STEP_EVENT = `event_type LIKE 'step\\_%' ESCAPE '\\'`;
215215
+ EVENT_GROUPS_SQL = `
215216
+ SELECT event_type,
215217
+ COUNT(*) AS events,
215218
+ SUM(${PAYLOAD_BYTES_SQL}) AS bytes
215219
+ FROM events
215220
+ WHERE run_id = ?1 AND seq > ?2 AND seq <= ?3 AND NOT (${IS_STEP_EVENT})
215221
+ GROUP BY event_type
215222
+ `;
215223
+ STEP_GROUPS_SQL = `
215224
+ SELECT correlation_id,
215225
+ COUNT(*) AS events,
215226
+ SUM(event_type = 'step_created') AS created,
215227
+ SUM(event_type = 'step_started') AS started,
215228
+ SUM(event_type = 'step_completed') AS completed,
215229
+ SUM(event_type = 'step_failed') AS failed,
215230
+ SUM(event_type = 'step_retrying') AS retries,
215231
+ SUM(${PAYLOAD_BYTES_SQL}) AS bytes
215232
+ FROM events
215233
+ WHERE run_id = ?1 AND seq > ?2 AND seq <= ?3 AND ${IS_STEP_EVENT}
215234
+ GROUP BY correlation_id
215235
+ `;
215236
+ WAIT_IDS_SQL = `
215237
+ SELECT DISTINCT correlation_id
215238
+ FROM events
215239
+ WHERE run_id = ?1 AND seq > ?2 AND seq <= ?3
215240
+ AND correlation_id IS NOT NULL AND substr(event_type, 1, 5) = 'wait_'
215241
+ `;
215242
+ HOOK_GROUPS_SQL = `
215243
+ SELECT correlation_id, COUNT(*) AS events
215244
+ FROM events
215245
+ WHERE run_id = ?1 AND seq > ?2 AND seq <= ?3
215246
+ AND correlation_id IS NOT NULL AND substr(event_type, 1, 5) = 'hook_'
215247
+ GROUP BY correlation_id
215248
+ `;
215249
+ HOOK_TOKEN_SQL = `
215250
+ SELECT json_extract(doc, '$.eventData.token') AS token
215251
+ FROM ${EVENTS_BY_CORRELATION}
215252
+ WHERE run_id = ? AND correlation_id = ?
215253
+ AND event_type IN ('hook_created', 'hook_conflict')
215254
+ ORDER BY seq LIMIT 1
215255
+ `;
215256
+ HOOK_ROW_TOKEN_SQL = "SELECT token FROM hooks WHERE hook_id = ?";
215257
+ START_HOOK_TOKEN_SQL = `
215258
+ SELECT json_extract(doc, '$.eventData.startHook.token') AS token
215259
+ FROM events
215260
+ WHERE run_id = ? AND event_type = 'run_created'
215261
+ LIMIT 1
215262
+ `;
215263
+ STEP_NAME_SQL = `
215264
+ SELECT json_extract(doc, '$.stepName') AS step_name
215265
+ FROM steps WHERE run_id = ? AND step_id = ?
215266
+ `;
215267
+ BATCH_END_SQL = `
215268
+ SELECT MAX(seq) AS seq FROM (
215269
+ SELECT seq FROM events WHERE run_id = ? AND seq > ? ORDER BY seq LIMIT ?
215270
+ )
215271
+ `;
215272
+ EVENTS_AFTER_SQL = `
215273
+ SELECT event_type, SUM(${PAYLOAD_BYTES_SQL}) AS bytes
215274
+ FROM events
215275
+ WHERE run_id = ? AND seq > ?
215276
+ GROUP BY event_type
215277
+ `;
215278
+ PURGED_RUN_SQL = `
215279
+ SELECT json_extract(doc, '$.expiredAt') IS NOT NULL AS purged
215280
+ FROM runs WHERE run_id = ?
215281
+ `;
215282
+ newCounts = /* @__PURE__ */ __name2(() => ({
215283
+ countedSeq: 0,
215284
+ finished: false,
215285
+ eventTypes: /* @__PURE__ */ new Map(),
215286
+ steps: /* @__PURE__ */ new Map(),
215287
+ hooks: /* @__PURE__ */ new Map(),
215288
+ waitIds: /* @__PURE__ */ new Set()
215289
+ }), "newCounts");
215290
+ __name2(countRange, "countRange");
215291
+ __name2(hookToken, "hookToken");
215292
+ __name2(hookGroupsOf, "hookGroupsOf");
215293
+ __name2(eventGroupsOf, "eventGroupsOf");
215294
+ __name2(stepGroupsOf, "stepGroupsOf");
215295
+ __name2(purgedDataWritten, "purgedDataWritten");
215296
+ yieldToEventLoop = /* @__PURE__ */ __name2(() => new Promise((resolve22) => setImmediate(resolve22)), "yieldToEventLoop");
215297
+ __name2(createUsageStorage, "createUsageStorage");
215298
+ }
215299
+ });
213286
215300
  function createStorage(basedir, tag) {
213287
215301
  const db = databaseFor(basedir);
213288
215302
  const runs = createRunsStorage(db, tag);
@@ -213290,12 +215304,14 @@ function createStorage(basedir, tag) {
213290
215304
  const events = createEventsStorage(db, tag);
213291
215305
  const hooks = createHooksStorage(db, tag);
213292
215306
  const snapshots = createSnapshotsStorage(db);
215307
+ const usage = createUsageStorage(db, tag);
213293
215308
  return {
213294
215309
  runs: instrumentObject("world.runs", runs),
213295
215310
  steps: instrumentObject("world.steps", steps),
213296
215311
  events: instrumentObject("world.events", events),
213297
215312
  hooks: instrumentObject("world.hooks", hooks),
213298
215313
  experimental_snapshots: instrumentObject("world.experimental_snapshots", snapshots),
215314
+ experimental_usage: instrumentObject("world.experimental_usage", usage),
213299
215315
  clearCache: /* @__PURE__ */ __name2(() => {
213300
215316
  }, "clearCache")
213301
215317
  };
@@ -213311,6 +215327,7 @@ var init_storage = __esm2({
213311
215327
  init_runs_storage();
213312
215328
  init_snapshots_storage();
213313
215329
  init_steps_storage();
215330
+ init_usage_storage();
213314
215331
  __name2(createStorage, "createStorage");
213315
215332
  }
213316
215333
  });
@@ -213744,9 +215761,16 @@ function createWorld(args) {
213744
215761
  ]) {
213745
215762
  db.run(`DELETE FROM ${table}`);
213746
215763
  }
215764
+ deletePurgedUsage(db);
213747
215765
  return;
213748
215766
  }
213749
215767
  const runs = "SELECT run_id FROM runs WHERE tag = ?";
215768
+ deletePurgedUsage(db, {
215769
+ runIdsSql: runs,
215770
+ params: [
215771
+ tag
215772
+ ]
215773
+ });
213750
215774
  for (const table of [
213751
215775
  "events",
213752
215776
  "steps",
@@ -213788,6 +215812,7 @@ var init_dist5 = __esm2({
213788
215812
  init_queue2();
213789
215813
  init_queue_auth_key();
213790
215814
  init_recovery_wake();
215815
+ init_purged_usage();
213791
215816
  init_storage2();
213792
215817
  init_streamer();
213793
215818
  init_build_target_mismatch();
@@ -217759,7 +219784,7 @@ var version3;
217759
219784
  var init_version2 = __esm2({
217760
219785
  "../world-vercel/dist/version.js"() {
217761
219786
  "use strict";
217762
- version3 = "5.7.0";
219787
+ version3 = "5.7.2";
217763
219788
  }
217764
219789
  });
217765
219790
  function getQueueAgentOptions2() {
@@ -226838,17 +228863,17 @@ var require_exec = __commonJS2({
226838
228863
  var import_node_path62 = __toESM22(__require2("node:path"));
226839
228864
  var import_execa = __toESM22(require_execa());
226840
228865
  var import_envpath = require_envpath();
226841
- var import_errors592 = require_errors2();
228866
+ var import_errors602 = require_errors2();
226842
228867
  var import_lookup = require_lookup();
226843
228868
  async function execVercelCli2(args, options = {}) {
226844
228869
  const cwd = import_node_path62.default.resolve(options.cwd ?? process.cwd());
226845
- await (0, import_errors592.assertValidCwd)(cwd);
228870
+ await (0, import_errors602.assertValidCwd)(cwd);
226846
228871
  const env = mergeExecEnv(options.env);
226847
228872
  const pathValue = (0, import_envpath.getEnvPath)(env);
226848
228873
  try {
226849
228874
  return await execResolvedVercelCli(args, options, cwd, env, pathValue);
226850
228875
  } catch (error622) {
226851
- if (error622 instanceof import_errors592.VercelCliError && error622.code === "VERCEL_CLI_NOT_FOUND") {
228876
+ if (error622 instanceof import_errors602.VercelCliError && error622.code === "VERCEL_CLI_NOT_FOUND") {
226852
228877
  (0, import_lookup.clearCachedCliInvocation)(cwd, pathValue);
226853
228878
  return await execResolvedVercelCli(args, options, cwd, env, pathValue);
226854
228879
  }
@@ -226884,7 +228909,7 @@ var require_exec = __commonJS2({
226884
228909
  invocation
226885
228910
  };
226886
228911
  } catch (error622) {
226887
- throw (0, import_errors592.toVercelCliError)(invocation, error622);
228912
+ throw (0, import_errors602.toVercelCliError)(invocation, error622);
226888
228913
  }
226889
228914
  }
226890
228915
  __name(execResolvedVercelCli, "execResolvedVercelCli");
@@ -226892,9 +228917,9 @@ var require_exec = __commonJS2({
226892
228917
  async function resolveInvocationOrThrow(cwd, pathValue) {
226893
228918
  const resolution = await (0, import_lookup.resolveCachedCliInvocation)(cwd, pathValue);
226894
228919
  if (!resolution.found) {
226895
- throw new import_errors592.VercelCliError({
228920
+ throw new import_errors602.VercelCliError({
226896
228921
  code: "VERCEL_CLI_NOT_FOUND",
226897
- message: (0, import_errors592.getCliNotFoundMessage)(resolution.diagnostics)
228922
+ message: (0, import_errors602.getCliNotFoundMessage)(resolution.diagnostics)
226898
228923
  });
226899
228924
  }
226900
228925
  return (0, import_lookup.toVercelCliInvocation)(resolution);
@@ -226954,13 +228979,13 @@ var require_dist2 = __commonJS2({
226954
228979
  }), mod), "__toCommonJS");
226955
228980
  var src_exports = {};
226956
228981
  __export22(src_exports, {
226957
- VercelCliError: /* @__PURE__ */ __name2(() => import_errors592.VercelCliError, "VercelCliError"),
228982
+ VercelCliError: /* @__PURE__ */ __name2(() => import_errors602.VercelCliError, "VercelCliError"),
226958
228983
  clearVercelCliLookupCache: /* @__PURE__ */ __name2(() => import_lookup.clearVercelCliLookupCache, "clearVercelCliLookupCache"),
226959
228984
  execVercelCli: /* @__PURE__ */ __name2(() => import_exec.execVercelCli, "execVercelCli"),
226960
228985
  findVercelCli: /* @__PURE__ */ __name2(() => import_lookup.findVercelCli, "findVercelCli")
226961
228986
  });
226962
228987
  module.exports = __toCommonJS(src_exports);
226963
- var import_errors592 = require_errors2();
228988
+ var import_errors602 = require_errors2();
226964
228989
  var import_exec = require_exec();
226965
228990
  var import_lookup = require_lookup();
226966
228991
  }
@@ -230305,12 +232330,12 @@ ${content.join(`
230305
232330
  return this._map.has(schema);
230306
232331
  }
230307
232332
  };
230308
- function registry22() {
232333
+ function registry32() {
230309
232334
  return new $ZodRegistry22();
230310
232335
  }
230311
- __name(registry22, "registry2");
230312
- __name2(registry22, "registry");
230313
- (_a22 = globalThis).__zod_globalRegistry ?? (_a22.__zod_globalRegistry = registry22());
232336
+ __name(registry32, "registry3");
232337
+ __name2(registry32, "registry");
232338
+ (_a22 = globalThis).__zod_globalRegistry ?? (_a22.__zod_globalRegistry = registry32());
230314
232339
  var globalRegistry22 = globalThis.__zod_globalRegistry;
230315
232340
  function snapshotChecks22(def) {
230316
232341
  return def.checks && (def.checks = [
@@ -244587,10 +246612,10 @@ function registerHandlerForFile(filePath, handler, client, options) {
244587
246612
  const absolutePath = path7.isAbsolute(filePath) ? filePath : path7.resolve(process.cwd(), filePath);
244588
246613
  const fileMappings = findMappingsForFile(absolutePath);
244589
246614
  if (fileMappings.length === 0) return false;
244590
- const registry22 = getHandlerRegistry();
246615
+ const registry32 = getHandlerRegistry();
244591
246616
  for (const mapping of fileMappings) {
244592
246617
  const key = mapping.topic;
244593
- const existing = registry22.get(key) ?? [];
246618
+ const existing = registry32.get(key) ?? [];
244594
246619
  const nextEntry = {
244595
246620
  consumerGroup: mapping.consumer,
244596
246621
  handler,
@@ -244603,7 +246628,7 @@ function registerHandlerForFile(filePath, handler, client, options) {
244603
246628
  } else {
244604
246629
  existing.push(nextEntry);
244605
246630
  }
244606
- registry22.set(key, existing);
246631
+ registry32.set(key, existing);
244607
246632
  }
244608
246633
  return true;
244609
246634
  }
@@ -244638,9 +246663,9 @@ Add a trigger to vercel.json:
244638
246663
  }
244639
246664
  __name(registerDevHandler, "registerDevHandler");
244640
246665
  function lookupHandlers(topicName) {
244641
- const registry22 = getHandlerRegistry();
246666
+ const registry32 = getHandlerRegistry();
244642
246667
  const result2 = [];
244643
- for (const [pattern, handlers] of registry22) {
246668
+ for (const [pattern, handlers] of registry32) {
244644
246669
  const matches = pattern.includes("*") ? matchesWildcardPattern(topicName, pattern) : pattern === topicName;
244645
246670
  if (matches) {
244646
246671
  result2.push(...handlers);
@@ -256023,22 +258048,22 @@ function getAllBaseReducers(global2 = globalThis) {
256023
258048
  __name(getAllBaseReducers, "getAllBaseReducers");
256024
258049
  function reduceAbortWithListener(signal, holder, global2, ops, runId, cryptoKey, framedAbortStreams) {
256025
258050
  let streamName = holder[ABORT_STREAM_NAME];
256026
- let hookToken = holder[ABORT_HOOK_TOKEN];
258051
+ let hookToken22 = holder[ABORT_HOOK_TOKEN];
256027
258052
  if (!streamName) {
256028
258053
  const id = (global2[STABLE_ULID] || defaultUlid)();
256029
258054
  streamName = getAbortStreamId(id);
256030
- hookToken = `abrt_${id}`;
258055
+ hookToken22 = `abrt_${id}`;
256031
258056
  holder[ABORT_STREAM_NAME] = streamName;
256032
- holder[ABORT_HOOK_TOKEN] = hookToken;
258057
+ holder[ABORT_HOOK_TOKEN] = hookToken22;
256033
258058
  if (holder.signal) {
256034
258059
  holder.signal[ABORT_STREAM_NAME] = streamName;
256035
- holder.signal[ABORT_HOOK_TOKEN] = hookToken;
258060
+ holder.signal[ABORT_HOOK_TOKEN] = hookToken22;
256036
258061
  }
256037
258062
  }
256038
258063
  attachAbortListenerOnce(signal, streamName, runId, cryptoKey, ops, framedAbortStreams);
256039
258064
  return {
256040
258065
  streamName,
256041
- hookToken,
258066
+ hookToken: hookToken22,
256042
258067
  aborted: signal.aborted,
256043
258068
  reason: signal.aborted ? signal.reason : void 0
256044
258069
  };
@@ -256046,13 +258071,13 @@ function reduceAbortWithListener(signal, holder, global2, ops, runId, cryptoKey,
256046
258071
  __name(reduceAbortWithListener, "reduceAbortWithListener");
256047
258072
  function reduceAbortBySymbol(signal, holder) {
256048
258073
  const streamName = holder[ABORT_STREAM_NAME] ?? holder.signal?.[ABORT_STREAM_NAME];
256049
- const hookToken = holder[ABORT_HOOK_TOKEN] ?? holder.signal?.[ABORT_HOOK_TOKEN];
258074
+ const hookToken22 = holder[ABORT_HOOK_TOKEN] ?? holder.signal?.[ABORT_HOOK_TOKEN];
256050
258075
  if (!streamName) {
256051
258076
  throw new Error("AbortController/AbortSignal stream name is not set");
256052
258077
  }
256053
258078
  return {
256054
258079
  streamName,
256055
- hookToken,
258080
+ hookToken: hookToken22,
256056
258081
  aborted: signal.aborted,
256057
258082
  reason: signal.aborted ? signal.reason : void 0
256058
258083
  };
@@ -256070,6 +258095,7 @@ function attachAbortListenerOnce(signal, streamName, runId, cryptoKey, ops, fram
256070
258095
  aborted: true,
256071
258096
  reason: signal.reason
256072
258097
  }, runId, key);
258098
+ publishLocalAbort(runId, streamName, payload);
256073
258099
  const writable = new WorkflowServerWritableStream(runId, streamName);
256074
258100
  const writer = writable.getWriter();
256075
258101
  await writer.write(framedAbortStreams ? frameAbortStreamPayload(payload) : payload);
@@ -256368,41 +258394,84 @@ function cancelAbortReaders(...values) {
256368
258394
  for (const v of values) walk(v);
256369
258395
  }
256370
258396
  __name(cancelAbortReaders, "cancelAbortReaders");
256371
- function setupAbortStreamReader(controller, runId, streamName, ops, cryptoKey) {
258397
+ function setupAbortStreamReader(controller, runId, streamName, ops, cryptoKey, untilCancelled) {
256372
258398
  const readerCancel = new AbortController();
258399
+ let resolveLocal;
258400
+ const localPacket = new Promise((resolve22) => {
258401
+ resolveLocal = resolve22;
258402
+ });
258403
+ const stopLocal = onLocalAbort(runId, streamName, (packet) => resolveLocal?.(packet));
256373
258404
  ops.push((async () => {
256374
258405
  let reader;
258406
+ let keepListening = false;
256375
258407
  try {
256376
- const readable = new WorkflowServerReadableStream(runId, streamName);
256377
- reader = readable.getReader();
256378
258408
  let keyPromise;
256379
258409
  let decoded;
256380
258410
  const decodePacket = /* @__PURE__ */ __name2(async (packet) => {
256381
258411
  keyPromise ??= resolveEncryptionKey(cryptoKey);
256382
258412
  decoded = await hydrateStepArguments(packet, runId, await keyPromise);
256383
258413
  }, "decodePacket");
256384
- const result2 = await Promise.race([
256385
- readAbortStreamPacket(reader, decodePacket),
256386
- new Promise((resolve22) => {
256387
- if (readerCancel.signal.aborted) {
256388
- resolve22(void 0);
256389
- return;
256390
- }
256391
- readerCancel.signal.addEventListener("abort", () => resolve22(void 0), {
256392
- once: true
256393
- });
256394
- })
256395
- ]);
256396
- if (result2) {
258414
+ const abortWith = /* @__PURE__ */ __name2(async (packet, already) => {
256397
258415
  try {
256398
- if (decoded === void 0) await decodePacket(result2);
258416
+ decoded = already;
258417
+ if (decoded === void 0) await decodePacket(packet);
256399
258418
  controller.abort(decoded?.reason);
256400
258419
  } catch {
256401
258420
  controller.abort();
256402
258421
  }
258422
+ }, "abortWith");
258423
+ const cancelled = new Promise((resolve22) => {
258424
+ if (readerCancel.signal.aborted) {
258425
+ resolve22(void 0);
258426
+ return;
258427
+ }
258428
+ readerCancel.signal.addEventListener("abort", () => resolve22(void 0), {
258429
+ once: true
258430
+ });
258431
+ });
258432
+ let streamPacket;
258433
+ try {
258434
+ const readable = new WorkflowServerReadableStream(runId, streamName);
258435
+ reader = readable.getReader();
258436
+ streamPacket = readAbortStreamPacket(reader, decodePacket);
258437
+ } catch {
258438
+ streamPacket = new Promise(() => {
258439
+ });
258440
+ }
258441
+ const local = localPacket.then((packet) => ({
258442
+ packet,
258443
+ local: true
258444
+ }));
258445
+ const winner = await Promise.race([
258446
+ local,
258447
+ untilCancelled ? streamPacket.then((packet) => packet ? {
258448
+ packet,
258449
+ local: false
258450
+ } : void 0, () => void 0) : streamPacket.then((packet) => packet ? {
258451
+ packet,
258452
+ local: false
258453
+ } : void 0),
258454
+ cancelled
258455
+ ]);
258456
+ if (winner) {
258457
+ await abortWith(winner.packet, winner.local ? void 0 : decoded);
258458
+ } else if (untilCancelled && !readerCancel.signal.aborted) {
258459
+ keepListening = true;
258460
+ const expiry = setTimeout(stopLocal, LOCAL_ABORT_LISTEN_AFTER_STREAM_END_MS);
258461
+ expiry.unref?.();
258462
+ void Promise.race([
258463
+ local,
258464
+ cancelled
258465
+ ]).then(async (late) => {
258466
+ clearTimeout(expiry);
258467
+ stopLocal();
258468
+ if (late) await abortWith(late.packet, void 0);
258469
+ }).catch(() => {
258470
+ });
256403
258471
  }
256404
258472
  } catch {
256405
258473
  } finally {
258474
+ if (!keepListening) stopLocal();
256406
258475
  void reader?.cancel().catch(() => {
256407
258476
  });
256408
258477
  }
@@ -256437,13 +258506,13 @@ function copyAbortInternals(src22, dest) {
256437
258506
  }
256438
258507
  }
256439
258508
  __name(copyAbortInternals, "copyAbortInternals");
256440
- function reviveAbortController(value, ops, runId, cryptoKey) {
258509
+ function reviveAbortController(value, ops, runId, cryptoKey, untilCancelled = false) {
256441
258510
  const controller = new AbortController();
256442
258511
  if (value.aborted) {
256443
258512
  tagAbortPair(controller, value);
256444
258513
  controller.abort(value.reason);
256445
258514
  } else if (value.streamName) {
256446
- const readerCancel = setupAbortStreamReader(controller, runId, value.streamName, ops, cryptoKey);
258515
+ const readerCancel = setupAbortStreamReader(controller, runId, value.streamName, ops, cryptoKey, untilCancelled);
256447
258516
  tagAbortPair(controller, value, readerCancel);
256448
258517
  } else {
256449
258518
  tagAbortPair(controller, value);
@@ -256460,6 +258529,7 @@ function reviveAbortController(value, ops, runId, cryptoKey) {
256460
258529
  aborted: true,
256461
258530
  reason
256462
258531
  }, ctx.workflowMetadata.workflowRunId, ctx.encryptionKey);
258532
+ publishLocalAbort(ctx.workflowMetadata.workflowRunId, value.streamName, payload);
256463
258533
  const writable = new WorkflowServerWritableStream(ctx.workflowMetadata.workflowRunId, value.streamName);
256464
258534
  const writer = writable.getWriter();
256465
258535
  await writer.write(frameAbortStreamPayload(payload));
@@ -256485,13 +258555,13 @@ function reviveAbortController(value, ops, runId, cryptoKey) {
256485
258555
  return controller;
256486
258556
  }
256487
258557
  __name(reviveAbortController, "reviveAbortController");
256488
- function reviveAbortSignal(value, ops, runId, cryptoKey) {
258558
+ function reviveAbortSignal(value, ops, runId, cryptoKey, untilCancelled = false) {
256489
258559
  const controller = new AbortController();
256490
258560
  if (value.aborted) {
256491
258561
  tagAbortPair(controller, value);
256492
258562
  controller.abort(value.reason);
256493
258563
  } else if (value.streamName) {
256494
- const readerCancel = setupAbortStreamReader(controller, runId, value.streamName, ops, cryptoKey);
258564
+ const readerCancel = setupAbortStreamReader(controller, runId, value.streamName, ops, cryptoKey, untilCancelled);
256495
258565
  tagAbortPair(controller, value, readerCancel);
256496
258566
  } else {
256497
258567
  tagAbortPair(controller, value);
@@ -257004,8 +259074,10 @@ function getStepRevivers(global2 = globalThis, ops, runId, cryptoKey, deployment
257004
259074
  }
257005
259075
  return writable;
257006
259076
  }, "WritableStream"),
257007
- AbortController: /* @__PURE__ */ __name2((value) => reviveAbortController(value, ops, runId, cryptoKey), "AbortController"),
257008
- AbortSignal: /* @__PURE__ */ __name2((value) => reviveAbortSignal(value, ops, runId, cryptoKey), "AbortSignal")
259077
+ // A step's readers are cancelled when the step returns
259078
+ // (`cancelAbortReaders`), so they may outlive an empty stream.
259079
+ AbortController: /* @__PURE__ */ __name2((value) => reviveAbortController(value, ops, runId, cryptoKey, true), "AbortController"),
259080
+ AbortSignal: /* @__PURE__ */ __name2((value) => reviveAbortSignal(value, ops, runId, cryptoKey, true), "AbortSignal")
257009
259081
  };
257010
259082
  }
257011
259083
  __name(getStepRevivers, "getStepRevivers");
@@ -257377,6 +259449,7 @@ var FRAMED_STREAM_MIN_STALL_SESSION_MS;
257377
259449
  var STREAM_FLUSH_INTERVAL_MS;
257378
259450
  var getEnvStreamFlushIntervalMs;
257379
259451
  var WorkflowServerWritableStream;
259452
+ var LOCAL_ABORT_LISTEN_AFTER_STREAM_END_MS;
257380
259453
  var prepareReplayPayload;
257381
259454
  var STREAM_AND_REQUEST_KEYS;
257382
259455
  var init_serialization2 = __esm2({
@@ -257394,6 +259467,7 @@ var init_serialization2 = __esm2({
257394
259467
  init_private();
257395
259468
  init_get_world_lazy();
257396
259469
  init_sealed_box();
259470
+ init_abort_local();
257397
259471
  init_abort_stream();
257398
259472
  init_client();
257399
259473
  init_compression();
@@ -257787,6 +259861,7 @@ var init_serialization2 = __esm2({
257787
259861
  __name2(getWorkflowReducers, "getWorkflowReducers");
257788
259862
  __name2(getStepReducers, "getStepReducers");
257789
259863
  __name2(cancelAbortReaders, "cancelAbortReaders");
259864
+ LOCAL_ABORT_LISTEN_AFTER_STREAM_END_MS = 60 * 60 * 1e3;
257790
259865
  __name2(setupAbortStreamReader, "setupAbortStreamReader");
257791
259866
  __name2(tagAbortPair, "tagAbortPair");
257792
259867
  __name2(copyAbortInternals, "copyAbortInternals");
@@ -265518,7 +267593,7 @@ __name(isPermanentWorldError, "isPermanentWorldError");
265518
267593
  __name2(isPermanentWorldError, "isPermanentWorldError");
265519
267594
  function assertDynamicWorkflowsEnabled() {
265520
267595
  if (!isDynamicWorkflowsEnabled()) {
265521
- 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.`);
267596
+ throw new DynamicWorkflowsNotEnabledError("Dynamic workflows are not enabled for this project, so start() did not create a run for the given workflow source.");
265522
267597
  }
265523
267598
  }
265524
267599
  __name(assertDynamicWorkflowsEnabled, "assertDynamicWorkflowsEnabled");
@@ -266076,7 +268151,7 @@ __name2(start, "start");
266076
268151
  value: "start",
266077
268152
  configurable: true
266078
268153
  });
266079
- })(start, "step//@workflow/core/runtime/start@5.7.0//start");
268154
+ })(start, "step//@workflow/core/runtime/start@5.7.2//start");
266080
268155
  function isSingleOrchestratorRun(run22) {
266081
268156
  return (run22.specVersion ?? SPEC_VERSION_LEGACY) >= SPEC_VERSION_SINGLE_ORCHESTRATOR;
266082
268157
  }
@@ -266853,7 +268928,7 @@ var Run = class _Run {
266853
268928
  value: "readFinishedRunIds",
266854
268929
  configurable: true
266855
268930
  });
266856
- })(Run.readFinishedRunIds, "step//@workflow/core/runtime/run@5.7.0//Run.readFinishedRunIds");
268931
+ })(Run.readFinishedRunIds, "step//@workflow/core/runtime/run@5.7.2//Run.readFinishedRunIds");
266857
268932
  (function(__wf_fn, __wf_id) {
266858
268933
  var __wf_sym = /* @__PURE__ */ Symbol.for("@workflow/core//registeredSteps"), __wf_reg = globalThis[__wf_sym] || (globalThis[__wf_sym] = /* @__PURE__ */ new Map());
266859
268934
  __wf_reg.set(__wf_id, __wf_fn);
@@ -266862,7 +268937,7 @@ var Run = class _Run {
266862
268937
  value: "wakeUp",
266863
268938
  configurable: true
266864
268939
  });
266865
- })(Run.prototype["wakeUp"], "step//@workflow/core/runtime/run@5.7.0//Run#wakeUp");
268940
+ })(Run.prototype["wakeUp"], "step//@workflow/core/runtime/run@5.7.2//Run#wakeUp");
266866
268941
  (function(__wf_fn, __wf_id) {
266867
268942
  var __wf_sym = /* @__PURE__ */ Symbol.for("@workflow/core//registeredSteps"), __wf_reg = globalThis[__wf_sym] || (globalThis[__wf_sym] = /* @__PURE__ */ new Map());
266868
268943
  __wf_reg.set(__wf_id, __wf_fn);
@@ -266871,7 +268946,7 @@ var Run = class _Run {
266871
268946
  value: "cancel",
266872
268947
  configurable: true
266873
268948
  });
266874
- })(Run.prototype["cancel"], "step//@workflow/core/runtime/run@5.7.0//Run#cancel");
268949
+ })(Run.prototype["cancel"], "step//@workflow/core/runtime/run@5.7.2//Run#cancel");
266875
268950
  (function(__wf_fn, __wf_id) {
266876
268951
  var __wf_sym = /* @__PURE__ */ Symbol.for("@workflow/core//registeredSteps"), __wf_reg = globalThis[__wf_sym] || (globalThis[__wf_sym] = /* @__PURE__ */ new Map());
266877
268952
  __wf_reg.set(__wf_id, __wf_fn);
@@ -266880,7 +268955,7 @@ var Run = class _Run {
266880
268955
  value: "delete",
266881
268956
  configurable: true
266882
268957
  });
266883
- })(Run.prototype["delete"], "step//@workflow/core/runtime/run@5.7.0//Run#delete");
268958
+ })(Run.prototype["delete"], "step//@workflow/core/runtime/run@5.7.2//Run#delete");
266884
268959
  (function(__wf_fn, __wf_id) {
266885
268960
  var __wf_sym = /* @__PURE__ */ Symbol.for("@workflow/core//registeredSteps"), __wf_reg = globalThis[__wf_sym] || (globalThis[__wf_sym] = /* @__PURE__ */ new Map());
266886
268961
  __wf_reg.set(__wf_id, __wf_fn);
@@ -266889,7 +268964,7 @@ var Run = class _Run {
266889
268964
  value: "readReturnValue",
266890
268965
  configurable: true
266891
268966
  });
266892
- })(Run.prototype["readReturnValue"], "step//@workflow/core/runtime/run@5.7.0//Run#readReturnValue");
268967
+ })(Run.prototype["readReturnValue"], "step//@workflow/core/runtime/run@5.7.2//Run#readReturnValue");
266893
268968
  (function(__wf_fn, __wf_id) {
266894
268969
  var __wf_sym = /* @__PURE__ */ Symbol.for("@workflow/core//registeredSteps"), __wf_reg = globalThis[__wf_sym] || (globalThis[__wf_sym] = /* @__PURE__ */ new Map());
266895
268970
  __wf_reg.set(__wf_id, __wf_fn);
@@ -266898,7 +268973,7 @@ var Run = class _Run {
266898
268973
  value: "getReadable",
266899
268974
  configurable: true
266900
268975
  });
266901
- })(Run.prototype["getReadable"], "step//@workflow/core/runtime/run@5.7.0//Run#getReadable");
268976
+ })(Run.prototype["getReadable"], "step//@workflow/core/runtime/run@5.7.2//Run#getReadable");
266902
268977
  (function(__wf_fn, __wf_id) {
266903
268978
  var __wf_sym = /* @__PURE__ */ Symbol.for("@workflow/core//registeredSteps"), __wf_reg = globalThis[__wf_sym] || (globalThis[__wf_sym] = /* @__PURE__ */ new Map());
266904
268979
  __wf_reg.set(__wf_id, __wf_fn);
@@ -266907,7 +268982,7 @@ var Run = class _Run {
266907
268982
  value: "getWritable",
266908
268983
  configurable: true
266909
268984
  });
266910
- })(Run.prototype["getWritable"], "step//@workflow/core/runtime/run@5.7.0//Run#getWritable");
268985
+ })(Run.prototype["getWritable"], "step//@workflow/core/runtime/run@5.7.2//Run#getWritable");
266911
268986
  (function(__wf_fn, __wf_id) {
266912
268987
  var __wf_sym = /* @__PURE__ */ Symbol.for("@workflow/core//registeredSteps"), __wf_reg = globalThis[__wf_sym] || (globalThis[__wf_sym] = /* @__PURE__ */ new Map());
266913
268988
  __wf_reg.set(__wf_id, __wf_fn);
@@ -266916,7 +268991,7 @@ var Run = class _Run {
266916
268991
  value: "exists",
266917
268992
  configurable: true
266918
268993
  });
266919
- })(Object.getOwnPropertyDescriptor(Run.prototype, "exists").get, "step//@workflow/core/runtime/run@5.7.0//Run#exists");
268994
+ })(Object.getOwnPropertyDescriptor(Run.prototype, "exists").get, "step//@workflow/core/runtime/run@5.7.2//Run#exists");
266920
268995
  (function(__wf_fn, __wf_id) {
266921
268996
  var __wf_sym = /* @__PURE__ */ Symbol.for("@workflow/core//registeredSteps"), __wf_reg = globalThis[__wf_sym] || (globalThis[__wf_sym] = /* @__PURE__ */ new Map());
266922
268997
  __wf_reg.set(__wf_id, __wf_fn);
@@ -266925,7 +269000,7 @@ var Run = class _Run {
266925
269000
  value: "status",
266926
269001
  configurable: true
266927
269002
  });
266928
- })(Object.getOwnPropertyDescriptor(Run.prototype, "status").get, "step//@workflow/core/runtime/run@5.7.0//Run#status");
269003
+ })(Object.getOwnPropertyDescriptor(Run.prototype, "status").get, "step//@workflow/core/runtime/run@5.7.2//Run#status");
266929
269004
  (function(__wf_fn, __wf_id) {
266930
269005
  var __wf_sym = /* @__PURE__ */ Symbol.for("@workflow/core//registeredSteps"), __wf_reg = globalThis[__wf_sym] || (globalThis[__wf_sym] = /* @__PURE__ */ new Map());
266931
269006
  __wf_reg.set(__wf_id, __wf_fn);
@@ -266934,7 +269009,7 @@ var Run = class _Run {
266934
269009
  value: "workflowName",
266935
269010
  configurable: true
266936
269011
  });
266937
- })(Object.getOwnPropertyDescriptor(Run.prototype, "workflowName").get, "step//@workflow/core/runtime/run@5.7.0//Run#workflowName");
269012
+ })(Object.getOwnPropertyDescriptor(Run.prototype, "workflowName").get, "step//@workflow/core/runtime/run@5.7.2//Run#workflowName");
266938
269013
  (function(__wf_fn, __wf_id) {
266939
269014
  var __wf_sym = /* @__PURE__ */ Symbol.for("@workflow/core//registeredSteps"), __wf_reg = globalThis[__wf_sym] || (globalThis[__wf_sym] = /* @__PURE__ */ new Map());
266940
269015
  __wf_reg.set(__wf_id, __wf_fn);
@@ -266943,7 +269018,7 @@ var Run = class _Run {
266943
269018
  value: "createdAt",
266944
269019
  configurable: true
266945
269020
  });
266946
- })(Object.getOwnPropertyDescriptor(Run.prototype, "createdAt").get, "step//@workflow/core/runtime/run@5.7.0//Run#createdAt");
269021
+ })(Object.getOwnPropertyDescriptor(Run.prototype, "createdAt").get, "step//@workflow/core/runtime/run@5.7.2//Run#createdAt");
266947
269022
  (function(__wf_fn, __wf_id) {
266948
269023
  var __wf_sym = /* @__PURE__ */ Symbol.for("@workflow/core//registeredSteps"), __wf_reg = globalThis[__wf_sym] || (globalThis[__wf_sym] = /* @__PURE__ */ new Map());
266949
269024
  __wf_reg.set(__wf_id, __wf_fn);
@@ -266952,7 +269027,7 @@ var Run = class _Run {
266952
269027
  value: "startedAt",
266953
269028
  configurable: true
266954
269029
  });
266955
- })(Object.getOwnPropertyDescriptor(Run.prototype, "startedAt").get, "step//@workflow/core/runtime/run@5.7.0//Run#startedAt");
269030
+ })(Object.getOwnPropertyDescriptor(Run.prototype, "startedAt").get, "step//@workflow/core/runtime/run@5.7.2//Run#startedAt");
266956
269031
  (function(__wf_fn, __wf_id) {
266957
269032
  var __wf_sym = /* @__PURE__ */ Symbol.for("@workflow/core//registeredSteps"), __wf_reg = globalThis[__wf_sym] || (globalThis[__wf_sym] = /* @__PURE__ */ new Map());
266958
269033
  __wf_reg.set(__wf_id, __wf_fn);
@@ -266961,7 +269036,7 @@ var Run = class _Run {
266961
269036
  value: "completedAt",
266962
269037
  configurable: true
266963
269038
  });
266964
- })(Object.getOwnPropertyDescriptor(Run.prototype, "completedAt").get, "step//@workflow/core/runtime/run@5.7.0//Run#completedAt");
269039
+ })(Object.getOwnPropertyDescriptor(Run.prototype, "completedAt").get, "step//@workflow/core/runtime/run@5.7.2//Run#completedAt");
266965
269040
  (function(__wf_cls, __wf_id) {
266966
269041
  var __wf_sym = /* @__PURE__ */ Symbol.for("workflow-class-registry"), __wf_reg = globalThis[__wf_sym] || (globalThis[__wf_sym] = /* @__PURE__ */ new Map());
266967
269042
  __wf_reg.set(__wf_id, __wf_cls);
@@ -266971,7 +269046,7 @@ var Run = class _Run {
266971
269046
  enumerable: false,
266972
269047
  configurable: false
266973
269048
  });
266974
- })(Run, "class//@workflow/core/runtime/run@5.7.0//Run");
269049
+ })(Run, "class//@workflow/core/runtime/run@5.7.2//Run");
266975
269050
  async function fetch2(...args) {
266976
269051
  return globalThis.fetch(...args);
266977
269052
  }
@@ -269870,7 +271945,7 @@ async function runDelivery(delivery, inlineStepsInFlight, inlineRetryPublication
269870
271945
  return;
269871
271946
  }
269872
271947
  if (maxEventsLimit !== void 0) {
269873
- const workflowEventCount = eventLog.events.reduce((n, e) => isSealedNoopEvent(e) ? n : n + 1, 0);
271948
+ const workflowEventCount = eventLog.events.reduce((n, e) => isSealedNoopEvent2(e) ? n : n + 1, 0);
269874
271949
  if (workflowEventCount >= maxEventsLimit) {
269875
271950
  throw new MaxEventsExceededError(workflowEventCount, maxEventsLimit);
269876
271951
  }
@@ -269882,7 +271957,7 @@ async function runDelivery(delivery, inlineStepsInFlight, inlineRetryPublication
269882
271957
  isQuickJS: false
269883
271958
  });
269884
271959
  }
269885
- invocationStartedClean ??= eventLog.events.every((e) => e.eventType === "run_created" || e.eventType === "run_started" || e.eventType === "attr_set" || isSealedNoopEvent(e));
271960
+ invocationStartedClean ??= eventLog.events.every((e) => e.eventType === "run_created" || e.eventType === "run_started" || e.eventType === "attr_set" || isSealedNoopEvent2(e));
269886
271961
  runtimeLogger2.debug("Starting workflow execution", {
269887
271962
  workflowRunId: runId,
269888
271963
  loopIteration,
@@ -271679,6 +273754,8 @@ var WorkflowStartError = class extends WorkflowError {
271679
273754
  return isError(value) && value.name === "WorkflowStartError";
271680
273755
  }
271681
273756
  };
273757
+ var DYNAMIC_WORKFLOWS_ENV_VAR = "WORKFLOW_EXPERIMENTAL_DYNAMIC_WORKFLOWS";
273758
+ var 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.\`;
271682
273759
  var WorkflowRuntimeError = class extends WorkflowError {
271683
273760
  static {
271684
273761
  __name(this, "WorkflowRuntimeError");
@@ -272169,14 +274246,14 @@ var Run = class _Run {
272169
274246
  return this.getWritable();
272170
274247
  }
272171
274248
  };
272172
- Run.readFinishedRunIds = globalThis[/* @__PURE__ */ Symbol.for("WORKFLOW_USE_STEP")]("step//@workflow/core/runtime/run@5.7.0//Run.readFinishedRunIds");
272173
- Run.prototype["wakeUp"] = globalThis[/* @__PURE__ */ Symbol.for("WORKFLOW_USE_STEP")]("step//@workflow/core/runtime/run@5.7.0//Run#wakeUp");
272174
- Run.prototype["cancel"] = globalThis[/* @__PURE__ */ Symbol.for("WORKFLOW_USE_STEP")]("step//@workflow/core/runtime/run@5.7.0//Run#cancel");
272175
- Run.prototype["delete"] = globalThis[/* @__PURE__ */ Symbol.for("WORKFLOW_USE_STEP")]("step//@workflow/core/runtime/run@5.7.0//Run#delete");
272176
- Run.prototype["readReturnValue"] = globalThis[/* @__PURE__ */ Symbol.for("WORKFLOW_USE_STEP")]("step//@workflow/core/runtime/run@5.7.0//Run#readReturnValue");
272177
- Run.prototype["getReadable"] = globalThis[/* @__PURE__ */ Symbol.for("WORKFLOW_USE_STEP")]("step//@workflow/core/runtime/run@5.7.0//Run#getReadable");
272178
- Run.prototype["getWritable"] = globalThis[/* @__PURE__ */ Symbol.for("WORKFLOW_USE_STEP")]("step//@workflow/core/runtime/run@5.7.0//Run#getWritable");
272179
- var __step_Run$exists = globalThis[/* @__PURE__ */ Symbol.for("WORKFLOW_USE_STEP")]("step//@workflow/core/runtime/run@5.7.0//Run#exists");
274249
+ Run.readFinishedRunIds = globalThis[/* @__PURE__ */ Symbol.for("WORKFLOW_USE_STEP")]("step//@workflow/core/runtime/run@5.7.2//Run.readFinishedRunIds");
274250
+ Run.prototype["wakeUp"] = globalThis[/* @__PURE__ */ Symbol.for("WORKFLOW_USE_STEP")]("step//@workflow/core/runtime/run@5.7.2//Run#wakeUp");
274251
+ Run.prototype["cancel"] = globalThis[/* @__PURE__ */ Symbol.for("WORKFLOW_USE_STEP")]("step//@workflow/core/runtime/run@5.7.2//Run#cancel");
274252
+ Run.prototype["delete"] = globalThis[/* @__PURE__ */ Symbol.for("WORKFLOW_USE_STEP")]("step//@workflow/core/runtime/run@5.7.2//Run#delete");
274253
+ Run.prototype["readReturnValue"] = globalThis[/* @__PURE__ */ Symbol.for("WORKFLOW_USE_STEP")]("step//@workflow/core/runtime/run@5.7.2//Run#readReturnValue");
274254
+ Run.prototype["getReadable"] = globalThis[/* @__PURE__ */ Symbol.for("WORKFLOW_USE_STEP")]("step//@workflow/core/runtime/run@5.7.2//Run#getReadable");
274255
+ Run.prototype["getWritable"] = globalThis[/* @__PURE__ */ Symbol.for("WORKFLOW_USE_STEP")]("step//@workflow/core/runtime/run@5.7.2//Run#getWritable");
274256
+ var __step_Run$exists = globalThis[/* @__PURE__ */ Symbol.for("WORKFLOW_USE_STEP")]("step//@workflow/core/runtime/run@5.7.2//Run#exists");
272180
274257
  Object.defineProperty(Run.prototype, "exists", {
272181
274258
  get() {
272182
274259
  return __step_Run$exists.call(this);
@@ -272184,7 +274261,7 @@ Object.defineProperty(Run.prototype, "exists", {
272184
274261
  configurable: true,
272185
274262
  enumerable: false
272186
274263
  });
272187
- var __step_Run$status = globalThis[/* @__PURE__ */ Symbol.for("WORKFLOW_USE_STEP")]("step//@workflow/core/runtime/run@5.7.0//Run#status");
274264
+ var __step_Run$status = globalThis[/* @__PURE__ */ Symbol.for("WORKFLOW_USE_STEP")]("step//@workflow/core/runtime/run@5.7.2//Run#status");
272188
274265
  Object.defineProperty(Run.prototype, "status", {
272189
274266
  get() {
272190
274267
  return __step_Run$status.call(this);
@@ -272192,7 +274269,7 @@ Object.defineProperty(Run.prototype, "status", {
272192
274269
  configurable: true,
272193
274270
  enumerable: false
272194
274271
  });
272195
- var __step_Run$workflowName = globalThis[/* @__PURE__ */ Symbol.for("WORKFLOW_USE_STEP")]("step//@workflow/core/runtime/run@5.7.0//Run#workflowName");
274272
+ var __step_Run$workflowName = globalThis[/* @__PURE__ */ Symbol.for("WORKFLOW_USE_STEP")]("step//@workflow/core/runtime/run@5.7.2//Run#workflowName");
272196
274273
  Object.defineProperty(Run.prototype, "workflowName", {
272197
274274
  get() {
272198
274275
  return __step_Run$workflowName.call(this);
@@ -272200,7 +274277,7 @@ Object.defineProperty(Run.prototype, "workflowName", {
272200
274277
  configurable: true,
272201
274278
  enumerable: false
272202
274279
  });
272203
- var __step_Run$createdAt = globalThis[/* @__PURE__ */ Symbol.for("WORKFLOW_USE_STEP")]("step//@workflow/core/runtime/run@5.7.0//Run#createdAt");
274280
+ var __step_Run$createdAt = globalThis[/* @__PURE__ */ Symbol.for("WORKFLOW_USE_STEP")]("step//@workflow/core/runtime/run@5.7.2//Run#createdAt");
272204
274281
  Object.defineProperty(Run.prototype, "createdAt", {
272205
274282
  get() {
272206
274283
  return __step_Run$createdAt.call(this);
@@ -272208,7 +274285,7 @@ Object.defineProperty(Run.prototype, "createdAt", {
272208
274285
  configurable: true,
272209
274286
  enumerable: false
272210
274287
  });
272211
- var __step_Run$startedAt = globalThis[/* @__PURE__ */ Symbol.for("WORKFLOW_USE_STEP")]("step//@workflow/core/runtime/run@5.7.0//Run#startedAt");
274288
+ var __step_Run$startedAt = globalThis[/* @__PURE__ */ Symbol.for("WORKFLOW_USE_STEP")]("step//@workflow/core/runtime/run@5.7.2//Run#startedAt");
272212
274289
  Object.defineProperty(Run.prototype, "startedAt", {
272213
274290
  get() {
272214
274291
  return __step_Run$startedAt.call(this);
@@ -272216,7 +274293,7 @@ Object.defineProperty(Run.prototype, "startedAt", {
272216
274293
  configurable: true,
272217
274294
  enumerable: false
272218
274295
  });
272219
- var __step_Run$completedAt = globalThis[/* @__PURE__ */ Symbol.for("WORKFLOW_USE_STEP")]("step//@workflow/core/runtime/run@5.7.0//Run#completedAt");
274296
+ var __step_Run$completedAt = globalThis[/* @__PURE__ */ Symbol.for("WORKFLOW_USE_STEP")]("step//@workflow/core/runtime/run@5.7.2//Run#completedAt");
272220
274297
  Object.defineProperty(Run.prototype, "completedAt", {
272221
274298
  get() {
272222
274299
  return __step_Run$completedAt.call(this);
@@ -272233,7 +274310,7 @@ Object.defineProperty(Run.prototype, "completedAt", {
272233
274310
  enumerable: false,
272234
274311
  configurable: false
272235
274312
  });
272236
- })(Run, "class//@workflow/core/runtime/run@5.7.0//Run");
274313
+ })(Run, "class//@workflow/core/runtime/run@5.7.2//Run");
272237
274314
 
272238
274315
  // ../core/dist/workflow/create-hook.js
272239
274316
  aliasSerializationClass(RUN_CLASS_ID, Run);
@@ -295729,7 +297806,7 @@ var latestNoOpWarning = globalSingleton("@workflow/core//latestNoOpWarning", 1,
295729
297806
  var probeMissWarning = globalSingleton("@workflow/core//crossDeploymentProbeMissWarning", 1, () => ({
295730
297807
  warned: false
295731
297808
  }));
295732
- var start = globalThis[/* @__PURE__ */ Symbol.for("WORKFLOW_USE_STEP")]("step//@workflow/core/runtime/start@5.7.0//start");
297809
+ var start = globalThis[/* @__PURE__ */ Symbol.for("WORKFLOW_USE_STEP")]("step//@workflow/core/runtime/start@5.7.2//start");
295733
297810
 
295734
297811
  // workflows/lineage.ts
295735
297812
  var noop = globalThis[/* @__PURE__ */ Symbol.for("WORKFLOW_USE_STEP")]("step//./workflows/lineage//noop");