@workflow/world-testing 5.0.0-beta.25 → 5.0.0-beta.26

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.
@@ -350,11 +350,11 @@ var init_dist5 = __esm({
350
350
  });
351
351
 
352
352
  // ../errors/dist/error-codes.js
353
- var RUN_ERROR_CODES;
353
+ var RUN_ERROR_CODES2;
354
354
  var init_error_codes2 = __esm({
355
355
  "../errors/dist/error-codes.js"() {
356
356
  "use strict";
357
- RUN_ERROR_CODES = {
357
+ RUN_ERROR_CODES2 = {
358
358
  /** Error thrown in user workflow or step code */
359
359
  USER_ERROR: "USER_ERROR",
360
360
  /** Internal runtime error (missing timestamps, runtime invariant failures) */
@@ -398,7 +398,7 @@ function buildFramedDetails2(hint3, slug) {
398
398
  out.push({ label: "docs", value: `${BASE_URL2}/${slug}` });
399
399
  return out;
400
400
  }
401
- var BASE_URL2, ERROR_SLUGS2, WorkflowError2, WorkflowWorldError2, WorkflowRunFailedError2, WorkflowRunNotCompletedError2, WorkflowRuntimeError2, CorruptedEventLogError, ReplayDivergenceError, RuntimeDecryptionError2, SerializationError2, StepNotRegisteredError, WorkflowNotRegisteredError, WorkflowRunNotFoundError2, HookConflictError2, HookNotFoundError2, EntityConflictError2, RunExpiredError, TooEarlyError, ThrottleError2, WorkflowRunCancelledError2, RunNotSupportedError, FatalError2, RetryableError2, FATAL_ERROR_KEY2, RETRYABLE_ERROR_KEY2, HOOK_CONFLICT_ERROR_KEY2, RUNTIME_DECRYPTION_ERROR_KEY2;
401
+ var BASE_URL2, ERROR_SLUGS2, WorkflowError2, WorkflowWorldError2, WorkflowRunFailedError2, WorkflowRunNotCompletedError2, WorkflowRuntimeError2, CorruptedEventLogError, ReplayDivergenceError, RuntimeDecryptionError2, SerializationError2, StepNotRegisteredError2, WorkflowNotRegisteredError2, WorkflowRunNotFoundError2, HookConflictError2, HookNotFoundError2, EntityConflictError2, RunExpiredError, TooEarlyError, ThrottleError2, WorkflowRunCancelledError2, RunNotSupportedError, FatalError2, RetryableError2, FATAL_ERROR_KEY2, RETRYABLE_ERROR_KEY2, HOOK_CONFLICT_ERROR_KEY2, RUNTIME_DECRYPTION_ERROR_KEY2;
402
402
  var init_dist6 = __esm({
403
403
  "../errors/dist/index.js"() {
404
404
  "use strict";
@@ -597,7 +597,7 @@ Caused by: ${options.cause.stack}`;
597
597
  return isError2(value) && value.name === "SerializationError";
598
598
  }
599
599
  };
600
- StepNotRegisteredError = class extends WorkflowRuntimeError2 {
600
+ StepNotRegisteredError2 = class extends WorkflowRuntimeError2 {
601
601
  static {
602
602
  __name(this, "StepNotRegisteredError");
603
603
  }
@@ -611,7 +611,7 @@ Caused by: ${options.cause.stack}`;
611
611
  return isError2(value) && value.name === "StepNotRegisteredError";
612
612
  }
613
613
  };
614
- WorkflowNotRegisteredError = class extends WorkflowRuntimeError2 {
614
+ WorkflowNotRegisteredError2 = class extends WorkflowRuntimeError2 {
615
615
  static {
616
616
  __name(this, "WorkflowNotRegisteredError");
617
617
  }
@@ -19204,7 +19204,7 @@ var version4;
19204
19204
  var init_version3 = __esm({
19205
19205
  "../core/dist/version.js"() {
19206
19206
  "use strict";
19207
- version4 = "5.0.0-beta.25";
19207
+ version4 = "5.0.0-beta.26";
19208
19208
  }
19209
19209
  });
19210
19210
 
@@ -19272,7 +19272,7 @@ async function handleHealthCheckMessage(healthCheck3, endpoint, worldSpecVersion
19272
19272
  await world.streams.close(fakeRunId, streamName);
19273
19273
  }
19274
19274
  function eventPaginationContractError(runId, message) {
19275
- return new WorkflowWorldError2(`Event pagination ${message} for workflow run "${runId}".`, { code: RUN_ERROR_CODES.WORLD_CONTRACT_ERROR });
19275
+ return new WorkflowWorldError2(`Event pagination ${message} for workflow run "${runId}".`, { code: RUN_ERROR_CODES2.WORLD_CONTRACT_ERROR });
19276
19276
  }
19277
19277
  function recordRequestedEventCursor(runId, cursor, requestedCursors) {
19278
19278
  if (!cursor) {
@@ -53063,7 +53063,7 @@ var require_token_util = __commonJS({
53063
53063
  findProjectInfo: /* @__PURE__ */ __name(() => findProjectInfo, "findProjectInfo"),
53064
53064
  getTokenPayload: /* @__PURE__ */ __name(() => getTokenPayload, "getTokenPayload"),
53065
53065
  getVercelDataDir: /* @__PURE__ */ __name(() => getVercelDataDir, "getVercelDataDir"),
53066
- getVercelOidcToken: /* @__PURE__ */ __name(() => getVercelOidcToken6, "getVercelOidcToken"),
53066
+ getVercelOidcToken: /* @__PURE__ */ __name(() => getVercelOidcToken5, "getVercelOidcToken"),
53067
53067
  getVercelToken: /* @__PURE__ */ __name(() => getVercelToken2, "getVercelToken"),
53068
53068
  isExpired: /* @__PURE__ */ __name(() => isExpired, "isExpired"),
53069
53069
  loadToken: /* @__PURE__ */ __name(() => loadToken, "loadToken"),
@@ -53125,7 +53125,7 @@ var require_token_util = __commonJS({
53125
53125
  }
53126
53126
  }
53127
53127
  __name(getVercelToken2, "getVercelToken");
53128
- async function getVercelOidcToken6(authToken, projectId, teamId) {
53128
+ async function getVercelOidcToken5(authToken, projectId, teamId) {
53129
53129
  const url3 = `https://api.vercel.com/v1/projects/${projectId}/token?source=vercel-oidc-refresh${teamId ? `&teamId=${teamId}` : ""}`;
53130
53130
  const res = await fetch(url3, {
53131
53131
  method: "POST",
@@ -53142,7 +53142,7 @@ var require_token_util = __commonJS({
53142
53142
  assertVercelOidcTokenResponse(tokenRes);
53143
53143
  return tokenRes;
53144
53144
  }
53145
- __name(getVercelOidcToken6, "getVercelOidcToken");
53145
+ __name(getVercelOidcToken5, "getVercelOidcToken");
53146
53146
  function assertVercelOidcTokenResponse(res) {
53147
53147
  if (!res || typeof res !== "object") {
53148
53148
  throw new TypeError(
@@ -53317,13 +53317,13 @@ var require_get_vercel_oidc_token = __commonJS({
53317
53317
  var __toCommonJS = /* @__PURE__ */ __name((mod) => __copyProps3(__defProp3({}, "__esModule", { value: true }), mod), "__toCommonJS");
53318
53318
  var get_vercel_oidc_token_exports = {};
53319
53319
  __export3(get_vercel_oidc_token_exports, {
53320
- getVercelOidcToken: /* @__PURE__ */ __name(() => getVercelOidcToken6, "getVercelOidcToken"),
53320
+ getVercelOidcToken: /* @__PURE__ */ __name(() => getVercelOidcToken5, "getVercelOidcToken"),
53321
53321
  getVercelOidcTokenSync: /* @__PURE__ */ __name(() => getVercelOidcTokenSync2, "getVercelOidcTokenSync")
53322
53322
  });
53323
53323
  module.exports = __toCommonJS(get_vercel_oidc_token_exports);
53324
53324
  var import_get_context = require_get_context3();
53325
53325
  var import_token_error = require_token_error();
53326
- async function getVercelOidcToken6(options) {
53326
+ async function getVercelOidcToken5(options) {
53327
53327
  let token = "";
53328
53328
  let err;
53329
53329
  try {
@@ -53353,7 +53353,7 @@ ${error95.message}`;
53353
53353
  }
53354
53354
  return token;
53355
53355
  }
53356
- __name(getVercelOidcToken6, "getVercelOidcToken");
53356
+ __name(getVercelOidcToken5, "getVercelOidcToken");
53357
53357
  function getVercelOidcTokenSync2() {
53358
53358
  const token = (0, import_get_context.getContext)().headers?.["x-vercel-oidc-token"] ?? process.env.VERCEL_OIDC_TOKEN;
53359
53359
  if (!token) {
@@ -55095,9 +55095,26 @@ var init_dist = __esm2({
55095
55095
  init_world_target();
55096
55096
  }
55097
55097
  });
55098
+ var RUN_ERROR_CODES;
55098
55099
  var init_error_codes = __esm2({
55099
55100
  "../errors/dist/error-codes.js"() {
55100
55101
  "use strict";
55102
+ RUN_ERROR_CODES = {
55103
+ /** Error thrown in user workflow or step code */
55104
+ USER_ERROR: "USER_ERROR",
55105
+ /** Internal runtime error (missing timestamps, runtime invariant failures) */
55106
+ RUNTIME_ERROR: "RUNTIME_ERROR",
55107
+ /** Event log contains orphaned or mismatched events and cannot be replayed */
55108
+ CORRUPTED_EVENT_LOG: "CORRUPTED_EVENT_LOG",
55109
+ /** One replay could not consume the event log deterministically; retryable */
55110
+ REPLAY_DIVERGENCE: "REPLAY_DIVERGENCE",
55111
+ /** Run exceeded the maximum number of queue deliveries */
55112
+ MAX_DELIVERIES_EXCEEDED: "MAX_DELIVERIES_EXCEEDED",
55113
+ /** Workflow replay exceeded the maximum allowed duration */
55114
+ REPLAY_TIMEOUT: "REPLAY_TIMEOUT",
55115
+ /** World response violated the SDK contract and cannot be retried safely */
55116
+ WORLD_CONTRACT_ERROR: "WORLD_CONTRACT_ERROR"
55117
+ };
55101
55118
  }
55102
55119
  });
55103
55120
  function isError(value) {
@@ -55141,6 +55158,8 @@ var WorkflowRunNotCompletedError;
55141
55158
  var WorkflowRuntimeError;
55142
55159
  var RuntimeDecryptionError;
55143
55160
  var SerializationError;
55161
+ var StepNotRegisteredError;
55162
+ var WorkflowNotRegisteredError;
55144
55163
  var WorkflowRunNotFoundError;
55145
55164
  var HookConflictError;
55146
55165
  var HookNotFoundError;
@@ -55344,6 +55363,44 @@ Caused by: ${options.cause.stack}`;
55344
55363
  return isError(value) && value.name === "SerializationError";
55345
55364
  }
55346
55365
  };
55366
+ StepNotRegisteredError = class extends WorkflowRuntimeError {
55367
+ static {
55368
+ __name(this, "StepNotRegisteredError");
55369
+ }
55370
+ static {
55371
+ __name2(this, "StepNotRegisteredError");
55372
+ }
55373
+ stepName;
55374
+ constructor(stepName) {
55375
+ super(`Step "${stepName}" is not registered in the current deployment. This usually indicates a build or bundling issue that caused the step to not be included in the deployment.`, {
55376
+ slug: ERROR_SLUGS.STEP_NOT_REGISTERED
55377
+ });
55378
+ this.name = "StepNotRegisteredError";
55379
+ this.stepName = stepName;
55380
+ }
55381
+ static is(value) {
55382
+ return isError(value) && value.name === "StepNotRegisteredError";
55383
+ }
55384
+ };
55385
+ WorkflowNotRegisteredError = class extends WorkflowRuntimeError {
55386
+ static {
55387
+ __name(this, "WorkflowNotRegisteredError");
55388
+ }
55389
+ static {
55390
+ __name2(this, "WorkflowNotRegisteredError");
55391
+ }
55392
+ workflowName;
55393
+ constructor(workflowName) {
55394
+ super(`Workflow "${workflowName}" is not registered in the current deployment. This usually means a run was started against a deployment that does not have this workflow, or there was a build/bundling issue.`, {
55395
+ slug: ERROR_SLUGS.WORKFLOW_NOT_REGISTERED
55396
+ });
55397
+ this.name = "WorkflowNotRegisteredError";
55398
+ this.workflowName = workflowName;
55399
+ }
55400
+ static is(value) {
55401
+ return isError(value) && value.name === "WorkflowNotRegisteredError";
55402
+ }
55403
+ };
55347
55404
  WorkflowRunNotFoundError = class extends WorkflowError {
55348
55405
  static {
55349
55406
  __name(this, "WorkflowRunNotFoundError");
@@ -79607,7 +79664,7 @@ var version2;
79607
79664
  var init_version = __esm2({
79608
79665
  "../core/dist/version.js"() {
79609
79666
  "use strict";
79610
- version2 = "5.0.0-beta.25";
79667
+ version2 = "5.0.0-beta.26";
79611
79668
  }
79612
79669
  });
79613
79670
  function getWorkflowQueueName(workflowName, namespace) {
@@ -82668,6 +82725,40 @@ function normalizeAttributeChanges(attrs, options = {}) {
82668
82725
  __name(normalizeAttributeChanges, "normalizeAttributeChanges");
82669
82726
  __name2(normalizeAttributeChanges, "normalizeAttributeChanges");
82670
82727
  init_capabilities();
82728
+ init_dist2();
82729
+ var WORLD_CONTRACT_ERROR_CODES = /* @__PURE__ */ new Set([
82730
+ "PARSE_ERROR",
82731
+ "SCHEMA_VALIDATION",
82732
+ RUN_ERROR_CODES.WORLD_CONTRACT_ERROR
82733
+ ]);
82734
+ var RETRYABLE_WORLD_ERROR_CODES = /* @__PURE__ */ new Set([
82735
+ "TRANSPORT",
82736
+ "TIMEOUT"
82737
+ ]);
82738
+ var RUNTIME_ERROR_CHECKS = [
82739
+ WorkflowRuntimeError.is,
82740
+ StepNotRegisteredError.is,
82741
+ WorkflowNotRegisteredError.is,
82742
+ // SDK-level encryption failures (most notably AES-GCM auth-tag
82743
+ // mismatches surfacing as a native `OperationError` from
82744
+ // `AESCipherJob.onDone`) are wrapped in `RuntimeDecryptionError` at
82745
+ // the encryption module boundary.
82746
+ RuntimeDecryptionError.is
82747
+ ];
82748
+ function isRetryableWorldError(err) {
82749
+ if (ThrottleError.is(err)) {
82750
+ return true;
82751
+ }
82752
+ if (!WorkflowWorldError.is(err)) {
82753
+ return false;
82754
+ }
82755
+ if (err.status !== void 0 && err.status >= 500) {
82756
+ return true;
82757
+ }
82758
+ return err.code !== void 0 && RETRYABLE_WORLD_ERROR_CODES.has(err.code);
82759
+ }
82760
+ __name(isRetryableWorldError, "isRetryableWorldError");
82761
+ __name2(isRetryableWorldError, "isRetryableWorldError");
82671
82762
  init_encryption();
82672
82763
  init_logger();
82673
82764
  init_serialization2();
@@ -82820,7 +82911,7 @@ async function start(workflow, argsOrOptions, options) {
82820
82911
  if (runCreatedResult.status === "rejected") {
82821
82912
  const err = runCreatedResult.reason;
82822
82913
  if (EntityConflictError.is(err)) {
82823
- } else if (isRetryableStartError(err)) {
82914
+ } else if (isRetryableWorldError(err)) {
82824
82915
  resilientStart = true;
82825
82916
  runtimeLogger.warn("Run creation event failed, but the run was accepted via the queue. The run_created event will be re-tried async by the runtime.", {
82826
82917
  workflowRunId: runId,
@@ -82865,14 +82956,7 @@ __name2(start, "start");
82865
82956
  value: "start",
82866
82957
  configurable: true
82867
82958
  });
82868
- })(start, "step//@workflow/core/runtime/start@5.0.0-beta.25//start");
82869
- function isRetryableStartError(err) {
82870
- if (ThrottleError.is(err)) return true;
82871
- if (WorkflowWorldError.is(err) && err.status && err.status >= 500) return true;
82872
- return false;
82873
- }
82874
- __name(isRetryableStartError, "isRetryableStartError");
82875
- __name2(isRetryableStartError, "isRetryableStartError");
82959
+ })(start, "step//@workflow/core/runtime/start@5.0.0-beta.26//start");
82876
82960
  async function wakeUpRun(world, runId, options) {
82877
82961
  try {
82878
82962
  const run22 = await world.runs.get(runId, {
@@ -83199,7 +83283,7 @@ var Run = class _Run {
83199
83283
  value: "wakeUp",
83200
83284
  configurable: true
83201
83285
  });
83202
- })(Run.prototype["wakeUp"], "step//@workflow/core/runtime/run@5.0.0-beta.25//Run#wakeUp");
83286
+ })(Run.prototype["wakeUp"], "step//@workflow/core/runtime/run@5.0.0-beta.26//Run#wakeUp");
83203
83287
  (function(__wf_fn, __wf_id) {
83204
83288
  var __wf_sym = /* @__PURE__ */ Symbol.for("@workflow/core//registeredSteps"), __wf_reg = globalThis[__wf_sym] || (globalThis[__wf_sym] = /* @__PURE__ */ new Map());
83205
83289
  __wf_reg.set(__wf_id, __wf_fn);
@@ -83208,7 +83292,7 @@ var Run = class _Run {
83208
83292
  value: "cancel",
83209
83293
  configurable: true
83210
83294
  });
83211
- })(Run.prototype["cancel"], "step//@workflow/core/runtime/run@5.0.0-beta.25//Run#cancel");
83295
+ })(Run.prototype["cancel"], "step//@workflow/core/runtime/run@5.0.0-beta.26//Run#cancel");
83212
83296
  (function(__wf_fn, __wf_id) {
83213
83297
  var __wf_sym = /* @__PURE__ */ Symbol.for("@workflow/core//registeredSteps"), __wf_reg = globalThis[__wf_sym] || (globalThis[__wf_sym] = /* @__PURE__ */ new Map());
83214
83298
  __wf_reg.set(__wf_id, __wf_fn);
@@ -83217,7 +83301,7 @@ var Run = class _Run {
83217
83301
  value: "getReadable",
83218
83302
  configurable: true
83219
83303
  });
83220
- })(Run.prototype["getReadable"], "step//@workflow/core/runtime/run@5.0.0-beta.25//Run#getReadable");
83304
+ })(Run.prototype["getReadable"], "step//@workflow/core/runtime/run@5.0.0-beta.26//Run#getReadable");
83221
83305
  (function(__wf_fn, __wf_id) {
83222
83306
  var __wf_sym = /* @__PURE__ */ Symbol.for("@workflow/core//registeredSteps"), __wf_reg = globalThis[__wf_sym] || (globalThis[__wf_sym] = /* @__PURE__ */ new Map());
83223
83307
  __wf_reg.set(__wf_id, __wf_fn);
@@ -83226,7 +83310,7 @@ var Run = class _Run {
83226
83310
  value: "exists",
83227
83311
  configurable: true
83228
83312
  });
83229
- })(Object.getOwnPropertyDescriptor(Run.prototype, "exists").get, "step//@workflow/core/runtime/run@5.0.0-beta.25//Run#exists");
83313
+ })(Object.getOwnPropertyDescriptor(Run.prototype, "exists").get, "step//@workflow/core/runtime/run@5.0.0-beta.26//Run#exists");
83230
83314
  (function(__wf_fn, __wf_id) {
83231
83315
  var __wf_sym = /* @__PURE__ */ Symbol.for("@workflow/core//registeredSteps"), __wf_reg = globalThis[__wf_sym] || (globalThis[__wf_sym] = /* @__PURE__ */ new Map());
83232
83316
  __wf_reg.set(__wf_id, __wf_fn);
@@ -83235,7 +83319,7 @@ var Run = class _Run {
83235
83319
  value: "status",
83236
83320
  configurable: true
83237
83321
  });
83238
- })(Object.getOwnPropertyDescriptor(Run.prototype, "status").get, "step//@workflow/core/runtime/run@5.0.0-beta.25//Run#status");
83322
+ })(Object.getOwnPropertyDescriptor(Run.prototype, "status").get, "step//@workflow/core/runtime/run@5.0.0-beta.26//Run#status");
83239
83323
  (function(__wf_fn, __wf_id) {
83240
83324
  var __wf_sym = /* @__PURE__ */ Symbol.for("@workflow/core//registeredSteps"), __wf_reg = globalThis[__wf_sym] || (globalThis[__wf_sym] = /* @__PURE__ */ new Map());
83241
83325
  __wf_reg.set(__wf_id, __wf_fn);
@@ -83244,7 +83328,7 @@ var Run = class _Run {
83244
83328
  value: "returnValue",
83245
83329
  configurable: true
83246
83330
  });
83247
- })(Object.getOwnPropertyDescriptor(Run.prototype, "returnValue").get, "step//@workflow/core/runtime/run@5.0.0-beta.25//Run#returnValue");
83331
+ })(Object.getOwnPropertyDescriptor(Run.prototype, "returnValue").get, "step//@workflow/core/runtime/run@5.0.0-beta.26//Run#returnValue");
83248
83332
  (function(__wf_fn, __wf_id) {
83249
83333
  var __wf_sym = /* @__PURE__ */ Symbol.for("@workflow/core//registeredSteps"), __wf_reg = globalThis[__wf_sym] || (globalThis[__wf_sym] = /* @__PURE__ */ new Map());
83250
83334
  __wf_reg.set(__wf_id, __wf_fn);
@@ -83253,7 +83337,7 @@ var Run = class _Run {
83253
83337
  value: "workflowName",
83254
83338
  configurable: true
83255
83339
  });
83256
- })(Object.getOwnPropertyDescriptor(Run.prototype, "workflowName").get, "step//@workflow/core/runtime/run@5.0.0-beta.25//Run#workflowName");
83340
+ })(Object.getOwnPropertyDescriptor(Run.prototype, "workflowName").get, "step//@workflow/core/runtime/run@5.0.0-beta.26//Run#workflowName");
83257
83341
  (function(__wf_fn, __wf_id) {
83258
83342
  var __wf_sym = /* @__PURE__ */ Symbol.for("@workflow/core//registeredSteps"), __wf_reg = globalThis[__wf_sym] || (globalThis[__wf_sym] = /* @__PURE__ */ new Map());
83259
83343
  __wf_reg.set(__wf_id, __wf_fn);
@@ -83262,7 +83346,7 @@ var Run = class _Run {
83262
83346
  value: "createdAt",
83263
83347
  configurable: true
83264
83348
  });
83265
- })(Object.getOwnPropertyDescriptor(Run.prototype, "createdAt").get, "step//@workflow/core/runtime/run@5.0.0-beta.25//Run#createdAt");
83349
+ })(Object.getOwnPropertyDescriptor(Run.prototype, "createdAt").get, "step//@workflow/core/runtime/run@5.0.0-beta.26//Run#createdAt");
83266
83350
  (function(__wf_fn, __wf_id) {
83267
83351
  var __wf_sym = /* @__PURE__ */ Symbol.for("@workflow/core//registeredSteps"), __wf_reg = globalThis[__wf_sym] || (globalThis[__wf_sym] = /* @__PURE__ */ new Map());
83268
83352
  __wf_reg.set(__wf_id, __wf_fn);
@@ -83271,7 +83355,7 @@ var Run = class _Run {
83271
83355
  value: "startedAt",
83272
83356
  configurable: true
83273
83357
  });
83274
- })(Object.getOwnPropertyDescriptor(Run.prototype, "startedAt").get, "step//@workflow/core/runtime/run@5.0.0-beta.25//Run#startedAt");
83358
+ })(Object.getOwnPropertyDescriptor(Run.prototype, "startedAt").get, "step//@workflow/core/runtime/run@5.0.0-beta.26//Run#startedAt");
83275
83359
  (function(__wf_fn, __wf_id) {
83276
83360
  var __wf_sym = /* @__PURE__ */ Symbol.for("@workflow/core//registeredSteps"), __wf_reg = globalThis[__wf_sym] || (globalThis[__wf_sym] = /* @__PURE__ */ new Map());
83277
83361
  __wf_reg.set(__wf_id, __wf_fn);
@@ -83280,7 +83364,7 @@ var Run = class _Run {
83280
83364
  value: "completedAt",
83281
83365
  configurable: true
83282
83366
  });
83283
- })(Object.getOwnPropertyDescriptor(Run.prototype, "completedAt").get, "step//@workflow/core/runtime/run@5.0.0-beta.25//Run#completedAt");
83367
+ })(Object.getOwnPropertyDescriptor(Run.prototype, "completedAt").get, "step//@workflow/core/runtime/run@5.0.0-beta.26//Run#completedAt");
83284
83368
  (function(__wf_cls, __wf_id) {
83285
83369
  var __wf_sym = /* @__PURE__ */ Symbol.for("workflow-class-registry"), __wf_reg = globalThis[__wf_sym] || (globalThis[__wf_sym] = /* @__PURE__ */ new Map());
83286
83370
  __wf_reg.set(__wf_id, __wf_cls);
@@ -83290,7 +83374,7 @@ var Run = class _Run {
83290
83374
  enumerable: false,
83291
83375
  configurable: false
83292
83376
  });
83293
- })(Run, "class//@workflow/core/runtime/run@5.0.0-beta.25//Run");
83377
+ })(Run, "class//@workflow/core/runtime/run@5.0.0-beta.26//Run");
83294
83378
  async function fetch2(...args) {
83295
83379
  return globalThis.fetch(...args);
83296
83380
  }
@@ -83752,15 +83836,16 @@ import { types as types6 } from "node:util";
83752
83836
 
83753
83837
  // ../core/dist/classify-error.js
83754
83838
  init_dist6();
83755
- var WORLD_CONTRACT_ERROR_CODES = /* @__PURE__ */ new Set([
83839
+ var WORLD_CONTRACT_ERROR_CODES2 = /* @__PURE__ */ new Set([
83756
83840
  "PARSE_ERROR",
83757
83841
  "SCHEMA_VALIDATION",
83758
- RUN_ERROR_CODES.WORLD_CONTRACT_ERROR
83842
+ RUN_ERROR_CODES2.WORLD_CONTRACT_ERROR
83759
83843
  ]);
83760
- var RUNTIME_ERROR_CHECKS = [
83844
+ var RETRYABLE_WORLD_ERROR_CODES2 = /* @__PURE__ */ new Set(["TRANSPORT", "TIMEOUT"]);
83845
+ var RUNTIME_ERROR_CHECKS2 = [
83761
83846
  WorkflowRuntimeError2.is,
83762
- StepNotRegisteredError.is,
83763
- WorkflowNotRegisteredError.is,
83847
+ StepNotRegisteredError2.is,
83848
+ WorkflowNotRegisteredError2.is,
83764
83849
  // SDK-level encryption failures (most notably AES-GCM auth-tag
83765
83850
  // mismatches surfacing as a native `OperationError` from
83766
83851
  // `AESCipherJob.onDone`) are wrapped in `RuntimeDecryptionError` at
@@ -83772,25 +83857,38 @@ function isWorldContractError(err) {
83772
83857
  return false;
83773
83858
  }
83774
83859
  const cause = "cause" in err ? err.cause : void 0;
83775
- return err.code !== void 0 && WORLD_CONTRACT_ERROR_CODES.has(err.code) || err.message.startsWith("Failed to parse response body for ") || err.message.startsWith("Schema validation failed for ") || typeof cause === "object" && cause !== null && "name" in cause && cause.name === "ZodError";
83860
+ return err.code !== void 0 && WORLD_CONTRACT_ERROR_CODES2.has(err.code) || err.message.startsWith("Failed to parse response body for ") || err.message.startsWith("Schema validation failed for ") || typeof cause === "object" && cause !== null && "name" in cause && cause.name === "ZodError";
83776
83861
  }
83777
83862
  __name(isWorldContractError, "isWorldContractError");
83863
+ function isRetryableWorldError2(err) {
83864
+ if (ThrottleError2.is(err)) {
83865
+ return true;
83866
+ }
83867
+ if (!WorkflowWorldError2.is(err)) {
83868
+ return false;
83869
+ }
83870
+ if (err.status !== void 0 && err.status >= 500) {
83871
+ return true;
83872
+ }
83873
+ return err.code !== void 0 && RETRYABLE_WORLD_ERROR_CODES2.has(err.code);
83874
+ }
83875
+ __name(isRetryableWorldError2, "isRetryableWorldError");
83778
83876
  function classifyRunError(err) {
83779
83877
  if (ReplayDivergenceError.is(err)) {
83780
- return RUN_ERROR_CODES.REPLAY_DIVERGENCE;
83878
+ return RUN_ERROR_CODES2.REPLAY_DIVERGENCE;
83781
83879
  }
83782
83880
  if (CorruptedEventLogError.is(err)) {
83783
- return RUN_ERROR_CODES.CORRUPTED_EVENT_LOG;
83881
+ return RUN_ERROR_CODES2.CORRUPTED_EVENT_LOG;
83784
83882
  }
83785
- if (isWorldContractError(err)) {
83786
- return RUN_ERROR_CODES.WORLD_CONTRACT_ERROR;
83883
+ if (isWorldContractError(err) || isRetryableWorldError2(err)) {
83884
+ return RUN_ERROR_CODES2.WORLD_CONTRACT_ERROR;
83787
83885
  }
83788
- for (const isMatch of RUNTIME_ERROR_CHECKS) {
83886
+ for (const isMatch of RUNTIME_ERROR_CHECKS2) {
83789
83887
  if (isMatch(err)) {
83790
- return RUN_ERROR_CODES.RUNTIME_ERROR;
83888
+ return RUN_ERROR_CODES2.RUNTIME_ERROR;
83791
83889
  }
83792
83890
  }
83793
- return RUN_ERROR_CODES.USER_ERROR;
83891
+ return RUN_ERROR_CODES2.USER_ERROR;
83794
83892
  }
83795
83893
  __name(classifyRunError, "classifyRunError");
83796
83894
 
@@ -84014,28 +84112,28 @@ function describeError(err, errorCode) {
84014
84112
  hint: RUNTIME_ERROR_HINT
84015
84113
  };
84016
84114
  }
84017
- if (effectiveCode === RUN_ERROR_CODES.REPLAY_TIMEOUT) {
84115
+ if (effectiveCode === RUN_ERROR_CODES2.REPLAY_TIMEOUT) {
84018
84116
  return {
84019
84117
  attribution: "sdk",
84020
84118
  errorCode: effectiveCode,
84021
84119
  hint: REPLAY_TIMEOUT_HINT
84022
84120
  };
84023
84121
  }
84024
- if (effectiveCode === RUN_ERROR_CODES.MAX_DELIVERIES_EXCEEDED) {
84122
+ if (effectiveCode === RUN_ERROR_CODES2.MAX_DELIVERIES_EXCEEDED) {
84025
84123
  return {
84026
84124
  attribution: "sdk",
84027
84125
  errorCode: effectiveCode,
84028
84126
  hint: MAX_DELIVERIES_HINT
84029
84127
  };
84030
84128
  }
84031
- if (effectiveCode === RUN_ERROR_CODES.CORRUPTED_EVENT_LOG) {
84129
+ if (effectiveCode === RUN_ERROR_CODES2.CORRUPTED_EVENT_LOG) {
84032
84130
  return {
84033
84131
  attribution: "sdk",
84034
84132
  errorCode: effectiveCode,
84035
84133
  hint: CORRUPTED_EVENT_LOG_HINT
84036
84134
  };
84037
84135
  }
84038
- if (effectiveCode === RUN_ERROR_CODES.WORLD_CONTRACT_ERROR) {
84136
+ if (effectiveCode === RUN_ERROR_CODES2.WORLD_CONTRACT_ERROR) {
84039
84137
  return {
84040
84138
  attribution: "sdk",
84041
84139
  errorCode: effectiveCode,
@@ -87156,7 +87254,6 @@ __name(createLocalWorld, "createLocalWorld");
87156
87254
  init_dist7();
87157
87255
 
87158
87256
  // ../world-vercel/dist/encryption.js
87159
- var import_oidc = __toESM(require_dist(), 1);
87160
87257
  init_zod2();
87161
87258
  import { webcrypto } from "node:crypto";
87162
87259
 
@@ -87182,11 +87279,17 @@ var EVENTS_AGENT_OPTIONS = {
87182
87279
  };
87183
87280
  var RETRY_AGENT_OPTIONS = {
87184
87281
  // Observe Retry-After header if received
87185
- retryAfter: true
87186
- // By default, we observe re-try headers, and also separately
87187
- // re-try on these status codes: 429 / 500 / 502 / 503 / 504.
87188
- // TODO: We might want to let 429s pass through, so that we can do
87189
- // runtime retry-after handling through the queue.
87282
+ retryAfter: true,
87283
+ // Retry 5xx in-process (genuine transient blips recover fast), but NOT 429.
87284
+ // The Vercel firewall issues a challenge as a 429: our server-to-server
87285
+ // client cannot solve a challenge, so in-process retries just re-trigger it
87286
+ // ~5× per request and amplify load against an already-overloaded firewall
87287
+ // during an incident. Letting 429 pass through surfaces it immediately to
87288
+ // makeRequest — which maps it to a ThrottleError carrying the
87289
+ // `x-vercel-mitigated` / `x-vercel-id` headers — and the queue does the
87290
+ // (backed-off) retry instead. This is the long-standing "let 429s pass
87291
+ // through" intent. (undici default is [500, 502, 503, 504, 429].)
87292
+ statusCodes: [500, 502, 503, 504]
87190
87293
  };
87191
87294
  var STREAM_RETRY_OPTIONS = {
87192
87295
  retryAfter: true,
@@ -87205,28 +87308,263 @@ function getStreamDispatcher(config4) {
87205
87308
  return config4?.dispatcher ?? getDefaultStreamDispatcher();
87206
87309
  }
87207
87310
  __name(getStreamDispatcher, "getStreamDispatcher");
87311
+ function makeRetryDispatcher(agentOptions, retryOptions) {
87312
+ return new import_undici2.RetryAgent(new import_undici2.Agent(agentOptions), retryOptions);
87313
+ }
87314
+ __name(makeRetryDispatcher, "makeRetryDispatcher");
87208
87315
  function getDefaultDispatcher() {
87209
- if (!_dispatcher) {
87210
- _dispatcher = new import_undici2.RetryAgent(new import_undici2.Agent(DEFAULT_AGENT_OPTIONS), RETRY_AGENT_OPTIONS);
87211
- }
87316
+ _dispatcher ??= makeRetryDispatcher(DEFAULT_AGENT_OPTIONS, RETRY_AGENT_OPTIONS);
87212
87317
  return _dispatcher;
87213
87318
  }
87214
87319
  __name(getDefaultDispatcher, "getDefaultDispatcher");
87215
87320
  function getDefaultEventsDispatcher() {
87216
- if (!_eventsDispatcher) {
87217
- _eventsDispatcher = new import_undici2.RetryAgent(new import_undici2.Agent(EVENTS_AGENT_OPTIONS), RETRY_AGENT_OPTIONS);
87218
- }
87321
+ _eventsDispatcher ??= makeRetryDispatcher(EVENTS_AGENT_OPTIONS, RETRY_AGENT_OPTIONS);
87219
87322
  return _eventsDispatcher;
87220
87323
  }
87221
87324
  __name(getDefaultEventsDispatcher, "getDefaultEventsDispatcher");
87222
87325
  function getDefaultStreamDispatcher() {
87223
- if (!_streamDispatcher) {
87224
- _streamDispatcher = new import_undici2.RetryAgent(new import_undici2.Agent(EVENTS_AGENT_OPTIONS), STREAM_RETRY_OPTIONS);
87225
- }
87326
+ _streamDispatcher ??= makeRetryDispatcher(EVENTS_AGENT_OPTIONS, STREAM_RETRY_OPTIONS);
87226
87327
  return _streamDispatcher;
87227
87328
  }
87228
87329
  __name(getDefaultStreamDispatcher, "getDefaultStreamDispatcher");
87229
87330
 
87331
+ // ../world-vercel/dist/http-core.js
87332
+ var import_oidc = __toESM(require_dist(), 1);
87333
+ init_dist6();
87334
+
87335
+ // ../world-vercel/dist/telemetry.js
87336
+ var otelApiPromise2 = null;
87337
+ async function getOtelApi2() {
87338
+ if (!otelApiPromise2) {
87339
+ otelApiPromise2 = Promise.resolve().then(() => (init_esm(), esm_exports)).catch(() => null);
87340
+ }
87341
+ return otelApiPromise2;
87342
+ }
87343
+ __name(getOtelApi2, "getOtelApi");
87344
+ var tracerPromise2 = null;
87345
+ async function getTracer2() {
87346
+ if (!tracerPromise2) {
87347
+ tracerPromise2 = getOtelApi2().then((otel) => otel ? otel.trace.getTracer("workflow") : null);
87348
+ }
87349
+ return tracerPromise2;
87350
+ }
87351
+ __name(getTracer2, "getTracer");
87352
+ async function trace5(spanName, ...args) {
87353
+ const [tracer, otel] = await Promise.all([getTracer2(), getOtelApi2()]);
87354
+ const { fn, opts } = typeof args[0] === "function" ? { fn: args[0], opts: {} } : { fn: args[1], opts: args[0] };
87355
+ if (!fn)
87356
+ throw new Error("Function to trace must be provided");
87357
+ if (!tracer || !otel) {
87358
+ return await fn();
87359
+ }
87360
+ return tracer.startActiveSpan(spanName, opts, async (span) => {
87361
+ try {
87362
+ const result = await fn(span);
87363
+ span.setStatus({ code: otel.SpanStatusCode.OK });
87364
+ return result;
87365
+ } catch (e) {
87366
+ span.setStatus({
87367
+ code: otel.SpanStatusCode.ERROR,
87368
+ message: e.message
87369
+ });
87370
+ throw e;
87371
+ } finally {
87372
+ span.end();
87373
+ }
87374
+ });
87375
+ }
87376
+ __name(trace5, "trace");
87377
+ async function getSpanKind3(field) {
87378
+ const otel = await getOtelApi2();
87379
+ if (!otel)
87380
+ return void 0;
87381
+ return otel.SpanKind[field];
87382
+ }
87383
+ __name(getSpanKind3, "getSpanKind");
87384
+ async function injectTraceContextIntoHeaders(headers) {
87385
+ const otel = await getOtelApi2();
87386
+ if (!otel)
87387
+ return;
87388
+ const carrier = {};
87389
+ otel.propagation.inject(otel.context.active(), carrier);
87390
+ for (const [key, value] of Object.entries(carrier)) {
87391
+ headers.set(key, value);
87392
+ }
87393
+ }
87394
+ __name(injectTraceContextIntoHeaders, "injectTraceContextIntoHeaders");
87395
+ function SemanticConvention4(...names) {
87396
+ return (value) => Object.fromEntries(names.map((name) => [name, value]));
87397
+ }
87398
+ __name(SemanticConvention4, "SemanticConvention");
87399
+ var HttpRequestMethod3 = SemanticConvention4("http.request.method");
87400
+ var UrlFull3 = SemanticConvention4("url.full");
87401
+ var ServerAddress3 = SemanticConvention4("server.address");
87402
+ var ServerPort3 = SemanticConvention4("server.port");
87403
+ var HttpResponseStatusCode3 = SemanticConvention4("http.response.status_code");
87404
+ var ErrorType3 = SemanticConvention4("error.type");
87405
+ var WorldParseFormat3 = SemanticConvention4("workflow.world.parse.format");
87406
+ var PeerService4 = SemanticConvention4("peer.service");
87407
+ var RpcSystem4 = SemanticConvention4("rpc.system");
87408
+ var RpcService4 = SemanticConvention4("rpc.service");
87409
+ var RpcMethod4 = SemanticConvention4("rpc.method");
87410
+ var WorkflowRunId4 = SemanticConvention4("workflow.run.id");
87411
+ var StepId4 = SemanticConvention4("step.id");
87412
+
87413
+ // ../world-vercel/dist/http-core.js
87414
+ var REQUEST_TIMEOUT_MS = 6e4;
87415
+ var HTTP_DEBUG_ENABLED = typeof process !== "undefined" && typeof process.env.DEBUG === "string" && (process.env.DEBUG.includes("workflow:") || process.env.DEBUG === "*");
87416
+ var DIAGNOSTIC_HEADERS = [
87417
+ "x-vercel-id",
87418
+ "x-vercel-error",
87419
+ "x-vercel-mitigated"
87420
+ ];
87421
+ function getVercelDiagnostics(headers) {
87422
+ return DIAGNOSTIC_HEADERS.flatMap((header) => {
87423
+ const value = headers.get(header);
87424
+ return value ? [`${header}=${value}`] : [];
87425
+ });
87426
+ }
87427
+ __name(getVercelDiagnostics, "getVercelDiagnostics");
87428
+ function formatVercelDiagnostics(headers) {
87429
+ const diagnostics = getVercelDiagnostics(headers);
87430
+ return diagnostics.length > 0 ? ` (${diagnostics.join("; ")})` : "";
87431
+ }
87432
+ __name(formatVercelDiagnostics, "formatVercelDiagnostics");
87433
+ function httpLog(method, label, response, ms2) {
87434
+ if (!HTTP_DEBUG_ENABLED)
87435
+ return;
87436
+ const diagnostics = getVercelDiagnostics(response.headers);
87437
+ const suffix = diagnostics.length > 0 ? `; ${diagnostics.join("; ")}` : "";
87438
+ console.debug(`[workflow:world-vercel:http] ${method} ${label} -> ${response.status} (${ms2}ms${suffix})`);
87439
+ }
87440
+ __name(httpLog, "httpLog");
87441
+ function logCurlRepro(method, url3, headers) {
87442
+ if (!process.env.DEBUG)
87443
+ return;
87444
+ const stringifiedHeaders = Array.from(headers.entries()).filter(([key]) => key.toLowerCase() !== "authorization").map(([key, value]) => `-H "${key}: ${value}"`).join(" ");
87445
+ console.error(`Failed to fetch, reproduce with:
87446
+ curl -X ${method} ${stringifiedHeaders} "${url3}"`);
87447
+ }
87448
+ __name(logCurlRepro, "logCurlRepro");
87449
+ function parseRetryAfter(value) {
87450
+ if (!value)
87451
+ return void 0;
87452
+ const parsed = parseInt(value, 10);
87453
+ return Number.isNaN(parsed) ? void 0 : parsed;
87454
+ }
87455
+ __name(parseRetryAfter, "parseRetryAfter");
87456
+ function errorForResponse(status, message, opts = {}) {
87457
+ const { retryAfter, code: code3, url: url3, mitigated } = opts;
87458
+ if (status === 409)
87459
+ return new EntityConflictError2(message);
87460
+ if (status === 410)
87461
+ return new RunExpiredError(message);
87462
+ if (status === 425)
87463
+ return new TooEarlyError(message, { retryAfter });
87464
+ if (status === 429) {
87465
+ if (isFirewallChallenge429(status, mitigated)) {
87466
+ return new WorkflowWorldError2(`${message} (x-vercel-mitigated=challenge)`, {
87467
+ url: url3,
87468
+ status,
87469
+ code: "TRANSPORT",
87470
+ retryAfter
87471
+ });
87472
+ }
87473
+ return new ThrottleError2(message, { retryAfter });
87474
+ }
87475
+ return new WorkflowWorldError2(message, { url: url3, status, code: code3, retryAfter });
87476
+ }
87477
+ __name(errorForResponse, "errorForResponse");
87478
+ function isFirewallChallenge429(status, mitigated) {
87479
+ return status === 429 && mitigated === "challenge";
87480
+ }
87481
+ __name(isFirewallChallenge429, "isFirewallChallenge429");
87482
+ async function resolveVercelApiToken(opts) {
87483
+ return opts?.token ?? process.env.VERCEL_TOKEN ?? await (0, import_oidc.getVercelOidcToken)().catch(() => null);
87484
+ }
87485
+ __name(resolveVercelApiToken, "resolveVercelApiToken");
87486
+ function parseServer(url3) {
87487
+ try {
87488
+ const parsed = new URL(url3);
87489
+ return {
87490
+ serverAddress: parsed.hostname,
87491
+ serverPort: parsed.port ? parseInt(parsed.port, 10) : parsed.protocol === "https:" ? 443 : 80
87492
+ };
87493
+ } catch {
87494
+ return {};
87495
+ }
87496
+ }
87497
+ __name(parseServer, "parseServer");
87498
+ function httpClientSpanAttributes(args) {
87499
+ const { method, url: url3, peerService } = args;
87500
+ const { serverAddress, serverPort } = parseServer(url3);
87501
+ return {
87502
+ ...HttpRequestMethod3(method),
87503
+ ...UrlFull3(url3),
87504
+ ...serverAddress ? ServerAddress3(serverAddress) : {},
87505
+ ...serverPort ? ServerPort3(serverPort) : {},
87506
+ ...PeerService4(peerService),
87507
+ ...RpcSystem4("http"),
87508
+ ...RpcService4(peerService)
87509
+ };
87510
+ }
87511
+ __name(httpClientSpanAttributes, "httpClientSpanAttributes");
87512
+ async function instrumentedFetch(opts) {
87513
+ const { method, url: url3, headers, body, dispatcher, peerService = "workflow-server", timeoutMs = REQUEST_TIMEOUT_MS, signal: callerSignal, injectTraceContext = true, cacheBust = true, logLabel, buildError } = opts;
87514
+ const label = logLabel ?? url3;
87515
+ return trace5(`http ${method}`, { kind: await getSpanKind3("CLIENT") }, async (span) => {
87516
+ span?.setAttributes(httpClientSpanAttributes({ method, url: url3, peerService }));
87517
+ if (injectTraceContext)
87518
+ await injectTraceContextIntoHeaders(headers);
87519
+ if (cacheBust)
87520
+ headers.set("X-Request-Time", Date.now().toString());
87521
+ const timeoutSignal = timeoutMs != null ? AbortSignal.timeout(timeoutMs) : void 0;
87522
+ const signal = callerSignal && timeoutSignal ? AbortSignal.any([callerSignal, timeoutSignal]) : callerSignal ?? timeoutSignal;
87523
+ const start3 = Date.now();
87524
+ let response;
87525
+ try {
87526
+ response = await fetch(url3, {
87527
+ method,
87528
+ headers,
87529
+ body,
87530
+ signal,
87531
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any -- undici dispatcher type doesn't match @types/node's RequestInit
87532
+ dispatcher
87533
+ });
87534
+ } catch (error95) {
87535
+ const elapsed = Date.now() - start3;
87536
+ if (error95 instanceof Error && (error95.name === "TimeoutError" || error95.name === "AbortError")) {
87537
+ const timeoutError = new WorkflowWorldError2(`${method} ${label} timed out after ${elapsed}ms`, { url: url3, cause: error95 });
87538
+ span?.setAttributes({ ...ErrorType3("TIMEOUT") });
87539
+ span?.recordException?.(timeoutError);
87540
+ throw timeoutError;
87541
+ }
87542
+ throw error95;
87543
+ }
87544
+ const ms2 = Date.now() - start3;
87545
+ httpLog(method, label, response, ms2);
87546
+ span?.setAttributes({ ...HttpResponseStatusCode3(response.status) });
87547
+ if (!response.ok) {
87548
+ span?.setAttributes({ ...ErrorType3(`HTTP ${response.status}`) });
87549
+ logCurlRepro(method, url3, headers);
87550
+ if (buildError) {
87551
+ const error96 = await buildError(response);
87552
+ span?.recordException?.(error96);
87553
+ throw error96;
87554
+ }
87555
+ const text = await response.text().catch(() => "");
87556
+ const error95 = errorForResponse(response.status, `${method} ${label} -> HTTP ${response.status}: ${response.statusText}${text ? ` ${text}` : ""}${formatVercelDiagnostics(response.headers)}`, {
87557
+ url: url3,
87558
+ retryAfter: parseRetryAfter(response.headers.get("Retry-After"))
87559
+ });
87560
+ span?.recordException?.(error95);
87561
+ throw error95;
87562
+ }
87563
+ return response;
87564
+ });
87565
+ }
87566
+ __name(instrumentedFetch, "instrumentedFetch");
87567
+
87230
87568
  // ../world-vercel/dist/encryption.js
87231
87569
  var KEY_BYTES = 32;
87232
87570
  async function deriveRunKey(deploymentKey, projectId, runId) {
@@ -87253,7 +87591,7 @@ async function deriveRunKey(deploymentKey, projectId, runId) {
87253
87591
  }
87254
87592
  __name(deriveRunKey, "deriveRunKey");
87255
87593
  async function fetchRunKey(deploymentId, projectId, runId, options) {
87256
- const token = options?.token ?? process.env.VERCEL_TOKEN ?? await (0, import_oidc.getVercelOidcToken)().catch(() => null);
87594
+ const token = await resolveVercelApiToken({ token: options?.token });
87257
87595
  if (!token) {
87258
87596
  throw new Error("Cannot fetch run key: no OIDC token or VERCEL_TOKEN available");
87259
87597
  }
@@ -87261,23 +87599,25 @@ async function fetchRunKey(deploymentId, projectId, runId, options) {
87261
87599
  if (options?.teamId) {
87262
87600
  params.set("teamId", options.teamId);
87263
87601
  }
87264
- const response = await fetch(`https://api.vercel.com/v1/workflow/run-key/${deploymentId}?${params}`, {
87602
+ const response = await instrumentedFetch({
87265
87603
  method: "GET",
87266
- headers: {
87267
- Authorization: `Bearer ${token}`
87268
- },
87269
- // @ts-expect-error -- undici dispatcher is accepted by Node.js fetch but not in @types/node's RequestInit
87270
- dispatcher: getDispatcher({ dispatcher: options?.dispatcher })
87604
+ url: `https://api.vercel.com/v1/workflow/run-key/${deploymentId}?${params}`,
87605
+ headers: new Headers({ Authorization: `Bearer ${token}` }),
87606
+ dispatcher: getDispatcher({ dispatcher: options?.dispatcher }),
87607
+ peerService: "vercel-api",
87608
+ // Preserve the prior no-timeout behavior for this Vercel-API call; the
87609
+ // shared RetryAgent still handles transient/5xx retries.
87610
+ timeoutMs: null,
87611
+ buildError: /* @__PURE__ */ __name(async (res) => {
87612
+ let body;
87613
+ try {
87614
+ body = await res.text();
87615
+ } catch {
87616
+ body = "<unable to read response body>";
87617
+ }
87618
+ return new Error(`Failed to fetch run key for ${runId} (deployment ${deploymentId}): HTTP ${res.status} ${res.statusText}${body ? ` \u2014 ${body}` : ""}`);
87619
+ }, "buildError")
87271
87620
  });
87272
- if (!response.ok) {
87273
- let body;
87274
- try {
87275
- body = await response.text();
87276
- } catch {
87277
- body = "<unable to read response body>";
87278
- }
87279
- throw new Error(`Failed to fetch run key for ${runId} (deployment ${deploymentId}): HTTP ${response.status} ${response.statusText}${body ? ` \u2014 ${body}` : ""}`);
87280
- }
87281
87621
  const data = await response.json();
87282
87622
  const result = object2({ key: string5().nullable() }).safeParse(data);
87283
87623
  if (!result.success) {
@@ -87326,84 +87666,6 @@ function createGetEncryptionKeyForRun(projectId, teamId, token, dispatcher) {
87326
87666
  }
87327
87667
  __name(createGetEncryptionKeyForRun, "createGetEncryptionKeyForRun");
87328
87668
 
87329
- // ../world-vercel/dist/telemetry.js
87330
- var otelApiPromise2 = null;
87331
- async function getOtelApi2() {
87332
- if (!otelApiPromise2) {
87333
- otelApiPromise2 = Promise.resolve().then(() => (init_esm(), esm_exports)).catch(() => null);
87334
- }
87335
- return otelApiPromise2;
87336
- }
87337
- __name(getOtelApi2, "getOtelApi");
87338
- var tracerPromise2 = null;
87339
- async function getTracer2() {
87340
- if (!tracerPromise2) {
87341
- tracerPromise2 = getOtelApi2().then((otel) => otel ? otel.trace.getTracer("workflow") : null);
87342
- }
87343
- return tracerPromise2;
87344
- }
87345
- __name(getTracer2, "getTracer");
87346
- async function trace5(spanName, ...args) {
87347
- const [tracer, otel] = await Promise.all([getTracer2(), getOtelApi2()]);
87348
- const { fn, opts } = typeof args[0] === "function" ? { fn: args[0], opts: {} } : { fn: args[1], opts: args[0] };
87349
- if (!fn)
87350
- throw new Error("Function to trace must be provided");
87351
- if (!tracer || !otel) {
87352
- return await fn();
87353
- }
87354
- return tracer.startActiveSpan(spanName, opts, async (span) => {
87355
- try {
87356
- const result = await fn(span);
87357
- span.setStatus({ code: otel.SpanStatusCode.OK });
87358
- return result;
87359
- } catch (e) {
87360
- span.setStatus({
87361
- code: otel.SpanStatusCode.ERROR,
87362
- message: e.message
87363
- });
87364
- throw e;
87365
- } finally {
87366
- span.end();
87367
- }
87368
- });
87369
- }
87370
- __name(trace5, "trace");
87371
- async function getSpanKind3(field) {
87372
- const otel = await getOtelApi2();
87373
- if (!otel)
87374
- return void 0;
87375
- return otel.SpanKind[field];
87376
- }
87377
- __name(getSpanKind3, "getSpanKind");
87378
- async function injectTraceContextIntoHeaders(headers) {
87379
- const otel = await getOtelApi2();
87380
- if (!otel)
87381
- return;
87382
- const carrier = {};
87383
- otel.propagation.inject(otel.context.active(), carrier);
87384
- for (const [key, value] of Object.entries(carrier)) {
87385
- headers.set(key, value);
87386
- }
87387
- }
87388
- __name(injectTraceContextIntoHeaders, "injectTraceContextIntoHeaders");
87389
- function SemanticConvention4(...names) {
87390
- return (value) => Object.fromEntries(names.map((name) => [name, value]));
87391
- }
87392
- __name(SemanticConvention4, "SemanticConvention");
87393
- var HttpRequestMethod3 = SemanticConvention4("http.request.method");
87394
- var UrlFull3 = SemanticConvention4("url.full");
87395
- var ServerAddress3 = SemanticConvention4("server.address");
87396
- var ServerPort3 = SemanticConvention4("server.port");
87397
- var HttpResponseStatusCode3 = SemanticConvention4("http.response.status_code");
87398
- var ErrorType3 = SemanticConvention4("error.type");
87399
- var WorldParseFormat3 = SemanticConvention4("workflow.world.parse.format");
87400
- var PeerService4 = SemanticConvention4("peer.service");
87401
- var RpcSystem4 = SemanticConvention4("rpc.system");
87402
- var RpcService4 = SemanticConvention4("rpc.service");
87403
- var RpcMethod4 = SemanticConvention4("rpc.method");
87404
- var WorkflowRunId4 = SemanticConvention4("workflow.run.id");
87405
- var StepId4 = SemanticConvention4("step.id");
87406
-
87407
87669
  // ../world-vercel/dist/instrumentObject.js
87408
87670
  var WORKFLOW_SERVER_SERVICE = {
87409
87671
  peerService: "workflow-server",
@@ -94433,35 +94695,41 @@ import os from "node:os";
94433
94695
  import { inspect } from "node:util";
94434
94696
 
94435
94697
  // ../world-vercel/dist/version.js
94436
- var version5 = "5.0.0-beta.21";
94698
+ var version5 = "5.0.0-beta.22";
94437
94699
 
94438
94700
  // ../world-vercel/dist/utils.js
94439
- var HTTP_DEBUG_ENABLED = typeof process !== "undefined" && typeof process.env.DEBUG === "string" && (process.env.DEBUG.includes("workflow:") || process.env.DEBUG === "*");
94440
- function httpLog(method, endpoint, response, ms2) {
94441
- if (HTTP_DEBUG_ENABLED) {
94442
- const responseContext = getResponseDiagnosticHeaders(response);
94443
- const diagnosticSuffix = responseContext.length > 0 ? `; ${responseContext.join("; ")}` : "";
94444
- console.debug(`[workflow:world-vercel:http] ${method} ${endpoint} -> ${response.status} (${ms2}ms${diagnosticSuffix})`);
94445
- }
94446
- }
94447
- __name(httpLog, "httpLog");
94448
- function getResponseDiagnosticHeaders(response) {
94449
- return ["x-vercel-id", "x-vercel-error"].flatMap((header) => {
94450
- const value = response.headers.get(header);
94451
- return value ? [`${header}=${value}`] : [];
94452
- });
94453
- }
94454
- __name(getResponseDiagnosticHeaders, "getResponseDiagnosticHeaders");
94455
- function formatResponseDiagnostics(response) {
94456
- const headers = getResponseDiagnosticHeaders(response);
94457
- return headers.length > 0 ? ` (${headers.join("; ")})` : "";
94458
- }
94459
- __name(formatResponseDiagnostics, "formatResponseDiagnostics");
94460
94701
  var WORKFLOW_SERVER_URL_OVERRIDE = "";
94461
- var REQUEST_TIMEOUT_MS = 6e4;
94462
94702
  var IDEMPOTENT_METHODS = /* @__PURE__ */ new Set(["GET", "HEAD"]);
94463
94703
  var MAX_BODY_PARSE_RETRIES = 2;
94464
94704
  var BODY_PARSE_RETRY_BASE_MS = 100;
94705
+ var TRANSIENT_TRANSPORT_ERROR_CODES = /* @__PURE__ */ new Set([
94706
+ "UND_ERR_REQ_RETRY",
94707
+ "UND_ERR_SOCKET",
94708
+ "UND_ERR_CONNECT",
94709
+ "UND_ERR_CONNECT_TIMEOUT",
94710
+ "UND_ERR_HEADERS_TIMEOUT",
94711
+ "UND_ERR_BODY_TIMEOUT",
94712
+ "UND_ERR_CLOSED",
94713
+ "ECONNRESET",
94714
+ "ECONNREFUSED",
94715
+ "ENOTFOUND",
94716
+ "EAI_AGAIN",
94717
+ "EPIPE"
94718
+ ]);
94719
+ function getTransientTransportCode(error95) {
94720
+ let current = error95;
94721
+ for (let depth = 0; current != null && depth < 5; depth++) {
94722
+ if (typeof current === "object" && "code" in current) {
94723
+ const code3 = current.code;
94724
+ if (typeof code3 === "string" && TRANSIENT_TRANSPORT_ERROR_CODES.has(code3)) {
94725
+ return code3;
94726
+ }
94727
+ }
94728
+ current = current?.cause;
94729
+ }
94730
+ return void 0;
94731
+ }
94732
+ __name(getTransientTransportCode, "getTransientTransportCode");
94465
94733
  var getWorkflowServerUrlOverride = /* @__PURE__ */ __name(() => WORKFLOW_SERVER_URL_OVERRIDE || process.env.VERCEL_WORKFLOW_SERVER_URL || "", "getWorkflowServerUrlOverride");
94466
94734
  var DEFAULT_RESOLVE_DATA_OPTION2 = "all";
94467
94735
  function deserializeError(obj) {
@@ -94532,25 +94800,12 @@ async function makeRequest({ endpoint, options = {}, config: config4 = {}, schem
94532
94800
  const method = options.method || "GET";
94533
94801
  const { baseUrl, headers } = await getHttpConfig(config4);
94534
94802
  const url3 = `${baseUrl}${endpoint}`;
94535
- let serverAddress;
94536
- let serverPort;
94537
- try {
94538
- const parsedUrl = new URL(url3);
94539
- serverAddress = parsedUrl.hostname;
94540
- serverPort = parsedUrl.port ? parseInt(parsedUrl.port, 10) : parsedUrl.protocol === "https:" ? 443 : 80;
94541
- } catch {
94542
- }
94543
94803
  return trace5(`http ${method}`, { kind: await getSpanKind3("CLIENT") }, async (span) => {
94544
- span?.setAttributes({
94545
- ...HttpRequestMethod3(method),
94546
- ...UrlFull3(url3),
94547
- ...serverAddress && ServerAddress3(serverAddress),
94548
- ...serverPort && ServerPort3(serverPort),
94549
- // Peer service for Datadog service maps
94550
- ...PeerService4("workflow-server"),
94551
- ...RpcSystem4("http"),
94552
- ...RpcService4("workflow-server")
94553
- });
94804
+ span?.setAttributes(httpClientSpanAttributes({
94805
+ method,
94806
+ url: url3,
94807
+ peerService: "workflow-server"
94808
+ }));
94554
94809
  headers.set("Accept", "application/cbor");
94555
94810
  await injectTraceContextIntoHeaders(headers);
94556
94811
  let body;
@@ -94580,60 +94835,42 @@ async function makeRequest({ endpoint, options = {}, config: config4 = {}, schem
94580
94835
  } catch (error95) {
94581
94836
  const elapsed = Date.now() - fetchStart;
94582
94837
  if (error95 instanceof Error && (error95.name === "TimeoutError" || error95.name === "AbortError")) {
94583
- const timeoutError = new WorkflowWorldError2(`${method} ${endpoint} timed out after ${elapsed}ms`, { url: url3, cause: error95 });
94838
+ const timeoutError = new WorkflowWorldError2(`${method} ${endpoint} timed out after ${elapsed}ms`, { url: url3, code: "TIMEOUT", cause: error95 });
94584
94839
  span?.setAttributes({ ...ErrorType3("TIMEOUT") });
94585
94840
  span?.recordException?.(timeoutError);
94586
94841
  throw timeoutError;
94587
94842
  }
94843
+ const transportCode = getTransientTransportCode(error95);
94844
+ if (transportCode) {
94845
+ const transportError = new WorkflowWorldError2(`${method} ${endpoint} transport failure after ${elapsed}ms (${transportCode})`, { url: url3, code: "TRANSPORT", cause: error95 });
94846
+ span?.setAttributes({ ...ErrorType3("TRANSPORT") });
94847
+ span?.recordException?.(transportError);
94848
+ throw transportError;
94849
+ }
94588
94850
  throw error95;
94589
94851
  }
94590
94852
  const fetchMs = Date.now() - fetchStart;
94591
- responseDiagnostics = formatResponseDiagnostics(response);
94853
+ responseDiagnostics = formatVercelDiagnostics(response.headers);
94592
94854
  httpLog(method, endpoint, response, fetchMs);
94593
94855
  span?.setAttributes({
94594
94856
  ...HttpResponseStatusCode3(response.status)
94595
94857
  });
94596
94858
  if (!response.ok) {
94597
94859
  const errorData = await parseResponseBody(response).then((r) => r.data).catch(() => ({}));
94598
- if (process.env.DEBUG) {
94599
- const stringifiedHeaders = Array.from(headers.entries()).filter(([key]) => key.toLowerCase() !== "authorization").map(([key, value]) => `-H "${key}: ${value}"`).join(" ");
94600
- console.error(`Failed to fetch, reproduce with:
94601
- curl -X ${request.method} ${stringifiedHeaders} "${url3}"`);
94602
- }
94603
- let retryAfter;
94604
- const retryAfterHeader = response.headers.get("Retry-After");
94605
- if (retryAfterHeader) {
94606
- const parsed = parseInt(retryAfterHeader, 10);
94607
- if (!Number.isNaN(parsed)) {
94608
- retryAfter = parsed;
94609
- }
94610
- }
94860
+ logCurlRepro(request.method, url3, headers);
94861
+ const retryAfter = parseRetryAfter(response.headers.get("Retry-After"));
94611
94862
  const defaultMessage = (errorData.message || `${request.method} ${endpoint} -> HTTP ${response.status}: ${response.statusText}`) + responseDiagnostics;
94612
- const throwWithTrace = /* @__PURE__ */ __name((error95) => {
94613
- span?.setAttributes({
94614
- ...ErrorType3(errorData.code || `HTTP ${response.status}`)
94615
- });
94616
- span?.recordException?.(error95);
94617
- throw error95;
94618
- }, "throwWithTrace");
94619
- if (response.status === 409) {
94620
- throwWithTrace(new EntityConflictError2(defaultMessage));
94621
- }
94622
- if (response.status === 410) {
94623
- throwWithTrace(new RunExpiredError(defaultMessage));
94624
- }
94625
- if (response.status === 425) {
94626
- throwWithTrace(new TooEarlyError(defaultMessage, { retryAfter }));
94627
- }
94628
- if (response.status === 429) {
94629
- throwWithTrace(new ThrottleError2(defaultMessage, { retryAfter }));
94630
- }
94631
- throwWithTrace(new WorkflowWorldError2(defaultMessage, {
94863
+ const error95 = errorForResponse(response.status, defaultMessage, {
94632
94864
  url: url3,
94633
- status: response.status,
94634
94865
  code: errorData.code,
94635
- retryAfter
94636
- }));
94866
+ retryAfter,
94867
+ mitigated: response.headers.get("x-vercel-mitigated")
94868
+ });
94869
+ span?.setAttributes({
94870
+ ...ErrorType3(errorData.code || `HTTP ${response.status}`)
94871
+ });
94872
+ span?.recordException?.(error95);
94873
+ throw error95;
94637
94874
  }
94638
94875
  onResponse?.(response);
94639
94876
  try {
@@ -94790,7 +95027,7 @@ var MAX_DELAY_SECONDS = Number(
94790
95027
  // 23 hours - leave 1h buffer before 24h retention limit
94791
95028
  );
94792
95029
  var HANDLER_ERROR_RETRY_AFTER_SECONDS = 1;
94793
- var HANDLER_ERROR_MAX_RETRY_AFTER_SECONDS = 60;
95030
+ var HANDLER_ERROR_MAX_RETRY_AFTER_SECONDS = 900;
94794
95031
  var HANDLER_ERROR_RETRY_JITTER_RATIO = 0.25;
94795
95032
  function getHandlerErrorRetryAfterSeconds(deliveryCount) {
94796
95033
  const backoffSeconds = Math.min(Math.max(HANDLER_ERROR_RETRY_AFTER_SECONDS, 2 ** (deliveryCount - 1)), HANDLER_ERROR_MAX_RETRY_AFTER_SECONDS);
@@ -94920,7 +95157,6 @@ function createQueue2(config4) {
94920
95157
  __name(createQueue2, "createQueue");
94921
95158
 
94922
95159
  // ../world-vercel/dist/resolve-latest-deployment.js
94923
- var import_oidc4 = __toESM(require_dist(), 1);
94924
95160
  init_zod2();
94925
95161
  var ResolveLatestDeploymentResponseSchema = object2({
94926
95162
  id: string5()
@@ -94931,28 +95167,30 @@ function createResolveLatestDeploymentId(config4) {
94931
95167
  if (!currentDeploymentId) {
94932
95168
  throw new Error("Cannot resolve latest deployment: VERCEL_DEPLOYMENT_ID environment variable is not set");
94933
95169
  }
94934
- const token = config4?.token ?? process.env.VERCEL_TOKEN ?? await (0, import_oidc4.getVercelOidcToken)().catch(() => null);
95170
+ const token = await resolveVercelApiToken(config4);
94935
95171
  if (!token) {
94936
95172
  throw new Error("Cannot resolve latest deployment: no OIDC token or VERCEL_TOKEN available");
94937
95173
  }
94938
95174
  const url3 = `https://api.vercel.com/v1/workflow/resolve-latest-deployment/${encodeURIComponent(currentDeploymentId)}`;
94939
- const response = await fetch(url3, {
95175
+ const response = await instrumentedFetch({
94940
95176
  method: "GET",
94941
- headers: {
94942
- Authorization: `Bearer ${token}`
94943
- },
94944
- // @ts-expect-error -- undici dispatcher is accepted by Node.js fetch but not in @types/node's RequestInit
94945
- dispatcher: getDispatcher(config4)
95177
+ url: url3,
95178
+ headers: new Headers({ Authorization: `Bearer ${token}` }),
95179
+ dispatcher: getDispatcher(config4),
95180
+ peerService: "vercel-api",
95181
+ // Preserve the prior no-timeout behavior for this Vercel-API call; the
95182
+ // shared RetryAgent still handles transient/5xx retries.
95183
+ timeoutMs: null,
95184
+ buildError: /* @__PURE__ */ __name(async (res) => {
95185
+ let body;
95186
+ try {
95187
+ body = await res.text();
95188
+ } catch {
95189
+ body = "<unable to read response body>";
95190
+ }
95191
+ return new Error(`Failed to resolve latest deployment for ${currentDeploymentId}: HTTP ${res.status} ${res.statusText}${body ? ` \u2014 ${body}` : ""}`);
95192
+ }, "buildError")
94946
95193
  });
94947
- if (!response.ok) {
94948
- let body;
94949
- try {
94950
- body = await response.text();
94951
- } catch {
94952
- body = "<unable to read response body>";
94953
- }
94954
- throw new Error(`Failed to resolve latest deployment for ${currentDeploymentId}: HTTP ${response.status} ${response.statusText}${body ? ` \u2014 ${body}` : ""}`);
94955
- }
94956
95194
  const data = await response.json();
94957
95195
  const result = ResolveLatestDeploymentResponseSchema.safeParse(data);
94958
95196
  if (!result.success) {
@@ -94967,8 +95205,187 @@ __name(createResolveLatestDeploymentId, "createResolveLatestDeploymentId");
94967
95205
  init_dist6();
94968
95206
  init_dist7();
94969
95207
 
94970
- // ../world-vercel/dist/events-v4.js
95208
+ // ../world-vercel/dist/event-retry.js
94971
95209
  init_dist6();
95210
+ var EVENT_RETRY_ELIGIBILITY = {
95211
+ // Creates: conditional create → 409 EntityConflictError if it already exists.
95212
+ run_created: {
95213
+ retryable: true,
95214
+ reason: "conditional create \u2192 409 if exists"
95215
+ },
95216
+ step_created: {
95217
+ retryable: true,
95218
+ reason: "conditional create \u2192 409 if exists"
95219
+ },
95220
+ wait_created: {
95221
+ retryable: true,
95222
+ reason: "conditional create \u2192 409 if exists"
95223
+ },
95224
+ hook_created: {
95225
+ retryable: true,
95226
+ reason: "transactional token uniqueness \u2192 409 if exists"
95227
+ },
95228
+ // Run start: early-returns if already running, writes no duplicate row.
95229
+ run_started: {
95230
+ retryable: true,
95231
+ reason: "early-returns if already running, no duplicate row"
95232
+ },
95233
+ // Terminal transitions: conditional `.where()` excludes terminal states →
95234
+ // 409 before the event row is written.
95235
+ run_completed: {
95236
+ retryable: true,
95237
+ reason: "terminal-state guard \u2192 409, no duplicate row"
95238
+ },
95239
+ run_failed: {
95240
+ retryable: true,
95241
+ reason: "terminal-state guard \u2192 409, no duplicate row"
95242
+ },
95243
+ run_cancelled: {
95244
+ retryable: true,
95245
+ reason: "terminal-state guard \u2192 409, no duplicate row"
95246
+ },
95247
+ step_completed: {
95248
+ retryable: true,
95249
+ reason: "terminal-state guard \u2192 409, no duplicate row"
95250
+ },
95251
+ step_failed: {
95252
+ retryable: true,
95253
+ reason: "terminal-state guard \u2192 409, no duplicate row"
95254
+ },
95255
+ wait_completed: {
95256
+ retryable: true,
95257
+ reason: "waiting-state guard \u2192 409, no duplicate row"
95258
+ },
95259
+ hook_disposed: {
95260
+ retryable: true,
95261
+ reason: "conditional delete (exists) \u2192 409, no duplicate row"
95262
+ },
95263
+ // True idempotency via a correlationId constraint that reuses the eventId.
95264
+ attr_set: {
95265
+ retryable: true,
95266
+ reason: "correlationId constraint reuses eventId (idempotent replay)"
95267
+ },
95268
+ // NOT safe to retry — see the module comment.
95269
+ step_started: {
95270
+ retryable: false,
95271
+ reason: "unconditional attempt increment \u2192 a retry double-counts attempts"
95272
+ },
95273
+ step_retrying: {
95274
+ retryable: false,
95275
+ reason: "no duplicate guard \u2192 a retry appends a second event row"
95276
+ },
95277
+ hook_received: {
95278
+ retryable: false,
95279
+ reason: "no server guard \u2192 a retry duplicates the row / re-delivers payload"
95280
+ },
95281
+ // Server-originated; the SDK never POSTs it.
95282
+ hook_conflict: {
95283
+ retryable: false,
95284
+ reason: "server-originated; never POSTed by the SDK"
95285
+ }
95286
+ };
95287
+ var MAX_EVENT_POST_RETRIES = 2;
95288
+ var EVENT_POST_RETRY_BASE_MS = 100;
95289
+ var EVENT_POST_RETRY_JITTER_MS = 50;
95290
+ var TRANSIENT_CODES = /* @__PURE__ */ new Set([
95291
+ "ECONNRESET",
95292
+ "ECONNREFUSED",
95293
+ "ENOTFOUND",
95294
+ "ENETDOWN",
95295
+ "ENETUNREACH",
95296
+ "EHOSTDOWN",
95297
+ "EHOSTUNREACH",
95298
+ "EPIPE",
95299
+ "ETIMEDOUT",
95300
+ "UND_ERR_SOCKET",
95301
+ "UND_ERR_REQ_RETRY",
95302
+ "UND_ERR_CONNECT_TIMEOUT",
95303
+ "UND_ERR_HEADERS_TIMEOUT",
95304
+ "UND_ERR_BODY_TIMEOUT",
95305
+ // Names (undici/Node surface these on the error or its cause).
95306
+ // `TimeoutError` is our own per-request deadline (`AbortSignal.timeout` in
95307
+ // makeRequest) — a genuinely ambiguous failure worth retrying. We deliberately
95308
+ // do NOT include `AbortError`: that is how an external/caller-supplied
95309
+ // cancellation surfaces (makeRequest composes the caller's signal via
95310
+ // `AbortSignal.any`), and re-issuing a write the caller asked to cancel —
95311
+ // stalling the abort by the full backoff budget — would be wrong.
95312
+ "TimeoutError",
95313
+ "RequestRetryError"
95314
+ ]);
95315
+ function collectErrorMarkers(err, depth = 0) {
95316
+ if (depth > 5 || err === null || typeof err !== "object")
95317
+ return [];
95318
+ const markers = [];
95319
+ const e = err;
95320
+ if (typeof e.code === "string")
95321
+ markers.push(e.code);
95322
+ if (typeof e.name === "string")
95323
+ markers.push(e.name);
95324
+ if (e.cause)
95325
+ markers.push(...collectErrorMarkers(e.cause, depth + 1));
95326
+ return markers;
95327
+ }
95328
+ __name(collectErrorMarkers, "collectErrorMarkers");
95329
+ function isRetryableEventPostError(err) {
95330
+ if (EntityConflictError2.is(err) || RunExpiredError.is(err) || TooEarlyError.is(err) || ThrottleError2.is(err)) {
95331
+ return false;
95332
+ }
95333
+ if (WorkflowWorldError2.is(err)) {
95334
+ if (err.code === "PARSE_ERROR")
95335
+ return true;
95336
+ if (typeof err.status === "number") {
95337
+ return err.status >= 500 && err.status <= 599;
95338
+ }
95339
+ }
95340
+ return collectErrorMarkers(err).some((m) => TRANSIENT_CODES.has(m));
95341
+ }
95342
+ __name(isRetryableEventPostError, "isRetryableEventPostError");
95343
+ var sleep = /* @__PURE__ */ __name((ms2) => new Promise((resolve3) => setTimeout(resolve3, ms2)), "sleep");
95344
+ var RETRY_DEBUG_ENABLED = typeof process !== "undefined" && typeof process.env.DEBUG === "string" && (process.env.DEBUG.includes("workflow:") || process.env.DEBUG === "*");
95345
+ function logRetry(message, fields) {
95346
+ if (!RETRY_DEBUG_ENABLED)
95347
+ return;
95348
+ const suffix = Object.entries(fields).map(([k, v]) => `${k}=${v}`).join(" ");
95349
+ console.debug(`[workflow:world-vercel:event-retry] ${message} ${suffix}`);
95350
+ }
95351
+ __name(logRetry, "logRetry");
95352
+ function errorMarker(err) {
95353
+ if (WorkflowWorldError2.is(err)) {
95354
+ return err.code ?? (err.status != null ? `status_${err.status}` : err.name);
95355
+ }
95356
+ return collectErrorMarkers(err)[0] ?? (err instanceof Error ? err.name : "unknown");
95357
+ }
95358
+ __name(errorMarker, "errorMarker");
95359
+ async function withEventPostRetry(fn, eventType) {
95360
+ const retryable = EVENT_RETRY_ELIGIBILITY[eventType]?.retryable ?? false;
95361
+ for (let attempt = 0; ; attempt++) {
95362
+ try {
95363
+ return await fn();
95364
+ } catch (err) {
95365
+ const transient = retryable && isRetryableEventPostError(err);
95366
+ if (transient && attempt < MAX_EVENT_POST_RETRIES) {
95367
+ const backoff = EVENT_POST_RETRY_BASE_MS * 2 ** attempt + Math.floor(Math.random() * EVENT_POST_RETRY_JITTER_MS);
95368
+ logRetry("retrying event POST after transient failure", {
95369
+ eventType,
95370
+ attempt: attempt + 1,
95371
+ backoffMs: backoff,
95372
+ error: errorMarker(err)
95373
+ });
95374
+ await sleep(backoff);
95375
+ continue;
95376
+ }
95377
+ if (transient) {
95378
+ logRetry("exhausted in-process retries; surfacing for queue redelivery", {
95379
+ eventType,
95380
+ attempts: attempt + 1,
95381
+ error: errorMarker(err)
95382
+ });
95383
+ }
95384
+ throw err;
95385
+ }
95386
+ }
95387
+ }
95388
+ __name(withEventPostRetry, "withEventPostRetry");
94972
95389
 
94973
95390
  // ../world-vercel/dist/frames.js
94974
95391
  var V4_FRAME_CONTENT_TYPE = "application/vnd.workflow.v4-frames";
@@ -95045,15 +95462,16 @@ async function* readerToIterator(reader) {
95045
95462
  __name(readerToIterator, "readerToIterator");
95046
95463
 
95047
95464
  // ../world-vercel/dist/events-v4.js
95048
- async function fetchV4(url3, init, config4) {
95049
- init.headers.set("X-Request-Time", Date.now().toString());
95050
- await injectTraceContextIntoHeaders(init.headers);
95051
- return fetch(url3, {
95465
+ async function fetchV4(url3, init, config4, opName) {
95466
+ return instrumentedFetch({
95052
95467
  method: init.method,
95468
+ url: url3,
95053
95469
  headers: init.headers,
95054
95470
  body: init.body,
95055
- // eslint-disable-next-line @typescript-eslint/no-explicit-any -- undici dispatcher type doesn't match @types/node's RequestInit
95056
- dispatcher: getEventsDispatcher(config4)
95471
+ dispatcher: getEventsDispatcher(config4),
95472
+ timeoutMs: null,
95473
+ logLabel: opName,
95474
+ buildError: /* @__PURE__ */ __name(async (response) => errorFromV4Response(response.status, headersToRecord(response.headers), await response.text(), opName, url3), "buildError")
95057
95475
  });
95058
95476
  }
95059
95477
  __name(fetchV4, "fetchV4");
@@ -95123,7 +95541,7 @@ function buildPostFrameMeta(input) {
95123
95541
  return meta5;
95124
95542
  }
95125
95543
  __name(buildPostFrameMeta, "buildPostFrameMeta");
95126
- function throwForErrorResponse(statusCode, responseHeaders, errorBody, opName, url3) {
95544
+ function errorFromV4Response(statusCode, responseHeaders, errorBody, opName, url3) {
95127
95545
  let message = `v4 ${opName} failed: HTTP ${statusCode}`;
95128
95546
  let code3;
95129
95547
  try {
@@ -95136,40 +95554,22 @@ function throwForErrorResponse(statusCode, responseHeaders, errorBody, opName, u
95136
95554
  if (errorBody)
95137
95555
  message += ` ${errorBody}`;
95138
95556
  }
95139
- let retryAfter;
95140
- const retryAfterHeader = readHeader(responseHeaders, "retry-after");
95141
- if (retryAfterHeader) {
95142
- const parsed = parseInt(retryAfterHeader, 10);
95143
- if (!Number.isNaN(parsed))
95144
- retryAfter = parsed;
95145
- }
95146
- if (statusCode === 409)
95147
- throw new EntityConflictError2(message);
95148
- if (statusCode === 410)
95149
- throw new RunExpiredError(message);
95150
- if (statusCode === 425)
95151
- throw new TooEarlyError(message, { retryAfter });
95152
- if (statusCode === 429)
95153
- throw new ThrottleError2(message, { retryAfter });
95154
- throw new WorkflowWorldError2(message, {
95155
- status: statusCode,
95557
+ const retryAfter = parseRetryAfter(readHeader(responseHeaders, "retry-after"));
95558
+ return errorForResponse(statusCode, message, {
95559
+ retryAfter,
95156
95560
  code: code3,
95157
95561
  url: url3,
95158
- retryAfter
95562
+ mitigated: readHeader(responseHeaders, "x-vercel-mitigated")
95159
95563
  });
95160
95564
  }
95161
- __name(throwForErrorResponse, "throwForErrorResponse");
95565
+ __name(errorFromV4Response, "errorFromV4Response");
95162
95566
  async function createWorkflowRunEventV4(input, config4) {
95163
95567
  const { baseUrl, headers: baseHeaders } = await getHttpConfig(config4);
95164
95568
  const headers = new Headers(baseHeaders);
95165
95569
  headers.set("Content-Type", "application/octet-stream");
95166
95570
  const frame3 = encodeFrame(buildPostFrameMeta(input), input.payload ?? new Uint8Array(0));
95167
95571
  const url3 = `${baseUrl}/v4/runs/${encodeURIComponent(input.runId)}/events/${encodeURIComponent(input.eventType)}`;
95168
- const response = await fetchV4(url3, { method: "POST", headers, body: frame3 }, config4);
95169
- if (!response.ok) {
95170
- const errorBody = await response.text();
95171
- throwForErrorResponse(response.status, headersToRecord(response.headers), errorBody, "createEvent", url3);
95172
- }
95572
+ const response = await fetchV4(url3, { method: "POST", headers, body: frame3 }, config4, "createEvent");
95173
95573
  const eventId = response.headers.get(V4_RESPONSE_HEADERS.eventId);
95174
95574
  const runId = response.headers.get(V4_RESPONSE_HEADERS.runId);
95175
95575
  const createdAt = response.headers.get(V4_RESPONSE_HEADERS.createdAt);
@@ -95193,11 +95593,7 @@ __name(readHeader, "readHeader");
95193
95593
  async function getEventV4(runId, eventId, config4) {
95194
95594
  const { baseUrl, headers } = await getHttpConfig(config4);
95195
95595
  const url3 = `${baseUrl}/v4/runs/${encodeURIComponent(runId)}/events/${encodeURIComponent(eventId)}`;
95196
- const response = await fetchV4(url3, { method: "GET", headers }, config4);
95197
- if (!response.ok) {
95198
- const errorBody = await response.text();
95199
- throwForErrorResponse(response.status, headersToRecord(response.headers), errorBody, "getEvent", url3);
95200
- }
95596
+ const response = await fetchV4(url3, { method: "GET", headers }, config4, "getEvent");
95201
95597
  const contentType = response.headers.get("content-type");
95202
95598
  if (!contentType?.startsWith(V4_FRAME_CONTENT_TYPE)) {
95203
95599
  throw new Error(`v4 getEvent: expected ${V4_FRAME_CONTENT_TYPE}, got ${contentType ?? "(none)"}`);
@@ -95210,11 +95606,7 @@ async function getEventV4(runId, eventId, config4) {
95210
95606
  }
95211
95607
  __name(getEventV4, "getEventV4");
95212
95608
  async function consumeListFrameStream(url3, headers, config4, opName) {
95213
- const response = await fetchV4(url3, { method: "GET", headers }, config4);
95214
- if (!response.ok) {
95215
- const errorBody = await response.text();
95216
- throwForErrorResponse(response.status, headersToRecord(response.headers), errorBody, opName, url3);
95217
- }
95609
+ const response = await fetchV4(url3, { method: "GET", headers }, config4, opName);
95218
95610
  const contentType = response.headers.get("content-type");
95219
95611
  if (!contentType?.startsWith(V4_FRAME_CONTENT_TYPE)) {
95220
95612
  throw new Error(`v4 ${opName}: expected ${V4_FRAME_CONTENT_TYPE}, got ${contentType ?? "(none)"}`);
@@ -95690,7 +96082,7 @@ async function getWorkflowRunEvents(params, config4) {
95690
96082
  __name(getWorkflowRunEvents, "getWorkflowRunEvents");
95691
96083
  async function createWorkflowRunEvent(id, data, params, config4) {
95692
96084
  try {
95693
- return await createWorkflowRunEventInner(id, data, params, config4);
96085
+ return await withEventPostRetry(() => createWorkflowRunEventInner(id, data, params, config4), data.eventType);
95694
96086
  } catch (err) {
95695
96087
  if (hookEventsRequiringExistence.has(data.eventType) && WorkflowWorldError2.is(err) && err.status === 404 && data.correlationId) {
95696
96088
  throw new HookNotFoundError2(data.correlationId);
@@ -95895,13 +96287,10 @@ function getStreamReadUrl(name, runId, httpConfig) {
95895
96287
  }
95896
96288
  __name(getStreamReadUrl, "getStreamReadUrl");
95897
96289
  function createStreamRequestError(operation, url3, response, text) {
95898
- const context2 = [`PUT ${url3.origin}${url3.pathname}`];
95899
- for (const header of ["x-vercel-id", "x-vercel-error"]) {
95900
- const value = response.headers.get(header);
95901
- if (value) {
95902
- context2.push(`${header}=${value}`);
95903
- }
95904
- }
96290
+ const context2 = [
96291
+ `PUT ${url3.origin}${url3.pathname}`,
96292
+ ...getVercelDiagnostics(response.headers)
96293
+ ];
95905
96294
  return new Error(`Stream ${operation} failed: HTTP ${response.status} (${context2.join("; ")}): ${text}`);
95906
96295
  }
95907
96296
  __name(createStreamRequestError, "createStreamRequestError");
@@ -95946,17 +96335,17 @@ function createStreamer2(config4) {
95946
96335
  const resolvedRunId = await runId;
95947
96336
  const httpConfig = await getHttpConfig(config4);
95948
96337
  const url3 = getStreamUrl(name, resolvedRunId, httpConfig);
95949
- const response = await fetch(url3, {
96338
+ const response = await instrumentedFetch({
95950
96339
  method: "PUT",
96340
+ url: url3.toString(),
95951
96341
  body: chunk,
95952
96342
  headers: httpConfig.headers,
95953
- // eslint-disable-next-line @typescript-eslint/no-explicit-any -- undici dispatcher type doesn't match @types/node's RequestInit
95954
- dispatcher: getStreamDispatcher(config4)
96343
+ dispatcher: getStreamDispatcher(config4),
96344
+ timeoutMs: null,
96345
+ logLabel: url3.pathname,
96346
+ buildError: /* @__PURE__ */ __name(async (res) => createStreamRequestError("write", url3, res, await res.text()), "buildError")
95955
96347
  });
95956
- const text = await response.text();
95957
- if (!response.ok) {
95958
- throw createStreamRequestError("write", url3, response, text);
95959
- }
96348
+ await response.text();
95960
96349
  },
95961
96350
  async writeMulti(runId, name, chunks) {
95962
96351
  if (chunks.length === 0)
@@ -95968,17 +96357,17 @@ function createStreamer2(config4) {
95968
96357
  const batch = chunks.slice(i, i + MAX_CHUNKS_PER_REQUEST);
95969
96358
  const body = encodeMultiChunks(batch);
95970
96359
  const url3 = getStreamUrl(name, resolvedRunId, httpConfig);
95971
- const response = await fetch(url3, {
96360
+ const response = await instrumentedFetch({
95972
96361
  method: "PUT",
96362
+ url: url3.toString(),
95973
96363
  body,
95974
96364
  headers: httpConfig.headers,
95975
- // eslint-disable-next-line @typescript-eslint/no-explicit-any -- undici dispatcher type doesn't match @types/node's RequestInit
95976
- dispatcher: getStreamDispatcher(config4)
96365
+ dispatcher: getStreamDispatcher(config4),
96366
+ timeoutMs: null,
96367
+ logLabel: url3.pathname,
96368
+ buildError: /* @__PURE__ */ __name(async (res) => createStreamRequestError("write", url3, res, await res.text()), "buildError")
95977
96369
  });
95978
- const text = await response.text();
95979
- if (!response.ok) {
95980
- throw createStreamRequestError("write", url3, response, text);
95981
- }
96370
+ await response.text();
95982
96371
  }
95983
96372
  },
95984
96373
  async close(runId, name) {
@@ -95986,16 +96375,16 @@ function createStreamer2(config4) {
95986
96375
  const httpConfig = await getHttpConfig(config4);
95987
96376
  httpConfig.headers.set("X-Stream-Done", "true");
95988
96377
  const url3 = getStreamUrl(name, resolvedRunId, httpConfig);
95989
- const response = await fetch(url3, {
96378
+ const response = await instrumentedFetch({
95990
96379
  method: "PUT",
96380
+ url: url3.toString(),
95991
96381
  headers: httpConfig.headers,
95992
- // eslint-disable-next-line @typescript-eslint/no-explicit-any -- undici dispatcher type doesn't match @types/node's RequestInit
95993
- dispatcher: getStreamDispatcher(config4)
96382
+ dispatcher: getStreamDispatcher(config4),
96383
+ timeoutMs: null,
96384
+ logLabel: url3.pathname,
96385
+ buildError: /* @__PURE__ */ __name(async (res) => createStreamRequestError("close", url3, res, await res.text()), "buildError")
95994
96386
  });
95995
- const text = await response.text();
95996
- if (!response.ok) {
95997
- throw createStreamRequestError("close", url3, response, text);
95998
- }
96387
+ await response.text();
95999
96388
  },
96000
96389
  async get(runId, name, startIndex) {
96001
96390
  const httpConfig = await getHttpConfig(config4);
@@ -96003,12 +96392,15 @@ function createStreamer2(config4) {
96003
96392
  if (typeof startIndex === "number") {
96004
96393
  url3.searchParams.set("startIndex", String(startIndex));
96005
96394
  }
96006
- const response = await fetch(url3, {
96007
- headers: httpConfig.headers
96395
+ const response = await instrumentedFetch({
96396
+ method: "GET",
96397
+ url: url3.toString(),
96398
+ headers: httpConfig.headers,
96399
+ dispatcher: void 0,
96400
+ timeoutMs: null,
96401
+ logLabel: url3.pathname,
96402
+ buildError: /* @__PURE__ */ __name((res) => new Error(`Failed to fetch stream: ${res.status}`), "buildError")
96008
96403
  });
96009
- if (!response.ok) {
96010
- throw new Error(`Failed to fetch stream: ${response.status}`);
96011
- }
96012
96404
  if (!response.body) {
96013
96405
  throw new Error("No response body for stream");
96014
96406
  }
@@ -96041,12 +96433,15 @@ function createStreamer2(config4) {
96041
96433
  async list(runId) {
96042
96434
  const httpConfig = await getHttpConfig(config4);
96043
96435
  const url3 = new URL(`${httpConfig.baseUrl}/v2/runs/${encodeURIComponent(runId)}/streams`);
96044
- const response = await fetch(url3, {
96045
- headers: httpConfig.headers
96436
+ const response = await instrumentedFetch({
96437
+ method: "GET",
96438
+ url: url3.toString(),
96439
+ headers: httpConfig.headers,
96440
+ dispatcher: void 0,
96441
+ timeoutMs: null,
96442
+ logLabel: url3.pathname,
96443
+ buildError: /* @__PURE__ */ __name((res) => new Error(`Failed to list streams: ${res.status}`), "buildError")
96046
96444
  });
96047
- if (!response.ok) {
96048
- throw new Error(`Failed to list streams: ${response.status}`);
96049
- }
96050
96445
  return await response.json();
96051
96446
  }
96052
96447
  }
@@ -96256,7 +96651,7 @@ async function handleReplayBudgetExhausted(args) {
96256
96651
  specVersion: SPEC_VERSION_CURRENT2,
96257
96652
  eventData: {
96258
96653
  error: await dehydrateRunError(timeoutErr, runId, await getEncryptionKey()),
96259
- errorCode: RUN_ERROR_CODES.REPLAY_TIMEOUT
96654
+ errorCode: RUN_ERROR_CODES2.REPLAY_TIMEOUT
96260
96655
  }
96261
96656
  }, { requestId });
96262
96657
  } catch (err) {
@@ -96276,7 +96671,7 @@ async function handleReplayBudgetExhausted(args) {
96276
96671
  });
96277
96672
  process.exit(1);
96278
96673
  }
96279
- const replayTimeoutDescription = describeError(void 0, RUN_ERROR_CODES.REPLAY_TIMEOUT);
96674
+ const replayTimeoutDescription = describeError(void 0, RUN_ERROR_CODES2.REPLAY_TIMEOUT);
96280
96675
  runLogger.error("Workflow replay exceeded timeout and max retries exceeded. Failing the run", {
96281
96676
  timeoutMs: limitMs,
96282
96677
  attempt,
@@ -96292,7 +96687,7 @@ async function handleReplayBudgetExhausted(args) {
96292
96687
  specVersion: SPEC_VERSION_CURRENT2,
96293
96688
  eventData: {
96294
96689
  error: await dehydrateRunError(timeoutErr, runId, await getEncryptionKey()),
96295
- errorCode: RUN_ERROR_CODES.REPLAY_TIMEOUT
96690
+ errorCode: RUN_ERROR_CODES2.REPLAY_TIMEOUT
96296
96691
  }
96297
96692
  }, { requestId });
96298
96693
  } catch (err) {
@@ -99119,7 +99514,7 @@ function createSleep(ctx) {
99119
99514
  __name(createSleep, "createSleep");
99120
99515
 
99121
99516
  // ../core/dist/workflow.js
99122
- async function drainPendingQueueItems(runId, pendingQueue, vmGlobalThis, workflowRun, outcome) {
99517
+ async function drainPendingQueueItems(runId, pendingQueue, vmGlobalThis, workflowRun, outcome, runReadyBarrier) {
99123
99518
  if (pendingQueue.size === 0)
99124
99519
  return;
99125
99520
  for (const item of pendingQueue.values()) {
@@ -99133,7 +99528,8 @@ async function drainPendingQueueItems(runId, pendingQueue, vmGlobalThis, workflo
99133
99528
  await handleSuspension({
99134
99529
  suspension: synthesized,
99135
99530
  world,
99136
- run: workflowRun
99531
+ run: workflowRun,
99532
+ runReadyBarrier
99137
99533
  });
99138
99534
  } catch (err) {
99139
99535
  runtimeLogger2.warn(`Failed to drain pending queue items for ${outcome} workflow run`, {
@@ -99143,7 +99539,7 @@ async function drainPendingQueueItems(runId, pendingQueue, vmGlobalThis, workflo
99143
99539
  }
99144
99540
  }
99145
99541
  __name(drainPendingQueueItems, "drainPendingQueueItems");
99146
- async function runWorkflow(workflowCode2, workflowRun, events, encryptionKey, stepHydrationCache) {
99542
+ async function runWorkflow(workflowCode2, workflowRun, events, encryptionKey, stepHydrationCache, runReadyBarrier) {
99147
99543
  return trace3(`workflow.run ${workflowRun.workflowName}`, async (span) => {
99148
99544
  span?.setAttributes({
99149
99545
  ...WorkflowName2(workflowRun.workflowName),
@@ -99222,12 +99618,12 @@ async function runWorkflow(workflowCode2, workflowRun, events, encryptionKey, st
99222
99618
  });
99223
99619
  const useStep = createUseStep(workflowContext);
99224
99620
  const createHook = createCreateHook(workflowContext);
99225
- const sleep = createSleep(workflowContext);
99621
+ const sleep2 = createSleep(workflowContext);
99226
99622
  const setAttributes = createSetAttributes(workflowContext);
99227
99623
  vmGlobalThis[WORKFLOW_USE_STEP] = useStep;
99228
99624
  vmGlobalThis[WORKFLOW_SET_ATTRIBUTES] = setAttributes;
99229
99625
  vmGlobalThis[WORKFLOW_CREATE_HOOK] = createHook;
99230
- vmGlobalThis[WORKFLOW_SLEEP] = sleep;
99626
+ vmGlobalThis[WORKFLOW_SLEEP] = sleep2;
99231
99627
  vmGlobalThis[WORKFLOW_GET_STREAM_ID] = (namespace) => getWorkflowRunStreamId2(workflowRun.runId, namespace);
99232
99628
  const url3 = isVercel ? `https://${process.env.VERCEL_URL}` : `http://localhost:${port ?? 3e3}`;
99233
99629
  const ctx = {
@@ -99626,7 +100022,7 @@ Learn more: https://workflow-sdk.dev/err/${ERROR_SLUGS2.FETCH_IN_WORKFLOW_FUNCTI
99626
100022
  runCachedWorkflowScript(workflowCode2, filename, context2);
99627
100023
  const workflowFn = runCachedWorkflowScript(`globalThis.__private_workflows?.get(${JSON.stringify(workflowRun.workflowName)})`, filename, context2);
99628
100024
  if (typeof workflowFn !== "function") {
99629
- throw new WorkflowNotRegisteredError(workflowRun.workflowName);
100025
+ throw new WorkflowNotRegisteredError2(workflowRun.workflowName);
99630
100026
  }
99631
100027
  let args = [];
99632
100028
  workflowContext.promiseQueue = workflowContext.promiseQueue.then(async () => {
@@ -99655,13 +100051,13 @@ Learn more: https://workflow-sdk.dev/err/${ERROR_SLUGS2.FETCH_IN_WORKFLOW_FUNCTI
99655
100051
  span?.setAttributes({
99656
100052
  ...WorkflowResultType2(typeof result)
99657
100053
  });
99658
- await drainPendingQueueItems(workflowRun.runId, workflowContext.invocationsQueue, vmGlobalThis, workflowRun, "completed");
100054
+ await drainPendingQueueItems(workflowRun.runId, workflowContext.invocationsQueue, vmGlobalThis, workflowRun, "completed", runReadyBarrier);
99659
100055
  return dehydrated;
99660
100056
  } catch (err) {
99661
100057
  if (WorkflowSuspension2.is(err) || ReplayDivergenceError.is(err)) {
99662
100058
  throw err;
99663
100059
  }
99664
- await drainPendingQueueItems(workflowRun.runId, workflowContext.invocationsQueue, vmGlobalThis, workflowRun, "failed");
100060
+ await drainPendingQueueItems(workflowRun.runId, workflowContext.invocationsQueue, vmGlobalThis, workflowRun, "failed", runReadyBarrier);
99665
100061
  throw err;
99666
100062
  }
99667
100063
  });
@@ -100021,10 +100417,10 @@ var Run2 = class _Run2 {
100021
100417
  // ../core/dist/runtime.js
100022
100418
  function getWorkflowSetupErrorCode(err) {
100023
100419
  if (WorkflowRuntimeError2.is(err)) {
100024
- return RUN_ERROR_CODES.RUNTIME_ERROR;
100420
+ return RUN_ERROR_CODES2.RUNTIME_ERROR;
100025
100421
  }
100026
100422
  if (isWorldContractError(err)) {
100027
- return RUN_ERROR_CODES.WORLD_CONTRACT_ERROR;
100423
+ return RUN_ERROR_CODES2.WORLD_CONTRACT_ERROR;
100028
100424
  }
100029
100425
  return null;
100030
100426
  }
@@ -100052,7 +100448,7 @@ async function recordFatalRunError({ world, workflowRun, runId, requestId, err,
100052
100448
  if (isWorldContractError(failErr)) {
100053
100449
  runtimeLogger2.error("Fatal world contract error while recording workflow failure", {
100054
100450
  workflowRunId: runId,
100055
- errorCode: RUN_ERROR_CODES.WORLD_CONTRACT_ERROR,
100451
+ errorCode: RUN_ERROR_CODES2.WORLD_CONTRACT_ERROR,
100056
100452
  error: failErr instanceof Error ? failErr.message : String(failErr)
100057
100453
  });
100058
100454
  return;
@@ -100111,7 +100507,7 @@ function workflowEntrypoint(workflowCode2, options) {
100111
100507
  const workflowName = metadata.queueName.slice(workflowPrefix.length);
100112
100508
  const runLogger = runtimeLogger2.forRun(runId, workflowName);
100113
100509
  if (metadata.attempt > MAX_QUEUE_DELIVERIES) {
100114
- const maxDeliveriesDescription = describeError(void 0, RUN_ERROR_CODES.MAX_DELIVERIES_EXCEEDED);
100510
+ const maxDeliveriesDescription = describeError(void 0, RUN_ERROR_CODES2.MAX_DELIVERIES_EXCEEDED);
100115
100511
  runLogger.error(`Workflow handler exceeded max deliveries (${metadata.attempt}/${MAX_QUEUE_DELIVERIES})`, {
100116
100512
  attempt: metadata.attempt,
100117
100513
  errorCode: maxDeliveriesDescription.errorCode,
@@ -100126,7 +100522,7 @@ function workflowEntrypoint(workflowCode2, options) {
100126
100522
  specVersion: SPEC_VERSION_CURRENT2,
100127
100523
  eventData: {
100128
100524
  error: await dehydrateRunError(err, runId, await getEncryptionKey()),
100129
- errorCode: RUN_ERROR_CODES.MAX_DELIVERIES_EXCEEDED
100525
+ errorCode: RUN_ERROR_CODES2.MAX_DELIVERIES_EXCEEDED
100130
100526
  }
100131
100527
  }, { requestId });
100132
100528
  } catch (err) {
@@ -100551,7 +100947,18 @@ function workflowEntrypoint(workflowCode2, options) {
100551
100947
  eventCount: events.length
100552
100948
  });
100553
100949
  replayStart = Date.now();
100554
- const result = await runWorkflow(workflowCode2, workflowRun, events, encryptionKey, stepHydrationCache);
100950
+ const result = await runWorkflow(
100951
+ workflowCode2,
100952
+ workflowRun,
100953
+ events,
100954
+ encryptionKey,
100955
+ stepHydrationCache,
100956
+ // Turbo: the end-of-run drain inside runWorkflow commits
100957
+ // fire-and-forget `*_created` events before the terminal
100958
+ // `awaitRunReady()` below, so gate those writes on the
100959
+ // backgrounded run_started too. Undefined outside turbo.
100960
+ runReadyBarrier
100961
+ );
100555
100962
  runtimeLogger2.debug("Workflow replay completed", {
100556
100963
  workflowRunId: runId,
100557
100964
  loopIteration,
@@ -100797,12 +101204,20 @@ function workflowEntrypoint(workflowCode2, options) {
100797
101204
  }
100798
101205
  }
100799
101206
  } else {
101207
+ if (isRetryableWorldError2(err)) {
101208
+ runLogger.warn("Transient world error during replay; redelivering via queue instead of failing the run", {
101209
+ errorName: err instanceof Error ? err.name : "UnknownError",
101210
+ errorMessage: err instanceof Error ? err.message : String(err),
101211
+ deliveryAttempt: metadata.attempt
101212
+ });
101213
+ throw err;
101214
+ }
100800
101215
  let terminalError = err;
100801
101216
  if (ReplayDivergenceError.is(err)) {
100802
101217
  const divergenceCount = (replayDivergence?.count ?? 0) + 1;
100803
101218
  if (divergenceCount <= REPLAY_DIVERGENCE_MAX_RETRIES) {
100804
101219
  runLogger.warn("Workflow replay diverged; queueing a recovery replay before declaring the event log corrupted", {
100805
- errorCode: RUN_ERROR_CODES.REPLAY_DIVERGENCE,
101220
+ errorCode: RUN_ERROR_CODES2.REPLAY_DIVERGENCE,
100806
101221
  divergenceEventId: err.eventId,
100807
101222
  priorDivergenceEventId: replayDivergence?.eventId,
100808
101223
  divergenceCount,
@@ -100866,7 +101281,7 @@ function workflowEntrypoint(workflowCode2, options) {
100866
101281
  if (isWorldContractError(failErr)) {
100867
101282
  runtimeLogger2.error("Fatal world contract error while recording workflow failure", {
100868
101283
  workflowRunId: runId,
100869
- errorCode: RUN_ERROR_CODES.WORLD_CONTRACT_ERROR,
101284
+ errorCode: RUN_ERROR_CODES2.WORLD_CONTRACT_ERROR,
100870
101285
  error: failErr instanceof Error ? failErr.message : String(failErr)
100871
101286
  });
100872
101287
  return;
@@ -117204,10 +117619,10 @@ var Run = class _Run {
117204
117619
  return this.getReadable();
117205
117620
  }
117206
117621
  };
117207
- Run.prototype["wakeUp"] = globalThis[/* @__PURE__ */ Symbol.for("WORKFLOW_USE_STEP")]("step//@workflow/core/runtime/run@5.0.0-beta.25//Run#wakeUp");
117208
- Run.prototype["cancel"] = globalThis[/* @__PURE__ */ Symbol.for("WORKFLOW_USE_STEP")]("step//@workflow/core/runtime/run@5.0.0-beta.25//Run#cancel");
117209
- Run.prototype["getReadable"] = globalThis[/* @__PURE__ */ Symbol.for("WORKFLOW_USE_STEP")]("step//@workflow/core/runtime/run@5.0.0-beta.25//Run#getReadable");
117210
- var __step_Run$exists = globalThis[/* @__PURE__ */ Symbol.for("WORKFLOW_USE_STEP")]("step//@workflow/core/runtime/run@5.0.0-beta.25//Run#exists");
117622
+ Run.prototype["wakeUp"] = globalThis[/* @__PURE__ */ Symbol.for("WORKFLOW_USE_STEP")]("step//@workflow/core/runtime/run@5.0.0-beta.26//Run#wakeUp");
117623
+ Run.prototype["cancel"] = globalThis[/* @__PURE__ */ Symbol.for("WORKFLOW_USE_STEP")]("step//@workflow/core/runtime/run@5.0.0-beta.26//Run#cancel");
117624
+ Run.prototype["getReadable"] = globalThis[/* @__PURE__ */ Symbol.for("WORKFLOW_USE_STEP")]("step//@workflow/core/runtime/run@5.0.0-beta.26//Run#getReadable");
117625
+ var __step_Run$exists = globalThis[/* @__PURE__ */ Symbol.for("WORKFLOW_USE_STEP")]("step//@workflow/core/runtime/run@5.0.0-beta.26//Run#exists");
117211
117626
  Object.defineProperty(Run.prototype, "exists", {
117212
117627
  get() {
117213
117628
  return __step_Run$exists.call(this);
@@ -117215,7 +117630,7 @@ Object.defineProperty(Run.prototype, "exists", {
117215
117630
  configurable: true,
117216
117631
  enumerable: false
117217
117632
  });
117218
- var __step_Run$status = globalThis[/* @__PURE__ */ Symbol.for("WORKFLOW_USE_STEP")]("step//@workflow/core/runtime/run@5.0.0-beta.25//Run#status");
117633
+ var __step_Run$status = globalThis[/* @__PURE__ */ Symbol.for("WORKFLOW_USE_STEP")]("step//@workflow/core/runtime/run@5.0.0-beta.26//Run#status");
117219
117634
  Object.defineProperty(Run.prototype, "status", {
117220
117635
  get() {
117221
117636
  return __step_Run$status.call(this);
@@ -117223,7 +117638,7 @@ Object.defineProperty(Run.prototype, "status", {
117223
117638
  configurable: true,
117224
117639
  enumerable: false
117225
117640
  });
117226
- var __step_Run$returnValue = globalThis[/* @__PURE__ */ Symbol.for("WORKFLOW_USE_STEP")]("step//@workflow/core/runtime/run@5.0.0-beta.25//Run#returnValue");
117641
+ var __step_Run$returnValue = globalThis[/* @__PURE__ */ Symbol.for("WORKFLOW_USE_STEP")]("step//@workflow/core/runtime/run@5.0.0-beta.26//Run#returnValue");
117227
117642
  Object.defineProperty(Run.prototype, "returnValue", {
117228
117643
  get() {
117229
117644
  return __step_Run$returnValue.call(this);
@@ -117231,7 +117646,7 @@ Object.defineProperty(Run.prototype, "returnValue", {
117231
117646
  configurable: true,
117232
117647
  enumerable: false
117233
117648
  });
117234
- var __step_Run$workflowName = globalThis[/* @__PURE__ */ Symbol.for("WORKFLOW_USE_STEP")]("step//@workflow/core/runtime/run@5.0.0-beta.25//Run#workflowName");
117649
+ var __step_Run$workflowName = globalThis[/* @__PURE__ */ Symbol.for("WORKFLOW_USE_STEP")]("step//@workflow/core/runtime/run@5.0.0-beta.26//Run#workflowName");
117235
117650
  Object.defineProperty(Run.prototype, "workflowName", {
117236
117651
  get() {
117237
117652
  return __step_Run$workflowName.call(this);
@@ -117239,7 +117654,7 @@ Object.defineProperty(Run.prototype, "workflowName", {
117239
117654
  configurable: true,
117240
117655
  enumerable: false
117241
117656
  });
117242
- var __step_Run$createdAt = globalThis[/* @__PURE__ */ Symbol.for("WORKFLOW_USE_STEP")]("step//@workflow/core/runtime/run@5.0.0-beta.25//Run#createdAt");
117657
+ var __step_Run$createdAt = globalThis[/* @__PURE__ */ Symbol.for("WORKFLOW_USE_STEP")]("step//@workflow/core/runtime/run@5.0.0-beta.26//Run#createdAt");
117243
117658
  Object.defineProperty(Run.prototype, "createdAt", {
117244
117659
  get() {
117245
117660
  return __step_Run$createdAt.call(this);
@@ -117247,7 +117662,7 @@ Object.defineProperty(Run.prototype, "createdAt", {
117247
117662
  configurable: true,
117248
117663
  enumerable: false
117249
117664
  });
117250
- var __step_Run$startedAt = globalThis[/* @__PURE__ */ Symbol.for("WORKFLOW_USE_STEP")]("step//@workflow/core/runtime/run@5.0.0-beta.25//Run#startedAt");
117665
+ var __step_Run$startedAt = globalThis[/* @__PURE__ */ Symbol.for("WORKFLOW_USE_STEP")]("step//@workflow/core/runtime/run@5.0.0-beta.26//Run#startedAt");
117251
117666
  Object.defineProperty(Run.prototype, "startedAt", {
117252
117667
  get() {
117253
117668
  return __step_Run$startedAt.call(this);
@@ -117255,7 +117670,7 @@ Object.defineProperty(Run.prototype, "startedAt", {
117255
117670
  configurable: true,
117256
117671
  enumerable: false
117257
117672
  });
117258
- var __step_Run$completedAt = globalThis[/* @__PURE__ */ Symbol.for("WORKFLOW_USE_STEP")]("step//@workflow/core/runtime/run@5.0.0-beta.25//Run#completedAt");
117673
+ var __step_Run$completedAt = globalThis[/* @__PURE__ */ Symbol.for("WORKFLOW_USE_STEP")]("step//@workflow/core/runtime/run@5.0.0-beta.26//Run#completedAt");
117259
117674
  Object.defineProperty(Run.prototype, "completedAt", {
117260
117675
  get() {
117261
117676
  return __step_Run$completedAt.call(this);
@@ -117272,7 +117687,7 @@ Object.defineProperty(Run.prototype, "completedAt", {
117272
117687
  enumerable: false,
117273
117688
  configurable: false
117274
117689
  });
117275
- })(Run, "class//@workflow/core/runtime/run@5.0.0-beta.25//Run");
117690
+ })(Run, "class//@workflow/core/runtime/run@5.0.0-beta.26//Run");
117276
117691
 
117277
117692
  // ../core/dist/workflow/create-hook.js
117278
117693
  aliasSerializationClass(RUN_CLASS_ID, Run);