eve 0.31.0 → 0.31.2

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.
Files changed (93) hide show
  1. package/CHANGELOG.md +15 -0
  2. package/dist/src/channel/cross-channel-receive.d.ts +1 -1
  3. package/dist/src/compiled/.vendor-stamp.json +6 -6
  4. package/dist/src/compiled/@workflow/core/_quickjs-wasi.d.ts +8 -0
  5. package/dist/src/compiled/@workflow/core/correlation-id.d.ts +109 -0
  6. package/dist/src/compiled/@workflow/core/events-consumer.d.ts +1 -0
  7. package/dist/src/compiled/@workflow/core/index.js +2 -2
  8. package/dist/src/compiled/@workflow/core/private.d.ts +17 -1
  9. package/dist/src/compiled/@workflow/core/private.js +1 -1
  10. package/dist/src/compiled/@workflow/core/runtime/constants.d.ts +19 -0
  11. package/dist/src/compiled/@workflow/core/runtime/deployment-guard.d.ts +99 -0
  12. package/dist/src/compiled/@workflow/core/runtime/quickjs-assets.generated.d.ts +14 -0
  13. package/dist/src/compiled/@workflow/core/runtime/quickjs-entrypoint.d.ts +124 -0
  14. package/dist/src/compiled/@workflow/core/runtime/quickjs-runtime.d.ts +193 -0
  15. package/dist/src/compiled/@workflow/core/runtime/run.d.ts +2 -0
  16. package/dist/src/compiled/@workflow/core/runtime/runs.d.ts +18 -1
  17. package/dist/src/compiled/@workflow/core/runtime/suspension-handler.d.ts +7 -0
  18. package/dist/src/compiled/@workflow/core/runtime/vm-mode.d.ts +44 -0
  19. package/dist/src/compiled/@workflow/core/runtime/vm-serde-bundle.generated.d.ts +14 -0
  20. package/dist/src/compiled/@workflow/core/runtime.d.ts +1 -1
  21. package/dist/src/compiled/@workflow/core/runtime.js +3 -3
  22. package/dist/src/compiled/@workflow/core/serialization/codec-devalue-vm.d.ts +9 -0
  23. package/dist/src/compiled/@workflow/core/serialization/reducers/class-vm.d.ts +20 -0
  24. package/dist/src/compiled/@workflow/core/serialization/reducers/common-vm.d.ts +15 -0
  25. package/dist/src/compiled/@workflow/core/serialization/reducers/step-function-vm.d.ts +44 -0
  26. package/dist/src/compiled/@workflow/core/serialization/vm-bundle-entry.d.ts +12 -0
  27. package/dist/src/compiled/@workflow/core/serialization/workflow-vm.d.ts +24 -0
  28. package/dist/src/compiled/@workflow/core/serialization.d.ts +2 -1
  29. package/dist/src/compiled/@workflow/core/source-map.d.ts +20 -0
  30. package/dist/src/compiled/@workflow/core/telemetry/semantic-conventions.d.ts +78 -0
  31. package/dist/src/compiled/@workflow/core/telemetry.d.ts +5 -0
  32. package/dist/src/compiled/@workflow/core/version.d.ts +1 -1
  33. package/dist/src/compiled/@workflow/core/workflow.js +1 -1
  34. package/dist/src/compiled/@workflow/errors/error-codes.d.ts +2 -0
  35. package/dist/src/compiled/@workflow/errors/index.d.ts +24 -0
  36. package/dist/src/compiled/@workflow/errors/index.js +1 -1
  37. package/dist/src/compiled/@workflow/world/analytics.d.ts +2 -0
  38. package/dist/src/compiled/@workflow/world/events.d.ts +51 -1
  39. package/dist/src/compiled/@workflow/world/hooks.d.ts +1 -0
  40. package/dist/src/compiled/@workflow/world/index.d.ts +1 -1
  41. package/dist/src/compiled/@workflow/world/interfaces.d.ts +28 -1
  42. package/dist/src/compiled/@workflow/world/queue.d.ts +8 -0
  43. package/dist/src/compiled/@workflow/world/runs.d.ts +83 -0
  44. package/dist/src/compiled/@workflow/world-local/index.js +5 -4
  45. package/dist/src/compiled/@workflow/world-vercel/index.js +15 -15
  46. package/dist/src/compiled/_chunks/workflow/_eve-core-quickjs-entrypoint-stub-qIV0OaFz.js +1 -0
  47. package/dist/src/compiled/_chunks/workflow/{attribute-changes-DROfGk6l.js → attribute-changes-Du5ztewf.js} +2 -2
  48. package/dist/src/compiled/_chunks/workflow/{dist-D5bR13zs.js → dist-CNXUKQCp.js} +1 -1
  49. package/dist/src/compiled/_chunks/workflow/dist-CRTn4Sg8.js +3 -0
  50. package/dist/src/compiled/_chunks/workflow/dist-tJoQXAF6.js +1 -0
  51. package/dist/src/compiled/_chunks/workflow/functions-ClJbpZhR.js +1 -0
  52. package/dist/src/compiled/_chunks/workflow/{private-BcwCGTV5.js → private-CiWVdS5v.js} +1 -1
  53. package/dist/src/compiled/_chunks/workflow/resume-hook-CT0keOww.js +1 -0
  54. package/dist/src/compiled/_chunks/workflow/run-DBheaFhH.js +1 -0
  55. package/dist/src/compiled/_chunks/workflow/signal-exit-C8vsI6zj.js +1 -0
  56. package/dist/src/compiled/_chunks/workflow/sleep-BeH4B0Cd.js +1 -0
  57. package/dist/src/compiled/_chunks/workflow/{token-hiUWkDKe.js → token-DtCUEpJs.js} +1 -1
  58. package/dist/src/compiled/_chunks/workflow/{token-util-DURSL1l8.js → token-util-DNwIAn_u.js} +9 -9
  59. package/dist/src/compiled/_chunks/workflow/undici-CUIybhQ2.js +95 -0
  60. package/dist/src/compiled/_chunks/workflow/wait-until-CMX5LUWJ.js +15 -0
  61. package/dist/src/compiler/extension-compatibility.d.ts +2 -2
  62. package/dist/src/compiler/extension-compatibility.js +1 -1
  63. package/dist/src/context/container.d.ts +3 -0
  64. package/dist/src/context/container.js +1 -1
  65. package/dist/src/discover/filesystem.js +1 -1
  66. package/dist/src/execution/parked-delivery-wait.js +1 -1
  67. package/dist/src/execution/session-command-inbox.d.ts +11 -3
  68. package/dist/src/execution/session-command-wire.d.ts +24 -0
  69. package/dist/src/execution/session-command-wire.js +1 -0
  70. package/dist/src/execution/turn-control-receiver.js +1 -1
  71. package/dist/src/execution/workflow-runtime.js +1 -1
  72. package/dist/src/execution/workflow-steps.js +1 -1
  73. package/dist/src/harness/authorization.d.ts +8 -0
  74. package/dist/src/harness/authorization.js +1 -1
  75. package/dist/src/internal/application/package.js +1 -1
  76. package/dist/src/internal/nitro/dev-runtime-source-snapshot-copy.js +1 -1
  77. package/dist/src/internal/nitro/host/dev-authored-source-watcher.js +1 -1
  78. package/dist/src/public/definitions/tool.d.ts +18 -14
  79. package/dist/src/runtime/connections/scoped-authorization.js +1 -1
  80. package/dist/src/runtime/framework-tools/connection-search-dynamic.js +2 -2
  81. package/dist/src/setup/scaffold/create/project.js +1 -1
  82. package/docs/guides/meta.json +2 -1
  83. package/docs/guides/remote-agents.md +6 -4
  84. package/docs/guides/ucp.mdx +181 -0
  85. package/package.json +6 -6
  86. package/dist/src/compiled/_chunks/workflow/dist-B-vbuNqP.js +0 -1
  87. package/dist/src/compiled/_chunks/workflow/dist-dNxTT6nO.js +0 -3
  88. package/dist/src/compiled/_chunks/workflow/functions-CiVUVDNB.js +0 -1
  89. package/dist/src/compiled/_chunks/workflow/resume-hook-bc-OQVI0.js +0 -1
  90. package/dist/src/compiled/_chunks/workflow/run-DM3ouA3U.js +0 -1
  91. package/dist/src/compiled/_chunks/workflow/sleep-D5iWly6-.js +0 -1
  92. package/dist/src/compiled/_chunks/workflow/undici-DWL_MYmT.js +0 -95
  93. package/dist/src/compiled/_chunks/workflow/wait-until-DoW76jdb.js +0 -15
@@ -1,3 +1,3 @@
1
- import{i as e,o as t,t as n}from"../../_chunks/workflow/rolldown-runtime-DaDcL9Zw.js";import{$ as r,$t as i,At as a,B as o,Bt as s,C as c,Cn as l,Ct as u,D as d,Dt as f,E as p,En as m,Et as h,F as g,Ft as _,G as v,Gn as y,Gt as b,H as x,Ht as S,I as C,It as w,J as T,Jn as E,Jt as ee,K as D,Kn as O,Kt as k,L as A,Ln as j,Lt as M,Mt as N,Nn as P,Nt as te,On as ne,Ot as F,P as re,Pt as I,Q as L,Qt as ie,Rn as R,Rt as z,St as ae,T as B,Tn as V,Tt as oe,U as se,Ut as ce,V as le,Vt as ue,W as de,Wn as fe,Wt as pe,X as me,Xt as he,Y as H,Yn as ge,Yt as _e,Z as ve,Zt as ye,_n as U,_t as be,a as xe,an as Se,at as Ce,b as we,bt as Te,c as Ee,cn as De,ct as Oe,d as ke,dn as Ae,dt as je,en as Me,er as Ne,et as Pe,f as Fe,fn as Ie,g as Le,gn as Re,h as ze,hn as Be,ht as Ve,i as He,in as Ue,it as W,jt as We,k as Ge,kt as Ke,l as qe,ln as Je,lt as Ye,m as Xe,mn as Ze,nn as Qe,nr as $e,o as et,on as tt,ot as nt,p as rt,pn as it,q as at,qn as ot,qt as st,r as ct,rn as lt,rr as ut,s as dt,sn as ft,t as pt,tn as mt,tr as ht,tt as gt,u as _t,un as vt,ut as yt,v as bt,vn as G,vt as xt,w as St,wt as Ct,xt as wt,y as Tt,yt as Et,z as Dt,zt as Ot}from"../../_chunks/workflow/wait-until-DoW76jdb.js";import{a as kt,n as At,r as jt,s as Mt,t as Nt}from"../../_chunks/workflow/private-BcwCGTV5.js";import{t as Pt}from"../../_chunks/workflow/dist-B-vbuNqP.js";import{a as Ft,n as It}from"../../_chunks/workflow/workflow-routes-CwqB063q.js";import{D as Lt,E as K,O as q,_ as Rt,a as zt,c as Bt,d as J,g as Vt,i as Y,l as X,m as Ht,n as Ut,o as Wt,r as Z,s as Gt,t as Kt,u as qt,x as Jt}from"../../_chunks/workflow/dist-dNxTT6nO.js";import{d as Yt,l as Xt,n as Zt,s as Qt,u as $t}from"../../_chunks/workflow/attribute-changes-DROfGk6l.js";import{K as en,W as tn,_ as nn,a as rn,g as an,o as on,s as sn,y as cn}from"../../_chunks/workflow/dist-D5bR13zs.js";import{t as ln}from"../../_chunks/workflow/env-config-CYoX3muK.js";import{t as un}from"../../_chunks/workflow/spec-version-C0hBsfu-.js";import{n as dn,r as fn,t as pn}from"../../_chunks/workflow/resume-hook-bc-OQVI0.js";import{a as mn,c as hn,i as gn,l as _n,n as vn,o as yn,r as bn,s as xn,t as Sn}from"../../_chunks/workflow/run-DM3ouA3U.js";import{t as Cn}from"../../_chunks/workflow/run-id-BdE0MZz9.js";import{createRequire as wn}from"node:module";import{createHash as Tn}from"node:crypto";import{types as Q}from"node:util";import{pathToFileURL as En}from"node:url";import{Script as Dn,createContext as On,runInContext as kn}from"node:vm";function An(e=process.env){return e.WORKFLOW_TARGET_WORLD||(e.VERCEL_DEPLOYMENT_ID?`vercel`:`local`)}function jn(e){return e===`vercel`||e===`@workflow/world-vercel`}function Mn(e){return e instanceof $t||e instanceof Xt||e instanceof Yt||e instanceof Zt}const Nn=`The workflow event log contains orphaned or mismatched events and cannot be replayed. This is an internal workflow SDK error; please report it with the runId.`;function Pn(e,t){let n=t??bt(e);return Ht.is(e)?{attribution:`user`,errorCode:n,hint:`A value passed across a workflow/step boundary could not be serialized. See the error message for the offending path and the Learn More link for details.`}:Mn(e)?{attribution:`user`,errorCode:n,hint:`A workflow-only or step-only API was called from the wrong context. The error message includes the exact API and how to move the call.`}:Kt.is(e)?{attribution:`sdk`,errorCode:n,hint:Nn}:e instanceof K?{attribution:`sdk`,errorCode:n,hint:`This is an internal workflow SDK error, not a bug in your code. If it keeps happening, please report it with the stack trace and the runId.`}:n===q.REPLAY_TIMEOUT?{attribution:`sdk`,errorCode:n,hint:'The workflow replay between step boundaries took too long. This bounds workflow-VM and event-log replay time only — step bodies (`"use step"` functions) are excluded. This usually means the event log is unusually large or the workflow function is doing heavy synchronous work in workflow code outside of step bodies. Override the default budget via the WORKFLOW_REPLAY_TIMEOUT_MS env var if needed.'}:n===q.MAX_DELIVERIES_EXCEEDED?{attribution:`sdk`,errorCode:n,hint:`The workflow queue exceeded its max-delivery budget. This usually indicates a persistent runtime failure — check the most recent stack traces for the underlying cause.`}:n===q.MAX_EVENTS_EXCEEDED?{attribution:`user`,errorCode:n,hint:`The workflow exceeded the maximum number of events per run. This usually means unbounded work in the workflow function — e.g. a loop that keeps creating steps without terminating. Break long-running workflows into child workflows to stay under the limit.`}:n===q.CORRUPTED_EVENT_LOG?{attribution:`sdk`,errorCode:n,hint:Nn}:n===q.WORLD_CONTRACT_ERROR?{attribution:`sdk`,errorCode:n,hint:`The workflow backend returned data that violated the SDK contract. This is not retryable; please report it with the stack trace and runId.`}:{attribution:`user`,errorCode:n}}const Fn=4096;function In(e){if(e===null)return!0;let t=typeof e;return t===`object`||t===`function`?!1:t===`string`?e.length<=Fn:t!==`bigint`||e.toString().length<=Fn}var Ln=class{encryptionKey;preparer;preparedPayloads=new Map;primitiveStepResults=new Map;nextUnscannedEventIndex=0;constructor(e,t=Dt){this.encryptionKey=e,this.preparer=t}async prewarm(e,t){let n=[],r=(e,t)=>{t instanceof Uint8Array&&(this.preparedPayloads.has(e)||n.push(this.ensurePreparation(e,t)))};r(this.workflowInputKey(e.runId),e.input);for(let e=this.nextUnscannedEventIndex;e<t.length;e++){let n=t[e];switch(n.eventType){case`step_completed`:r(this.eventPayloadKey(n.eventId,`result`),n.eventData?.result);break;case`step_failed`:r(this.eventPayloadKey(n.eventId,`error`),n.eventData?.error);break;case`hook_received`:r(this.eventPayloadKey(n.eventId,`payload`),n.eventData?.payload);break}}this.nextUnscannedEventIndex=t.length,await Promise.allSettled(n)}resetScan(){this.nextUnscannedEventIndex=0}prepareWorkflowInput(e){return this.consumePreparation(this.workflowInputKey(e.runId),e.input)}prepareEventPayload(e,t,n){return this.consumePreparation(this.eventPayloadKey(e,t),n)}async getStepResult(e,t){if(this.primitiveStepResults.has(e))return this.primitiveStepResults.get(e);let n=await t();return In(n)&&this.primitiveStepResults.set(e,n),n}consumePreparation(e,t){if(!(t instanceof Uint8Array))return this.runPreparation(t);let n=this.ensurePreparation(e,t);return n.catch(()=>{this.preparedPayloads.get(e)===n&&this.preparedPayloads.delete(e)}),n}ensurePreparation(e,t){let n=this.preparedPayloads.get(e);if(n)return n;let r=this.runPreparation(t);return this.preparedPayloads.set(e,r),r}async runPreparation(e){return this.preparer(e,this.encryptionKey)}workflowInputKey(e){return`run:${e}:input`}eventPayloadKey(e,t){return`event:${e}:${t}`}};const Rn=`cinst_${sn()}`;function zn(){return ln(`WORKFLOW_MAX_QUEUE_DELIVERIES`,48,{integer:!0,min:1,max:48})}const Bn=24e4,Vn=3e4,Hn=78e4,Un=new Set;function Wn(e,t,n){Un.has(e)||(Un.add(e),T.warn(t,n))}function Gn(){let e=process.env.WORKFLOW_REPLAY_TIMEOUT_MS;if(!e)return Bn;let t=Number(e);return!Number.isFinite(t)||t<=0?(Wn(e,`Ignoring WORKFLOW_REPLAY_TIMEOUT_MS: not a positive finite number; using default`,{raw:e,defaultMs:Bn}),Bn):t<3e4?(Wn(e,`WORKFLOW_REPLAY_TIMEOUT_MS below minimum; clamped`,{raw:e,clampedMs:Vn,minMs:Vn}),Vn):t>78e4?(Wn(e,`WORKFLOW_REPLAY_TIMEOUT_MS above maximum; clamped`,{raw:e,clampedMs:Hn,maxMs:Hn}),Hn):t}function Kn(){return ln(`WORKFLOW_REPLAY_TIMEOUT_MAX_RETRIES`,3,{integer:!0})}const qn=new Set;function Jn(){let e=process.env.WORKFLOW_MAX_INLINE_STEPS;if(!e)return 3;let t=Number(e);return!Number.isInteger(t)||t<=0?(qn.has(e)||(qn.add(e),T.warn(`Ignoring WORKFLOW_MAX_INLINE_STEPS: not a positive integer; using default`,{raw:e,defaultValue:3})),3):t<1?1:t>16?(qn.has(e)||(qn.add(e),T.warn(`WORKFLOW_MAX_INLINE_STEPS above maximum; clamped`,{raw:e,clampedValue:16,maxValue:16})),16):t}const Yn=new Set;function Xn(){let e=process.env.WORKFLOW_MAX_EVENTS_OVERRIDE;if(!e)return;let t=Number(e);if(!Number.isInteger(t)||t<=0){Yn.has(e)||(Yn.add(e),T.warn(`Ignoring WORKFLOW_MAX_EVENTS_OVERRIDE: not a positive integer; using server limit`,{raw:e}));return}return t}function Zn(){let e=process.env.WORKFLOW_OPTIMISTIC_INLINE_START;return e===void 0||e===``?!1:e===`1`||e.toLowerCase()===`true`}function Qn(){let e=process.env.WORKFLOW_OPTIMISTIC_INLINE_START;return e===void 0||e===``?!1:e===`0`||e.toLowerCase()===`false`}function $n(){let e=process.env.WORKFLOW_TURBO;return e===void 0||e===``||!(e===`0`||e.toLowerCase()===`false`)}function er(){let e=process.env.WORKFLOW_INLINE_OWNERSHIP;return e===void 0||e===``||!(e===`0`||e.toLowerCase()===`false`)}function tr(){return ln(`WORKFLOW_INLINE_OWNERSHIP_LEASE_SECONDS`,860,{integer:!0,min:1,max:900})}function nr(){return ln(`WORKFLOW_REPLAY_DIVERGENCE_MAX_RETRIES`,3,{integer:!0})}function rr(){return ln(`WORKFLOW_PRECONDITION_MAX_INPROCESS_RESTARTS`,3,{integer:!0})}function ir(){return ln(`WORKFLOW_PRECONDITION_MAX_REINVOCATIONS`,5,{integer:!0})}function ar(){return ln(`WORKFLOW_PRECONDITION_REINVOKE_DELAY_SECONDS`,2,{integer:!0})}const or=e=>`eventData`in e&&e.eventData&&`ownerMessageId`in e.eventData&&typeof e.eventData.ownerMessageId==`string`?e.eventData.ownerMessageId:void 0;function sr(e,t,n){if(!e)return 0;let r=0,i=new Map;for(let n of e){if(n.eventType!==`step_started`||n.correlationId!==t)continue;let e=or(n);e===void 0?r++:i.set(e,(i.get(e)??0)+1)}if(n===void 0){let e=r;for(let t of i.values())e+=t;return e}if(n.type===`ownedBy`)return i.get(n.messageId)??0;let a=0;for(let e of i.values())e>a&&(a=e);return r+a}function cr(){throw Error(`Unsupported in eve: @workflow/core createWorld(). eve selects and wires the workflow world explicitly at build time.`)}function lr(){try{return wn(En(process.cwd()+`/package.json`).href)}catch{return wn(import.meta.url)}}const ur=Symbol.for(`@workflow/world//cache`),dr=Symbol.for(`@workflow/world//stubbedCache`),fr=Symbol.for(`@workflow/world//cachePromise`),pr=Symbol.for(`@workflow/world//stubbedCachePromise`),$=globalThis;function mr(e){if(typeof e.createWorld==`function`)return e.createWorld();if(typeof e.default==`function`)return e.default();if(e.default&&typeof e.default==`object`)return e.default;throw Error(`Invalid target world module: must export createWorld(), a default factory, or a default World instance.`)}function hr(e){if(e.startsWith(`file://`))return e;if(e.startsWith(`/`))return En(e).href;if(e.startsWith(`./`)||e.startsWith(`../`))return En(process.cwd()+`/`+e).href;try{return En(lr().resolve(e)).href}catch{return e}}const gr=async()=>{let e=An();if(jn(e)){let e=[`WORKFLOW_VERCEL_PROJECT`,`WORKFLOW_VERCEL_TEAM`,`WORKFLOW_VERCEL_AUTH_TOKEN`,`WORKFLOW_VERCEL_ENV`].filter(e=>process.env[e]);return e.length>0&&process.env.VERCEL===`1`&&console.warn(`[workflow] Warning: ${e.join(`, `)} env var(s) are set but have no effect at runtime. These are only used by the Workflow CLI. Remove them from your Vercel project environment variables.`),cr()}if(e===`local`)return cr({dataDir:process.env.WORKFLOW_LOCAL_DATA_DIR});let t;try{t=lr()(e)}catch{t=await import(hr(e))}if(typeof t==`function`)return t();try{return await mr(t)}catch{throw Error(`Invalid target world module: ${e}, must export a createWorld function or a default function that returns a World instance.`)}},_r=async()=>{if($[dr])return P($[dr]),$[dr];$[pr]||($[pr]=gr().catch(e=>{throw $[pr]=void 0,e}));let e=await $[pr];return P(e),$[dr]=e,{createQueueHandler:e.createQueueHandler,specVersion:e.specVersion}},vr=async()=>$[ur]?(P($[ur]),$[ur]):($[fr]||($[fr]=gr().catch(e=>{throw $[fr]=void 0,e})),$[ur]=await $[fr],P($[ur]),$[ur]),yr=e=>{$[ur]=e,$[dr]=e,$[fr]=void 0,$[pr]=void 0},br=Symbol.for(`@workflow/world//getWorldFn`);globalThis[br]??=vr;var xr=class{limitMs;elapsedMs=0;intervalStart;constructor(e=Gn()){this.limitMs=e,this.intervalStart=Date.now()}get configuredLimitMs(){return this.limitMs}elapsed(){let e=this.intervalStart===null?0:Date.now()-this.intervalStart;return this.elapsedMs+e}pause(){this.intervalStart!==null&&(this.elapsedMs+=Date.now()-this.intervalStart,this.intervalStart=null)}resume(){this.intervalStart=Date.now()}isExhausted(){return this.elapsed()>=this.limitMs}};async function Sr(e){let{runId:t,workflowName:n,requestId:r,attempt:i,limitMs:a}=e,o=T.forRun(t,n),s=await vr();if(s.processExitTriggersQueueRedelivery!==!0){o.warn(`Workflow replay exceeded timeout; current World does not support process exit for redelivery — failing the run and returning`,{timeoutMs:a,attempt:i});try{let e=ke(s,t),n=new Y(`Workflow replay exceeded maximum duration (${a/1e3}s)`);await s.events.create(t,{eventType:`run_failed`,specVersion:5,eventData:{error:await St(n,t,await e()),errorCode:q.REPLAY_TIMEOUT}},{requestId:r})}catch(e){o.warn(`Unable to mark run as failed`,{attempt:i,errorName:e instanceof Error?e.name:`UnknownError`,errorMessage:e instanceof Error?e.message:String(e)})}return}let c=Kn();i<=c&&(o.warn(`Workflow replay exceeded timeout but will be re-attempted (attempt < maxRetries)`,{timeoutMs:a,attempt:i,maxRetries:c}),process.exit(1));let l=Pn(void 0,q.REPLAY_TIMEOUT);o.error(`Workflow replay exceeded timeout and max retries exceeded. Failing the run`,{timeoutMs:a,attempt:i,maxRetries:c,errorCode:l.errorCode,errorAttribution:l.attribution});try{let e=ke(s,t),n=new Y(`Workflow replay exceeded maximum duration (${a/1e3}s) after ${i} attempts`);await s.events.create(t,{eventType:`run_failed`,specVersion:5,eventData:{error:await St(n,t,await e()),errorCode:q.REPLAY_TIMEOUT}},{requestId:r})}catch(e){o.warn(`Unable to mark run as failed. The queue will continue to retry`,{attempt:i,errorName:e instanceof Error?e.name:`UnknownError`,errorMessage:e instanceof Error?e.message:String(e),errorStack:e instanceof Error?e.stack:void 0})}process.exit(1)}var Cr=class{divergenceCount;active=!1;reported=!1;constructor(e){this.divergenceCount=e}static inert(){return new wr}activate(){this.active=!0}async withEventCreate(e,t){if(!this.active||this.reported)return t(e);this.reported=!0;try{return await t({...e,replayDivergenceCount:this.divergenceCount})}catch(e){throw this.reported=!1,e}}},wr=class extends Cr{constructor(){super(0)}activate(){}};function Tr(e){let t=e.startsWith(`wrun_`)?e.slice(5):e;try{return rn(Cn(t).ulid)}catch{return}}function Er(e){return Q.isNativeError(e)?e.name:`Error`}function Dr(e){return Q.isNativeError(e)?e.stack??``:``}function Or(e){return typeof e==`object`&&!!e&&`name`in e&&e.name===`AbortError`&&`message`in e&&typeof e.message==`string`&&(!(`stack`in e)||e.stack===void 0||typeof e.stack==`string`)}function kr(e){if(!Or(e)||Y.is(e))return e;let t=new Y(`Aborted: ${e.message}`);return e.stack&&(t.stack=e.stack),t}function Ar(e){return typeof e==`object`&&!!e&&`then`in e&&typeof e.then==`function`}function jr(e){if(Q.isNativeError(e))return{name:e.name,message:e.message,stack:e.stack??``};if(typeof e==`string`)return{name:`Error`,message:e,stack:``};try{return{name:`Error`,message:JSON.stringify(e),stack:``}}catch{return{name:`Error`,message:String(e),stack:``}}}async function Mr(e){if(Ar(e))try{let t=await Mr(await e);return{...t,message:`Promise rejection: ${t.message}`}}catch(e){let t=await Mr(e);return{...t,message:`Promise rejection: ${t.message}`}}return jr(e)}let Nr,Pr,Fr;async function Ir(){if(Pr!==void 0)return Pr;if(Fr)return Fr;if(!Nr)try{let e=[`@workflow/utils`,`get-port`].join(`/`);Nr=wn(En(process.cwd()+`/package.json`).href)(e).getPort}catch{Nr=async()=>void 0}return Fr=(Nr??(async()=>void 0))().then(e=>(typeof e==`number`&&(Pr=e),e)).finally(()=>{Fr=void 0}),Fr}const Lr=new Set([`step_created`,`step_started`,`step_completed`,`step_failed`,`step_retrying`,`hook_received`,`wait_created`,`wait_completed`]);function Rr(e){let{events:t}=e,n=e.invocationStartedClean&&e.runCreatedAtMs!==void 0&&!e.suspensionHasWaits,r;if(n)for(let e of t){if(Lr.has(e.eventType)){n=!1;break}if(e.eventType===`attr_set`){let t=+(e.occurredAt??e.createdAt);r=r===void 0?t:Math.min(r,t)}}let i,a,o,s=t[t.length-1];if(!e.suspensionHasWaits&&!e.suspensionCreatedHooks&&s&&(s.eventType===`step_completed`||s.eventType===`step_failed`)){i=+(s.occurredAt??s.createdAt);let e=new Set;for(let n of t)(n.eventType===`step_completed`||n.eventType===`step_failed`)&&n.correlationId!==void 0&&e.add(n.correlationId);a=e.size,o=t.length}let c=n&&e.runStartedReceivedAtMs!==void 0;if(!(!n&&i===void 0))return{...n?{ttfsAnchorMs:e.runCreatedAtMs,preStepBlockingMs:r===void 0?e.preStepBlockingMs:e.preStepBlockingBeforeAttrMs??0,...r===void 0?{}:{preStepAttrStartMs:r}}:{},...c?{rsfsAnchorMs:e.runStartedReceivedAtMs,replayMs:e.replayMs}:{},...i===void 0?{}:{prevStepEndMs:i,stepCount:a,eventCount:o},turbo:e.turbo}}function zr(e){let{tracking:t}=e;if(!t||e.attempt!==1)return;let n=t.preStepAttrStartMs??e.stepCodeStartedAtMs,r=t.ttfsAnchorMs===void 0?void 0:n-t.ttfsAnchorMs-(t.preStepBlockingMs??0),i=r!==void 0&&r>=-6e4?Math.max(0,r):void 0,a=t.prevStepEndMs===void 0?void 0:e.stepCodeStartedAtMs-t.prevStepEndMs,o=a!==void 0&&a>=-6e4?Math.max(0,a):void 0,s=t.rsfsAnchorMs!==void 0&&e.stepStartPostSentAtMs!==void 0?Math.max(0,e.stepStartPostSentAtMs-t.rsfsAnchorMs):void 0,c=t.replayMs===void 0?void 0:Math.max(0,t.replayMs);if(i===void 0&&o===void 0)return;let l=[];return t.turbo&&l.push(`turbo`),e.lazyStepStart&&l.push(`lazyStepStart`),e.optimisticStart&&l.push(`optimisticStart`),{...i===void 0?{}:{ttfs:i},...o===void 0?{}:{stso:o},...o!==void 0&&t.stepCount!==void 0?{stepCount:t.stepCount}:{},...o!==void 0&&t.eventCount!==void 0?{eventCount:t.eventCount}:{},...s===void 0?{}:{rsfs:s},...c===void 0?{}:{finalSchedulingReplay:c},optimizations:l}}function Br(e,t){if(t&&!(!e.events||e.cursor===void 0))return{events:e.events,cursor:e.cursor,hasMore:e.hasMore??!1}}async function Vr(e){let{world:t,workflowRunId:n,workflowName:r,workflowStartedAt:i,stepId:o,stepName:l}=e,u=!!process.env.VERCEL_URL,m=(e.runSpecVersion??0)>=5,v=e.replayRecoveryReporter??Cr.inert(),y=(e,r)=>v.withEventCreate(r,r=>t.events.create(n,e,r));return W(`step.execute ${$e(l)}`,{},async v=>{v?.setAttributes({...w(l),...Me(r),...Je(n),...te(o)});let x=ke(t,n),C=At(l);if(!C||typeof C!=`function`){let t=`Step "${l}" 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.`;if(T.error(`Step function not registered, failing step`,{workflowRunId:n,stepName:l,stepId:o}),e.lazyStepInput!==void 0)try{e.runReadyBarrier&&await e.runReadyBarrier.catch(()=>{}),await y({eventType:`step_started`,specVersion:5,correlationId:o,eventData:{stepName:l,workflowName:r,input:e.lazyStepInput,...e.ownerMessageId===void 0?{}:{ownerMessageId:e.ownerMessageId}}},{computeInstanceId:Rn})}catch(e){if(Z.is(e))return{type:`skipped`};if(J.is(e))return{type:`gone`};throw e}try{await y({eventType:`step_failed`,specVersion:5,correlationId:o,eventData:{stepName:l,error:await p(new Y(t),n,await x(),[],globalThis,m)}})}catch(e){if(Z.is(e))return{type:`skipped`};throw e}return v?.setAttributes({...pe(`failed`),...We(!0)}),{type:`failed`}}let E=C.maxRetries??3;if(v?.setAttributes({..._(E)}),e.authoritativeAttempt!==void 0&&e.authoritativeAttempt>E+1){let t=E,r=`Step "${l}" exceeded max retries (${t} ${Ne(`retry`,`retries`,t)})`;H.error(`Step exceeded max retries`,{workflowRunId:n,stepName:l,stepId:o,attempt:e.authoritativeAttempt,maxRetries:E});try{await y({eventType:`step_failed`,specVersion:5,correlationId:o,eventData:{stepName:l,error:await p(new Y(r),n,await x(),[],globalThis,m)}})}catch(e){if(Z.is(e))return T.info(`Tried failing step for exceeded retries, but step has already finished.`,{workflowRunId:n,stepId:o,stepName:l,message:e instanceof Error?e.message:String(e)}),{type:`skipped`};if(J.is(e))return{type:`gone`};throw e}return v?.setAttributes({...pe(`failed`),...z(!0)}),{type:`failed`}}let ee=e=>{if(Vt.is(e)){let t=Math.max(1,typeof e.retryAfter==`number`?e.retryAfter:1);return T.info(`Throttled on step_started, deferring`,{retryAfterSeconds:t}),{type:`throttled`,timeoutSeconds:t}}if(J.is(e))return T.info(`Workflow run "${n}" has already completed, skipping step "${o}": ${e.message}`),{type:`gone`};if(Z.is(e))return T.debug(`Step in terminal state, skipping`,{stepName:l,stepId:o,workflowRunId:n,error:e instanceof Error?e.message:String(e)}),v?.setAttributes({...ce(!0),...S(`completed`)}),{type:`skipped`};if(Rt.is(e)){let t=Math.max(1,e.retryAfter??1);return T.debug(`Step retryAfter timestamp not yet reached`,{stepName:l,stepId:o,timeoutSeconds:t}),{type:`retry`,timeoutSeconds:t}}},D=e.lazyStepInput!==void 0&&e.suppressOptimisticStart!==!0&&(Zn()||e.forceOptimisticStart===!0&&!Qn()),O,A={computeInstanceId:Rn,...e.preconditionSnapshot},j,P,ne=async()=>{if(!P)return;let e=await P;if(e.ok)return;let t=ee(e.err);if(!t)throw e.err;return t};if(D){P=(e.runReadyBarrier??Promise.resolve()).then(()=>(j=Date.now(),y({eventType:`step_started`,specVersion:5,correlationId:o,eventData:{stepName:l,workflowName:r,input:e.lazyStepInput,...e.ownerMessageId===void 0?{}:{ownerMessageId:e.ownerMessageId}}},A))).then(()=>({ok:!0}),e=>({ok:!1,err:e}));let t=new Date;O={runId:n,stepId:o,stepName:l,status:`running`,input:e.lazyStepInput,attempt:1,startedAt:t,createdAt:t,updatedAt:t}}else try{let t=e.ownerMessageId===void 0?{}:{ownerMessageId:e.ownerMessageId};j=Date.now();let n=await y({eventType:`step_started`,specVersion:5,correlationId:o,eventData:e.lazyStepInput===void 0?{stepName:l,...t}:{stepName:l,workflowName:r,input:e.lazyStepInput,...t}},A);if(!n.step)throw new K(`step_started event for "${o}" did not return step entity`);O=n.step}catch(e){let t=ee(e);if(t)return t;throw e}T.debug(`Step execution details`,{stepName:l,stepId:O.stepId,status:O.status,attempt:O.attempt}),v?.setAttributes({...pe(O.status)});let L;if(O.attempt>E+1&&O.error){let e=O.attempt-1,t=`Step "${l}" exceeded max retries (${e} ${Ne(`retry`,`retries`,e)})`;H.error(`Step exceeded max retries`,{workflowRunId:n,stepName:l,retryCount:e});let r=new Y(t);if(O.error!=null)try{r.cause=await g(O.error,n,await x())}catch{}try{await y({eventType:`step_failed`,specVersion:5,correlationId:o,eventData:{stepName:l,error:await p(r,n,await x(),[],globalThis,m)}})}catch(e){if(Z.is(e))return T.info(`Tried failing step, but step has already finished.`,{workflowRunId:n,stepId:o,stepName:l,message:e.message}),{type:`skipped`};throw e}return v?.setAttributes({...pe(`failed`),...z(!0)}),{type:`failed`}}let ie=[],R=[],ae=!0,B,V=()=>{if(!B||B.rsfs!==void 0)return;let t=e.latencyTracking?.rsfsAnchorMs;t===void 0||j===void 0||(B.rsfs=Math.max(0,j-t),v&&v.setAttributes({...ue(B.rsfs)}))};try{let t=O.attempt;if(!O.startedAt)throw new K(`Step "${o}" has no "startedAt" timestamp`);let a=O.startedAt,s=e.encryptionKey??await x(),p=await W(`step.hydrate`,{},async t=>{let r=Date.now(),i=await re(O.input,n,s,R,globalThis,{},e.workflowDeploymentId),a=Date.now()-r;return t?.setAttributes({...f(i.args.length),...Ct(a)}),i}),g=p.args,_=p.thisVal??null,y=It(u?`https://${process.env.VERCEL_URL}`:`http://localhost:${await Ir()??3e3}`),S,w=!1,E=Date.now();B=zr({tracking:e.latencyTracking,stepCodeStartedAtMs:E,attempt:t,lazyStepStart:e.lazyStepInput!==void 0,optimisticStart:D,stepStartPostSentAtMs:j}),B&&v?.setAttributes({...B.ttfs===void 0?{}:k(B.ttfs),...B.stso===void 0?{}:b(B.stso),...B.rsfs===void 0?{}:ue(B.rsfs),...B.finalSchedulingReplay===void 0?{}:N(B.finalSchedulingReplay),...I(B.optimizations??[])});try{L=await W(`step.execute`,{},async()=>await at.run({stepMetadata:{stepName:l,stepId:o,stepStartedAt:new Date(+a),attempt:t},workflowMetadata:{workflowName:r,workflowRunId:n,workflowStartedAt:new Date(+i),url:y,features:{encryption:!!s}},workflowDeploymentId:e.workflowDeploymentId,rootRunId:e.rootRunId,ops:R,preCompletionOps:ie,closureVars:p.closureVars,encryptionKey:s,runReadyBarrier:D?e.runReadyBarrier:void 0},()=>C.apply(_,g)))}catch(e){S=e,w=!0}let ee=Date.now()-E;if(c(...g,_,p.closureVars),w)throw S;if(v?.setAttributes({...oe(ee)}),L=await W(`step.dehydrate`,{},async t=>{let r=Date.now(),i=await d(L,n,s,R,globalThis,!1,!1,m,D?e.runReadyBarrier:void 0),a=Date.now()-r;return t?.setAttributes({...h(a),...M(typeof i)}),i}),R.length>0){let e=Promise.all(R);pt(e,e=>{T.warn(`Background flush of step stream ops failed`,{workflowRunId:n,stepId:o,error:e instanceof Error?e.message:String(e)})}),ae=await Promise.race([e.then(()=>!0,e=>{if(e?.name===`AbortError`||e?.name===`ResponseAborted`)return!0;throw e}),new Promise(e=>setTimeout(()=>e(!1),500))])}if(D){let e=await ne();if(e)return e;V()}ie.length>0&&await Promise.all(ie).catch(()=>{})}catch(e){if(D){let e=await ne();if(e)return e;V()}ie.length>0&&await Promise.all(ie).catch(()=>{});let t=kr(e),r=await Mr(t),i=r.stack||Dr(t)||``;t instanceof Error&&v?.recordException?.(t);let c=Y.is(t);if(v?.setAttributes({...a(Er(t)),...Ke(r.message),...yt(Er(t)),...Oe(c?`fatal`:qt.is(t)?`retryable`:`transient`),...Ye(!c)}),J.is(e))return H.info(`Workflow run already completed, skipping step`,{workflowRunId:n,stepId:o,message:e.message}),{type:`gone`};if(c){H.error(`Encountered FatalError while executing step, bubbling up to parent workflow`,{workflowRunId:n,stepName:l,errorStack:i}),Q.isNativeError(t)&&i&&(t.stack=i);try{await y({eventType:`step_failed`,specVersion:5,correlationId:o,eventData:{stepName:l,error:await p(t,n,await x(),[],globalThis,m),...B}})}catch(e){if(Z.is(e))return T.info(`Tried failing step, but step has already finished.`,{workflowRunId:n,stepId:o,stepName:l,message:e.message}),{type:`skipped`};throw e}return v?.setAttributes({...pe(`failed`),...We(!0)}),{type:`failed`}}let u=O.attempt;if(v?.setAttributes({...F(u),..._(E)}),u>=E+1){let t=O.attempt-1;H.error(`Max retries reached, bubbling error to parent workflow`,{workflowRunId:n,stepName:l,attempt:O.attempt,retryCount:t,errorStack:i});let a=new Y(`Step "${l}" failed after ${E} ${Ne(`retry`,`retries`,E)}: ${r.message}`);a.cause=e,i&&(a.stack=i);try{await y({eventType:`step_failed`,specVersion:5,correlationId:o,eventData:{stepName:l,error:await p(a,n,await x(),[],globalThis,m),...B}})}catch(e){if(Z.is(e))return T.info(`Tried failing step, but step has already finished.`,{workflowRunId:n,stepId:o,stepName:l,message:e.message}),{type:`skipped`};throw e}return v?.setAttributes({...pe(`failed`),...z(!0)}),{type:`failed`}}qt.is(e)?H.info(`Encountered RetryableError, step will be retried`,{workflowRunId:n,stepName:l,attempt:u,message:e.message}):H.info(`Encountered Error, step will be retried`,{workflowRunId:n,stepName:l,attempt:u,errorStack:i}),Q.isNativeError(e)&&i&&(e.stack=i);try{await y({eventType:`step_retrying`,specVersion:5,correlationId:o,eventData:{stepName:l,error:await p(e,n,await x(),[],globalThis,m),...qt.is(e)&&{retryAfter:e.retryAfter}}})}catch(e){if(Z.is(e))return T.info(`Tried retrying step, but step has already finished.`,{workflowRunId:n,stepId:o,stepName:l,message:e.message}),{type:`skipped`};throw e}let d=Math.max(1,qt.is(e)?Math.ceil((+e.retryAfter.getTime()-Date.now())/1e3):1);return v?.setAttributes({...Ot(d),...s(!0)}),{type:`retry`,timeoutSeconds:d}}let se;try{se=await y({eventType:`step_completed`,specVersion:5,correlationId:o,eventData:{stepName:l,workflowName:r,result:L,...B}},e.inlineDeltaSinceCursor===void 0?void 0:{sinceCursor:e.inlineDeltaSinceCursor})}catch(e){if(Z.is(e))return T.info(`Tried completing step, but step has already finished.`,{workflowRunId:n,stepId:o,stepName:l,message:e.message}),{type:`skipped`};if(J.is(e))return H.info(`Workflow run already completed, skipping step`,{workflowRunId:n,stepId:o,message:e.message}),{type:`gone`};throw e}let le=Br(se,e.inlineDeltaSinceCursor!==void 0);return v?.setAttributes({...pe(`completed`),...M(typeof L)}),R.length>0&&H.debug(`Step has pending ops`,{workflowRunId:n,stepName:l,opsCount:R.length}),{type:`completed`,hasPendingOps:!ae,inlineDelta:le}})}function Hr(e){return e.hasCreatedEvent===!0&&e.ownerMessageId!==void 0&&e.sawRetrying!==!0}function Ur(e,t){if(e.lastStartedAt===void 0)return 0;let n=tr(),r=e.lastStartedAt+n*1e3-t;return Math.min(n,Math.max(0,Math.ceil(r/1e3)))}function Wr(e){return`${e.correlationId}:backstop:${e.lastStartedAt}`}function Gr(e,t,n){let r=new Map,i=new Set;for(let t of e)if(t.correlationId!==void 0)if(t.eventType===`step_started`){let e=`eventData`in t&&t.eventData&&`ownerMessageId`in t.eventData&&typeof t.eventData.ownerMessageId==`string`?t.eventData.ownerMessageId:void 0;r.set(t.correlationId,e)}else t.eventType===`step_retrying`&&i.add(t.correlationId);for(let e of t)if(e!==void 0&&!i.has(e)&&r.get(e)===n)return!0;return!1}const Kr=new Map;async function qr(e,t,n){let r=`${e}:${t}`,i=Kr.get(r);if(i){T.warn(`Step execution already in flight in this process; awaiting its settlement instead of executing again`,{workflowRunId:e,stepId:t});try{await i}catch{}return{type:`skipped`}}let a=n();Kr.set(r,a);try{return await a}finally{Kr.delete(r)}}async function Jr({runId:e,hookEvent:t,queueItem:n,requestId:r,createEvent:i}){try{return(await i(t,{requestId:r})).event?.eventType===`hook_conflict`?{hasHookConflict:!0,hasAwaitedHookCreation:!1}:{hasHookConflict:!1,hasAwaitedHookCreation:n.hasConflictAwaiter===!0}}catch(t){if(Z.is(t))return T.info(`Hook already exists, continuing`,{workflowRunId:e,message:t.message}),{hasHookConflict:!1,hasAwaitedHookCreation:n.hasConflictAwaiter===!0};if(J.is(t))return T.info(`Workflow run already completed, skipping hook`,{workflowRunId:e,message:t.message}),{hasHookConflict:!1,hasAwaitedHookCreation:!1};throw t}}async function Yr({suspension:e,world:t,run:n,span:r,requestId:a,eventLog:o,runReadyBarrier:s,replayRecoveryReporter:c}){let l=n.runId,u=async()=>{if(s)try{await s}catch{}},d=async e=>{let t=(await Promise.allSettled(e)).filter(e=>e.status===`rejected`).map(e=>e.reason);if(t.length!==0)throw t.find(e=>Bt.is(e))??t[0]},f=c??Cr.inert(),p=(e,n)=>f.withEventCreate(n,n=>t.events.create(l,e,n)),m=(e,t)=>o?p(e,{...t,...Xe(o.events,o.cursor)}):p(e,t),h=e.steps.filter(e=>e.type===`step`),g=e.steps.filter(e=>e.type===`hook`),_=e.steps.filter(e=>e.type===`wait`),y=e.steps.filter(e=>e.type===`attribute`),b=g.filter(e=>!e.hasCreatedEvent),x=new Map;for(let e of g){if(e.hasCreatedEvent&&!e.disposed)continue;let t=x.get(e.token);t?t.push(e):x.set(e.token,[e])}let S=await t.getEncryptionKeyForRun?.(n),C=S?await ge(S):void 0,w=(n.specVersion??0)>=5;async function E(e){let t={eventType:`hook_disposed`,specVersion:5,correlationId:e.correlationId,eventData:{token:e.token}};try{await m(t,{requestId:a})}catch(t){if(Z.is(t))T.info(`Hook already disposed, skipping duplicate disposal`,{workflowRunId:l,correlationId:e.correlationId,message:t.message});else if(J.is(t))T.info(`Workflow run already completed, skipping hook disposal`,{workflowRunId:l,correlationId:e.correlationId,message:t.message});else if(Wt.is(t))T.info(`Hook not found for disposal, continuing`,{workflowRunId:l,correlationId:e.correlationId,message:t.message});else throw t}}let ee=!1,D=!1,O=0;if(x.size>0){let t=Date.now();await u(),await d([...x.values()].map(async t=>{for(let n of t){let t=!1;if(!n.hasCreatedEvent){let r=n.metadata===void 0?void 0:await B(n.metadata,l,C,e.globalThis,!1,w),i={eventType:`hook_created`,specVersion:5,correlationId:n.correlationId,eventData:{token:n.token,tokenRetentionUntil:n.tokenRetentionUntil,metadata:r,isWebhook:n.isWebhook??!1,...n.isSystem&&{isSystem:!0}}},o=await Jr({runId:l,hookEvent:i,queueItem:n,requestId:a,createEvent:m});ee||=o.hasHookConflict,D||=o.hasAwaitedHookCreation,t=o.hasHookConflict}n.disposed&&!t&&await E(n)}})),O=Date.now()-t}let k=g.filter(e=>e.abortRequested&&!e.disposed);k.length>0&&(await u(),await d(k.map(async n=>{try{let r=await B({aborted:!0,reason:n.abortReason},l,C,e.globalThis,!1,w);await m({eventType:`hook_received`,specVersion:5,correlationId:n.correlationId,eventData:{token:n.token,payload:r}});try{let e=v(n.token);await t.streams.write(l,e,r),await t.streams.close(l,e)}catch{T.debug(`Failed to write abort stream packet, hook event will provide fallback`,{workflowRunId:l,correlationId:n.correlationId})}}catch(e){if(Z.is(e)||J.is(e))T.info(`Workflow run already completed, skipping abort`,{workflowRunId:l,correlationId:n.correlationId,message:e.message});else throw e}})));let A=new Set(h.filter(e=>!e.hasCreatedEvent).map(e=>e.correlationId)),j=new Set,M=new Set(D===!1?h.filter(e=>A.has(e.correlationId)).slice(0,Jn()).map(e=>e.correlationId):[]),N=new Map,P=[];for(let t of h)A.has(t.correlationId)&&P.push((async()=>{let r=await B({args:t.args,closureVars:t.closureVars,thisVal:t.thisVal},l,C,e.globalThis,!1,w);if(M.has(t.correlationId)){N.set(t.correlationId,{correlationId:t.correlationId,stepName:t.stepName,dehydratedInput:r});return}let i={eventType:`step_created`,specVersion:5,correlationId:t.correlationId,eventData:{stepName:t.stepName,workflowName:n.workflowName,input:r}};try{await u(),await m(i,{requestId:a}),j.add(t.correlationId)}catch(e){if(Z.is(e))T.info(`Step already exists, continuing`,{workflowRunId:l,correlationId:t.correlationId,message:e.message});else throw e}})());for(let e of _)e.hasCreatedEvent||P.push((async()=>{let t={eventType:`wait_created`,specVersion:5,correlationId:e.correlationId,eventData:{resumeAt:e.resumeAt}};try{await u(),await m(t,{requestId:a})}catch(t){if(Z.is(t))T.info(`Wait already exists, continuing`,{workflowRunId:l,correlationId:e.correlationId,message:t.message});else throw t}})());for(let e of y)P.push((async()=>{try{await u(),await m({eventType:`attr_set`,specVersion:5,correlationId:e.correlationId,eventData:{changes:e.changes,writer:{type:`workflow`},...e.allowReservedAttributes?{allowReservedAttributes:!0}:{}}},{requestId:a})}catch(t){if(Z.is(t))T.info(`Workflow attribute event already exists, continuing`,{workflowRunId:l,correlationId:e.correlationId,message:t.message});else if(Xr(t)){let e=new Y(`setAttributes failed World validation: ${t instanceof Error?t.message:String(t)}`);throw e.cause=t,e}else throw t}})());await d(P);let te=[];for(let e of M){let t=N.get(e);t&&te.push(t)}let ne=Date.now(),F;for(let e of _){let t=e.resumeAt.getTime(),n=Math.max(1e3,t-ne),r=Math.ceil(n/1e3);(!F||r<F.seconds)&&(F={seconds:r,correlationId:e.correlationId})}return r?.setAttributes({...vt(`workflow_suspended`),...Ie(h.length),...i(b.length),...Re(_.length)}),{pendingSteps:h,createdStepCorrelationIds:j,lazyInlineSteps:te,waitTimeout:ee?void 0:F,hasHookConflict:ee,hasAwaitedHookCreation:D,hasAttributeEvents:y.length>0,hasHookEvents:b.length>0,hookCreationMs:O}}function Xr(e){return e instanceof tn||e instanceof Error&&e.name===`AttributeValidationError`||Lt.is(e)&&e.status===400}const Zr=()=>ln(`WORKFLOW_WAIT_CONTINUATION_MAX_DELAY_SECONDS`,82800,{integer:!0,min:1}),Qr=()=>ln(`WORKFLOW_NEAR_ELAPSED_WAIT_THRESHOLD_SECONDS`,2);function $r(e,t,n=Date.now()){let r=Zr();if(e<=Math.min(Qr(),r))return{delaySeconds:e,idempotencyKey:`${t}:${Math.floor(n/1e3)}`};let i=Math.ceil(e/r);return{delaySeconds:Math.min(e,r),idempotencyKey:i===1?t:`${t}:hop-${i}`}}var ei=44,ti=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/`,ni=new Uint8Array(64),ri=new Uint8Array(128);for(let e=0;e<ti.length;e++){let t=ti.charCodeAt(e);ni[e]=t,ri[t]=e}function ii(e,t){let n=0,r=0,i=0;do i=ri[e.next()],n|=(i&31)<<r,r+=5;while(i&32);let a=n&1;return n>>>=1,a&&(n=-2147483648|-n),t+n}function ai(e,t){return e.pos>=t?!1:e.peek()!==ei}var oi=class{constructor(e){this.pos=0,this.buffer=e}next(){return this.buffer.charCodeAt(this.pos++)}peek(){return this.buffer.charCodeAt(this.pos)}indexOf(e){let{buffer:t,pos:n}=this,r=t.indexOf(e,n);return r===-1?t.length:r}};function si(e){let{length:t}=e,n=new oi(e),r=[],i=0,a=0,o=0,s=0,c=0;do{let e=n.indexOf(`;`),t=[],l=!0,u=0;for(i=0;n.pos<e;){let r;i=ii(n,i),i<u&&(l=!1),u=i,ai(n,e)?(a=ii(n,a),o=ii(n,o),s=ii(n,s),ai(n,e)?(c=ii(n,c),r=[i,a,o,s,c]):r=[i,a,o,s]):r=[i],t.push(r),n.pos++}l||ci(t),r.push(t),n.pos=e+1}while(n.pos<=t);return r}function ci(e){e.sort(li)}function li(e,t){return e[0]-t[0]}const ui=/^[\w+.-]+:\/\//,di=/^([\w+.-]+:)\/\/([^@/#?]*@)?([^:/#?]*)(:\d+)?(\/[^#?]*)?(\?[^#]*)?(#.*)?/,fi=/^file:(?:\/\/((?![a-z]:)[^/#?]*)?)?(\/?[^#?]*)(\?[^#]*)?(#.*)?/i;function pi(e){return ui.test(e)}function mi(e){return e.startsWith(`//`)}function hi(e){return e.startsWith(`/`)}function gi(e){return e.startsWith(`file:`)}function _i(e){return/^[.?#]/.test(e)}function vi(e){let t=di.exec(e);return bi(t[1],t[2]||``,t[3],t[4]||``,t[5]||`/`,t[6]||``,t[7]||``)}function yi(e){let t=fi.exec(e),n=t[2];return bi(`file:`,``,t[1]||``,``,hi(n)?n:`/`+n,t[3]||``,t[4]||``)}function bi(e,t,n,r,i,a,o){return{scheme:e,user:t,host:n,port:r,path:i,query:a,hash:o,type:7}}function xi(e){if(mi(e)){let t=vi(`http:`+e);return t.scheme=``,t.type=6,t}if(hi(e)){let t=vi(`http://foo.com`+e);return t.scheme=``,t.host=``,t.type=5,t}if(gi(e))return yi(e);if(pi(e))return vi(e);let t=vi(`http://foo.com/`+e);return t.scheme=``,t.host=``,t.type=e?e.startsWith(`?`)?3:e.startsWith(`#`)?2:4:1,t}function Si(e){if(e.endsWith(`/..`))return e;let t=e.lastIndexOf(`/`);return e.slice(0,t+1)}function Ci(e,t){wi(t,t.type),e.path===`/`?e.path=t.path:e.path=Si(t.path)+e.path}function wi(e,t){let n=t<=4,r=e.path.split(`/`),i=1,a=0,o=!1;for(let e=1;e<r.length;e++){let t=r[e];if(!t){o=!0;continue}if(o=!1,t!==`.`){if(t===`..`){a?(o=!0,a--,i--):n&&(r[i++]=t);continue}r[i++]=t,a++}}let s=``;for(let e=1;e<i;e++)s+=`/`+r[e];(!s||o&&!s.endsWith(`/..`))&&(s+=`/`),e.path=s}function Ti(e,t){if(!e&&!t)return``;let n=xi(e),r=n.type;if(t&&r!==7){let e=xi(t),i=e.type;switch(r){case 1:n.hash=e.hash;case 2:n.query=e.query;case 3:case 4:Ci(n,e);case 5:n.user=e.user,n.host=e.host,n.port=e.port;case 6:n.scheme=e.scheme}i>r&&(r=i)}wi(n,r);let i=n.query+n.hash;switch(r){case 2:case 3:return i;case 4:{let r=n.path.slice(1);return r?_i(t||e)&&!_i(r)?`./`+r+i:r+i:i||`.`}case 5:return n.path+i;default:return n.scheme+`//`+n.user+n.host+n.port+n.path+i}}function Ei(e){if(!e)return``;let t=e.lastIndexOf(`/`);return e.slice(0,t+1)}function Di(e,t){let n=Ei(e),r=t?t+`/`:``;return e=>Ti(r+(e||``),n)}var Oi=0,ki=1,Ai=2,ji=3,Mi=4;function Ni(e,t){let n=Pi(e,0);if(n===e.length)return e;t||(e=e.slice());for(let r=n;r<e.length;r=Pi(e,r+1))e[r]=Ii(e[r],t);return e}function Pi(e,t){for(let n=t;n<e.length;n++)if(!Fi(e[n]))return n;return e.length}function Fi(e){for(let t=1;t<e.length;t++)if(e[t][Oi]<e[t-1][Oi])return!1;return!0}function Ii(e,t){return t||(e=e.slice()),e.sort(Li)}function Li(e,t){return e[Oi]-t[Oi]}var Ri=!1;function zi(e,t,n,r){for(;n<=r;){let i=n+(r-n>>1),a=e[i][Oi]-t;if(a===0)return Ri=!0,i;a<0?n=i+1:r=i-1}return Ri=!1,n-1}function Bi(e,t,n){for(let r=n+1;r<e.length&&e[r][Oi]===t;n=r++);return n}function Vi(e,t,n){for(let r=n-1;r>=0&&e[r][Oi]===t;n=r--);return n}function Hi(){return{lastKey:-1,lastNeedle:-1,lastIndex:-1}}function Ui(e,t,n,r){let{lastKey:i,lastNeedle:a,lastIndex:o}=n,s=0,c=e.length-1;if(r===i){if(t===a)return Ri=o!==-1&&e[o][Oi]===t,o;t>=a?s=o===-1?0:o:c=o}return n.lastKey=r,n.lastNeedle=t,n.lastIndex=zi(e,t,s,c)}function Wi(e){return typeof e==`string`?JSON.parse(e):e}var Gi="`line` must be greater than 0 (lines start at line 1)",Ki="`column` must be greater than or equal to 0 (columns start at column 0)",qi=class{constructor(e,t){let n=typeof e==`string`;if(!n&&e._decodedMemo)return e;let r=Wi(e),{version:i,file:a,names:o,sourceRoot:s,sources:c,sourcesContent:l}=r;this.version=i,this.file=a,this.names=o||[],this.sourceRoot=s,this.sources=c,this.sourcesContent=l,this.ignoreList=r.ignoreList||r.x_google_ignoreList||void 0;let u=Di(t,s);this.resolvedSources=c.map(u);let{mappings:d}=r;if(typeof d==`string`)this._encoded=d,this._decoded=void 0;else if(Array.isArray(d))this._encoded=void 0,this._decoded=Ni(d,n);else if(r.sections)throw Error(`TraceMap passed sectioned source map, please use FlattenMap export instead`);else throw Error(`invalid source map: ${JSON.stringify(r)}`);this._decodedMemo=Hi(),this._bySources=void 0,this._bySourceMemos=void 0}};function Ji(e){return e}function Yi(e){var t;return(t=Ji(e))._decoded||(t._decoded=si(Ji(e)._encoded))}function Xi(e,t){let{line:n,column:r,bias:i}=t;if(n--,n<0)throw Error(Gi);if(r<0)throw Error(Ki);let a=Yi(e);if(n>=a.length)return Zi(null,null,null,null);let o=a[n],s=Qi(o,Ji(e)._decodedMemo,n,r,i||1);if(s===-1)return Zi(null,null,null,null);let c=o[s];if(c.length===1)return Zi(null,null,null,null);let{names:l,resolvedSources:u}=e;return Zi(u[c[ki]],c[Ai]+1,c[ji],c.length===5?l[c[Mi]]:null)}function Zi(e,t,n,r){return{source:e,line:t,column:n,name:r}}function Qi(e,t,n,r,i){let a=Ui(e,r,t,n);return Ri?a=(i===-1?Bi:Vi)(e,r,a):i===-1&&a++,a===-1||a===e.length?-1:a}function $i(e){return e>=65&&e<=90||e>=97&&e<=122||e>=48&&e<=57||e===43||e===47||e===61}function ea(e){let t=0;for(;t<e.length;){let n=e.indexOf(`//# sourceMappingURL=data:application/json`,t);if(n===-1)return;let r=e.indexOf(`;base64,`,n+42);if(r===-1){t=n+42;continue}let i=e.indexOf(`,`,n);if(i!==-1&&i<r){t=r+8;continue}let a=r+8,o=a;for(;o<e.length&&$i(e.charCodeAt(o));)o++;if(o>a)return e.slice(a,o);t=o}}const ta=new Map;function na(e){let t=ta.get(e);if(t!==void 0)return ta.delete(e),ta.set(e,t),t;let n=null,r=ea(e);if(r)try{let e=Buffer.from(r,`base64`).toString(`utf-8`);n=new qi(JSON.parse(e))}catch{n=null}for(ta.set(e,n);ta.size>8;){let e=ta.keys().next().value;if(e===void 0)break;ta.delete(e)}return n}function ra(e,t,n){if(!e.includes(t))return e;let r=na(n);if(!r)return e;try{return e.split(`
2
- `).map(e=>{let n=e.match(/^\s*at\s+(?:(.+?)\s+\()?(.+?):(\d+):(\d+)\)?$/);if(!n)return e;let[,i,a,o,s]=n;if(!a.includes(t))return e;let c=parseInt(o,10),l=parseInt(s,10),u=Xi(r,{line:c,column:l});if(u.source&&u.line!==null){let e=i||u.name||`anonymous`,t=u.column===null?l:u.column;return` at ${e} (${u.source}:${u.line}:${t})`}return e}).join(`
3
- `)}catch{return e}}function ia(e,t,n){let r=(2<<31-Math.clz32(e.length-1|1))-1,i=Math.ceil(1.6*r*t/e.length);return(a=t)=>{if(!a)return``;let o=``;for(;;){let t=n(i),s=i;for(;s--;)if(o+=e[t[s]&r]||``,o.length>=a)return o}}}function aa(e){return function(t,n){let r=function(...r){let{promise:i,resolve:a,reject:o}=Mt(),s=`step_${e.generateUlid()}`,c={type:`step`,correlationId:s,stepName:t,args:r};this!==void 0&&this!==null&&this!==globalThis&&(c.thisVal=this);let l=n?.();return l&&(c.closureVars=l),e.invocationsQueue.set(s,c),H.debug(`Step consumer setup`,{correlationId:s,stepName:t,args:r}),e.eventsConsumer.subscribe(n=>{if(!n)return kt(e,()=>{e.onWorkflowError(new G(e.invocationsQueue,e.globalThis))}),x.NotConsumed;if(H.debug(`Step consumer event processing`,{correlationId:s,stepName:t,args:r.join(`, `),incomingCorrelationId:n.correlationId,isMatch:s===n.correlationId,eventType:n.eventType}),n.correlationId!==s)return x.NotConsumed;let i=`eventData`in n&&n.eventData&&`stepName`in n.eventData?n.eventData.stepName:void 0;if(typeof i==`string`&&i!==t)return e.promiseQueue=e.promiseQueue.then(()=>{e.onWorkflowError(new X(`Replay divergence: step event ${n.eventType} for ${s} belongs to "${i}", but the current step consumer is "${t}"`,{eventId:n.eventId}))}),x.Finished;if(n.eventType===`step_created`){let r=e.invocationsQueue.get(s);return!r||r.type!==`step`?(e.promiseQueue=e.promiseQueue.then(()=>{o(new X(`Replay divergence: step ${s} (${t}) created but not found in invocation queue`,{eventId:n.eventId}))}),x.Finished):(r.hasCreatedEvent=!0,x.Consumed)}if(n.eventType===`step_started`){let t=e.invocationsQueue.get(s);return t&&t.type===`step`&&(t.ownerMessageId=`eventData`in n&&n.eventData&&`ownerMessageId`in n.eventData&&typeof n.eventData.ownerMessageId==`string`?n.eventData.ownerMessageId:void 0,t.lastStartedAt=+n.createdAt),x.Consumed}if(n.eventType===`step_retrying`){let t=e.invocationsQueue.get(s);return t&&t.type===`step`&&(t.sawRetrying=!0,t.ownerMessageId=void 0),x.Consumed}if(n.eventType===`step_failed`){e.invocationsQueue.delete(n.correlationId);let t=e.eventsConsumer.eventIndex,r=jt(e,t,`step`),i,a=Nt(e,t,`step`);return e.pendingDeliveries++,e.promiseQueue=e.promiseQueue.then(async()=>{try{let t=await e.replayPayloadCache.prepareEventPayload(n.eventId,`error`,n.eventData.error);i=await g(n.eventData.error,e.runId,e.encryptionKey,e.globalThis,{},t)}catch(e){H.error(`Failed to hydrate step_failed error`,{correlationId:n.correlationId,error:e instanceof Error?e.message:String(e)}),i=new Y(`Failed to hydrate step error: ${e instanceof Error?e.message:String(e)}`)}finally{e.pendingDeliveries--}a.then(()=>{r.markDelivered(),o(i)})}),x.Finished}if(n.eventType===`step_completed`){e.invocationsQueue.delete(n.correlationId);let t=n.eventId,r=n.eventData.result,i=e.eventsConsumer.eventIndex,s=jt(e,i,`step`),c,l=Nt(e,i,`step`);return e.pendingDeliveries++,e.promiseQueue=e.promiseQueue.then(async()=>{try{c={ok:!0,value:await e.replayPayloadCache.getStepResult(t,async()=>{let n=await e.replayPayloadCache.prepareEventPayload(t,`result`,r);return await C(r,e.runId,e.encryptionKey,e.globalThis,{},n)})}}catch(e){c={ok:!1,error:e}}finally{e.pendingDeliveries--}l.then(()=>{s.markDelivered(),c.ok?a(c.value):o(c.error)})}),x.Finished}return e.promiseQueue=e.promiseQueue.then(()=>{e.onWorkflowError(new X(`Replay divergence: Unexpected event type for step ${s} (name: ${t}) "${n.eventType}"`,{eventId:n.eventId}))}),x.Finished}),i},i=t.split(`//`).pop();return Object.defineProperty(r,"name",{value:i}),Object.defineProperty(r,"stepId",{value:t,writable:!1,enumerable:!1,configurable:!1}),n&&(ne(n),Object.defineProperty(r,"__closureVarsFn",{value:n,writable:!1,enumerable:!1,configurable:!1})),Object.defineProperty(r,"bind",{value:function(e,...r){let i=Function.prototype.bind.call(this,e,...r);return Object.defineProperty(i,"stepId",{value:t,writable:!1,enumerable:!1,configurable:!1}),n&&Object.defineProperty(i,"__closureVarsFn",{value:n,writable:!1,enumerable:!1,configurable:!1}),Object.defineProperty(i,"__boundThis",{value:e,writable:!1,enumerable:!1,configurable:!1}),r.length>0&&Object.defineProperty(i,"__boundArgs",{value:r,writable:!1,enumerable:!1,configurable:!1}),i},writable:!1,enumerable:!1,configurable:!1}),r}}var oa=n(((e,t)=>{(function(e,t,n){function r(e){var t=this,n=o();t.next=function(){var e=2091639*t.s0+t.c*23283064365386963e-26;return t.s0=t.s1,t.s1=t.s2,t.s2=e-(t.c=e|0)},t.c=1,t.s0=n(` `),t.s1=n(` `),t.s2=n(` `),t.s0-=n(e),t.s0<0&&(t.s0+=1),t.s1-=n(e),t.s1<0&&(t.s1+=1),t.s2-=n(e),t.s2<0&&(t.s2+=1),n=null}function i(e,t){return t.c=e.c,t.s0=e.s0,t.s1=e.s1,t.s2=e.s2,t}function a(e,t){var n=new r(e),a=t&&t.state,o=n.next;return o.int32=function(){return n.next()*4294967296|0},o.double=function(){return o()+(o()*2097152|0)*11102230246251565e-32},o.quick=o,a&&(typeof a==`object`&&i(a,n),o.state=function(){return i(n,{})}),o}function o(){var e=4022871197;return function(t){t=String(t);for(var n=0;n<t.length;n++){e+=t.charCodeAt(n);var r=.02519603282416938*e;e=r>>>0,r-=e,r*=e,e=r>>>0,r-=e,e+=r*4294967296}return(e>>>0)*23283064365386963e-26}}t&&t.exports?t.exports=a:n&&n.amd?n(function(){return a}):this.alea=a})(e,typeof t==`object`&&t,typeof define==`function`&&define)})),sa=n(((e,t)=>{(function(e,t,n){function r(e){var t=this,n=``;t.x=0,t.y=0,t.z=0,t.w=0,t.next=function(){var e=t.x^t.x<<11;return t.x=t.y,t.y=t.z,t.z=t.w,t.w^=t.w>>>19^e^e>>>8},e===(e|0)?t.x=e:n+=e;for(var r=0;r<n.length+64;r++)t.x^=n.charCodeAt(r)|0,t.next()}function i(e,t){return t.x=e.x,t.y=e.y,t.z=e.z,t.w=e.w,t}function a(e,t){var n=new r(e),a=t&&t.state,o=function(){return(n.next()>>>0)/4294967296};return o.double=function(){do var e=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21);while(e===0);return e},o.int32=n.next,o.quick=o,a&&(typeof a==`object`&&i(a,n),o.state=function(){return i(n,{})}),o}t&&t.exports?t.exports=a:n&&n.amd?n(function(){return a}):this.xor128=a})(e,typeof t==`object`&&t,typeof define==`function`&&define)})),ca=n(((e,t)=>{(function(e,t,n){function r(e){var t=this,n=``;t.next=function(){var e=t.x^t.x>>>2;return t.x=t.y,t.y=t.z,t.z=t.w,t.w=t.v,(t.d=t.d+362437|0)+(t.v=t.v^t.v<<4^(e^e<<1))|0},t.x=0,t.y=0,t.z=0,t.w=0,t.v=0,e===(e|0)?t.x=e:n+=e;for(var r=0;r<n.length+64;r++)t.x^=n.charCodeAt(r)|0,r==n.length&&(t.d=t.x<<10^t.x>>>4),t.next()}function i(e,t){return t.x=e.x,t.y=e.y,t.z=e.z,t.w=e.w,t.v=e.v,t.d=e.d,t}function a(e,t){var n=new r(e),a=t&&t.state,o=function(){return(n.next()>>>0)/4294967296};return o.double=function(){do var e=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21);while(e===0);return e},o.int32=n.next,o.quick=o,a&&(typeof a==`object`&&i(a,n),o.state=function(){return i(n,{})}),o}t&&t.exports?t.exports=a:n&&n.amd?n(function(){return a}):this.xorwow=a})(e,typeof t==`object`&&t,typeof define==`function`&&define)})),la=n(((e,t)=>{(function(e,t,n){function r(e){var t=this;t.next=function(){var e=t.x,n=t.i,r=e[n],i;return r^=r>>>7,i=r^r<<24,r=e[n+1&7],i^=r^r>>>10,r=e[n+3&7],i^=r^r>>>3,r=e[n+4&7],i^=r^r<<7,r=e[n+7&7],r^=r<<13,i^=r^r<<9,e[n]=i,t.i=n+1&7,i};function n(e,t){var n,r=[];if(t===(t|0))r[0]=t;else for(t=``+t,n=0;n<t.length;++n)r[n&7]=r[n&7]<<15^t.charCodeAt(n)+r[n+1&7]<<13;for(;r.length<8;)r.push(0);for(n=0;n<8&&r[n]===0;++n);for(n==8?r[7]=-1:r[n],e.x=r,e.i=0,n=256;n>0;--n)e.next()}n(t,e)}function i(e,t){return t.x=e.x.slice(),t.i=e.i,t}function a(e,t){e??=+new Date;var n=new r(e),a=t&&t.state,o=function(){return(n.next()>>>0)/4294967296};return o.double=function(){do var e=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21);while(e===0);return e},o.int32=n.next,o.quick=o,a&&(a.x&&i(a,n),o.state=function(){return i(n,{})}),o}t&&t.exports?t.exports=a:n&&n.amd?n(function(){return a}):this.xorshift7=a})(e,typeof t==`object`&&t,typeof define==`function`&&define)})),ua=n(((e,t)=>{(function(e,t,n){function r(e){var t=this;t.next=function(){var e=t.w,n=t.X,r=t.i,i,a;return t.w=e=e+1640531527|0,a=n[r+34&127],i=n[r=r+1&127],a^=a<<13,i^=i<<17,a^=a>>>15,i^=i>>>12,a=n[r]=a^i,t.i=r,a+(e^e>>>16)|0};function n(e,t){var n,r,i,a,o,s=[],c=128;for(t===(t|0)?(r=t,t=null):(t+=`\0`,r=0,c=Math.max(c,t.length)),i=0,a=-32;a<c;++a)t&&(r^=t.charCodeAt((a+32)%t.length)),a===0&&(o=r),r^=r<<10,r^=r>>>15,r^=r<<4,r^=r>>>13,a>=0&&(o=o+1640531527|0,n=s[a&127]^=r+o,i=n==0?i+1:0);for(i>=128&&(s[(t&&t.length||0)&127]=-1),i=127,a=512;a>0;--a)r=s[i+34&127],n=s[i=i+1&127],r^=r<<13,n^=n<<17,r^=r>>>15,n^=n>>>12,s[i]=r^n;e.w=o,e.X=s,e.i=i}n(t,e)}function i(e,t){return t.i=e.i,t.w=e.w,t.X=e.X.slice(),t}function a(e,t){e??=+new Date;var n=new r(e),a=t&&t.state,o=function(){return(n.next()>>>0)/4294967296};return o.double=function(){do var e=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21);while(e===0);return e},o.int32=n.next,o.quick=o,a&&(a.X&&i(a,n),o.state=function(){return i(n,{})}),o}t&&t.exports?t.exports=a:n&&n.amd?n(function(){return a}):this.xor4096=a})(e,typeof t==`object`&&t,typeof define==`function`&&define)})),da=n(((e,t)=>{(function(e,t,n){function r(e){var t=this,n=``;t.next=function(){var e=t.b,n=t.c,r=t.d,i=t.a;return e=e<<25^e>>>7^n,n=n-r|0,r=r<<24^r>>>8^i,i=i-e|0,t.b=e=e<<20^e>>>12^n,t.c=n=n-r|0,t.d=r<<16^n>>>16^i,t.a=i-e|0},t.a=0,t.b=0,t.c=-1640531527,t.d=1367130551,e===Math.floor(e)?(t.a=e/4294967296|0,t.b=e|0):n+=e;for(var r=0;r<n.length+20;r++)t.b^=n.charCodeAt(r)|0,t.next()}function i(e,t){return t.a=e.a,t.b=e.b,t.c=e.c,t.d=e.d,t}function a(e,t){var n=new r(e),a=t&&t.state,o=function(){return(n.next()>>>0)/4294967296};return o.double=function(){do var e=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21);while(e===0);return e},o.int32=n.next,o.quick=o,a&&(typeof a==`object`&&i(a,n),o.state=function(){return i(n,{})}),o}t&&t.exports?t.exports=a:n&&n.amd?n(function(){return a}):this.tychei=a})(e,typeof t==`object`&&t,typeof define==`function`&&define)})),fa=n(((t,n)=>{(function(t,r,i){var a=256,o=6,s=52,c=`random`,l=i.pow(a,o),u=i.pow(2,s),d=u*2,f=a-1,p;function m(e,t,n){var s=[];t=t==1?{entropy:!0}:t||{};var f=v(_(t.entropy?[e,b(r)]:e??y(),3),s),p=new h(s),m=function(){for(var e=p.g(o),t=l,n=0;e<u;)e=(e+n)*a,t*=a,n=p.g(1);for(;e>=d;)e/=2,t/=2,n>>>=1;return(e+n)/t};return m.int32=function(){return p.g(4)|0},m.quick=function(){return p.g(4)/4294967296},m.double=m,v(b(p.S),r),(t.pass||n||function(e,t,n,r){return r&&(r.S&&g(r,p),e.state=function(){return g(p,{})}),n?(i[c]=e,t):e})(m,f,`global`in t?t.global:this==i,t.state)}function h(e){var t,n=e.length,r=this,i=0,o=r.i=r.j=0,s=r.S=[];for(n||(e=[n++]);i<a;)s[i]=i++;for(i=0;i<a;i++)s[i]=s[o=f&o+e[i%n]+(t=s[i])],s[o]=t;(r.g=function(e){for(var t,n=0,i=r.i,o=r.j,s=r.S;e--;)t=s[i=f&i+1],n=n*a+s[f&(s[i]=s[o=f&o+t])+(s[o]=t)];return r.i=i,r.j=o,n})(a)}function g(e,t){return t.i=e.i,t.j=e.j,t.S=e.S.slice(),t}function _(e,t){var n=[],r=typeof e,i;if(t&&r==`object`)for(i in e)try{n.push(_(e[i],t-1))}catch{}return n.length?n:r==`string`?e:e+`\0`}function v(e,t){for(var n=e+``,r,i=0;i<n.length;)t[f&i]=f&(r^=t[f&i]*19)+n.charCodeAt(i++);return b(t)}function y(){try{var e;return p&&(e=p.randomBytes)?e=e(a):(e=new Uint8Array(a),(t.crypto||t.msCrypto).getRandomValues(e)),b(e)}catch{var n=t.navigator,i=n&&n.plugins;return[+new Date,t,i,t.screen,b(r)]}}function b(e){return String.fromCharCode.apply(0,e)}if(v(i.random(),r),typeof n==`object`&&n.exports){n.exports=m;try{p=e(`crypto`)}catch{}}else typeof define==`function`&&define.amd?define(function(){return m}):i[`seed`+c]=m})(typeof self<`u`?self:t,[],Math)})),pa=t(n(((e,t)=>{var n=oa(),r=sa(),i=ca(),a=la(),o=ua(),s=da(),c=fa();c.alea=n,c.xor128=r,c.xorwow=i,c.xorshift7=a,c.xor4096=o,c.tychei=s,t.exports=c}))(),1);const ma=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/`,ha=new Uint8Array(128).fill(255);for(let e=0;e<64;e++)ha[ma.charCodeAt(e)]=e;function ga(e){return e===9||e===10||e===12||e===13||e===32}function _a(e,t){for(;t<e.length&&ga(e.charCodeAt(t));)t++;return t}function va(e,t){let n=e.length,r=e;n===2?r=e+`AA`:n===3&&(r=e+`A`);let i=ha[r.charCodeAt(0)],a=ha[r.charCodeAt(1)],o=ha[r.charCodeAt(2)],s=ha[r.charCodeAt(3)],c=i<<2|a>>4,l=(a&15)<<4|o>>2,u=(o&3)<<6|s;if(n===2){if(t&&l!==0)throw SyntaxError(`Extra bits in base64 chunk`);return[c]}if(n===3){if(t&&u!==0)throw SyntaxError(`Extra bits in base64 chunk`);return[c,l]}return[c,l,u]}function ya(e,t,n,r){if(r===void 0&&(r=2**53-1),r===0)return{read:0,bytes:[],error:null};let i=0,a=[],o=``,s=0,c=0,l=e.length;for(;;){if(c=_a(e,c),c===l){if(s>0){if(n===`stop-before-partial`)return{read:i,bytes:a,error:null};if(n===`loose`){if(s===1)return{read:i,bytes:a,error:SyntaxError(`Invalid base64: lone character in final chunk`)};a.push(...va(o,!1))}else return{read:i,bytes:a,error:SyntaxError(`Invalid base64: incomplete chunk in strict mode`)}}return{read:l,bytes:a,error:null}}let u=e[c];if(c++,u===`=`){if(s<2)return{read:i,bytes:a,error:SyntaxError(`Invalid base64: padding in unexpected place`)};if(c=_a(e,c),s===2){if(c===l)return n===`stop-before-partial`?{read:i,bytes:a,error:null}:{read:i,bytes:a,error:SyntaxError(`Invalid base64: missing second padding character`)};u=e[c],u===`=`&&(c=_a(e,c+1))}if(c<l)return{read:i,bytes:a,error:SyntaxError(`Invalid base64: unexpected characters after padding`)};let t=n===`strict`;try{a.push(...va(o,t))}catch(e){return{read:i,bytes:a,error:e}}return{read:l,bytes:a,error:null}}if(t===`base64url`){if(u===`+`||u===`/`)return{read:i,bytes:a,error:SyntaxError(`Invalid base64url: unexpected character '${u}'`)};u===`-`?u=`+`:u===`_`&&(u=`/`)}let d=u.charCodeAt(0);if(d>=128||ha[d]===255)return{read:i,bytes:a,error:SyntaxError(`Invalid base64: unexpected character '${e[c-1]}'`)};let f=r-a.length;if(f===1&&s===2||f===2&&s===3||(o+=u,s=o.length,s===4&&(a.push(...va(o)),o=``,s=0,i=c,a.length===r)))return{read:i,bytes:a,error:null}}}function ba(e,t){t===void 0&&(t=2**53-1);let n=e.length,r=[],i=0;if(n%2!=0)return{read:0,bytes:[],error:SyntaxError(`Invalid hex: string length must be even`)};for(;i<n&&r.length<t;){let t=e.substring(i,i+2);if(!/^[0-9a-fA-F]{2}$/.test(t))return{read:i,bytes:r,error:SyntaxError(`Invalid hex: unexpected character at position ${i}`)};i+=2,r.push(Number.parseInt(t,16))}return{read:i,bytes:r,error:null}}function xa(e,t){let n=t?.alphabet??`base64`;if(n!==`base64`&&n!==`base64url`)throw TypeError(`Invalid alphabet: expected "base64" or "base64url", got "${n}"`);let r=!!t?.omitPadding,i=``,a=e.length;for(let t=0;t<a;t+=3){let n=e[t],o=t+1<a?e[t+1]:0,s=t+2<a?e[t+2]:0;i+=ma[n>>2&63],i+=ma[(n&3)<<4|o>>4&15],t+1<a?i+=ma[(o&15)<<2|s>>6&3]:r||(i+=`=`),t+2<a?i+=ma[s&63]:r||(i+=`=`)}return n===`base64url`&&(i=i.replace(/\+/g,`-`).replace(/\//g,`_`)),i}function Sa(e){let t=``;for(let n=0;n<e.length;n++)t+=e[n].toString(16).padStart(2,`0`);return t}function Ca(e){let t=e.prototype,n=e;t.toBase64||Object.defineProperty(t,"toBase64",{value:function(t){if(!(this instanceof e))throw TypeError(`this is not a Uint8Array`);return xa(this,t)},writable:!0,enumerable:!1,configurable:!0}),t.toHex||Object.defineProperty(t,"toHex",{value:function(){if(!(this instanceof e))throw TypeError(`this is not a Uint8Array`);return Sa(this)},writable:!0,enumerable:!1,configurable:!0}),t.setFromBase64||Object.defineProperty(t,"setFromBase64",{value:function(t,n){if(!(this instanceof e))throw TypeError(`this is not a Uint8Array`);if(typeof t!=`string`)throw TypeError(`expected a string`);let r=n?.alphabet??`base64`;if(r!==`base64`&&r!==`base64url`)throw TypeError(`Invalid alphabet: expected "base64" or "base64url", got "${r}"`);let i=n?.lastChunkHandling??`loose`;if(i!==`loose`&&i!==`strict`&&i!==`stop-before-partial`)throw TypeError(`Invalid lastChunkHandling: expected "loose", "strict", or "stop-before-partial", got "${i}"`);let a=ya(t,r,i,this.length),o=a.bytes,s=o.length;for(let e=0;e<s;e++)this[e]=o[e];if(a.error)throw a.error;return{read:a.read,written:s}},writable:!0,enumerable:!1,configurable:!0}),t.setFromHex||Object.defineProperty(t,"setFromHex",{value:function(t){if(!(this instanceof e))throw TypeError(`this is not a Uint8Array`);if(typeof t!=`string`)throw TypeError(`expected a string`);let n=ba(t,this.length),r=n.bytes,i=r.length;for(let e=0;e<i;e++)this[e]=r[e];if(n.error)throw n.error;return{read:n.read,written:i}},writable:!0,enumerable:!1,configurable:!0}),n.fromBase64||Object.defineProperty(e,"fromBase64",{value:function(t,n){if(typeof t!=`string`)throw TypeError(`expected a string`);let r=n?.alphabet??`base64`;if(r!==`base64`&&r!==`base64url`)throw TypeError(`Invalid alphabet: expected "base64" or "base64url", got "${r}"`);let i=n?.lastChunkHandling??`loose`;if(i!==`loose`&&i!==`strict`&&i!==`stop-before-partial`)throw TypeError(`Invalid lastChunkHandling: expected "loose", "strict", or "stop-before-partial", got "${i}"`);let a=ya(t,r,i);if(a.error)throw a.error;return new e(a.bytes)},writable:!0,enumerable:!1,configurable:!0}),n.fromHex||Object.defineProperty(e,"fromHex",{value:function(t){if(typeof t!=`string`)throw TypeError(`expected a string`);let n=ba(t);if(n.error)throw n.error;return new e(n.bytes)},writable:!0,enumerable:!1,configurable:!0})}function wa(e){return function(){let t=`0123456789abcdef`,n=``;for(let r=0;r<36;r++)r===8||r===13||r===18||r===23?n+=`-`:r===14?n+=`4`:r===19?n+=t[Math.floor(e()*4)+8]:n+=t[Math.floor(e()*16)];return n}}const Ta={"SHA-1":`sha1`,"SHA-256":`sha256`,"SHA-384":`sha384`,"SHA-512":`sha512`};function Ea(e){if(Q.isTypedArray(e)||Q.isDataView(e)){if(Q.isSharedArrayBuffer(e.buffer))throw TypeError(`crypto.subtle.digest does not accept SharedArrayBuffer-backed views`);return e}if(!Q.isArrayBuffer(e))throw TypeError(`data must be an ArrayBuffer or ArrayBufferView`);return new Uint8Array(e)}function Da(e){let{fixedTimestamp:t}=e,{seed:n}=e,r=(0,pa.default)(n),i=On(),a=kn(`globalThis`,i);a.Math.random=r;let o=a.Date;a.Date=function(...e){return e.length===0?new o(t):new o(...e)},a.Date.prototype=o.prototype,Object.setPrototypeOf(a.Date,o),a.Date.now=()=>t;let s=globalThis.crypto,c=s.subtle;function l(e){for(let t=0;t<e.length;t++)e[t]=Math.floor(r()*256);return e}let u=wa(r),d=a;delete d.Atomics.waitAsync,delete d.WebAssembly.compile,delete d.WebAssembly.instantiate,delete d.WebAssembly.compileStreaming,delete d.WebAssembly.instantiateStreaming,delete d.WeakRef,delete d.FinalizationRegistry;let f=async(e,t)=>{let n=typeof e==`string`?e:e.name,r=Ta[n.toUpperCase()];if(!r)throw new DOMException(`Unrecognized algorithm name: ${n}`,`NotSupportedError`);let i=Tn(r).update(Ea(t)).digest(),a=new ArrayBuffer(i.byteLength);return new Uint8Array(a).set(i),a};return a.crypto=new Proxy(s,{get(e,t){return t===`getRandomValues`?l:t===`randomUUID`?u:t===`subtle`?new Proxy(c,{get(e,t){if(t===`digest`)return f;let n=e[t];return typeof n==`function`?()=>{throw new K(`\`crypto.subtle.${String(t)}()\` is not available inside a workflow function. Move it to a step function where full Node.js crypto is available.`)}:n}}):e[t]}}),a.process={env:Object.freeze({...process.env})},a.DOMException=globalThis.DOMException,a.Headers=globalThis.Headers,a.TextEncoder=globalThis.TextEncoder,a.TextDecoder=globalThis.TextDecoder,a.console=globalThis.console,a.URL=globalThis.URL,a.URLSearchParams=globalThis.URLSearchParams,a.structuredClone=globalThis.structuredClone,a.atob=globalThis.atob,a.btoa=globalThis.btoa,Ca(a.Uint8Array),a.Symbol.dispose??=Symbol.for(`Symbol.dispose`),a.Symbol.asyncDispose??=Symbol.for(`Symbol.asyncDispose`),a.exports={},a.module={exports:a.exports},{context:i,globalThis:a,updateTimestamp:e=>{t=e}}}const Oa=new Map;function ka(e){let t=Oa.get(e);if(t!==void 0)return Oa.delete(e),Oa.set(e,t),t}function Aa(e,t){let n=ka(e);if(n===void 0)for(n=new Map,Oa.set(e,n);Oa.size>8;){let e=Oa.keys().next().value;if(e===void 0)break;Oa.delete(e)}let r=n.get(t);return r===void 0&&(r=new Dn(e,{filename:t}),n.set(t,r)),r}function ja(e,t,n){return Aa(e,t).runInContext(n)}function Ma(e){return async function(t,n={}){let{promise:r,resolve:i}=Mt(),a=`attr_${e.generateUlid()}`,o={type:`attribute`,correlationId:a,changes:t,...n.allowReservedAttributes===!0?{allowReservedAttributes:!0}:{}};return e.invocationsQueue.set(a,o),e.eventsConsumer.subscribe(r=>r?r.correlationId===a?r.eventType!==`attr_set`||r.eventData.writer.type!==`workflow`||JSON.stringify(r.eventData.changes)!==JSON.stringify(t)||r.eventData.allowReservedAttributes===!0!=(n.allowReservedAttributes===!0)?(e.promiseQueue=e.promiseQueue.then(()=>{e.onWorkflowError(new X(`Replay divergence: Unexpected attribute event for ${a}`,{eventId:r.eventId}))}),x.Finished):(e.invocationsQueue.delete(a),e.promiseQueue=e.promiseQueue.then(()=>{i()}),x.Finished):x.NotConsumed:(kt(e,()=>{e.onWorkflowError(new G(e.invocationsQueue,e.globalThis))}),x.NotConsumed)),r}}function Na(e,t){if(typeof t!=`string`)return null;let n=V(l,e.globalThis),r=n?.[m];return typeof r==`function`?r.call(n,{runId:t}):null}function Pa(e){return function(t={}){if(t.token===``)throw Error("`createHook()` was called with an empty string token. Pass a non-empty token, or omit the `token` option to use a randomly generated one.");if(t.isWebhook===!0&&t.experimental_minRetention!==void 0)throw Error("Webhook hooks do not support `experimental_minRetention`. Use a non-webhook `createHook()` with `resumeHook()`.");if(t.experimental_minRetention!==void 0&&e.worldCapabilities?.hookRetention?.active!==!0)throw new Y("The configured World does not support `experimental_minRetention` for Hooks.");let n=`hook_${e.generateUlid()}`,r=t.token??e.generateNanoid(),i=t.experimental_minRetention===void 0?void 0:Pt(t.experimental_minRetention),a=t.isWebhook??!1;e.invocationsQueue.set(n,{type:`hook`,correlationId:n,token:r,tokenRetentionUntil:i,metadata:t.metadata,isWebhook:a});let o=[],s=[],c=[],l=!1,u=!1,d=!1,f=!1,p=null,m=null,h=new Set;me.debug(`Hook consumer setup`,{correlationId:n,token:r}),e.eventsConsumer.subscribe(t=>{if(!t)return l=!0,(s.length>0&&o.length===0||c.length>0&&!u&&!f)&&kt(e,()=>{e.onWorkflowError(new G(e.invocationsQueue,e.globalThis))}),x.NotConsumed;if(t.correlationId!==n)return x.NotConsumed;let i=`eventData`in t&&t.eventData&&`token`in t.eventData?t.eventData.token:void 0;if(typeof i==`string`&&i!==r)return e.promiseQueue=e.promiseQueue.then(()=>{e.onWorkflowError(new X(`Replay divergence: hook event ${t.eventType} for ${n} belongs to token "${i}", but the current hook consumer expects "${r}"`,{eventId:t.eventId}))}),x.Finished;if(t.eventType===`hook_created`){let r=e.invocationsQueue.get(n);r&&r.type===`hook`&&(r.hasCreatedEvent=!0,r.tokenRetentionUntil=t.eventData.tokenRetentionUntil),u=!0;let i=c.slice();return c.length=0,e.promiseQueue=e.promiseQueue.then(()=>{for(let e of i)e.resolve(null)}),x.Consumed}if(t.eventType===`hook_conflict`){e.invocationsQueue.delete(n);let r=t,i=new zt(r.eventData.token,r.eventData.conflictingRunId);f=!0,p=i,m=Na(e,r.eventData.conflictingRunId);let a=s.slice();s.length=0;let o=c.slice();return c.length=0,e.promiseQueue=e.promiseQueue.then(()=>{for(let e of a)e.reject(i);for(let e of o)m?e.resolve(m):e.reject(i)}),x.Consumed}if(t.eventType===`hook_received`){let n=t.resumeId;if(typeof n==`string`){if(h.has(n))return x.Consumed;h.add(n)}let r=e.eventsConsumer.eventIndex,i=s.length>0,a=jt(e,r,`hook`,{armed:i});if(i){let n=Nt(e,r,`hook`),i=s.shift();if(i){e.pendingDeliveries++;let r;e.promiseQueue=e.promiseQueue.then(async()=>{try{let n=await e.replayPayloadCache.prepareEventPayload(t.eventId,`payload`,t.eventData.payload);r={ok:!0,value:await C(t.eventData.payload,e.runId,e.encryptionKey,e.globalThis,{},n)}}catch(e){r={ok:!1,error:e}}finally{e.pendingDeliveries--}n.then(()=>{a.markDelivered(),r.ok?i.resolve(r.value):i.reject(r.error)})})}}else{let n,i=Mt();e.pendingDeliveries++,e.promiseQueue=e.promiseQueue.then(async()=>{try{let r=await e.replayPayloadCache.prepareEventPayload(t.eventId,`payload`,t.eventData.payload);n={ok:!0,value:await C(t.eventData.payload,e.runId,e.encryptionKey,e.globalThis,{},r)}}catch(e){n={ok:!1,error:e}}finally{e.pendingDeliveries--,i.resolve()}}),o.push({claim:()=>(a.arm(),i.promise.then(()=>Nt(e,r,`hook`)).then(()=>{if(a.markDelivered(),n&&!n.ok)throw n.error;return n.value}))})}return x.Consumed}return t.eventType===`hook_disposed`?(e.invocationsQueue.delete(n),d=!0,x.Finished):(e.promiseQueue=e.promiseQueue.then(()=>{e.onWorkflowError(new X(`Replay divergence: Unexpected event type for hook ${n} (token: ${r}) "${t.eventType}"`,{eventId:t.eventId}))}),x.Finished)});let g=!1;function _(){let t=Mt();if(f&&p)return e.promiseQueue=e.promiseQueue.then(()=>{t.reject(p)}),t.promise;if(o.length>0){let e=o.shift();if(e)return e.claim()}return l&&kt(e,()=>{e.onWorkflowError(new G(e.invocationsQueue,e.globalThis))}),s.push(t),t.promise}function v(){let t=Mt();if(u)return e.promiseQueue=e.promiseQueue.then(()=>{t.resolve(null)}),t.promise;if(f)return e.promiseQueue=e.promiseQueue.then(()=>{m?t.resolve(m):t.reject(p)}),t.promise;let r=e.invocationsQueue.get(n);return r&&r.type===`hook`&&(r.hasConflictAwaiter=!0),l&&kt(e,()=>{e.onWorkflowError(new G(e.invocationsQueue,e.globalThis))}),c.push(t),t.promise}function y(){if(g||(g=!0,d))return;let t=e.invocationsQueue.get(n);t&&t.type===`hook`&&(t.disposed=!0),s.length>0&&(s.length=0,kt(e,()=>{e.onWorkflowError(new G(e.invocationsQueue,e.globalThis))})),me.debug(`Hook disposed`,{correlationId:n,token:r})}let b={token:r,getConflict(){return v()},then(e,t){return _().then(e,t)},async*[Symbol.asyncIterator](){for(;!g;)yield await this},dispose:y,[Symbol.dispose]:y},S=e.globalThis.Symbol.dispose;return S&&S!==Symbol.dispose&&(b[S]=y),b}}function Fa(e){return async function(t){let{promise:n,resolve:r}=Mt(),i=`wait_${e.generateUlid()}`,a=Pt(t),o={type:`wait`,correlationId:i,resumeAt:a};return e.invocationsQueue.set(i,o),e.eventsConsumer.subscribe(t=>{if(!t)return kt(e,()=>{e.onWorkflowError(new G(e.invocationsQueue,e.globalThis))}),x.NotConsumed;if(t.correlationId!==i)return x.NotConsumed;if(t.eventType===`wait_created`){let n=e.invocationsQueue.get(i);return n&&n.type===`wait`&&(n.hasCreatedEvent=!0,n.resumeAt=t.eventData.resumeAt),x.Consumed}if(t.eventType===`wait_completed`){let n=t.eventData?.resumeAt;if(n!==void 0){let r=e.invocationsQueue.get(i),o=r&&r.type===`wait`?r.resumeAt:a,s=new Date(n),c=s.getTime(),l=o.getTime(),u=Number.isFinite(c)?s.toISOString():String(n);if(c!==l)return e.promiseQueue=e.promiseQueue.then(()=>{e.onWorkflowError(new X(`Replay divergence: wait_completed event for ${i} has resumeAt "${u}", but the current wait consumer expects "${o.toISOString()}"`,{eventId:t.eventId}))}),x.Finished}e.invocationsQueue.delete(i);let o=e.eventsConsumer.eventIndex,s=jt(e,o,`wait`),c=Nt(e,o,`wait`);return e.promiseQueue.then(()=>c).then(()=>{s.markDelivered(),r()}),x.Finished}return e.promiseQueue=e.promiseQueue.then(()=>{e.onWorkflowError(new X(`Replay divergence: Unexpected event type for wait ${i} "${t.eventType}"`,{eventId:t.eventId}))}),x.Finished}),n}}async function Ia(e,t,n,r,i,a){if(t.size!==0){for(let e of t.values())e.type===`hook`&&e.isSystem&&!e.disposed&&!e.abortRequested&&(e.disposed=!0);try{let e=await vr();await Yr({suspension:new G(t,n),world:e,run:r,runReadyBarrier:a})}catch(t){T.warn(`Failed to drain pending queue items for ${i} workflow run`,{workflowRunId:e,message:t instanceof Error?t.message:String(t)})}}}async function La(e,t,n,r,i=new Ln(r),a,s){return W(`workflow.run ${t.workflowName}`,async c=>{c?.setAttributes({...Me(t.workflowName),...Je(t.runId),...vt(t.status),...ie(n.length)});let l=t.startedAt;if(!l)throw new K(`Workflow run "${t.runId}" has no "startedAt" timestamp (should not happen)`);let u=Tr(t.runId)??+t.createdAt,d=It(process.env.VERCEL_URL?`https://${process.env.VERCEL_URL}`:`http://localhost:${await Ir()??3e3}`),{context:f,globalThis:p,updateTimestamp:m}=Da({seed:`${t.runId}:${t.workflowName}:${t.deploymentId}`,fixedTimestamp:u}),h=Mt(),g=on(()=>p.Math.random()),_=ia(`useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict`,21,e=>new Uint8Array(e).map(()=>256*p.Math.random())),v={current:Promise.resolve()},b=new se(n,{onConsumedEvent:e=>{m(+e.createdAt)},onUnconsumedEvent:e=>{h.reject(new X(`Replay could not consume event: eventType=${e.eventType}, correlationId=${e.correlationId}, eventId=${e.eventId}.`,{eventId:e.eventId}))},getPromiseQueue:()=>v.current}),S={runId:t.runId,encryptionKey:r,worldCapabilities:s,globalThis:p,onWorkflowError:h.reject,eventsConsumer:b,generateUlid:()=>g(u),generateNanoid:_,invocationsQueue:new Map,get promiseQueue(){return v.current},set promiseQueue(e){v.current=e},pendingDeliveries:0,pendingDeliveryBarriers:new Map,replayPayloadCache:i};S.eventsConsumer.subscribe(e=>e&&(e.eventType===`run_created`||e.eventType===`run_started`||e.eventType===`attr_set`&&e.eventData.writer.type===`step`)?x.Consumed:x.NotConsumed);let C=aa(S),w=Pa(S),T=Fa(S),ee=Ma(S);p[E]=C,p[O]=ee,p[fe]=w,p[ot]=T,p[y]=e=>D(t.runId,e),p[Qt]={workflowName:t.workflowName,workflowRunId:t.runId,workflowStartedAt:new p.Date(+l),url:d,features:{encryption:!!r}},p[R]=g,p.fetch=()=>{throw new p.Error(`Global "fetch" is unavailable in workflow functions. Use the "fetch" step function from "workflow" to make HTTP requests.\n\nLearn more: https://workflow-sdk.dev/err/${Ut.FETCH_IN_WORKFLOW_FUNCTION}`)};let k=`Timeout functions like "setTimeout" and "setInterval" are not supported in workflow functions. Use the "sleep" function from "workflow" for time-based delays.`;p.setTimeout=()=>{throw new K(k,{slug:Ut.TIMEOUT_FUNCTIONS_IN_WORKFLOW})},p.setInterval=()=>{throw new K(k,{slug:Ut.TIMEOUT_FUNCTIONS_IN_WORKFLOW})},p.clearTimeout=()=>{throw new K(k,{slug:Ut.TIMEOUT_FUNCTIONS_IN_WORKFLOW})},p.clearInterval=()=>{throw new K(k,{slug:Ut.TIMEOUT_FUNCTIONS_IN_WORKFLOW})},p.setImmediate=()=>{throw new K(k,{slug:Ut.TIMEOUT_FUNCTIONS_IN_WORKFLOW})},p.clearImmediate=()=>{throw new K(k,{slug:Ut.TIMEOUT_FUNCTIONS_IN_WORKFLOW})},p.AbortController=le(S);let M=o();p.AbortSignal={abort:M.abort,any:M.any,timeout:M.timeout};class N{cache;credentials;destination;headers;integrity;method;mode;redirect;referrer;referrerPolicy;url;keepalive;signal;duplex;body;constructor(e,t){if(typeof e==`string`||e instanceof p.URL){let t=String(e);try{new p.URL(t),this.url=t}catch(e){throw TypeError(`Failed to parse URL from ${t}`,{cause:e})}}else{if(this.url=e.url,!t){this.method=e.method,this.headers=new p.Headers(e.headers),this.body=e.body,this.mode=e.mode,this.credentials=e.credentials,this.cache=e.cache,this.redirect=e.redirect,this.referrer=e.referrer,this.referrerPolicy=e.referrerPolicy,this.integrity=e.integrity,this.keepalive=e.keepalive,this.signal=e.signal,this.duplex=e.duplex,this.destination=e.destination;return}this.method=e.method,this.headers=new p.Headers(e.headers),this.body=e.body,this.mode=e.mode,this.credentials=e.credentials,this.cache=e.cache,this.redirect=e.redirect,this.referrer=e.referrer,this.referrerPolicy=e.referrerPolicy,this.integrity=e.integrity,this.keepalive=e.keepalive,this.signal=e.signal,this.duplex=e.duplex,this.destination=e.destination}t?.method?this.method=t.method.toUpperCase():typeof this.method!=`string`&&(this.method=`GET`),t?.headers?this.headers=new p.Headers(t.headers):(typeof e==`string`||e instanceof p.URL)&&(this.headers=new p.Headers),t?.mode===void 0?typeof this.mode!=`string`&&(this.mode=`cors`):this.mode=t.mode,t?.credentials===void 0?typeof this.credentials!=`string`&&(this.credentials=`same-origin`):this.credentials=t.credentials,t?.cache===void 0?typeof this.cache!=`string`&&(this.cache=`default`):this.cache=t.cache,t?.redirect===void 0?typeof this.redirect!=`string`&&(this.redirect=`follow`):this.redirect=t.redirect,t?.referrer===void 0?typeof this.referrer!=`string`&&(this.referrer=`about:client`):this.referrer=t.referrer,t?.referrerPolicy===void 0?typeof this.referrerPolicy!=`string`&&(this.referrerPolicy=``):this.referrerPolicy=t.referrerPolicy,t?.integrity===void 0?typeof this.integrity!=`string`&&(this.integrity=``):this.integrity=t.integrity,t?.keepalive===void 0?typeof this.keepalive!=`boolean`&&(this.keepalive=!1):this.keepalive=t.keepalive,t?.signal===void 0?this.signal||={aborted:!1}:this.signal=t.signal,this.duplex||=`half`,this.destination||=`document`;let n=t?.body;if(n!=null&&(this.method===`GET`||this.method===`HEAD`))throw TypeError(`Request with GET/HEAD method cannot have body.`);n==null?this.body=null:this.body=Object.create(p.ReadableStream.prototype,{[j]:{value:n,writable:!1}})}clone(){U()}get bodyUsed(){return!1}blob;formData;arrayBuffer;json;text;async bytes(){return new Uint8Array(await this.arrayBuffer())}}p.Request=N,Object.defineProperties(N.prototype,{arrayBuffer:{value:C(`__builtin_response_array_buffer`),writable:!0,configurable:!0},json:{value:C(`__builtin_response_json`),writable:!0,configurable:!0},text:{value:C(`__builtin_response_text`),writable:!0,configurable:!0}});class P{type;url;status;statusText;body;headers;redirected;constructor(e,t){if(this.status=t?.status??200,this.statusText=t?.statusText??``,this.headers=new p.Headers(t?.headers),this.type=`default`,this.url=``,this.redirected=!1,e!=null&&(this.status===204||this.status===205||this.status===304))throw TypeError(`Response constructor: Invalid response status code ${this.status}`);e==null?this.body=null:this.body=Object.create(p.ReadableStream.prototype,{[j]:{value:e,writable:!1}})}clone;blob;formData;get ok(){return this.status>=200&&this.status<300}get bodyUsed(){return!1}arrayBuffer;json;text;async bytes(){return new Uint8Array(await this.arrayBuffer())}static json(e,t){let n=JSON.stringify(e),r=new p.Headers(t?.headers);return r.has(`content-type`)||r.set(`content-type`,`application/json`),new P(n,{...t,headers:r})}static error(){U()}static redirect(e,t=302){if(![301,302,303,307,308].includes(t))throw RangeError(`Invalid redirect status code: ${t}. Must be one of: 301, 302, 303, 307, 308`);let n=new p.Headers;n.set(`Location`,String(e));let r=Object.create(P.prototype);return r.status=t,r.statusText=``,r.headers=n,r.body=null,r.type=`default`,r.url=``,r.redirected=!1,r}}p.Response=P,Object.defineProperties(P.prototype,{arrayBuffer:{value:C(`__builtin_response_array_buffer`),writable:!0,configurable:!0},json:{value:C(`__builtin_response_json`),writable:!0,configurable:!0},text:{value:C(`__builtin_response_text`),writable:!0,configurable:!0}});class te{constructor(){U()}get locked(){return!1}cancel(){U()}getReader(){U()}pipeThrough(){U()}pipeTo(){U()}tee(){U()}values(){U()}static from(){U()}[Symbol.asyncIterator](){U()}}p.ReadableStream=te;class ne{constructor(){U()}get locked(){return!1}abort(){U()}close(){U()}getWriter(){U()}}p.WritableStream=ne;class F{readable;writable;constructor(){U()}}p.TransformStream=F,p.console=globalThis.console;let re=Symbol.for(`@vercel/request-context`);p[re]=globalThis[re];let I=ht(t.workflowName)?.moduleSpecifier||t.workflowName;ja(e,I,f);let L=ja(`globalThis.__private_workflows?.get(${JSON.stringify(t.workflowName)})`,I,f);if(typeof L!=`function`)throw new Jt(t.workflowName);let z=[];S.promiseQueue=S.promiseQueue.then(async()=>{let e=await i.prepareWorkflowInput(t);z=await A(t.input,t.runId,r,p,{},e)}),await S.promiseQueue,c?.setAttributes({...st(z.length)});try{let e=await Promise.race([L(...z),h.promise]),n=await Ge(e,t.runId,r,p,!1,(t.specVersion??0)>=5);return c?.setAttributes({...lt(typeof e)}),await Ia(t.runId,S.invocationsQueue,p,t,`completed`,a),n}catch(e){throw G.is(e)||X.is(e)||await Ia(t.runId,S.invocationsQueue,p,t,`failed`,a),e}})}function Ra(e){let t=Xn();return t===void 0?e:e===void 0?t:Math.min(e,t)}function za({world:e,runInput:t,runId:n,runLogger:r}){let i=t?.environment;if(!i)return!1;let a=e.getEnvironment?.();return!a||a===i?!1:(r.error(`Refusing to run this workflow: it was created in the "${i}" environment but this deployment runs in "${a}". Executing it here would create a second copy of the same run id in both environments — one pending forever, one running — so the queue message is being discarded without executing and without retrying. The client that called start() wrote the run to its own environment but addressed the queue message to a deployment in another one. Check that the environment that client authenticates as (WORKFLOW_VERCEL_ENV for CLI and CI clients, or the OIDC token's environment inside a deployment) matches the environment of the deployment it targets. The run it created is still pending in "${i}" and will not run.`,{workflowRunId:n,creatorEnvironment:i,currentEnvironment:a,pinnedDeploymentId:t?.deploymentId}),!0)}async function Ba({world:e,runInput:t,runId:n,runLogger:r}){let i=t?.deploymentId;if(!i)return;let a;try{a=await e.getDeploymentId()}catch{return}!a||a===i||r.error(`Queue message was delivered to a deployment it was not pinned to. The run was created targeting a different deployment, so this invocation may be replaying against code the run was not started on. Continuing — this is expected if the Workflow SDK version changed mid-run in local development, where the deployment id is derived from that version.`,{workflowRunId:n,pinnedDeploymentId:i,currentDeploymentId:a})}function Va(e){return K.is(e)?q.RUNTIME_ERROR:we(e)?q.WORLD_CONTRACT_ERROR:null}async function Ha({world:e,workflowRun:t,runId:n,requestId:r,err:i,errorCode:a,logMessage:o}){T.error(o,{workflowRunId:n,errorCode:a,error:i instanceof Error?i.message:String(i)});try{let o=ke(e,t??n);await e.events.create(n,{eventType:`run_failed`,specVersion:5,eventData:{error:await St(i,n,await o(),globalThis,(t?.specVersion??0)>=5),errorCode:a}},{requestId:r})}catch(e){if(Z.is(e)||J.is(e))return;if(we(e)){T.error(`Fatal world contract error while recording workflow failure`,{workflowRunId:n,errorCode:q.WORLD_CONTRACT_ERROR,error:e instanceof Error?e.message:String(e)});return}throw e}}function Ua(e,t){let n=e.find(e=>e.runId===t&&(e.eventType===`run_completed`||e.eventType===`run_failed`||e.eventType===`run_cancelled`));return n?(T.debug(`Run reached terminal event, exiting`,{workflowRunId:t,eventType:n.eventType,eventId:n.eventId}),!0):!1}function Wa(e,t){let n=0;for(let r of e)t.has(r)||n++;return n}function Ga(e,t){return e?.[en]??t}function Ka(e){let t=new Set,n=new Set;for(let r of e)r.eventType===`hook_disposed`?t.add(r.correlationId):r.eventType===`wait_completed`&&n.add(r.correlationId);let r=!1,i=!1;for(let a of e)if(a.eventType===`hook_created`&&!t.has(a.correlationId)?r=!0:a.eventType===`wait_created`&&!n.has(a.correlationId)&&(i=!0),r&&i)break;return{openHook:r,openWait:i}}function qa(e,t){Ft(t?.basePath);let n=Number(process.env.WORKFLOW_V2_TIMEOUT_MS)||12e4,i=cn(t?.namespace),a=nn(`workflow`,i),o=t=>t.createQueueHandler(a,async(o,s)=>{let c=Fe(o);if(c){await et(c,t.specVersion);return}let{runId:l,traceCarrier:d,requestedAt:f,stepId:p,stepName:m,replayDivergence:h,preconditionReinvocations:g,runInput:_,hookInput:v}=an.parse(o),y=gt(d)?d:void 0,{requestId:b}=s,x=s.queueName.slice(a.length),S=T.forRun(l,x),C=zn();if(s.attempt>C){let e=Pn(void 0,q.MAX_DELIVERIES_EXCEEDED);S.error(`Workflow handler exceeded max deliveries (${s.attempt}/${C})`,{attempt:s.attempt,errorCode:e.errorCode,errorAttribution:e.attribution});try{let e=await vr(),t=ke(e,l),n=new Y(`Workflow exceeded maximum queue deliveries (${s.attempt}/${C})`);await e.events.create(l,{eventType:`run_failed`,specVersion:5,eventData:{error:await St(n,l,await t()),errorCode:q.MAX_DELIVERIES_EXCEEDED}},{requestId:b})}catch(e){if(Z.is(e)||J.is(e))return;S.error(`Failed to mark run as failed after ${s.attempt} delivery attempts. A persistent error is preventing the run from being terminated. The run will remain in its current state until manually resolved. This is most likely due to a persistent outage of the workflow backend or a bug in the workflow runtime and should be reported to the Workflow team.`,{attempt:s.attempt,errorName:e instanceof Error?e.name:`UnknownError`,errorMessage:e instanceof Error?e.message:String(e),errorStack:e instanceof Error?e.stack:void 0})}return}let w=Pe(),E=()=>L(w,y),D=await ve(w,y),O=new xr,k=w===`continuous`?y:void 0,A=await r(`CONSUMER`);return await Ce(k,async()=>await nt({workflowRunId:l,workflowName:x},async()=>{let t=await W(`workflow.route.get_world`,async()=>vr());if(!za({world:t,runInput:_,runId:l,runLogger:S}))return await Ba({world:t,runInput:_,runId:l,runLogger:S}),W(`workflow.execute ${ut(x)}`,{kind:A,links:D},async r=>{r?.setAttributes({...Me(x),...mt(`execute_v2`),...u(`vercel-queue`),...Te(s.queueName),...wt(s.messageId),...ae(`process`),...He({requestedAt:f}),...Je(l),...Ze(!!y),...it(w)});let a=Date.now(),o=0,c=h?new Cr(h.count):Cr.inert(),d=(e,n)=>c.withEventCreate(n,n=>t.events.create(l,e,n)),C=null,D=null,k=null,A,j,M=-1,N,P,te,ne,F=0,re,I=$n()&&_!==void 0&&s.attempt===1&&p===void 0&&!h;r?.setAttributes(Be(I));let L,ie=async()=>{if(L)try{await L}catch{}},R=new Set,z=e=>{R.size>0&&T.error(`Invariant violation: acking the workflow message while owned inline steps are still executing — crash recovery for these steps is broken`,{workflowRunId:l,ackPath:e,stepIds:[...R]})},B=async(e,n)=>{if(z(`reinvoke`),!I)return{timeoutSeconds:e};await ze(t,xe(x,i),{runId:l,traceCarrier:await E(),requestedAt:new Date,...n},e>0?{delaySeconds:e}:void 0)},V=0,oe=null,se=e=>{let t=oe;if(!t)return;oe=null;let n=new Set(e.map(e=>e.eventId)),r=Wa(n,t.ids),i=Wa(t.ids,n),a=i>0?`shrank`:r>0?`grew`:`unchanged`;T.warn(`Restarted replay reloaded its event log after a stale-snapshot rejection`,{workflowRunId:l,outcome:a,added:r,dropped:i,eventsBefore:t.ids.size,eventsAfter:n.size,preconditionRestarts:t.restart,reason:t.reason,source:t.source,loopIteration:o})},ce=(e,t,{allowDelta:n=!0}={})=>{if(V>=rr())return!1;V++;let i=n&&V===1?rt(t,l):null,a=!!(i&&C);return oe=C?{ids:new Set(C.map(e=>e.eventId)),restart:V,reason:e,source:a?`inline-delta`:`full-reload`}:null,a?k=i:(C=null,D=null,N=void 0,P=void 0,k=null,fe.resetScan()),T.warn(`Event creation rejected as stale; restarting replay in-process`,{workflowRunId:l,reason:e,loopIteration:o,preconditionRestarts:V,source:a?`inline-delta`:`full-reload`}),r?.setAttributes({"workflow.precondition_restarts":V}),!0},le=async(e,t)=>{let n=(g??0)+1,i=ir();return n>i?{reinvoked:!1,error:new K(`Event creation was rejected as stale after ${i} re-invocations of ${rr()} in-process replay restarts each: this run cannot observe its own event log completely enough to make progress. Last rejection (${e}): ${t instanceof Error?t.message:String(t)}`,{cause:t})}:(T.warn(`Event creation rejected as stale after in-process restarts; re-invoking run for a fresh replay`,{workflowRunId:l,reason:e,loopIteration:o,preconditionReinvocations:n,maxReinvocations:i}),r?.setAttributes({"workflow.precondition_reinvocations":n}),{reinvoked:!0,result:await B(ar(),{preconditionReinvocations:n})})};if(p&&m)try{let e=await t.runs.get(l,{resolveData:`none`});if(e.status!==`running`){T.debug(`Run already finished, skipping background step`,{workflowRunId:l,status:e.status});return}let n=e.startedAt?+e.startedAt:Date.now(),r=s.attempt,a=At(m)?.maxRetries??3;if(s.attempt>a+1){let e=await _t(l);C=e.events,D=e.cursor,r=sr(C,p,{type:`totalAttempts`})+1}O.pause();let o;try{o=await qr(l,p,()=>Vr({world:t,workflowRunId:l,workflowDeploymentId:e.deploymentId,workflowName:x,workflowStartedAt:n,rootRunId:Ga(e.attributes,l),stepId:p,stepName:m,runSpecVersion:e.specVersion,authoritativeAttempt:r}))}finally{O.resume()}if(o.type===`retry`||o.type===`throttled`)return{timeoutSeconds:o.timeoutSeconds};if(o.type===`completed`&&o.hasPendingOps){await ze(t,xe(x,i),{runId:l,traceCarrier:await E(),requestedAt:new Date});return}if(o.type===`completed`||o.type===`failed`||o.type===`skipped`){let r=await _t(l);C=r.events,D=r.cursor;let i=new Set,a=new Set;for(let e of C)e.eventType===`step_created`?i.add(e.correlationId):(e.eventType===`step_completed`||e.eventType===`step_failed`)&&a.add(e.correlationId);let o=new Set;for(let e of i)a.has(e)||o.add(e);if(o.size>0)if(er()&&Gr(C,o,s.messageId))T.debug(`Background step done; falling through to recover an inline step owned by this message`,{workflowRunId:l});else{T.debug(`Background step done but other steps pending, returning`,{workflowRunId:l});return}T.debug(`All parallel steps done, replaying inline after background step`,{workflowRunId:l});let c=C.find(e=>e.eventType===`run_created`),u;if(c)u=c.eventData.input;else{if(!un(e.specVersion))throw new K(`Workflow run "${l}" has no "run_created" event`);let n=await t.runs.get(l,{resolveData:`all`});if(n.status!==`running`)return;u=n.input}A={...e,input:u,status:`running`,output:void 0,error:void 0,completedAt:void 0},M=n}else return}catch(e){let n=Va(e);if(!n)throw e;await Ha({world:t,workflowRun:A,runId:l,requestId:b,err:e,errorCode:n,logMessage:`Fatal error while preparing background workflow step`});return}if(!A){let e={eventType:`run_started`,specVersion:_?.specVersion??5,..._?{eventData:{input:_.input,deploymentId:_.deploymentId,workflowName:_.workflowName,executionContext:_.executionContext,attributes:_.attributes,allowReservedAttributes:_.allowReservedAttributes}}:{}},n=e=>{r?.addEvent(`workflow.run_started.create.start`,{"workflow.run_started.skip_preload":e})};if(I&&_){n(!0);let t=d(e,{requestId:b,skipPreload:!0});L=t,t.then(e=>{let t=Ra(e?.maxEvents);t!==void 0&&(j=t)},()=>{}),t.catch(()=>{}),N=[];let i=new Date;A={runId:l,status:`running`,deploymentId:_.deploymentId,workflowName:_.workflowName,specVersion:_.specVersion,executionContext:_.executionContext,input:_.input,attributes:_.attributes??{},startedAt:i,createdAt:i,updatedAt:i},M=+i,ne=+i,r?.setAttributes({...vt(`running`),...Ae(M)})}else{try{n(!1);let t=await d(e,{requestId:b});if(!t.run)throw new K(`Event creation for 'run_started' did not return the run entity for run "${l}"`);if(A=t.run,j=Ra(t.maxEvents),ne=Date.now(),t.events&&t.events.length>0&&t.hasMore!==!0&&(N=t.events,P=t.cursor),!A.startedAt)throw new K(`Workflow run "${l}" has no "startedAt" timestamp`)}catch(e){if(Z.is(e)||J.is(e)){T.info(`Run already finished during setup, skipping`,{workflowRunId:l,message:e.message});return}else{let n=Va(e);if(!n)throw e;await Ha({world:t,workflowRun:A,runId:l,requestId:b,err:e,errorCode:n,logMessage:`Fatal runtime error during workflow setup`});return}}if(M=+A.startedAt,r?.setAttributes({...vt(A.status),...Ae(M)}),A.status!==`running`){T.info(`Workflow already completed or failed, skipping`,{workflowRunId:l,status:A.status});return}}}if(v&&!(v.resumeId!==void 0&&N?.some(e=>e.eventType===`hook_received`&&e.resumeId===v.resumeId))){let e;try{e=v.resumeId===void 0?void 0:new Date(rn(v.resumeId))}catch{e=void 0}let n;try{let i=await t.events.create(l,{eventType:`hook_received`,specVersion:5,correlationId:v.hookId,eventData:{token:v.token,payload:v.payload}},{requestId:b,occurredAt:e,resumeId:v.resumeId,resumePayloadDigest:v.payloadDigest});r?.setAttributes(Ve(!0));let a=i.event;n=a?{...a,eventData:{token:v.token,payload:v.payload}}:void 0}catch(e){if(Wt.is(e)||J.is(e))return;throw e}N&&n?Ee(N,n):(N=void 0,P=void 0)}let ue=await ke(t,A)(),fe=new Ln(ue);for(;;){if(o++,O.isExhausted()){await Sr({runId:l,workflowName:x,requestId:b,attempt:s.attempt,limitMs:O.configuredLimitMs});return}if(Date.now()-a>=n){T.info(`V2 timeout reached, re-scheduling workflow`,{workflowRunId:l,loopIteration:o,elapsedMs:Date.now()-a}),await ze(t,xe(x,i),{runId:l,traceCarrier:await E(),requestedAt:new Date});return}let u=0,f=null;try{let n;if(k&&C){let e=k;k=null,ct(C,e.events),D=e.cursor??D,n=C}else if(C===null)if(N)n=N,D=P??null;else{let e=await _t(l);n=e.events,D=e.cursor}else if(D){let e=await _t(l,D);ct(C,e.events),D=e.cursor??D,n=C}else if(N){T.debug(`No cursor after preloaded-events first iteration; doing full reload to pick up cursor.`,{workflowRunId:l});let e=await _t(l);C=e.events,D=e.cursor,n=C}else{T.warn(`Event cursor missing after initial load — falling back to full reload. This indicates a bug in the World implementation.`,{workflowRunId:l});let e=await _t(l);C=e.events,D=e.cursor,n=C}if(C=n,se(n),Ua(n,l))return;let i=Date.now(),a=new Set(n.filter(e=>e.eventType===`wait_completed`).map(e=>e.correlationId)),s=n.filter(e=>e.eventType===`wait_created`&&e.correlationId!==void 0&&!a.has(e.correlationId)&&i>=e.eventData.resumeAt.getTime()).map(e=>({eventType:`wait_completed`,specVersion:5,correlationId:e.correlationId,eventData:{resumeAt:e.eventData.resumeAt}}));for(let e of s)try{await d(e,{requestId:b,...Xe(n,D)})}catch(t){if(Z.is(t)){T.info(`Wait already completed, skipping`,{workflowRunId:l,correlationId:e.correlationId});continue}throw t}if(s.length>0)if(D){let e=await _t(l,D),t=new Set(e.events.filter(e=>e.eventType===`wait_completed`).map(e=>e.correlationId));if(s.every(e=>t.has(e.correlationId)))ct(n,e.events),D=e.cursor??D;else{let e=await _t(l);n=e.events,D=e.cursor}}else{let e=await _t(l);n=e.events,D=e.cursor}if(Ua(n,l))return;if(j!==void 0&&n.length>=j)throw new Gt(n.length,j);C=n,te??=n.every(e=>e.eventType===`run_created`||e.eventType===`run_started`||e.eventType===`attr_set`),f=D,T.debug(`Starting workflow replay`,{workflowRunId:l,loopIteration:o,eventCount:n.length}),u=Date.now();let p=fe.prewarm(A,n),m=await La(e,A,n,ue,fe,L,t.capabilities);await p,T.debug(`Workflow replay completed`,{workflowRunId:l,loopIteration:o,replayMs:Date.now()-u}),c.activate();try{await ie(),await d({eventType:`run_completed`,specVersion:5,eventData:{output:m}},{requestId:b,...Xe(n,D)})}catch(e){if(Z.is(e)||J.is(e)){T.info(`Tried completing workflow run, but run has already finished.`,{workflowRunId:l,message:e.message});return}throw e}r?.setAttributes({...vt(`completed`)});return}catch(n){if(G.is(n)){c.activate();let e=Date.now()-u;T.debug(`Workflow suspended`,{workflowRunId:l,loopIteration:o,replayMs:e,steps:n.stepCount,hooks:n.hookCount,waits:n.waitCount});let a=de(n.stepCount,n.hookCount,n.waitCount);a&&T.debug(a);let p=Date.now();if(!C)throw Error(`Invariant violation: workflow suspended before its event log was loaded`);let m={events:C,cursor:D},h;try{h=await Yr({suspension:n,world:t,run:A,span:r,requestId:b,eventLog:m,runReadyBarrier:L,replayRecoveryReporter:c})}catch(e){if(Bt.is(e)){if(ce(`suspension-create`,e))continue;let t=await le(`suspension-create`,e);if(t.reinvoked)return t.result;throw t.error}if(!Y.is(e))throw e;let t=bt(e);T.error(`Non-retryable error while committing workflow suspension; failing run`,{workflowRunId:l,errorCode:t,errorName:e.name,errorMessage:e.message});try{await ie(),await d({eventType:`run_failed`,specVersion:5,eventData:{error:await St(e,l,ue,globalThis,(A?.specVersion??0)>=5),errorCode:t}},{requestId:b})}catch(e){if(Z.is(e)||J.is(e)){T.info(`Tried failing workflow run, but run has already finished.`,{workflowRunId:l,message:e.message});return}throw e}r?.setAttributes({...vt(`failed`),..._e(t),...ye(e.name),...he(e.message),...yt(e.name)});return}if(D=m.cursor,F+=h.hookCreationMs,h.hasAttributeEvents&&re===void 0&&(re=F),T.debug(`Suspension handled`,{workflowRunId:l,suspensionMs:Date.now()-p,pendingSteps:h.pendingSteps.length,timeoutSeconds:h.waitTimeout?.seconds,hasHookConflict:h.hasHookConflict,hasAwaitedHookCreation:h.hasAwaitedHookCreation,hasAttributeEvents:h.hasAttributeEvents}),h.hasHookConflict)return await B(0);if(h.hasAttributeEvents)continue;let g=h.pendingSteps,_=h.lazyInlineSteps,v=new Set(_.map(e=>e.correlationId)),y=await E(),S=[],w=er(),j=Date.now(),N=[],P=0;for(let e of g){if(v.has(e.correlationId))continue;let n=w&&Hr(e);if(n&&e.ownerMessageId===s.messageId){N.push(e);continue}let r=n?Ur(e,j):0;if(r>0){P++,T.debug(`Pending step is inline-owned by a live invocation; ensuring delayed backstop wake instead of immediate requeue`,{workflowRunId:l,stepId:e.correlationId,ownerMessageId:e.ownerMessageId,backstopDelaySeconds:r}),S.push(ze(t,xe(x,i),{runId:l,traceCarrier:y,requestedAt:new Date},{delaySeconds:r,idempotencyKey:Wr(e)}));continue}S.push(ze(t,xe(x,i),{runId:l,stepId:e.correlationId,stepName:e.stepName,traceCarrier:y,requestedAt:new Date},{idempotencyKey:e.correlationId}))}h.waitTimeout&&S.push(ze(t,xe(x,i),{runId:l,traceCarrier:y,requestedAt:new Date},$r(h.waitTimeout.seconds,h.waitTimeout.correlationId))),await Promise.all(S);let z=[..._.map(e=>({correlationId:e.correlationId,stepName:e.stepName,lazyStepInput:e.dehydratedInput})),...N.map(e=>({correlationId:e.correlationId,stepName:e.stepName}))];if((P>0||N.length>0)&&r?.setAttributes({...N.length>0?Qe(N.length):{},...P>0?ee(P):{}}),N.length>0&&T.warn(`Re-executing inline steps owned by this queue message — a previous delivery crashed mid-body and this redelivery is recovering them`,{workflowRunId:l,stepIds:N.map(e=>e.correlationId)}),z.length===0)return h.hasAwaitedHookCreation?await B(0):void 0;let ae=Ka(C??[]),V=qe()&&t.capabilities?.preconditionGuard===!0,oe=typeof f==`string`&&n.stepCount===1&&n.waitCount===0&&g.length===1&&_.length===1&&N.length===0&&!h.waitTimeout&&!ae.openWait&&(V||n.hookCount===0&&!ae.openHook),se=V&&(ae.openHook||n.hookCount>0||h.hasHookEvents),fe=I&&!h.hasAttributeEvents&&!h.waitTimeout&&!h.hasHookEvents&&!h.hasAwaitedHookCreation&&!ae.openHook&&!ae.openWait,pe=Rr({events:C??[],invocationStartedClean:te===!0,runCreatedAtMs:Tr(l)??(I?void 0:+A.createdAt),runStartedReceivedAtMs:ne,replayMs:e,preStepBlockingMs:F,preStepBlockingBeforeAttrMs:re,suspensionHasWaits:n.waitCount>0||h.waitTimeout!==void 0,suspensionCreatedHooks:n.hookCount>0||h.hasHookEvents,turbo:I}),me=Xe(C??[],f);O.pause();let H,ge=z.map((e,n)=>{let r=()=>Vr({world:t,workflowRunId:l,workflowDeploymentId:A.deploymentId,workflowName:x,workflowStartedAt:M,rootRunId:Ga(A.attributes,l),stepId:e.correlationId,stepName:e.stepName,runSpecVersion:A.specVersion,authoritativeAttempt:e.lazyStepInput===void 0?sr(C,e.correlationId,{type:`ownedBy`,messageId:s.messageId})+1:1,lazyStepInput:e.lazyStepInput,ownerMessageId:s.messageId,forceOptimisticStart:fe,suppressOptimisticStart:se,runReadyBarrier:L,preconditionSnapshot:me,...n===0&&e.lazyStepInput!==void 0&&pe?{latencyTracking:pe}:{},...oe&&f?{inlineDeltaSinceCursor:f}:{},replayRecoveryReporter:c});return R.add(e.correlationId),(e.lazyStepInput===void 0?qr(l,e.correlationId,r):r()).finally(()=>R.delete(e.correlationId))});try{H=await Promise.all(ge)}catch(e){if(Bt.is(e)){if(ce(`inline-claim`,e,{allowDelta:!(await Promise.allSettled(ge)).some(e=>e.status===`fulfilled`&&(e.value.type===`completed`||e.value.type===`failed`||e.value.type===`retry`))}))continue;let t=await le(`inline-claim`,e);if(t.reinvoked)return t.result;throw t.error}throw e}finally{O.resume()}let ve=[],U=!1,be;for(let e=0;e<z.length;e++){let t=H[e],n=z[e];t.type===`retry`?ve.push({step:n,delaySeconds:t.timeoutSeconds}):t.type===`throttled`?be=Math.max(be??0,t.timeoutSeconds):t.type===`completed`&&t.hasPendingOps&&(U=!0)}if(be!==void 0)return await B(be);if(ve.length>0){let e=await E();await Promise.all(ve.map(({step:n,delaySeconds:r})=>ze(t,xe(x,i),{runId:l,stepId:n.correlationId,stepName:n.stepName,traceCarrier:e,requestedAt:new Date},{delaySeconds:r,idempotencyKey:n.correlationId})))}if(U){T.debug(`Breaking loop: inline step has pending ops`,{workflowRunId:l,loopIteration:o}),await ze(t,xe(x,i),{runId:l,traceCarrier:await E(),requestedAt:new Date});return}if(ve.length>0)return;if(z.length===1){let e=H[0];e.type===`completed`&&e.inlineDelta&&!e.inlineDelta.hasMore&&(k={events:e.inlineDelta.events,cursor:e.inlineDelta.cursor})}}else{let a=n;if(Bt.is(n)){if(ce(`replay-write`,n))continue;let e=await le(`replay-write`,n);if(e.reinvoked)return e.result;a=e.error}if(Tt(n))throw S.warn(`Transient world error during replay; redelivering via queue instead of failing the run`,{errorName:n instanceof Error?n.name:`UnknownError`,errorMessage:n instanceof Error?n.message:String(n),deliveryAttempt:s.attempt}),n;let o;if(X.is(n)){let e=(h?.count??0)+1,r=nr();if(e<=r){S.warn(`Workflow replay diverged; queueing a recovery replay before declaring the event log corrupted`,{errorCode:q.REPLAY_DIVERGENCE,divergenceEventId:n.eventId,priorDivergenceEventId:h?.eventId,divergenceCount:e,deliveryAttempt:s.attempt,maxRecoveryReplays:r,errorMessage:n.message}),await ze(t,xe(x,i),{runId:l,traceCarrier:await E(),requestedAt:new Date,replayDivergence:{eventId:n.eventId,count:e}});return}o=e,a=new Kt(`Workflow replay diverged ${e} times after ${r} recovery replays; latest divergent event was ${n.eventId}. Last divergence: ${n.message}`,{cause:n})}else u>0&&c.activate();a instanceof Error&&r?.recordException?.(a);let f=await Mr(a),p=f.name||Er(a),m=f.message,g=f.stack||Dr(a);if(g){let t=ht(x)?.moduleSpecifier||x;g=ra(g,t,e)}let _=bt(a);T.error(`Error while running workflow`,{workflowRunId:l,errorCode:_,errorName:p,errorStack:g}),Q.isNativeError(a)&&g&&(a.stack=g);try{await ie(),await d({eventType:`run_failed`,specVersion:5,eventData:{error:await St(a,l,ue,globalThis,(A?.specVersion??0)>=5),errorCode:_}},{requestId:b,...o===void 0?{}:{replayDivergenceCount:o}})}catch(e){if(Z.is(e)||J.is(e)){T.info(`Tried failing workflow run, but run has already finished.`,{workflowRunId:l,message:e.message});return}if(we(e)){T.error(`Fatal world contract error while recording workflow failure`,{workflowRunId:l,errorCode:q.WORLD_CONTRACT_ERROR,error:e instanceof Error?e.message:String(e)});return}throw e}r?.setAttributes({...vt(`failed`),..._e(_),...ye(p),...he(m),...yt(p)});return}}}})}))}),s,c=0,l=Date.now(),d=typeof t?.routeModuleBodyStartedAt==`number`?l-t.routeModuleBodyStartedAt:void 0;return Le(async e=>{c+=1;let t=s!==void 0;return W(`workflow.route.flow`,{kind:await r(`SERVER`),attributes:{...De(`flow`),...je(Rn),...Se(t),...tt(c),...Ue(Date.now()-l),...d===void 0?{}:ft(d),...be(e.method),...Et(`/.well-known/workflow/v1/flow`)}},async t=>{s||=await W(`workflow.route.init`,async()=>{let e=await W(`workflow.route.get_world_handlers`,async()=>_r());return o(e)});let n=await s(e);return n instanceof Response&&t?.setAttributes(xt(n.status)),n})})}export{Sn as Run,G as WorkflowSuspension,bn as cancelRun,gr as createWorld,mr as createWorldFromModule,pn as getHookByToken,vn as getRun,vr as getWorld,_r as getWorldHandlers,dt as healthCheck,gn as listStreams,mn as readStream,yn as recreateRunFromExisting,xn as reenqueueRun,dn as resumeHook,fn as resumeWebhook,yr as setWorld,_n as start,hn as wakeUpRun,qa as workflowEntrypoint};
1
+ import{i as e,o as t,t as n}from"../../_chunks/workflow/rolldown-runtime-DaDcL9Zw.js";import{$ as r,$n as i,$t as a,At as o,B as s,Bt as c,C as l,Cn as u,Ct as d,D as f,Dt as p,E as m,Et as h,F as g,Ft as _,G as v,Gt as y,H as b,Ht as x,I as S,It as C,J as w,Jt as T,K as E,Kt as D,L as O,Lt as k,Mn as A,Mt as j,Nt as M,Ot as N,P,Pn as F,Pt as I,Q as L,Qn as ee,Qt as R,Rt as te,Sn as ne,St as re,T as z,Tt as B,U as V,Un as ie,Ut as ae,V as H,Vt as oe,W as se,Wn as ce,Wt as le,X as ue,Xn as de,Xt as fe,Y as U,Yt as pe,Z as me,Zn as he,Zt as ge,_n as _e,_t as ve,a as ye,an as be,at as W,b as xe,bn as Se,bt as G,c as Ce,cn as we,cr as Te,d as Ee,dn as De,dt as Oe,en as ke,er as Ae,et as je,f as Me,fn as Ne,ft as Pe,g as Fe,gn as Ie,gt as Le,h as Re,hn as ze,i as Be,in as Ve,jn as He,jt as Ue,k as We,kn as Ge,kt as Ke,l as qe,ln as Je,lt as Ye,m as Xe,mn as Ze,nn as Qe,nt as $e,o as et,on as tt,or as nt,ot as rt,p as it,pn as at,q as ot,qt as st,r as ct,rn as lt,s as ut,sn as dt,sr as ft,st as pt,t as mt,tn as ht,tr as gt,tt as _t,u as vt,un as yt,ut as bt,v as xt,vn as St,w as Ct,wn as K,wt,xn as Tt,xt as Et,y as Dt,yn as Ot,yt as kt,z as At,zn as jt,zt as Mt}from"../../_chunks/workflow/wait-until-CMX5LUWJ.js";import{A as Nt,D as q,O as Pt,S as Ft,_ as It,a as Lt,b as Rt,c as zt,d as J,g as Bt,i as Y,k as X,l as Z,m as Vt,n as Ht,o as Ut,r as Q,s as Wt,t as Gt,u as Kt}from"../../_chunks/workflow/dist-CRTn4Sg8.js";import{a as qt,n as Jt,o as Yt,r as Xt,s as Zt,t as Qt}from"../../_chunks/workflow/private-CiWVdS5v.js";import{n as $t,t as en}from"../../_chunks/workflow/dist-tJoQXAF6.js";import{a as tn,n as nn}from"../../_chunks/workflow/workflow-routes-CwqB063q.js";import{d as rn,l as an,n as on,s as sn,u as cn}from"../../_chunks/workflow/attribute-changes-Du5ztewf.js";import{J as ln,X as un,a as dn,c as fn,l as pn,o as mn,s as hn,v as gn,x as _n,y as vn}from"../../_chunks/workflow/dist-CNXUKQCp.js";import{t as yn}from"../../_chunks/workflow/env-config-CYoX3muK.js";import{t as bn}from"../../_chunks/workflow/spec-version-C0hBsfu-.js";import{n as xn,r as Sn,t as Cn}from"../../_chunks/workflow/resume-hook-CT0keOww.js";import{a as wn,c as Tn,d as En,i as Dn,l as On,n as kn,o as An,r as jn,s as Mn,t as Nn,u as Pn}from"../../_chunks/workflow/run-DBheaFhH.js";import{t as Fn}from"../../_chunks/workflow/run-id-BdE0MZz9.js";import{createRequire as In}from"node:module";import{createHash as Ln}from"node:crypto";import{types as Rn}from"node:util";import{pathToFileURL as zn}from"node:url";import{Script as Bn,createContext as Vn,runInContext as Hn}from"node:vm";function Un(e=process.env){return e.WORKFLOW_TARGET_WORLD||(e.VERCEL_DEPLOYMENT_ID?`vercel`:`local`)}function Wn(e){return e===`vercel`||e===`@workflow/world-vercel`}var Gn=t($t(),1);function Kn(e){return e instanceof cn||e instanceof an||e instanceof rn||e instanceof on}const qn=`The workflow event log contains orphaned or mismatched events and cannot be replayed. This is an internal workflow SDK error; please report it with the runId.`;function Jn(e,t){let n=t??xt(e);return Vt.is(e)?{attribution:`user`,errorCode:n,hint:`A value passed across a workflow/step boundary could not be serialized. See the error message for the offending path and the Learn More link for details.`}:Kn(e)?{attribution:`user`,errorCode:n,hint:`A workflow-only or step-only API was called from the wrong context. The error message includes the exact API and how to move the call.`}:Gt.is(e)?{attribution:`sdk`,errorCode:n,hint:qn}:n===X.DEPLOYMENT_MISMATCH?{attribution:`sdk`,errorCode:n,hint:`The run was delivered to a deployment other than the deployment it is pinned to, and was stopped to protect against code-skew errors after the runtime failed to re-route it there. Verify that the run's deployment is still available and that queue callbacks route to it.`}:e instanceof q?{attribution:`sdk`,errorCode:n,hint:`This is an internal workflow SDK error, not a bug in your code. If it keeps happening, please report it with the stack trace and the runId.`}:n===X.REPLAY_TIMEOUT?{attribution:`sdk`,errorCode:n,hint:'The workflow replay between step boundaries took too long. This bounds workflow-VM and event-log replay time only — step bodies (`"use step"` functions) are excluded. This usually means the event log is unusually large or the workflow function is doing heavy synchronous work in workflow code outside of step bodies. Override the default budget via the WORKFLOW_REPLAY_TIMEOUT_MS env var if needed.'}:n===X.MAX_DELIVERIES_EXCEEDED?{attribution:`sdk`,errorCode:n,hint:`The workflow queue exceeded its max-delivery budget. This usually indicates a persistent runtime failure — check the most recent stack traces for the underlying cause.`}:n===X.MAX_EVENTS_EXCEEDED?{attribution:`user`,errorCode:n,hint:`The workflow exceeded the maximum number of events per run. This usually means unbounded work in the workflow function — e.g. a loop that keeps creating steps without terminating. Break long-running workflows into child workflows to stay under the limit.`}:n===X.CORRUPTED_EVENT_LOG?{attribution:`sdk`,errorCode:n,hint:qn}:n===X.WORLD_CONTRACT_ERROR?{attribution:`sdk`,errorCode:n,hint:`The workflow backend returned data that violated the SDK contract. This is not retryable; please report it with the stack trace and runId.`}:{attribution:`user`,errorCode:n}}const Yn=4096;function Xn(e){if(e===null)return!0;let t=typeof e;return t===`object`||t===`function`?!1:t===`string`?e.length<=Yn:t!==`bigint`||e.toString().length<=Yn}var Zn=class{encryptionKey;preparer;preparedPayloads=new Map;primitiveStepResults=new Map;nextUnscannedEventIndex=0;constructor(e,t=At){this.encryptionKey=e,this.preparer=t}async prewarm(e,t){let n=[],r=(e,t)=>{t instanceof Uint8Array&&(this.preparedPayloads.has(e)||n.push(this.ensurePreparation(e,t)))};r(this.workflowInputKey(e.runId),e.input);for(let e=this.nextUnscannedEventIndex;e<t.length;e++){let n=t[e];switch(n.eventType){case`step_completed`:r(this.eventPayloadKey(n.eventId,`result`),n.eventData?.result);break;case`step_failed`:r(this.eventPayloadKey(n.eventId,`error`),n.eventData?.error);break;case`hook_received`:r(this.eventPayloadKey(n.eventId,`payload`),n.eventData?.payload);break}}this.nextUnscannedEventIndex=t.length,await Promise.allSettled(n)}resetScan(){this.nextUnscannedEventIndex=0}prepareWorkflowInput(e){return this.consumePreparation(this.workflowInputKey(e.runId),e.input)}prepareEventPayload(e,t,n){return this.consumePreparation(this.eventPayloadKey(e,t),n)}async getStepResult(e,t){if(this.primitiveStepResults.has(e))return this.primitiveStepResults.get(e);let n=await t();return Xn(n)&&this.primitiveStepResults.set(e,n),n}consumePreparation(e,t){if(!(t instanceof Uint8Array))return this.runPreparation(t);let n=this.ensurePreparation(e,t);return n.catch(()=>{this.preparedPayloads.get(e)===n&&this.preparedPayloads.delete(e)}),n}ensurePreparation(e,t){let n=this.preparedPayloads.get(e);if(n)return n;let r=this.runPreparation(t);return this.preparedPayloads.set(e,r),r}async runPreparation(e){return this.preparer(e,this.encryptionKey)}workflowInputKey(e){return`run:${e}:input`}eventPayloadKey(e,t){return`event:${e}:${t}`}};const Qn=`cinst_${pn()}`;function $n(){return yn(`WORKFLOW_MAX_QUEUE_DELIVERIES`,48,{integer:!0,min:1,max:48})}const er=24e4,tr=3e4,nr=78e4,rr=new Set;function ir(e,t,n){rr.has(e)||(rr.add(e),w.warn(t,n))}function ar(){let e=process.env.WORKFLOW_REPLAY_TIMEOUT_MS;if(!e)return er;let t=Number(e);return!Number.isFinite(t)||t<=0?(ir(e,`Ignoring WORKFLOW_REPLAY_TIMEOUT_MS: not a positive finite number; using default`,{raw:e,defaultMs:er}),er):t<3e4?(ir(e,`WORKFLOW_REPLAY_TIMEOUT_MS below minimum; clamped`,{raw:e,clampedMs:tr,minMs:tr}),tr):t>78e4?(ir(e,`WORKFLOW_REPLAY_TIMEOUT_MS above maximum; clamped`,{raw:e,clampedMs:nr,maxMs:nr}),nr):t}function or(){return yn(`WORKFLOW_REPLAY_TIMEOUT_MAX_RETRIES`,3,{integer:!0})}const sr=new Set;function cr(){let e=process.env.WORKFLOW_MAX_INLINE_STEPS;if(!e)return 3;let t=Number(e);return!Number.isInteger(t)||t<=0?(sr.has(e)||(sr.add(e),w.warn(`Ignoring WORKFLOW_MAX_INLINE_STEPS: not a positive integer; using default`,{raw:e,defaultValue:3})),3):t<1?1:t>16?(sr.has(e)||(sr.add(e),w.warn(`WORKFLOW_MAX_INLINE_STEPS above maximum; clamped`,{raw:e,clampedValue:16,maxValue:16})),16):t}const lr=new Set;function ur(){let e=process.env.WORKFLOW_MAX_EVENTS_OVERRIDE;if(!e)return;let t=Number(e);if(!Number.isInteger(t)||t<=0){lr.has(e)||(lr.add(e),w.warn(`Ignoring WORKFLOW_MAX_EVENTS_OVERRIDE: not a positive integer; using server limit`,{raw:e}));return}return t}function dr(){let e=process.env.WORKFLOW_OPTIMISTIC_INLINE_START;return e===void 0||e===``?!1:e===`1`||e.toLowerCase()===`true`}function fr(){let e=process.env.WORKFLOW_OPTIMISTIC_INLINE_START;return e===void 0||e===``?!1:e===`0`||e.toLowerCase()===`false`}function pr(){let e=process.env.WORKFLOW_TURBO;return e===void 0||e===``||!(e===`0`||e.toLowerCase()===`false`)}function mr(){let e=process.env.WORKFLOW_RETAINED_VM;return e===void 0||e===``||!(e===`0`||e.toLowerCase()===`false`)}function hr(){let e=process.env.WORKFLOW_INLINE_OWNERSHIP;return e===void 0||e===``||!(e===`0`||e.toLowerCase()===`false`)}function gr(){return yn(`WORKFLOW_INLINE_OWNERSHIP_LEASE_SECONDS`,860,{integer:!0,min:1,max:900})}function _r(){return yn(`WORKFLOW_REPLAY_DIVERGENCE_MAX_RETRIES`,3,{integer:!0})}function vr(){return yn(`WORKFLOW_PRECONDITION_MAX_INPROCESS_RESTARTS`,3,{integer:!0})}function yr(){return yn(`WORKFLOW_PRECONDITION_MAX_REINVOCATIONS`,5,{integer:!0})}function br(){return yn(`WORKFLOW_PRECONDITION_REINVOKE_DELAY_SECONDS`,2,{integer:!0})}function xr(){return yn(`WORKFLOW_DEPLOYMENT_MISMATCH_MAX_RETRIES`,3,{integer:!0,min:0})}const Sr=e=>`eventData`in e&&e.eventData&&`ownerMessageId`in e.eventData&&typeof e.eventData.ownerMessageId==`string`?e.eventData.ownerMessageId:void 0;function Cr(e,t,n){if(!e)return 0;let r=0,i=new Map;for(let n of e){if(n.eventType!==`step_started`||n.correlationId!==t)continue;let e=Sr(n);e===void 0?r++:i.set(e,(i.get(e)??0)+1)}if(n===void 0){let e=r;for(let t of i.values())e+=t;return e}if(n.type===`ownedBy`)return i.get(n.messageId)??0;let a=0;for(let e of i.values())e>a&&(a=e);return r+a}const wr={outcome:`continue`};function Tr(e,t,n){return{outcome:e,spanAttributes:{...ze(t),...R(n),...ge(e===`rerouted`)}}}async function Er({world:e,run:t,requestId:n,retryCount:r=0,reenqueue:i,isDeploymentUnavailableError:a,beforeStop:o}){if(e.capabilities?.deploymentAffinity!==!0)return wr;let s=await e.getDeploymentId();if(t.deploymentId===s)return wr;await o?.();let c=xr(),l={workflowRunId:t.runId,pinnedDeploymentId:t.deploymentId,actualDeploymentId:s,retryCount:r,maxRetries:c},u=async(r,i)=>{let a=new Rt(t.runId,t.deploymentId,s,{recoveryAttempts:r,cause:i});try{await e.events.create(t.runId,{eventType:`run_failed`,specVersion:5,eventData:{error:await Ct(a,t.runId,void 0,void 0,(t.specVersion??0)>=5),errorCode:X.DEPLOYMENT_MISMATCH}},{requestId:n})}catch(e){if(!Q.is(e)&&!J.is(e))throw e}return Tr(`failed`,t.deploymentId,r)};if(i&&r<c){let e=r+1,n=Math.min(2**r,8);try{return await i({deploymentId:t.deploymentId,specVersion:t.specVersion,deploymentMismatchRetryCount:e,delaySeconds:n}),w.warn(`Workflow run received by a deployment it is not pinned to; re-routing to its own deployment`,{...l,attempt:e,delaySeconds:n}),Tr(`rerouted`,t.deploymentId,e)}catch(t){if(!a?.(t))throw t;return w.error(`Cannot re-route a misrouted workflow run to its own deployment; failing the run`,{...l,attempt:e,errorMessage:t instanceof Error?t.message:String(t)}),u(0,t)}}return w.error(r>0?`Workflow run kept arriving at a deployment it is not pinned to after re-routing; failing the run`:`Workflow run received by a deployment it is not pinned to; failing the run`,l),u(r)}function Dr(){throw Error(`Unsupported in eve: @workflow/core createWorld(). eve selects and wires the workflow world explicitly at build time.`)}function Or(){try{return In(zn(process.cwd()+`/package.json`).href)}catch{return In(import.meta.url)}}const kr=Symbol.for(`@workflow/world//cache`),Ar=Symbol.for(`@workflow/world//stubbedCache`),jr=Symbol.for(`@workflow/world//cachePromise`),Mr=Symbol.for(`@workflow/world//stubbedCachePromise`),$=globalThis;function Nr(e){if(typeof e.createWorld==`function`)return e.createWorld();if(typeof e.default==`function`)return e.default();if(e.default&&typeof e.default==`object`)return e.default;throw Error(`Invalid target world module: must export createWorld(), a default factory, or a default World instance.`)}function Pr(e){if(e.startsWith(`file://`))return e;if(e.startsWith(`/`))return zn(e).href;if(e.startsWith(`./`)||e.startsWith(`../`))return zn(process.cwd()+`/`+e).href;try{return zn(Or().resolve(e)).href}catch{return e}}const Fr=async()=>{let e=Un();if(Wn(e)){let e=[`WORKFLOW_VERCEL_PROJECT`,`WORKFLOW_VERCEL_TEAM`,`WORKFLOW_VERCEL_AUTH_TOKEN`,`WORKFLOW_VERCEL_ENV`].filter(e=>process.env[e]);return e.length>0&&process.env.VERCEL===`1`&&console.warn(`[workflow] Warning: ${e.join(`, `)} env var(s) are set but have no effect at runtime. These are only used by the Workflow CLI. Remove them from your Vercel project environment variables.`),Dr()}if(e===`local`)return Dr({dataDir:process.env.WORKFLOW_LOCAL_DATA_DIR});let t;try{t=Or()(e)}catch{t=await import(Pr(e))}if(typeof t==`function`)return t();try{return await Nr(t)}catch{throw Error(`Invalid target world module: ${e}, must export a createWorld function or a default function that returns a World instance.`)}},Ir=async()=>{if($[Ar])return jt($[Ar]),$[Ar];$[Mr]||($[Mr]=Fr().catch(e=>{throw $[Mr]=void 0,e}));let e=await $[Mr];return jt(e),$[Ar]=e,{createQueueHandler:e.createQueueHandler,specVersion:e.specVersion}},Lr=async()=>$[kr]?(jt($[kr]),$[kr]):($[jr]||($[jr]=Fr().catch(e=>{throw $[jr]=void 0,e})),$[kr]=await $[jr],jt($[kr]),$[kr]),Rr=e=>{$[kr]=e,$[Ar]=e,$[jr]=void 0,$[Mr]=void 0},zr=Symbol.for(`@workflow/world//getWorldFn`);globalThis[zr]??=Lr;var Br=class{limitMs;elapsedMs=0;intervalStart;constructor(e=ar()){this.limitMs=e,this.intervalStart=Date.now()}get configuredLimitMs(){return this.limitMs}elapsed(){let e=this.intervalStart===null?0:Date.now()-this.intervalStart;return this.elapsedMs+e}pause(){this.intervalStart!==null&&(this.elapsedMs+=Date.now()-this.intervalStart,this.intervalStart=null)}resume(){this.intervalStart=Date.now()}isExhausted(){return this.elapsed()>=this.limitMs}};async function Vr(e){let{runId:t,workflowName:n,requestId:r,attempt:i,limitMs:a}=e,o=w.forRun(t,n),s=await Lr();if(s.processExitTriggersQueueRedelivery!==!0){o.warn(`Workflow replay exceeded timeout; current World does not support process exit for redelivery — failing the run and returning`,{timeoutMs:a,attempt:i});try{let e=Ee(s,t),n=new Y(`Workflow replay exceeded maximum duration (${a/1e3}s)`);await s.events.create(t,{eventType:`run_failed`,specVersion:5,eventData:{error:await Ct(n,t,await e()),errorCode:X.REPLAY_TIMEOUT}},{requestId:r})}catch(e){o.warn(`Unable to mark run as failed`,{attempt:i,errorName:e instanceof Error?e.name:`UnknownError`,errorMessage:e instanceof Error?e.message:String(e)})}return}let c=or();i<=c&&(o.warn(`Workflow replay exceeded timeout but will be re-attempted (attempt < maxRetries)`,{timeoutMs:a,attempt:i,maxRetries:c}),process.exit(1));let l=Jn(void 0,X.REPLAY_TIMEOUT);o.error(`Workflow replay exceeded timeout and max retries exceeded. Failing the run`,{timeoutMs:a,attempt:i,maxRetries:c,errorCode:l.errorCode,errorAttribution:l.attribution});try{let e=Ee(s,t),n=new Y(`Workflow replay exceeded maximum duration (${a/1e3}s) after ${i} attempts`);await s.events.create(t,{eventType:`run_failed`,specVersion:5,eventData:{error:await Ct(n,t,await e()),errorCode:X.REPLAY_TIMEOUT}},{requestId:r})}catch(e){o.warn(`Unable to mark run as failed. The queue will continue to retry`,{attempt:i,errorName:e instanceof Error?e.name:`UnknownError`,errorMessage:e instanceof Error?e.message:String(e),errorStack:e instanceof Error?e.stack:void 0})}process.exit(1)}var Hr=class{divergenceCount;active=!1;reported=!1;constructor(e){this.divergenceCount=e}static inert(){return new Ur}activate(){this.active=!0}async withEventCreate(e,t){if(!this.active||this.reported)return t(e);this.reported=!0;try{return await t({...e,replayDivergenceCount:this.divergenceCount})}catch(e){throw this.reported=!1,e}}},Ur=class extends Hr{constructor(){super(0)}activate(){}};function Wr(e){let t=e.startsWith(`wrun_`)?e.slice(5):e;try{return dn(Fn(t).ulid)}catch{return}}function Gr(e){return Rn.isNativeError(e)?e.name:`Error`}function Kr(e){return Rn.isNativeError(e)?e.stack??``:``}function qr(e){return typeof e==`object`&&!!e&&`name`in e&&e.name===`AbortError`&&`message`in e&&typeof e.message==`string`&&(!(`stack`in e)||e.stack===void 0||typeof e.stack==`string`)}function Jr(e){if(!qr(e)||Y.is(e))return e;let t=new Y(`Aborted: ${e.message}`);return e.stack&&(t.stack=e.stack),t}function Yr(e){return typeof e==`object`&&!!e&&`then`in e&&typeof e.then==`function`}function Xr(e){if(Rn.isNativeError(e))return{name:e.name,message:e.message,stack:e.stack??``};if(typeof e==`string`)return{name:`Error`,message:e,stack:``};try{return{name:`Error`,message:JSON.stringify(e),stack:``}}catch{return{name:`Error`,message:String(e),stack:``}}}async function Zr(e){if(Yr(e))try{let t=await Zr(await e);return{...t,message:`Promise rejection: ${t.message}`}}catch(e){let t=await Zr(e);return{...t,message:`Promise rejection: ${t.message}`}}return Xr(e)}let Qr,$r,ei;async function ti(){if($r!==void 0)return $r;if(ei)return ei;if(!Qr)try{let e=[`@workflow/utils`,`get-port`].join(`/`);Qr=In(zn(process.cwd()+`/package.json`).href)(e).getPort}catch{Qr=async()=>void 0}return ei=(Qr??(async()=>void 0))().then(e=>(typeof e==`number`&&($r=e),e)).finally(()=>{ei=void 0}),ei}const ni=new Set([`step_created`,`step_started`,`step_completed`,`step_failed`,`step_retrying`,`hook_received`,`wait_created`,`wait_completed`]);function ri(e){let{events:t}=e,n=e.invocationStartedClean&&e.runCreatedAtMs!==void 0&&!e.suspensionHasWaits,r;if(n)for(let e of t){if(ni.has(e.eventType)){n=!1;break}if(e.eventType===`attr_set`){let t=+(e.occurredAt??e.createdAt);r=r===void 0?t:Math.min(r,t)}}let i,a,o,s=t[t.length-1];if(!e.suspensionHasWaits&&!e.suspensionCreatedHooks&&s&&(s.eventType===`step_completed`||s.eventType===`step_failed`)){i=+(s.occurredAt??s.createdAt);let e=new Set;for(let n of t)(n.eventType===`step_completed`||n.eventType===`step_failed`)&&n.correlationId!==void 0&&e.add(n.correlationId);a=e.size,o=t.length}let c=n&&e.runStartedReceivedAtMs!==void 0;if(!(!n&&i===void 0))return{...n?{ttfsAnchorMs:e.runCreatedAtMs,preStepBlockingMs:r===void 0?e.preStepBlockingMs:e.preStepBlockingBeforeAttrMs??0,...r===void 0?{}:{preStepAttrStartMs:r}}:{},...c?{rsfsAnchorMs:e.runStartedReceivedAtMs,replayMs:e.replayMs}:{},...i===void 0?{}:{prevStepEndMs:i,stepCount:a,eventCount:o},turbo:e.turbo}}function ii(e){let{tracking:t}=e;if(!t||e.attempt!==1)return;let n=t.preStepAttrStartMs??e.stepCodeStartedAtMs,r=t.ttfsAnchorMs===void 0?void 0:n-t.ttfsAnchorMs-(t.preStepBlockingMs??0),i=r!==void 0&&r>=-6e4?Math.max(0,r):void 0,a=t.prevStepEndMs===void 0?void 0:e.stepCodeStartedAtMs-t.prevStepEndMs,o=a!==void 0&&a>=-6e4?Math.max(0,a):void 0,s=t.rsfsAnchorMs!==void 0&&e.stepStartPostSentAtMs!==void 0?Math.max(0,e.stepStartPostSentAtMs-t.rsfsAnchorMs):void 0,c=t.replayMs===void 0?void 0:Math.max(0,t.replayMs);if(i===void 0&&o===void 0)return;let l=[];return t.turbo&&l.push(`turbo`),e.lazyStepStart&&l.push(`lazyStepStart`),e.optimisticStart&&l.push(`optimisticStart`),{...i===void 0?{}:{ttfs:i},...o===void 0?{}:{stso:o},...o!==void 0&&t.stepCount!==void 0?{stepCount:t.stepCount}:{},...o!==void 0&&t.eventCount!==void 0?{eventCount:t.eventCount}:{},...s===void 0?{}:{rsfs:s},...c===void 0?{}:{finalSchedulingReplay:c},optimizations:l}}function ai(e,t){if(t&&!(!e.events||e.cursor===void 0))return{events:e.events,cursor:e.cursor,hasMore:e.hasMore??!1}}async function oi(e){let{world:t,workflowRunId:n,workflowName:r,workflowStartedAt:i,stepId:a,stepName:s}=e,u=!!process.env.VERCEL_URL,d=(e.runSpecVersion??0)>=5,v=e.replayRecoveryReporter??Hr.inert(),b=(e,r)=>v.withEventCreate(r,r=>t.events.create(n,e,r));return W(`step.execute ${ft(s)}`,{},async v=>{v?.setAttributes({...te(s),...be(r),...Ze(n),..._(a)});let S=Ee(t,n),E=Jt(s);if(!E||typeof E!=`function`){let t=`Step "${s}" 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.`;if(w.error(`Step function not registered, failing step`,{workflowRunId:n,stepName:s,stepId:a}),e.lazyStepInput!==void 0)try{e.runReadyBarrier&&await e.runReadyBarrier.catch(()=>{}),await b({eventType:`step_started`,specVersion:5,correlationId:a,eventData:{stepName:s,workflowName:r,input:e.lazyStepInput,...e.ownerMessageId===void 0?{}:{ownerMessageId:e.ownerMessageId}}},{computeInstanceId:Qn})}catch(e){if(Q.is(e))return{type:`skipped`};if(J.is(e))return{type:`gone`};throw e}try{await b({eventType:`step_failed`,specVersion:5,correlationId:a,eventData:{stepName:s,error:await m(new Y(t),n,await S(),[],globalThis,d)}})}catch(e){if(Q.is(e))return{type:`skipped`};throw e}return v?.setAttributes({...D(`failed`),...M(!0)}),{type:`failed`}}let O=E.maxRetries??3;if(v?.setAttributes({...k(O)}),e.authoritativeAttempt!==void 0&&e.authoritativeAttempt>O+1){let t=O,r=`Step "${s}" exceeded max retries (${t} ${Nt(`retry`,`retries`,t)})`;U.error(`Step exceeded max retries`,{workflowRunId:n,stepName:s,stepId:a,attempt:e.authoritativeAttempt,maxRetries:O});try{await b({eventType:`step_failed`,specVersion:5,correlationId:a,eventData:{stepName:s,error:await m(new Y(r),n,await S(),[],globalThis,d)}})}catch(e){if(Q.is(e))return w.info(`Tried failing step for exceeded retries, but step has already finished.`,{workflowRunId:n,stepId:a,stepName:s,message:e instanceof Error?e.message:String(e)}),{type:`skipped`};if(J.is(e))return{type:`gone`};throw e}return v?.setAttributes({...D(`failed`),...c(!0)}),{type:`failed`}}let A=e=>{if(Bt.is(e)){let t=Math.max(1,typeof e.retryAfter==`number`?e.retryAfter:1);return w.info(`Throttled on step_started, deferring`,{retryAfterSeconds:t}),{type:`throttled`,timeoutSeconds:t}}if(J.is(e))return w.info(`Workflow run "${n}" has already completed, skipping step "${a}": ${e.message}`),{type:`gone`};if(Q.is(e))return w.debug(`Step in terminal state, skipping`,{stepName:s,stepId:a,workflowRunId:n,error:e instanceof Error?e.message:String(e)}),v?.setAttributes({...y(!0),...le(`completed`)}),{type:`skipped`};if(It.is(e)){let t=Math.max(1,e.retryAfter??1);return w.debug(`Step retryAfter timestamp not yet reached`,{stepName:s,stepId:a,timeoutSeconds:t}),{type:`retry`,timeoutSeconds:t}}},F=e.lazyStepInput!==void 0&&e.suppressOptimisticStart!==!0&&(dr()||e.forceOptimisticStart===!0&&!fr()),L,ee={computeInstanceId:Qn,...e.preconditionSnapshot},R,ne,re=async()=>{if(!ne)return;let e=await ne;if(e.ok)return;let t=A(e.err);if(!t)throw e.err;return t};if(F){ne=(e.runReadyBarrier??Promise.resolve()).then(()=>(R=Date.now(),b({eventType:`step_started`,specVersion:5,correlationId:a,eventData:{stepName:s,workflowName:r,input:e.lazyStepInput,...e.ownerMessageId===void 0?{}:{ownerMessageId:e.ownerMessageId}}},ee))).then(()=>({ok:!0}),e=>({ok:!1,err:e}));let t=new Date;L={runId:n,stepId:a,stepName:s,status:`running`,input:e.lazyStepInput,attempt:1,startedAt:t,createdAt:t,updatedAt:t}}else try{let t=e.ownerMessageId===void 0?{}:{ownerMessageId:e.ownerMessageId};R=Date.now();let n=await b({eventType:`step_started`,specVersion:5,correlationId:a,eventData:e.lazyStepInput===void 0?{stepName:s,...t}:{stepName:s,workflowName:r,input:e.lazyStepInput,...t}},ee);if(!n.step)throw new q(`step_started event for "${a}" did not return step entity`);L=n.step}catch(e){let t=A(e);if(t)return t;throw e}w.debug(`Step execution details`,{stepName:s,stepId:L.stepId,status:L.status,attempt:L.attempt}),v?.setAttributes({...D(L.status)});let z;if(L.attempt>O+1&&L.error){let e=L.attempt-1,t=`Step "${s}" exceeded max retries (${e} ${Nt(`retry`,`retries`,e)})`;U.error(`Step exceeded max retries`,{workflowRunId:n,stepName:s,retryCount:e});let r=new Y(t);if(L.error!=null)try{r.cause=await g(L.error,n,await S())}catch{}try{await b({eventType:`step_failed`,specVersion:5,correlationId:a,eventData:{stepName:s,error:await m(r,n,await S(),[],globalThis,d)}})}catch(e){if(Q.is(e))return w.info(`Tried failing step, but step has already finished.`,{workflowRunId:n,stepId:a,stepName:s,message:e.message}),{type:`skipped`};throw e}return v?.setAttributes({...D(`failed`),...c(!0)}),{type:`failed`}}let B=[],V=[],ie=!0,H,se=()=>{if(!H||H.rsfs!==void 0)return;let t=e.latencyTracking?.rsfsAnchorMs;t===void 0||R===void 0||(H.rsfs=Math.max(0,R-t),v&&v.setAttributes({...ae(H.rsfs)}))};try{let t=L.attempt;if(!L.startedAt)throw new q(`Step "${a}" has no "startedAt" timestamp`);let o=L.startedAt,c=e.encryptionKey??await S(),m=await W(`step.hydrate`,{},async t=>{let r=Date.now(),i=await P(L.input,n,c,V,globalThis,{},e.workflowDeploymentId),a=Date.now()-r;return t?.setAttributes({...Ke(i.args.length),...h(a)}),i}),g=m.args,_=m.thisVal??null,y=nn(u?`https://${process.env.VERCEL_URL}`:`http://localhost:${await ti()??3e3}`),b,x=!1,D=Date.now();H=ii({tracking:e.latencyTracking,stepCodeStartedAtMs:D,attempt:t,lazyStepStart:e.lazyStepInput!==void 0,optimisticStart:F,stepStartPostSentAtMs:R}),H&&v?.setAttributes({...H.ttfs===void 0?{}:T(H.ttfs),...H.stso===void 0?{}:st(H.stso),...H.rsfs===void 0?{}:ae(H.rsfs),...H.finalSchedulingReplay===void 0?{}:I(H.finalSchedulingReplay),...C(H.optimizations??[])});try{z=await W(`step.execute`,{},async()=>await ot.run({stepMetadata:{stepName:s,stepId:a,stepStartedAt:new Date(+o),attempt:t},workflowMetadata:{workflowName:r,workflowRunId:n,workflowStartedAt:new Date(+i),url:y,features:{encryption:!!c}},workflowDeploymentId:e.workflowDeploymentId,rootRunId:e.rootRunId,ops:V,preCompletionOps:B,closureVars:m.closureVars,encryptionKey:c,runReadyBarrier:F?e.runReadyBarrier:void 0},()=>E.apply(_,g)))}catch(e){b=e,x=!0}let O=Date.now()-D;if(l(...g,_,m.closureVars),x)throw b;if(v?.setAttributes({...p(O)}),z=await W(`step.dehydrate`,{},async t=>{let r=Date.now(),i=await f(z,n,c,V,globalThis,!1,!1,d,F?e.runReadyBarrier:void 0),a=Date.now()-r;return t?.setAttributes({...N(a),...Mt(typeof i)}),i}),V.length>0){let e=Promise.all(V);mt(e,e=>{w.warn(`Background flush of step stream ops failed`,{workflowRunId:n,stepId:a,error:e instanceof Error?e.message:String(e)})}),ie=await Promise.race([e.then(()=>!0,e=>{if(e?.name===`AbortError`||e?.name===`ResponseAborted`)return!0;throw e}),new Promise(e=>setTimeout(()=>e(!1),500))])}if(F){let e=await re();if(e)return e;se()}B.length>0&&await Promise.all(B).catch(()=>{})}catch(e){if(F){let e=await re();if(e)return e;se()}B.length>0&&await Promise.all(B).catch(()=>{});let t=Jr(e),r=await Zr(t),i=r.stack||Kr(t)||``;t instanceof Error&&v?.recordException?.(t);let l=Y.is(t);if(v?.setAttributes({...j(Gr(t)),...Ue(r.message),...Oe(Gr(t)),...Ye(l?`fatal`:Kt.is(t)?`retryable`:`transient`),...bt(!l)}),J.is(e))return U.info(`Workflow run already completed, skipping step`,{workflowRunId:n,stepId:a,message:e.message}),{type:`gone`};if(l){U.error(`Encountered FatalError while executing step, bubbling up to parent workflow`,{workflowRunId:n,stepName:s,errorStack:i}),Rn.isNativeError(t)&&i&&(t.stack=i);try{await b({eventType:`step_failed`,specVersion:5,correlationId:a,eventData:{stepName:s,error:await m(t,n,await S(),[],globalThis,d),...H}})}catch(e){if(Q.is(e))return w.info(`Tried failing step, but step has already finished.`,{workflowRunId:n,stepId:a,stepName:s,message:e.message}),{type:`skipped`};throw e}return v?.setAttributes({...D(`failed`),...M(!0)}),{type:`failed`}}let u=L.attempt;if(v?.setAttributes({...o(u),...k(O)}),u>=O+1){let t=L.attempt-1;U.error(`Max retries reached, bubbling error to parent workflow`,{workflowRunId:n,stepName:s,attempt:L.attempt,retryCount:t,errorStack:i});let o=new Y(`Step "${s}" failed after ${O} ${Nt(`retry`,`retries`,O)}: ${r.message}`);o.cause=e,i&&(o.stack=i);try{await b({eventType:`step_failed`,specVersion:5,correlationId:a,eventData:{stepName:s,error:await m(o,n,await S(),[],globalThis,d),...H}})}catch(e){if(Q.is(e))return w.info(`Tried failing step, but step has already finished.`,{workflowRunId:n,stepId:a,stepName:s,message:e.message}),{type:`skipped`};throw e}return v?.setAttributes({...D(`failed`),...c(!0)}),{type:`failed`}}Kt.is(e)?U.info(`Encountered RetryableError, step will be retried`,{workflowRunId:n,stepName:s,attempt:u,message:e.message}):U.info(`Encountered Error, step will be retried`,{workflowRunId:n,stepName:s,attempt:u,errorStack:i}),Rn.isNativeError(e)&&i&&(e.stack=i);try{await b({eventType:`step_retrying`,specVersion:5,correlationId:a,eventData:{stepName:s,error:await m(e,n,await S(),[],globalThis,d),...Kt.is(e)&&{retryAfter:e.retryAfter}}})}catch(e){if(Q.is(e))return w.info(`Tried retrying step, but step has already finished.`,{workflowRunId:n,stepId:a,stepName:s,message:e.message}),{type:`skipped`};throw e}let f=Math.max(1,Kt.is(e)?Math.ceil((+e.retryAfter.getTime()-Date.now())/1e3):1);return v?.setAttributes({...oe(f),...x(!0)}),{type:`retry`,timeoutSeconds:f}}let ce;try{ce=await b({eventType:`step_completed`,specVersion:5,correlationId:a,eventData:{stepName:s,workflowName:r,result:z,...H}},e.inlineDeltaSinceCursor===void 0?void 0:{sinceCursor:e.inlineDeltaSinceCursor})}catch(e){if(Q.is(e))return w.info(`Tried completing step, but step has already finished.`,{workflowRunId:n,stepId:a,stepName:s,message:e.message}),{type:`skipped`};if(J.is(e))return U.info(`Workflow run already completed, skipping step`,{workflowRunId:n,stepId:a,message:e.message}),{type:`gone`};throw e}let ue=ai(ce,e.inlineDeltaSinceCursor!==void 0);return v?.setAttributes({...D(`completed`),...Mt(typeof z)}),V.length>0&&U.debug(`Step has pending ops`,{workflowRunId:n,stepName:s,opsCount:V.length}),{type:`completed`,hasPendingOps:!ie,inlineDelta:ue}})}function si(e){return e.hasCreatedEvent===!0&&e.ownerMessageId!==void 0&&e.sawRetrying!==!0}function ci(e,t){if(e.lastStartedAt===void 0)return 0;let n=gr(),r=e.lastStartedAt+n*1e3-t;return Math.min(n,Math.max(0,Math.ceil(r/1e3)))}function li(e){return`${e.correlationId}:backstop:${e.lastStartedAt}`}function ui(e,t,n){let r=new Map,i=new Set;for(let t of e)if(t.correlationId!==void 0)if(t.eventType===`step_started`){let e=`eventData`in t&&t.eventData&&`ownerMessageId`in t.eventData&&typeof t.eventData.ownerMessageId==`string`?t.eventData.ownerMessageId:void 0;r.set(t.correlationId,e)}else t.eventType===`step_retrying`&&i.add(t.correlationId);for(let e of t)if(e!==void 0&&!i.has(e)&&r.get(e)===n)return!0;return!1}const di=new Map;async function fi(e,t,n){let r=`${e}:${t}`,i=di.get(r);if(i){w.warn(`Step execution already in flight in this process; awaiting its settlement instead of executing again`,{workflowRunId:e,stepId:t});try{await i}catch{}return{type:`skipped`}}let a=n();di.set(r,a);try{return await a}finally{di.delete(r)}}async function pi({runId:e,hookEvent:t,queueItem:n,requestId:r,createEvent:i}){try{return(await i(t,{requestId:r})).event?.eventType===`hook_conflict`?{hasHookConflict:!0,hasAwaitedHookCreation:!1}:{hasHookConflict:!1,hasAwaitedHookCreation:n.hasConflictAwaiter===!0}}catch(t){if(Q.is(t))return w.info(`Hook already exists, continuing`,{workflowRunId:e,message:t.message}),{hasHookConflict:!1,hasAwaitedHookCreation:n.hasConflictAwaiter===!0};if(J.is(t))return w.info(`Workflow run already completed, skipping hook`,{workflowRunId:e,message:t.message}),{hasHookConflict:!1,hasAwaitedHookCreation:!1};throw t}}async function mi({suspension:e,world:t,run:n,span:r,requestId:i,eventLog:a,runReadyBarrier:o,replayRecoveryReporter:s}){let c=n.runId,l=async()=>{if(o)try{await o}catch{}},u=async e=>{let t=(await Promise.allSettled(e)).filter(e=>e.status===`rejected`).map(e=>e.reason);if(t.length!==0)throw t.find(e=>zt.is(e))??t[0]},d=s??Hr.inert(),f=(e,n)=>d.withEventCreate(n,n=>t.events.create(c,e,n)),p=(e,t)=>a?f(e,{...t,...Xe(a.events,a.cursor)}):f(e,t),m=e.steps.filter(e=>e.type===`step`),h=e.steps.filter(e=>e.type===`hook`),g=e.steps.filter(e=>e.type===`wait`),_=e.steps.filter(e=>e.type===`attribute`),y=h.filter(e=>!e.hasCreatedEvent),b=new Map;for(let e of h){if(e.hasCreatedEvent&&!e.disposed)continue;let t=b.get(e.token);t?t.push(e):b.set(e.token,[e])}let x=await t.getEncryptionKeyForRun?.(n),S=x?await gt(x):void 0,C=(n.specVersion??0)>=5;async function T(e){let t={eventType:`hook_disposed`,specVersion:5,correlationId:e.correlationId,eventData:{token:e.token}};try{await p(t,{requestId:i})}catch(t){if(Q.is(t))w.info(`Hook already disposed, skipping duplicate disposal`,{workflowRunId:c,correlationId:e.correlationId,message:t.message});else if(J.is(t))w.info(`Workflow run already completed, skipping hook disposal`,{workflowRunId:c,correlationId:e.correlationId,message:t.message});else if(Ut.is(t))w.info(`Hook not found for disposal, continuing`,{workflowRunId:c,correlationId:e.correlationId,message:t.message});else throw t}}let E=!1,D=!1,O=0;if(b.size>0){let t=Date.now();await l(),await u([...b.values()].map(async t=>{for(let n of t){let t=!1;if(!n.hasCreatedEvent){let r=n.metadata===void 0?void 0:await z(n.metadata,c,S,e.globalThis,!1,C),a={eventType:`hook_created`,specVersion:5,correlationId:n.correlationId,eventData:{token:n.token,tokenRetentionUntil:n.tokenRetentionUntil,metadata:r,isWebhook:n.isWebhook??!1,...n.isSystem&&{isSystem:!0}}},o=await pi({runId:c,hookEvent:a,queueItem:n,requestId:i,createEvent:p});E||=o.hasHookConflict,D||=o.hasAwaitedHookCreation,t=o.hasHookConflict}n.disposed&&!t&&await T(n)}})),O=Date.now()-t}let k=h.filter(e=>e.abortRequested&&!e.disposed);k.length>0&&(await l(),await u(k.map(async n=>{try{let r=await z({aborted:!0,reason:n.abortReason},c,S,e.globalThis,!1,C);await p({eventType:`hook_received`,specVersion:5,correlationId:n.correlationId,eventData:{token:n.token,payload:r}});try{let e=v(n.token);await t.streams.write(c,e,r),await t.streams.close(c,e)}catch{w.debug(`Failed to write abort stream packet, hook event will provide fallback`,{workflowRunId:c,correlationId:n.correlationId})}}catch(e){if(Q.is(e)||J.is(e))w.info(`Workflow run already completed, skipping abort`,{workflowRunId:c,correlationId:n.correlationId,message:e.message});else throw e}})));let A=new Set(m.filter(e=>!e.hasCreatedEvent).map(e=>e.correlationId)),j=new Set,M={executions:[]},N=new Set(D===!1?m.filter(e=>A.has(e.correlationId)).slice(0,cr()).map(e=>e.correlationId):[]),P=new Map,F=[];for(let t of m)A.has(t.correlationId)&&F.push((async()=>{let r={executions:[]},a=await z({args:t.args,closureVars:t.closureVars,thisVal:t.thisVal},c,S,e.globalThis,!1,C,r);if(M.executions.push(...r.executions),N.has(t.correlationId)){P.set(t.correlationId,{correlationId:t.correlationId,stepName:t.stepName,dehydratedInput:a});return}let o={eventType:`step_created`,specVersion:5,correlationId:t.correlationId,eventData:{stepName:t.stepName,workflowName:n.workflowName,input:a}};try{await l(),await p(o,{requestId:i}),j.add(t.correlationId)}catch(e){if(Q.is(e))w.info(`Step already exists, continuing`,{workflowRunId:c,correlationId:t.correlationId,message:e.message});else throw e}})());for(let e of g)e.hasCreatedEvent||F.push((async()=>{let t={eventType:`wait_created`,specVersion:5,correlationId:e.correlationId,eventData:{resumeAt:e.resumeAt}};try{await l(),await p(t,{requestId:i})}catch(t){if(Q.is(t))w.info(`Wait already exists, continuing`,{workflowRunId:c,correlationId:e.correlationId,message:t.message});else throw t}})());for(let e of _)F.push((async()=>{try{await l(),await p({eventType:`attr_set`,specVersion:5,correlationId:e.correlationId,eventData:{changes:e.changes,writer:{type:`workflow`},...e.allowReservedAttributes?{allowReservedAttributes:!0}:{}}},{requestId:i})}catch(t){if(Q.is(t))w.info(`Workflow attribute event already exists, continuing`,{workflowRunId:c,correlationId:e.correlationId,message:t.message});else if(hi(t)){let e=new Y(`setAttributes failed World validation: ${t instanceof Error?t.message:String(t)}`);throw e.cause=t,e}else throw t}})());await u(F);let I=M.executions.length===0;I||w.debug(`Serializing step inputs executed workflow code; falling back to replay instead of retaining the VM`,{workflowRunId:c,executions:M.executions.slice(0,5).map(e=>e.detail?`${e.kind}(${e.detail})`:e.kind)});let L=[];for(let e of N){let t=P.get(e);t&&L.push(t)}let ee=Date.now(),R;for(let e of g){let t=e.resumeAt.getTime(),n=Math.max(1e3,t-ee),r=Math.ceil(n/1e3);(!R||r<R.seconds)&&(R={seconds:r,correlationId:e.correlationId})}return r?.setAttributes({...Ie(`workflow_suspended`),...St(m.length),...Ve(y.length),...ne(g.length)}),{pendingSteps:m,createdStepCorrelationIds:j,lazyInlineSteps:L,waitTimeout:E?void 0:R,hasHookConflict:E,hasAwaitedHookCreation:D,hasAttributeEvents:_.length>0,hasHookEvents:y.length>0,hookCreationMs:O,retainedStepInputsSafe:I}}function hi(e){return e instanceof ln||e instanceof Error&&e.name===`AttributeValidationError`||Pt.is(e)&&e.status===400}const gi=()=>yn(`WORKFLOW_WAIT_CONTINUATION_MAX_DELAY_SECONDS`,82800,{integer:!0,min:1}),_i=()=>yn(`WORKFLOW_NEAR_ELAPSED_WAIT_THRESHOLD_SECONDS`,2);function vi(e,t,n=Date.now()){let r=gi();if(e<=Math.min(_i(),r))return{delaySeconds:e,idempotencyKey:`${t}:${Math.floor(n/1e3)}`};let i=Math.ceil(e/r);return{delaySeconds:Math.min(e,r),idempotencyKey:i===1?t:`${t}:hop-${i}`}}var yi=44,bi=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/`,xi=new Uint8Array(64),Si=new Uint8Array(128);for(let e=0;e<bi.length;e++){let t=bi.charCodeAt(e);xi[e]=t,Si[t]=e}function Ci(e,t){let n=0,r=0,i=0;do i=Si[e.next()],n|=(i&31)<<r,r+=5;while(i&32);let a=n&1;return n>>>=1,a&&(n=-2147483648|-n),t+n}function wi(e,t){return e.pos>=t?!1:e.peek()!==yi}var Ti=class{constructor(e){this.pos=0,this.buffer=e}next(){return this.buffer.charCodeAt(this.pos++)}peek(){return this.buffer.charCodeAt(this.pos)}indexOf(e){let{buffer:t,pos:n}=this,r=t.indexOf(e,n);return r===-1?t.length:r}};function Ei(e){let{length:t}=e,n=new Ti(e),r=[],i=0,a=0,o=0,s=0,c=0;do{let e=n.indexOf(`;`),t=[],l=!0,u=0;for(i=0;n.pos<e;){let r;i=Ci(n,i),i<u&&(l=!1),u=i,wi(n,e)?(a=Ci(n,a),o=Ci(n,o),s=Ci(n,s),wi(n,e)?(c=Ci(n,c),r=[i,a,o,s,c]):r=[i,a,o,s]):r=[i],t.push(r),n.pos++}l||Di(t),r.push(t),n.pos=e+1}while(n.pos<=t);return r}function Di(e){e.sort(Oi)}function Oi(e,t){return e[0]-t[0]}const ki=/^[\w+.-]+:\/\//,Ai=/^([\w+.-]+:)\/\/([^@/#?]*@)?([^:/#?]*)(:\d+)?(\/[^#?]*)?(\?[^#]*)?(#.*)?/,ji=/^file:(?:\/\/((?![a-z]:)[^/#?]*)?)?(\/?[^#?]*)(\?[^#]*)?(#.*)?/i;function Mi(e){return ki.test(e)}function Ni(e){return e.startsWith(`//`)}function Pi(e){return e.startsWith(`/`)}function Fi(e){return e.startsWith(`file:`)}function Ii(e){return/^[.?#]/.test(e)}function Li(e){let t=Ai.exec(e);return zi(t[1],t[2]||``,t[3],t[4]||``,t[5]||`/`,t[6]||``,t[7]||``)}function Ri(e){let t=ji.exec(e),n=t[2];return zi(`file:`,``,t[1]||``,``,Pi(n)?n:`/`+n,t[3]||``,t[4]||``)}function zi(e,t,n,r,i,a,o){return{scheme:e,user:t,host:n,port:r,path:i,query:a,hash:o,type:7}}function Bi(e){if(Ni(e)){let t=Li(`http:`+e);return t.scheme=``,t.type=6,t}if(Pi(e)){let t=Li(`http://foo.com`+e);return t.scheme=``,t.host=``,t.type=5,t}if(Fi(e))return Ri(e);if(Mi(e))return Li(e);let t=Li(`http://foo.com/`+e);return t.scheme=``,t.host=``,t.type=e?e.startsWith(`?`)?3:e.startsWith(`#`)?2:4:1,t}function Vi(e){if(e.endsWith(`/..`))return e;let t=e.lastIndexOf(`/`);return e.slice(0,t+1)}function Hi(e,t){Ui(t,t.type),e.path===`/`?e.path=t.path:e.path=Vi(t.path)+e.path}function Ui(e,t){let n=t<=4,r=e.path.split(`/`),i=1,a=0,o=!1;for(let e=1;e<r.length;e++){let t=r[e];if(!t){o=!0;continue}if(o=!1,t!==`.`){if(t===`..`){a?(o=!0,a--,i--):n&&(r[i++]=t);continue}r[i++]=t,a++}}let s=``;for(let e=1;e<i;e++)s+=`/`+r[e];(!s||o&&!s.endsWith(`/..`))&&(s+=`/`),e.path=s}function Wi(e,t){if(!e&&!t)return``;let n=Bi(e),r=n.type;if(t&&r!==7){let e=Bi(t),i=e.type;switch(r){case 1:n.hash=e.hash;case 2:n.query=e.query;case 3:case 4:Hi(n,e);case 5:n.user=e.user,n.host=e.host,n.port=e.port;case 6:n.scheme=e.scheme}i>r&&(r=i)}Ui(n,r);let i=n.query+n.hash;switch(r){case 2:case 3:return i;case 4:{let r=n.path.slice(1);return r?Ii(t||e)&&!Ii(r)?`./`+r+i:r+i:i||`.`}case 5:return n.path+i;default:return n.scheme+`//`+n.user+n.host+n.port+n.path+i}}function Gi(e){if(!e)return``;let t=e.lastIndexOf(`/`);return e.slice(0,t+1)}function Ki(e,t){let n=Gi(e),r=t?t+`/`:``;return e=>Wi(r+(e||``),n)}var qi=0,Ji=1,Yi=2,Xi=3,Zi=4;function Qi(e,t){let n=$i(e,0);if(n===e.length)return e;t||(e=e.slice());for(let r=n;r<e.length;r=$i(e,r+1))e[r]=ta(e[r],t);return e}function $i(e,t){for(let n=t;n<e.length;n++)if(!ea(e[n]))return n;return e.length}function ea(e){for(let t=1;t<e.length;t++)if(e[t][qi]<e[t-1][qi])return!1;return!0}function ta(e,t){return t||(e=e.slice()),e.sort(na)}function na(e,t){return e[qi]-t[qi]}var ra=!1;function ia(e,t,n,r){for(;n<=r;){let i=n+(r-n>>1),a=e[i][qi]-t;if(a===0)return ra=!0,i;a<0?n=i+1:r=i-1}return ra=!1,n-1}function aa(e,t,n){for(let r=n+1;r<e.length&&e[r][qi]===t;n=r++);return n}function oa(e,t,n){for(let r=n-1;r>=0&&e[r][qi]===t;n=r--);return n}function sa(){return{lastKey:-1,lastNeedle:-1,lastIndex:-1}}function ca(e,t,n,r){let{lastKey:i,lastNeedle:a,lastIndex:o}=n,s=0,c=e.length-1;if(r===i){if(t===a)return ra=o!==-1&&e[o][qi]===t,o;t>=a?s=o===-1?0:o:c=o}return n.lastKey=r,n.lastNeedle=t,n.lastIndex=ia(e,t,s,c)}function la(e){return typeof e==`string`?JSON.parse(e):e}var ua="`line` must be greater than 0 (lines start at line 1)",da="`column` must be greater than or equal to 0 (columns start at column 0)",fa=class{constructor(e,t){let n=typeof e==`string`;if(!n&&e._decodedMemo)return e;let r=la(e),{version:i,file:a,names:o,sourceRoot:s,sources:c,sourcesContent:l}=r;this.version=i,this.file=a,this.names=o||[],this.sourceRoot=s,this.sources=c,this.sourcesContent=l,this.ignoreList=r.ignoreList||r.x_google_ignoreList||void 0;let u=Ki(t,s);this.resolvedSources=c.map(u);let{mappings:d}=r;if(typeof d==`string`)this._encoded=d,this._decoded=void 0;else if(Array.isArray(d))this._encoded=void 0,this._decoded=Qi(d,n);else if(r.sections)throw Error(`TraceMap passed sectioned source map, please use FlattenMap export instead`);else throw Error(`invalid source map: ${JSON.stringify(r)}`);this._decodedMemo=sa(),this._bySources=void 0,this._bySourceMemos=void 0}};function pa(e){return e}function ma(e){var t;return(t=pa(e))._decoded||(t._decoded=Ei(pa(e)._encoded))}function ha(e,t){let{line:n,column:r,bias:i}=t;if(n--,n<0)throw Error(ua);if(r<0)throw Error(da);let a=ma(e);if(n>=a.length)return ga(null,null,null,null);let o=a[n],s=_a(o,pa(e)._decodedMemo,n,r,i||1);if(s===-1)return ga(null,null,null,null);let c=o[s];if(c.length===1)return ga(null,null,null,null);let{names:l,resolvedSources:u}=e;return ga(u[c[Ji]],c[Yi]+1,c[Xi],c.length===5?l[c[Zi]]:null)}function ga(e,t,n,r){return{source:e,line:t,column:n,name:r}}function _a(e,t,n,r,i){let a=ca(e,r,t,n);return ra?a=(i===-1?aa:oa)(e,r,a):i===-1&&a++,a===-1||a===e.length?-1:a}function va(e){return e>=65&&e<=90||e>=97&&e<=122||e>=48&&e<=57||e===43||e===47||e===61}function ya(e){let t=0;for(;t<e.length;){let n=e.indexOf(`//# sourceMappingURL=data:application/json`,t);if(n===-1)return;let r=e.indexOf(`;base64,`,n+42);if(r===-1){t=n+42;continue}let i=e.indexOf(`,`,n);if(i!==-1&&i<r){t=r+8;continue}let a=r+8,o=a;for(;o<e.length&&va(e.charCodeAt(o));)o++;if(o>a)return e.slice(a,o);t=o}}const ba=new Map;function xa(e){let t=ba.get(e);if(t!==void 0)return ba.delete(e),ba.set(e,t),t;let n=null,r=ya(e);if(r)try{let e=Buffer.from(r,`base64`).toString(`utf-8`);n=new fa(JSON.parse(e))}catch{n=null}for(ba.set(e,n);ba.size>8;){let e=ba.keys().next().value;if(e===void 0)break;ba.delete(e)}return n}function Sa(e,t,n){if(!e.includes(t))return e;let r=xa(n);if(!r)return e;try{return e.split(`
2
+ `).map(e=>{let n=e.match(/^\s*at\s+(?:(.+?)\s+\()?(.+?):(\d+):(\d+)\)?$/);if(!n)return e;let[,i,a,o,s]=n;if(!a.includes(t))return e;let c=parseInt(o,10),l=parseInt(s,10),u=ha(r,{line:c,column:l});if(u.source&&u.line!==null){let e=i||u.name||`anonymous`,t=u.column===null?l:u.column;return` at ${e} (${u.source}:${u.line}:${t})`}return e}).join(`
3
+ `)}catch{return e}}function Ca(e,t,n){let r=(2<<31-Math.clz32(e.length-1|1))-1,i=Math.ceil(1.6*r*t/e.length);return(a=t)=>{if(!a)return``;let o=``;for(;;){let t=n(i),s=i;for(;s--;)if(o+=e[t[s]&r]||``,o.length>=a)return o}}}function wa(e,t){return Math.imul(e,t)>>>0}function Ta(e,t){return(e<<t|e>>>32-t)>>>0}function Ea(e){let t=e>>>0;return t=(t^t>>>16)>>>0,t=wa(t,2246822507),t=(t^t>>>13)>>>0,t=wa(t,3266489909),(t^t>>>16)>>>0}function Da(e){let t=[2654435761,2246822519,3266489917,668265263];for(let n=0;n<e.length;n++){let r=e.charCodeAt(n)>>>0;r=wa(r,3432918353),r=Ta(r,15),r=wa(r,461845907);let i=n&3,a=(t[i]^r)>>>0;a=Ta(a,13),t[i]=wa(a,5)+3864292196>>>0}t[0]=(t[0]^e.length)>>>0;for(let e=0;e<2;e++)for(let e=0;e<4;e++){let n=t[e+3&3];t[e]=Ea((t[e]^n)>>>0)}return t}function Oa(e,t){let n=Da(`${e} correlation-kind ${t}`),r=[n[0]>>>24&255,n[0]>>>16&255,n[0]>>>8&255,n[0]&255,n[1]>>>24&255,n[1]>>>16&255,n[1]>>>8&255,n[1]&255,n[2]>>>24&255,n[2]>>>16&255],i=``,a=0,o=0;for(let e of r)for(a=(a<<8|e)>>>0,o+=8;o>=5;){let e=a>>>o-5&31;i+=`0123456789ABCDEFGHJKMNPQRSTVWXYZ`[i.length===0?e&15:e],o-=5}return i}function ka(e){let{seed:t,fixedTimestamp:n,positional:r,perKind:i}=e;if(!i)return r;let a=mn(n,10),o=new Map;return e=>{let n=o.get(e),r=n===void 0?Oa(t,e):hn(n);return o.set(e,r),`${a}${r}`}}function Aa(){return process.env.WORKFLOW_PER_KIND_CORRELATION_IDS===`1`}function ja(e){return function(t,n){let r=function(...r){let{promise:i,resolve:a,reject:o}=Zt(),s=`step_${e.generateCorrelationId(`step`)}`,c={type:`step`,correlationId:s,stepName:t,args:r};this!==void 0&&this!==null&&this!==globalThis&&(c.thisVal=this);let l=n?.();return l&&(c.closureVars=l),e.invocationsQueue.set(s,c),U.debug(`Step consumer setup`,{correlationId:s,stepName:t,args:r}),e.eventsConsumer.subscribe(n=>{if(!n){let t=e.suspensionGeneration;return qt(e,()=>{t===e.suspensionGeneration&&e.onWorkflowError(new K(e.invocationsQueue,e.globalThis))}),b.NotConsumed}if(U.debug(`Step consumer event processing`,{correlationId:s,stepName:t,args:r.join(`, `),incomingCorrelationId:n.correlationId,isMatch:s===n.correlationId,eventType:n.eventType}),n.correlationId!==s)return b.NotConsumed;let i=`eventData`in n&&n.eventData&&`stepName`in n.eventData?n.eventData.stepName:void 0;if(typeof i==`string`&&i!==t)return e.promiseQueue=e.promiseQueue.then(()=>{e.onWorkflowError(new Z(`Replay divergence: step event ${n.eventType} for ${s} belongs to "${i}", but the current step consumer is "${t}"`,{eventId:n.eventId}))}),b.Finished;if(n.eventType===`step_created`){let r=e.invocationsQueue.get(s);return!r||r.type!==`step`?(e.promiseQueue=e.promiseQueue.then(()=>{o(new Z(`Replay divergence: step ${s} (${t}) created but not found in invocation queue`,{eventId:n.eventId}))}),b.Finished):(r.hasCreatedEvent=!0,b.Consumed)}if(n.eventType===`step_started`){let t=e.invocationsQueue.get(s);return t&&t.type===`step`&&(t.ownerMessageId=`eventData`in n&&n.eventData&&`ownerMessageId`in n.eventData&&typeof n.eventData.ownerMessageId==`string`?n.eventData.ownerMessageId:void 0,t.lastStartedAt=+n.createdAt),b.Consumed}if(n.eventType===`step_retrying`){let t=e.invocationsQueue.get(s);return t&&t.type===`step`&&(t.sawRetrying=!0,t.ownerMessageId=void 0),b.Consumed}if(n.eventType===`step_failed`){e.invocationsQueue.delete(n.correlationId);let t=e.eventsConsumer.eventIndex,r=Xt(e,t,`step`),i,a=Qt(e,t,`step`);return e.pendingDeliveries++,e.promiseQueue=e.promiseQueue.then(async()=>{try{let t=await e.replayPayloadCache.prepareEventPayload(n.eventId,`error`,n.eventData.error);i=await g(n.eventData.error,e.runId,e.encryptionKey,e.globalThis,{},t)}catch(e){U.error(`Failed to hydrate step_failed error`,{correlationId:n.correlationId,error:e instanceof Error?e.message:String(e)}),i=new Y(`Failed to hydrate step error: ${e instanceof Error?e.message:String(e)}`)}finally{e.pendingDeliveries--}a.then(()=>{r.markDelivered(),o(i)})}),b.Finished}if(n.eventType===`step_completed`){e.invocationsQueue.delete(n.correlationId);let t=n.eventId,r=n.eventData.result,i=e.eventsConsumer.eventIndex,s=Xt(e,i,`step`),c,l=Qt(e,i,`step`);return e.pendingDeliveries++,e.promiseQueue=e.promiseQueue.then(async()=>{try{c={ok:!0,value:await e.replayPayloadCache.getStepResult(t,async()=>{let n=await e.replayPayloadCache.prepareEventPayload(t,`result`,r);return await S(r,e.runId,e.encryptionKey,e.globalThis,{},n)})}}catch(e){c={ok:!1,error:e}}finally{e.pendingDeliveries--}l.then(()=>{s.markDelivered(),c.ok?a(c.value):o(c.error)})}),b.Finished}return e.promiseQueue=e.promiseQueue.then(()=>{e.onWorkflowError(new Z(`Replay divergence: Unexpected event type for step ${s} (name: ${t}) "${n.eventType}"`,{eventId:n.eventId}))}),b.Finished}),i},i=t.split(`//`).pop();return Object.defineProperty(r,"name",{value:i}),Object.defineProperty(r,"stepId",{value:t,writable:!1,enumerable:!1,configurable:!1}),n&&(F(n),Object.defineProperty(r,"__closureVarsFn",{value:n,writable:!1,enumerable:!1,configurable:!1})),Object.defineProperty(r,"bind",{value:function(e,...r){let i=Function.prototype.bind.call(this,e,...r);return Object.defineProperty(i,"stepId",{value:t,writable:!1,enumerable:!1,configurable:!1}),n&&Object.defineProperty(i,"__closureVarsFn",{value:n,writable:!1,enumerable:!1,configurable:!1}),Object.defineProperty(i,"__boundThis",{value:e,writable:!1,enumerable:!1,configurable:!1}),r.length>0&&Object.defineProperty(i,"__boundArgs",{value:r,writable:!1,enumerable:!1,configurable:!1}),i},writable:!1,enumerable:!1,configurable:!1}),r}}var Ma=n(((e,t)=>{(function(e,t,n){function r(e){var t=this,n=o();t.next=function(){var e=2091639*t.s0+t.c*23283064365386963e-26;return t.s0=t.s1,t.s1=t.s2,t.s2=e-(t.c=e|0)},t.c=1,t.s0=n(` `),t.s1=n(` `),t.s2=n(` `),t.s0-=n(e),t.s0<0&&(t.s0+=1),t.s1-=n(e),t.s1<0&&(t.s1+=1),t.s2-=n(e),t.s2<0&&(t.s2+=1),n=null}function i(e,t){return t.c=e.c,t.s0=e.s0,t.s1=e.s1,t.s2=e.s2,t}function a(e,t){var n=new r(e),a=t&&t.state,o=n.next;return o.int32=function(){return n.next()*4294967296|0},o.double=function(){return o()+(o()*2097152|0)*11102230246251565e-32},o.quick=o,a&&(typeof a==`object`&&i(a,n),o.state=function(){return i(n,{})}),o}function o(){var e=4022871197;return function(t){t=String(t);for(var n=0;n<t.length;n++){e+=t.charCodeAt(n);var r=.02519603282416938*e;e=r>>>0,r-=e,r*=e,e=r>>>0,r-=e,e+=r*4294967296}return(e>>>0)*23283064365386963e-26}}t&&t.exports?t.exports=a:n&&n.amd?n(function(){return a}):this.alea=a})(e,typeof t==`object`&&t,typeof define==`function`&&define)})),Na=n(((e,t)=>{(function(e,t,n){function r(e){var t=this,n=``;t.x=0,t.y=0,t.z=0,t.w=0,t.next=function(){var e=t.x^t.x<<11;return t.x=t.y,t.y=t.z,t.z=t.w,t.w^=t.w>>>19^e^e>>>8},e===(e|0)?t.x=e:n+=e;for(var r=0;r<n.length+64;r++)t.x^=n.charCodeAt(r)|0,t.next()}function i(e,t){return t.x=e.x,t.y=e.y,t.z=e.z,t.w=e.w,t}function a(e,t){var n=new r(e),a=t&&t.state,o=function(){return(n.next()>>>0)/4294967296};return o.double=function(){do var e=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21);while(e===0);return e},o.int32=n.next,o.quick=o,a&&(typeof a==`object`&&i(a,n),o.state=function(){return i(n,{})}),o}t&&t.exports?t.exports=a:n&&n.amd?n(function(){return a}):this.xor128=a})(e,typeof t==`object`&&t,typeof define==`function`&&define)})),Pa=n(((e,t)=>{(function(e,t,n){function r(e){var t=this,n=``;t.next=function(){var e=t.x^t.x>>>2;return t.x=t.y,t.y=t.z,t.z=t.w,t.w=t.v,(t.d=t.d+362437|0)+(t.v=t.v^t.v<<4^(e^e<<1))|0},t.x=0,t.y=0,t.z=0,t.w=0,t.v=0,e===(e|0)?t.x=e:n+=e;for(var r=0;r<n.length+64;r++)t.x^=n.charCodeAt(r)|0,r==n.length&&(t.d=t.x<<10^t.x>>>4),t.next()}function i(e,t){return t.x=e.x,t.y=e.y,t.z=e.z,t.w=e.w,t.v=e.v,t.d=e.d,t}function a(e,t){var n=new r(e),a=t&&t.state,o=function(){return(n.next()>>>0)/4294967296};return o.double=function(){do var e=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21);while(e===0);return e},o.int32=n.next,o.quick=o,a&&(typeof a==`object`&&i(a,n),o.state=function(){return i(n,{})}),o}t&&t.exports?t.exports=a:n&&n.amd?n(function(){return a}):this.xorwow=a})(e,typeof t==`object`&&t,typeof define==`function`&&define)})),Fa=n(((e,t)=>{(function(e,t,n){function r(e){var t=this;t.next=function(){var e=t.x,n=t.i,r=e[n],i;return r^=r>>>7,i=r^r<<24,r=e[n+1&7],i^=r^r>>>10,r=e[n+3&7],i^=r^r>>>3,r=e[n+4&7],i^=r^r<<7,r=e[n+7&7],r^=r<<13,i^=r^r<<9,e[n]=i,t.i=n+1&7,i};function n(e,t){var n,r=[];if(t===(t|0))r[0]=t;else for(t=``+t,n=0;n<t.length;++n)r[n&7]=r[n&7]<<15^t.charCodeAt(n)+r[n+1&7]<<13;for(;r.length<8;)r.push(0);for(n=0;n<8&&r[n]===0;++n);for(n==8?r[7]=-1:r[n],e.x=r,e.i=0,n=256;n>0;--n)e.next()}n(t,e)}function i(e,t){return t.x=e.x.slice(),t.i=e.i,t}function a(e,t){e??=+new Date;var n=new r(e),a=t&&t.state,o=function(){return(n.next()>>>0)/4294967296};return o.double=function(){do var e=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21);while(e===0);return e},o.int32=n.next,o.quick=o,a&&(a.x&&i(a,n),o.state=function(){return i(n,{})}),o}t&&t.exports?t.exports=a:n&&n.amd?n(function(){return a}):this.xorshift7=a})(e,typeof t==`object`&&t,typeof define==`function`&&define)})),Ia=n(((e,t)=>{(function(e,t,n){function r(e){var t=this;t.next=function(){var e=t.w,n=t.X,r=t.i,i,a;return t.w=e=e+1640531527|0,a=n[r+34&127],i=n[r=r+1&127],a^=a<<13,i^=i<<17,a^=a>>>15,i^=i>>>12,a=n[r]=a^i,t.i=r,a+(e^e>>>16)|0};function n(e,t){var n,r,i,a,o,s=[],c=128;for(t===(t|0)?(r=t,t=null):(t+=`\0`,r=0,c=Math.max(c,t.length)),i=0,a=-32;a<c;++a)t&&(r^=t.charCodeAt((a+32)%t.length)),a===0&&(o=r),r^=r<<10,r^=r>>>15,r^=r<<4,r^=r>>>13,a>=0&&(o=o+1640531527|0,n=s[a&127]^=r+o,i=n==0?i+1:0);for(i>=128&&(s[(t&&t.length||0)&127]=-1),i=127,a=512;a>0;--a)r=s[i+34&127],n=s[i=i+1&127],r^=r<<13,n^=n<<17,r^=r>>>15,n^=n>>>12,s[i]=r^n;e.w=o,e.X=s,e.i=i}n(t,e)}function i(e,t){return t.i=e.i,t.w=e.w,t.X=e.X.slice(),t}function a(e,t){e??=+new Date;var n=new r(e),a=t&&t.state,o=function(){return(n.next()>>>0)/4294967296};return o.double=function(){do var e=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21);while(e===0);return e},o.int32=n.next,o.quick=o,a&&(a.X&&i(a,n),o.state=function(){return i(n,{})}),o}t&&t.exports?t.exports=a:n&&n.amd?n(function(){return a}):this.xor4096=a})(e,typeof t==`object`&&t,typeof define==`function`&&define)})),La=n(((e,t)=>{(function(e,t,n){function r(e){var t=this,n=``;t.next=function(){var e=t.b,n=t.c,r=t.d,i=t.a;return e=e<<25^e>>>7^n,n=n-r|0,r=r<<24^r>>>8^i,i=i-e|0,t.b=e=e<<20^e>>>12^n,t.c=n=n-r|0,t.d=r<<16^n>>>16^i,t.a=i-e|0},t.a=0,t.b=0,t.c=-1640531527,t.d=1367130551,e===Math.floor(e)?(t.a=e/4294967296|0,t.b=e|0):n+=e;for(var r=0;r<n.length+20;r++)t.b^=n.charCodeAt(r)|0,t.next()}function i(e,t){return t.a=e.a,t.b=e.b,t.c=e.c,t.d=e.d,t}function a(e,t){var n=new r(e),a=t&&t.state,o=function(){return(n.next()>>>0)/4294967296};return o.double=function(){do var e=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21);while(e===0);return e},o.int32=n.next,o.quick=o,a&&(typeof a==`object`&&i(a,n),o.state=function(){return i(n,{})}),o}t&&t.exports?t.exports=a:n&&n.amd?n(function(){return a}):this.tychei=a})(e,typeof t==`object`&&t,typeof define==`function`&&define)})),Ra=n(((t,n)=>{(function(t,r,i){var a=256,o=6,s=52,c=`random`,l=i.pow(a,o),u=i.pow(2,s),d=u*2,f=a-1,p;function m(e,t,n){var s=[];t=t==1?{entropy:!0}:t||{};var f=v(_(t.entropy?[e,b(r)]:e??y(),3),s),p=new h(s),m=function(){for(var e=p.g(o),t=l,n=0;e<u;)e=(e+n)*a,t*=a,n=p.g(1);for(;e>=d;)e/=2,t/=2,n>>>=1;return(e+n)/t};return m.int32=function(){return p.g(4)|0},m.quick=function(){return p.g(4)/4294967296},m.double=m,v(b(p.S),r),(t.pass||n||function(e,t,n,r){return r&&(r.S&&g(r,p),e.state=function(){return g(p,{})}),n?(i[c]=e,t):e})(m,f,`global`in t?t.global:this==i,t.state)}function h(e){var t,n=e.length,r=this,i=0,o=r.i=r.j=0,s=r.S=[];for(n||(e=[n++]);i<a;)s[i]=i++;for(i=0;i<a;i++)s[i]=s[o=f&o+e[i%n]+(t=s[i])],s[o]=t;(r.g=function(e){for(var t,n=0,i=r.i,o=r.j,s=r.S;e--;)t=s[i=f&i+1],n=n*a+s[f&(s[i]=s[o=f&o+t])+(s[o]=t)];return r.i=i,r.j=o,n})(a)}function g(e,t){return t.i=e.i,t.j=e.j,t.S=e.S.slice(),t}function _(e,t){var n=[],r=typeof e,i;if(t&&r==`object`)for(i in e)try{n.push(_(e[i],t-1))}catch{}return n.length?n:r==`string`?e:e+`\0`}function v(e,t){for(var n=e+``,r,i=0;i<n.length;)t[f&i]=f&(r^=t[f&i]*19)+n.charCodeAt(i++);return b(t)}function y(){try{var e;return p&&(e=p.randomBytes)?e=e(a):(e=new Uint8Array(a),(t.crypto||t.msCrypto).getRandomValues(e)),b(e)}catch{var n=t.navigator,i=n&&n.plugins;return[+new Date,t,i,t.screen,b(r)]}}function b(e){return String.fromCharCode.apply(0,e)}if(v(i.random(),r),typeof n==`object`&&n.exports){n.exports=m;try{p=e(`crypto`)}catch{}}else typeof define==`function`&&define.amd?define(function(){return m}):i[`seed`+c]=m})(typeof self<`u`?self:t,[],Math)})),za=t(n(((e,t)=>{var n=Ma(),r=Na(),i=Pa(),a=Fa(),o=Ia(),s=La(),c=Ra();c.alea=n,c.xor128=r,c.xorwow=i,c.xorshift7=a,c.xor4096=o,c.tychei=s,t.exports=c}))(),1);const Ba=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/`,Va=new Uint8Array(128).fill(255);for(let e=0;e<64;e++)Va[Ba.charCodeAt(e)]=e;function Ha(e){return e===9||e===10||e===12||e===13||e===32}function Ua(e,t){for(;t<e.length&&Ha(e.charCodeAt(t));)t++;return t}function Wa(e,t){let n=e.length,r=e;n===2?r=e+`AA`:n===3&&(r=e+`A`);let i=Va[r.charCodeAt(0)],a=Va[r.charCodeAt(1)],o=Va[r.charCodeAt(2)],s=Va[r.charCodeAt(3)],c=i<<2|a>>4,l=(a&15)<<4|o>>2,u=(o&3)<<6|s;if(n===2){if(t&&l!==0)throw SyntaxError(`Extra bits in base64 chunk`);return[c]}if(n===3){if(t&&u!==0)throw SyntaxError(`Extra bits in base64 chunk`);return[c,l]}return[c,l,u]}function Ga(e,t,n,r){if(r===void 0&&(r=2**53-1),r===0)return{read:0,bytes:[],error:null};let i=0,a=[],o=``,s=0,c=0,l=e.length;for(;;){if(c=Ua(e,c),c===l){if(s>0){if(n===`stop-before-partial`)return{read:i,bytes:a,error:null};if(n===`loose`){if(s===1)return{read:i,bytes:a,error:SyntaxError(`Invalid base64: lone character in final chunk`)};a.push(...Wa(o,!1))}else return{read:i,bytes:a,error:SyntaxError(`Invalid base64: incomplete chunk in strict mode`)}}return{read:l,bytes:a,error:null}}let u=e[c];if(c++,u===`=`){if(s<2)return{read:i,bytes:a,error:SyntaxError(`Invalid base64: padding in unexpected place`)};if(c=Ua(e,c),s===2){if(c===l)return n===`stop-before-partial`?{read:i,bytes:a,error:null}:{read:i,bytes:a,error:SyntaxError(`Invalid base64: missing second padding character`)};u=e[c],u===`=`&&(c=Ua(e,c+1))}if(c<l)return{read:i,bytes:a,error:SyntaxError(`Invalid base64: unexpected characters after padding`)};let t=n===`strict`;try{a.push(...Wa(o,t))}catch(e){return{read:i,bytes:a,error:e}}return{read:l,bytes:a,error:null}}if(t===`base64url`){if(u===`+`||u===`/`)return{read:i,bytes:a,error:SyntaxError(`Invalid base64url: unexpected character '${u}'`)};u===`-`?u=`+`:u===`_`&&(u=`/`)}let d=u.charCodeAt(0);if(d>=128||Va[d]===255)return{read:i,bytes:a,error:SyntaxError(`Invalid base64: unexpected character '${e[c-1]}'`)};let f=r-a.length;if(f===1&&s===2||f===2&&s===3||(o+=u,s=o.length,s===4&&(a.push(...Wa(o)),o=``,s=0,i=c,a.length===r)))return{read:i,bytes:a,error:null}}}function Ka(e,t){t===void 0&&(t=2**53-1);let n=e.length,r=[],i=0;if(n%2!=0)return{read:0,bytes:[],error:SyntaxError(`Invalid hex: string length must be even`)};for(;i<n&&r.length<t;){let t=e.substring(i,i+2);if(!/^[0-9a-fA-F]{2}$/.test(t))return{read:i,bytes:r,error:SyntaxError(`Invalid hex: unexpected character at position ${i}`)};i+=2,r.push(Number.parseInt(t,16))}return{read:i,bytes:r,error:null}}function qa(e,t){let n=t?.alphabet??`base64`;if(n!==`base64`&&n!==`base64url`)throw TypeError(`Invalid alphabet: expected "base64" or "base64url", got "${n}"`);let r=!!t?.omitPadding,i=``,a=e.length;for(let t=0;t<a;t+=3){let n=e[t],o=t+1<a?e[t+1]:0,s=t+2<a?e[t+2]:0;i+=Ba[n>>2&63],i+=Ba[(n&3)<<4|o>>4&15],t+1<a?i+=Ba[(o&15)<<2|s>>6&3]:r||(i+=`=`),t+2<a?i+=Ba[s&63]:r||(i+=`=`)}return n===`base64url`&&(i=i.replace(/\+/g,`-`).replace(/\//g,`_`)),i}function Ja(e){let t=``;for(let n=0;n<e.length;n++)t+=e[n].toString(16).padStart(2,`0`);return t}function Ya(e){let t=e.prototype,n=e;t.toBase64||Object.defineProperty(t,"toBase64",{value:function(t){if(!(this instanceof e))throw TypeError(`this is not a Uint8Array`);return qa(this,t)},writable:!0,enumerable:!1,configurable:!0}),t.toHex||Object.defineProperty(t,"toHex",{value:function(){if(!(this instanceof e))throw TypeError(`this is not a Uint8Array`);return Ja(this)},writable:!0,enumerable:!1,configurable:!0}),t.setFromBase64||Object.defineProperty(t,"setFromBase64",{value:function(t,n){if(!(this instanceof e))throw TypeError(`this is not a Uint8Array`);if(typeof t!=`string`)throw TypeError(`expected a string`);let r=n?.alphabet??`base64`;if(r!==`base64`&&r!==`base64url`)throw TypeError(`Invalid alphabet: expected "base64" or "base64url", got "${r}"`);let i=n?.lastChunkHandling??`loose`;if(i!==`loose`&&i!==`strict`&&i!==`stop-before-partial`)throw TypeError(`Invalid lastChunkHandling: expected "loose", "strict", or "stop-before-partial", got "${i}"`);let a=Ga(t,r,i,this.length),o=a.bytes,s=o.length;for(let e=0;e<s;e++)this[e]=o[e];if(a.error)throw a.error;return{read:a.read,written:s}},writable:!0,enumerable:!1,configurable:!0}),t.setFromHex||Object.defineProperty(t,"setFromHex",{value:function(t){if(!(this instanceof e))throw TypeError(`this is not a Uint8Array`);if(typeof t!=`string`)throw TypeError(`expected a string`);let n=Ka(t,this.length),r=n.bytes,i=r.length;for(let e=0;e<i;e++)this[e]=r[e];if(n.error)throw n.error;return{read:n.read,written:i}},writable:!0,enumerable:!1,configurable:!0}),n.fromBase64||Object.defineProperty(e,"fromBase64",{value:function(t,n){if(typeof t!=`string`)throw TypeError(`expected a string`);let r=n?.alphabet??`base64`;if(r!==`base64`&&r!==`base64url`)throw TypeError(`Invalid alphabet: expected "base64" or "base64url", got "${r}"`);let i=n?.lastChunkHandling??`loose`;if(i!==`loose`&&i!==`strict`&&i!==`stop-before-partial`)throw TypeError(`Invalid lastChunkHandling: expected "loose", "strict", or "stop-before-partial", got "${i}"`);let a=Ga(t,r,i);if(a.error)throw a.error;return new e(a.bytes)},writable:!0,enumerable:!1,configurable:!0}),n.fromHex||Object.defineProperty(e,"fromHex",{value:function(t){if(typeof t!=`string`)throw TypeError(`expected a string`);let n=Ka(t);if(n.error)throw n.error;return new e(n.bytes)},writable:!0,enumerable:!1,configurable:!0})}function Xa(e){return function(){let t=`0123456789abcdef`,n=``;for(let r=0;r<36;r++)r===8||r===13||r===18||r===23?n+=`-`:r===14?n+=`4`:r===19?n+=t[Math.floor(e()*4)+8]:n+=t[Math.floor(e()*16)];return n}}const Za={"SHA-1":`sha1`,"SHA-256":`sha256`,"SHA-384":`sha384`,"SHA-512":`sha512`};function Qa(e){if(Rn.isTypedArray(e)||Rn.isDataView(e)){if(Rn.isSharedArrayBuffer(e.buffer))throw TypeError(`crypto.subtle.digest does not accept SharedArrayBuffer-backed views`);return e}if(!Rn.isArrayBuffer(e))throw TypeError(`data must be an ArrayBuffer or ArrayBufferView`);return new Uint8Array(e)}function $a(e){let{fixedTimestamp:t}=e,{seed:n}=e,r=(0,za.default)(n),i=Vn(),a=Hn(`globalThis`,i);a.Math.random=r;let o=a.Date;a.Date=function(...e){return e.length===0?new o(t):new o(...e)},a.Date.prototype=o.prototype,Object.setPrototypeOf(a.Date,o),a.Date.now=()=>t;let s=globalThis.crypto,c=s.subtle;function l(e){for(let t=0;t<e.length;t++)e[t]=Math.floor(r()*256);return e}let u=Xa(r),d=a;delete d.Atomics.waitAsync,delete d.WebAssembly.compile,delete d.WebAssembly.instantiate,delete d.WebAssembly.compileStreaming,delete d.WebAssembly.instantiateStreaming,delete d.WeakRef,delete d.FinalizationRegistry;let f=async(e,t)=>{let n=typeof e==`string`?e:e.name,r=Za[n.toUpperCase()];if(!r)throw new DOMException(`Unrecognized algorithm name: ${n}`,`NotSupportedError`);let i=Ln(r).update(Qa(t)).digest(),a=new ArrayBuffer(i.byteLength);return new Uint8Array(a).set(i),a};return a.crypto=new Proxy(s,{get(e,t){return t===`getRandomValues`?l:t===`randomUUID`?u:t===`subtle`?new Proxy(c,{get(e,t){if(t===`digest`)return f;let n=e[t];return typeof n==`function`?()=>{throw new q(`\`crypto.subtle.${String(t)}()\` is not available inside a workflow function. Move it to a step function where full Node.js crypto is available.`)}:n}}):e[t]}}),a.process={env:Object.freeze({...process.env})},a.DOMException=globalThis.DOMException,a.Headers=globalThis.Headers,a.TextEncoder=globalThis.TextEncoder,a.TextDecoder=globalThis.TextDecoder,a.console=globalThis.console,a.URL=globalThis.URL,a.URLSearchParams=globalThis.URLSearchParams,a.structuredClone=globalThis.structuredClone,a.atob=globalThis.atob,a.btoa=globalThis.btoa,Ya(a.Uint8Array),a.Symbol.dispose??=Symbol.for(`Symbol.dispose`),a.Symbol.asyncDispose??=Symbol.for(`Symbol.asyncDispose`),a.exports={},a.module={exports:a.exports},{context:i,globalThis:a,updateTimestamp:e=>{t=e}}}const eo=new Map;function to(e){let t=eo.get(e);if(t!==void 0)return eo.delete(e),eo.set(e,t),t}function no(e,t){let n=to(e);if(n===void 0)for(n=new Map,eo.set(e,n);eo.size>8;){let e=eo.keys().next().value;if(e===void 0)break;eo.delete(e)}let r=n.get(t);return r===void 0&&(r=new Bn(e,{filename:t}),n.set(t,r)),r}function ro(e,t,n){return no(e,t).runInContext(n)}function io(e){return async function(t,n={}){let{promise:r,resolve:i}=Zt(),a=`attr_${e.generateCorrelationId(`attr`)}`,o={type:`attribute`,correlationId:a,changes:t,...n.allowReservedAttributes===!0?{allowReservedAttributes:!0}:{}};return e.invocationsQueue.set(a,o),e.eventsConsumer.subscribe(r=>r?r.correlationId===a?r.eventType!==`attr_set`||r.eventData.writer.type!==`workflow`||JSON.stringify(r.eventData.changes)!==JSON.stringify(t)||r.eventData.allowReservedAttributes===!0!=(n.allowReservedAttributes===!0)?(e.promiseQueue=e.promiseQueue.then(()=>{e.onWorkflowError(new Z(`Replay divergence: Unexpected attribute event for ${a}`,{eventId:r.eventId}))}),b.Finished):(e.invocationsQueue.delete(a),e.promiseQueue=e.promiseQueue.then(()=>{i()}),b.Finished):b.NotConsumed:(qt(e,()=>{e.onWorkflowError(new K(e.invocationsQueue,e.globalThis))}),b.NotConsumed)),r}}function ao(e,t){if(typeof t!=`string`)return null;let n=He(Ge,e.globalThis),r=n?.[A];return typeof r==`function`?r.call(n,{runId:t}):null}function oo(e){return function(t={}){if(t.token===``)throw Error("`createHook()` was called with an empty string token. Pass a non-empty token, or omit the `token` option to use a randomly generated one.");if(t.isWebhook===!0&&t.experimental_minRetention!==void 0)throw Error("Webhook hooks do not support `experimental_minRetention`. Use a non-webhook `createHook()` with `resumeHook()`.");if(t.experimental_minRetention!==void 0&&e.worldCapabilities?.hookRetention?.active!==!0)throw new Y("The configured World does not support `experimental_minRetention` for Hooks.");let n=`hook_${e.generateCorrelationId(`hook`)}`,r=t.token??e.generateNanoid(),i=t.experimental_minRetention===void 0?void 0:en(t.experimental_minRetention),a=t.isWebhook??!1;e.invocationsQueue.set(n,{type:`hook`,correlationId:n,token:r,tokenRetentionUntil:i,metadata:t.metadata,isWebhook:a});let o=[],s=[],c=[],l=!1,u=!1,d=!1,f=!1,p=null,m=null,h=new Set;ue.debug(`Hook consumer setup`,{correlationId:n,token:r}),e.eventsConsumer.subscribe(t=>{if(!t)return l=!0,(s.length>0&&o.length===0||c.length>0&&!u&&!f)&&qt(e,()=>{e.onWorkflowError(new K(e.invocationsQueue,e.globalThis))}),b.NotConsumed;if(t.correlationId!==n)return b.NotConsumed;let i=`eventData`in t&&t.eventData&&`token`in t.eventData?t.eventData.token:void 0;if(typeof i==`string`&&i!==r)return e.promiseQueue=e.promiseQueue.then(()=>{e.onWorkflowError(new Z(`Replay divergence: hook event ${t.eventType} for ${n} belongs to token "${i}", but the current hook consumer expects "${r}"`,{eventId:t.eventId}))}),b.Finished;if(t.eventType===`hook_created`){let r=e.invocationsQueue.get(n);r&&r.type===`hook`&&(r.hasCreatedEvent=!0,r.tokenRetentionUntil=t.eventData.tokenRetentionUntil),u=!0;let i=c.slice();return c.length=0,e.promiseQueue=e.promiseQueue.then(()=>{for(let e of i)e.resolve(null)}),b.Consumed}if(t.eventType===`hook_conflict`){e.invocationsQueue.delete(n);let r=t,i=new Lt(r.eventData.token,r.eventData.conflictingRunId);f=!0,p=i,m=ao(e,r.eventData.conflictingRunId);let a=s.slice();s.length=0;let o=c.slice();return c.length=0,e.promiseQueue=e.promiseQueue.then(()=>{for(let e of a)e.reject(i);for(let e of o)m?e.resolve(m):e.reject(i)}),b.Consumed}if(t.eventType===`hook_received`){let n=t.resumeId;if(typeof n==`string`){if(h.has(n))return b.Consumed;h.add(n)}let r=e.eventsConsumer.eventIndex,i=s.length>0,a=Xt(e,r,`hook`,{armed:i});if(i){let n=Qt(e,r,`hook`),i=s.shift();if(i){e.pendingDeliveries++;let r;e.promiseQueue=e.promiseQueue.then(async()=>{try{let n=await e.replayPayloadCache.prepareEventPayload(t.eventId,`payload`,t.eventData.payload);r={ok:!0,value:await S(t.eventData.payload,e.runId,e.encryptionKey,e.globalThis,{},n)}}catch(e){r={ok:!1,error:e}}finally{e.pendingDeliveries--}n.then(()=>{a.markDelivered(),r.ok?i.resolve(r.value):i.reject(r.error)})})}}else{let n,i=Zt();e.pendingDeliveries++,e.promiseQueue=e.promiseQueue.then(async()=>{try{let r=await e.replayPayloadCache.prepareEventPayload(t.eventId,`payload`,t.eventData.payload);n={ok:!0,value:await S(t.eventData.payload,e.runId,e.encryptionKey,e.globalThis,{},r)}}catch(e){n={ok:!1,error:e}}finally{e.pendingDeliveries--,i.resolve()}}),o.push({claim:()=>(a.arm(),i.promise.then(()=>Qt(e,r,`hook`)).then(()=>{if(a.markDelivered(),n&&!n.ok)throw n.error;return n.value}))})}return b.Consumed}return t.eventType===`hook_disposed`?(e.invocationsQueue.delete(n),d=!0,b.Finished):(e.promiseQueue=e.promiseQueue.then(()=>{e.onWorkflowError(new Z(`Replay divergence: Unexpected event type for hook ${n} (token: ${r}) "${t.eventType}"`,{eventId:t.eventId}))}),b.Finished)});let g=!1;function _(){let t=Zt();if(f&&p)return e.promiseQueue=e.promiseQueue.then(()=>{t.reject(p)}),t.promise;if(o.length>0){let e=o.shift();if(e)return e.claim()}return l&&qt(e,()=>{e.onWorkflowError(new K(e.invocationsQueue,e.globalThis))}),s.push(t),t.promise}function v(){let t=Zt();if(u)return e.promiseQueue=e.promiseQueue.then(()=>{t.resolve(null)}),t.promise;if(f)return e.promiseQueue=e.promiseQueue.then(()=>{m?t.resolve(m):t.reject(p)}),t.promise;let r=e.invocationsQueue.get(n);return r&&r.type===`hook`&&(r.hasConflictAwaiter=!0),l&&qt(e,()=>{e.onWorkflowError(new K(e.invocationsQueue,e.globalThis))}),c.push(t),t.promise}function y(){if(g||(g=!0,d))return;let t=e.invocationsQueue.get(n);t&&t.type===`hook`&&(t.disposed=!0),s.length>0&&(s.length=0,qt(e,()=>{e.onWorkflowError(new K(e.invocationsQueue,e.globalThis))})),ue.debug(`Hook disposed`,{correlationId:n,token:r})}let x={token:r,getConflict(){return v()},then(e,t){return _().then(e,t)},async*[Symbol.asyncIterator](){for(;!g;)yield await this},dispose:y,[Symbol.dispose]:y},C=e.globalThis.Symbol.dispose;return C&&C!==Symbol.dispose&&(x[C]=y),x}}function so(e){return async function(t){let{promise:n,resolve:r}=Zt(),i=`wait_${e.generateCorrelationId(`wait`)}`,a=en(t),o={type:`wait`,correlationId:i,resumeAt:a};return e.invocationsQueue.set(i,o),e.eventsConsumer.subscribe(t=>{if(!t)return qt(e,()=>{e.onWorkflowError(new K(e.invocationsQueue,e.globalThis))}),b.NotConsumed;if(t.correlationId!==i)return b.NotConsumed;if(t.eventType===`wait_created`){let n=e.invocationsQueue.get(i);return n&&n.type===`wait`&&(n.hasCreatedEvent=!0,n.resumeAt=t.eventData.resumeAt),b.Consumed}if(t.eventType===`wait_completed`){let n=t.eventData?.resumeAt;if(n!==void 0){let r=e.invocationsQueue.get(i),o=r&&r.type===`wait`?r.resumeAt:a,s=new Date(n),c=s.getTime(),l=o.getTime(),u=Number.isFinite(c)?s.toISOString():String(n);if(c!==l)return e.promiseQueue=e.promiseQueue.then(()=>{e.onWorkflowError(new Z(`Replay divergence: wait_completed event for ${i} has resumeAt "${u}", but the current wait consumer expects "${o.toISOString()}"`,{eventId:t.eventId}))}),b.Finished}e.invocationsQueue.delete(i);let o=e.eventsConsumer.eventIndex,s=Xt(e,o,`wait`),c=Qt(e,o,`wait`);return e.promiseQueue.then(()=>c).then(()=>{s.markDelivered(),r()}),b.Finished}return e.promiseQueue=e.promiseQueue.then(()=>{e.onWorkflowError(new Z(`Replay divergence: Unexpected event type for wait ${i} "${t.eventType}"`,{eventId:t.eventId}))}),b.Finished}),n}}async function co(e,t,n,r,i,a){if(t.size!==0){for(let e of t.values())e.type===`hook`&&e.isSystem&&!e.disposed&&!e.abortRequested&&(e.disposed=!0);try{let e=await Lr();await mi({suspension:new K(t,n),world:e,run:r,runReadyBarrier:a})}catch(t){w.warn(`Failed to drain pending queue items for ${i} workflow run`,{workflowRunId:e,message:t instanceof Error?t.message:String(t)})}}}function lo(e){return fo(`replay`,e.workflowRun,e.events,async t=>{let{session:n,execution:r}=await mo(e);return t?.setAttributes({...pe(n.argumentCount)}),po(await r,t)})}function uo(e,t){return fo(`retained`,e.workflowRun,t,async n=>{n?.setAttributes({...pe(e.argumentCount)});let r=await e.resume(t);return r.type===`replay`?r:po(r,n)})}function fo(e,t,n,r){return W(`workflow.run ${t.workflowName}`,i=>(i?.setAttributes({...be(t.workflowName),...Ze(t.runId),...Ie(t.status),...Qe(n.length),...lt(e)}),r(i)))}function po(e,t){return e.type===`completed`?t?.setAttributes({...we(e.resultType)}):t&&me(e.suspension,t),e}async function mo({workflowCode:e,workflowRun:t,events:n,encryptionKey:r,replayPayloadCache:a,runReadyBarrier:o,worldCapabilities:c}){let l=t.startedAt;if(!l)throw new q(`Workflow run "${t.runId}" has no "startedAt" timestamp (should not happen)`);let d=Wr(t.runId)??+t.createdAt,f=nn(process.env.VERCEL_URL?`https://${process.env.VERCEL_URL}`:`http://localhost:${await ti()??3e3}`),p=`${t.runId}:${t.workflowName}:${t.deploymentId}`,{context:m,globalThis:h,updateTimestamp:g}=$a({seed:p,fixedTimestamp:d}),_=Zt(),v={type:`running`,interruption:_},y=e=>{switch(v.type){case`running`:{let{interruption:t}=v;v=K.is(e)?{type:`suspended`,suspension:e}:{type:`replay`},D.suspensionGeneration++,t.reject(e);return}case`suspended`:v={type:`replay`};return;case`replay`:case`completed`:return}},x=fn(()=>h.Math.random()),S=ka({seed:p,fixedTimestamp:d,positional:()=>x(d),perKind:Aa()}),C=Ca(`useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict`,21,e=>new Uint8Array(e).map(()=>256*h.Math.random())),w={current:Promise.resolve()},T=new V(n,{onConsumedEvent:e=>{g(+e.createdAt)},onUnconsumedEvent:e=>{y(new Z(`Replay could not consume event: eventType=${e.eventType}, correlationId=${e.correlationId}, eventId=${e.eventId}.`,{eventId:e.eventId}))},getPromiseQueue:()=>w.current}),D={runId:t.runId,encryptionKey:r,worldCapabilities:c,globalThis:h,onWorkflowError:y,eventsConsumer:T,generateCorrelationId:S,generateNanoid:C,invocationsQueue:new Map,get promiseQueue(){return w.current},set promiseQueue(e){w.current=e},pendingDeliveries:0,suspensionGeneration:0,pendingDeliveryBarriers:new Map,replayPayloadCache:a};D.eventsConsumer.subscribe(e=>e&&(e.eventType===`run_created`||e.eventType===`run_started`||e.eventType===`attr_set`&&e.eventData.writer.type===`step`)?b.Consumed:b.NotConsumed);let k=ja(D),A=oo(D),j=so(D),M=io(D);h[Ae]=k,h[ee]=M,h[de]=A,h[i]=j,h[he]=e=>E(t.runId,e),h[sn]={workflowName:t.workflowName,workflowRunId:t.runId,workflowStartedAt:new h.Date(+l),url:f,features:{encryption:!!r}},h[ce]=()=>S(`stream`),h.fetch=()=>{throw new h.Error(`Global "fetch" is unavailable in workflow functions. Use the "fetch" step function from "workflow" to make HTTP requests.\n\nLearn more: https://workflow-sdk.dev/err/${Ht.FETCH_IN_WORKFLOW_FUNCTION}`)};let N=`Timeout functions like "setTimeout" and "setInterval" are not supported in workflow functions. Use the "sleep" function from "workflow" for time-based delays.`;h.setTimeout=()=>{throw new q(N,{slug:Ht.TIMEOUT_FUNCTIONS_IN_WORKFLOW})},h.setInterval=()=>{throw new q(N,{slug:Ht.TIMEOUT_FUNCTIONS_IN_WORKFLOW})},h.clearTimeout=()=>{throw new q(N,{slug:Ht.TIMEOUT_FUNCTIONS_IN_WORKFLOW})},h.clearInterval=()=>{throw new q(N,{slug:Ht.TIMEOUT_FUNCTIONS_IN_WORKFLOW})},h.setImmediate=()=>{throw new q(N,{slug:Ht.TIMEOUT_FUNCTIONS_IN_WORKFLOW})},h.clearImmediate=()=>{throw new q(N,{slug:Ht.TIMEOUT_FUNCTIONS_IN_WORKFLOW})},h.AbortController=H(D);let P=s();h.AbortSignal={abort:P.abort,any:P.any,timeout:P.timeout};class F{cache;credentials;destination;headers;integrity;method;mode;redirect;referrer;referrerPolicy;url;keepalive;signal;duplex;body;constructor(e,t){if(typeof e==`string`||e instanceof h.URL){let t=String(e);try{new h.URL(t),this.url=t}catch(e){throw TypeError(`Failed to parse URL from ${t}`,{cause:e})}}else{if(this.url=e.url,!t){this.method=e.method,this.headers=new h.Headers(e.headers),this.body=e.body,this.mode=e.mode,this.credentials=e.credentials,this.cache=e.cache,this.redirect=e.redirect,this.referrer=e.referrer,this.referrerPolicy=e.referrerPolicy,this.integrity=e.integrity,this.keepalive=e.keepalive,this.signal=e.signal,this.duplex=e.duplex,this.destination=e.destination;return}this.method=e.method,this.headers=new h.Headers(e.headers),this.body=e.body,this.mode=e.mode,this.credentials=e.credentials,this.cache=e.cache,this.redirect=e.redirect,this.referrer=e.referrer,this.referrerPolicy=e.referrerPolicy,this.integrity=e.integrity,this.keepalive=e.keepalive,this.signal=e.signal,this.duplex=e.duplex,this.destination=e.destination}t?.method?this.method=t.method.toUpperCase():typeof this.method!=`string`&&(this.method=`GET`),t?.headers?this.headers=new h.Headers(t.headers):(typeof e==`string`||e instanceof h.URL)&&(this.headers=new h.Headers),t?.mode===void 0?typeof this.mode!=`string`&&(this.mode=`cors`):this.mode=t.mode,t?.credentials===void 0?typeof this.credentials!=`string`&&(this.credentials=`same-origin`):this.credentials=t.credentials,t?.cache===void 0?typeof this.cache!=`string`&&(this.cache=`default`):this.cache=t.cache,t?.redirect===void 0?typeof this.redirect!=`string`&&(this.redirect=`follow`):this.redirect=t.redirect,t?.referrer===void 0?typeof this.referrer!=`string`&&(this.referrer=`about:client`):this.referrer=t.referrer,t?.referrerPolicy===void 0?typeof this.referrerPolicy!=`string`&&(this.referrerPolicy=``):this.referrerPolicy=t.referrerPolicy,t?.integrity===void 0?typeof this.integrity!=`string`&&(this.integrity=``):this.integrity=t.integrity,t?.keepalive===void 0?typeof this.keepalive!=`boolean`&&(this.keepalive=!1):this.keepalive=t.keepalive,t?.signal===void 0?this.signal||={aborted:!1}:this.signal=t.signal,this.duplex||=`half`,this.destination||=`document`;let n=t?.body;if(n!=null&&(this.method===`GET`||this.method===`HEAD`))throw TypeError(`Request with GET/HEAD method cannot have body.`);n==null?this.body=null:this.body=Object.create(h.ReadableStream.prototype,{[ie]:{value:n,writable:!1}})}clone(){u()}get bodyUsed(){return!1}blob;formData;arrayBuffer;json;text;async bytes(){return new Uint8Array(await this.arrayBuffer())}}h.Request=F,Object.defineProperties(F.prototype,{arrayBuffer:{value:k(`__builtin_response_array_buffer`),writable:!0,configurable:!0},json:{value:k(`__builtin_response_json`),writable:!0,configurable:!0},text:{value:k(`__builtin_response_text`),writable:!0,configurable:!0}});class I{type;url;status;statusText;body;headers;redirected;constructor(e,t){if(this.status=t?.status??200,this.statusText=t?.statusText??``,this.headers=new h.Headers(t?.headers),this.type=`default`,this.url=``,this.redirected=!1,e!=null&&(this.status===204||this.status===205||this.status===304))throw TypeError(`Response constructor: Invalid response status code ${this.status}`);e==null?this.body=null:this.body=Object.create(h.ReadableStream.prototype,{[ie]:{value:e,writable:!1}})}clone;blob;formData;get ok(){return this.status>=200&&this.status<300}get bodyUsed(){return!1}arrayBuffer;json;text;async bytes(){return new Uint8Array(await this.arrayBuffer())}static json(e,t){let n=JSON.stringify(e),r=new h.Headers(t?.headers);return r.has(`content-type`)||r.set(`content-type`,`application/json`),new I(n,{...t,headers:r})}static error(){u()}static redirect(e,t=302){if(![301,302,303,307,308].includes(t))throw RangeError(`Invalid redirect status code: ${t}. Must be one of: 301, 302, 303, 307, 308`);let n=new h.Headers;n.set(`Location`,String(e));let r=Object.create(I.prototype);return r.status=t,r.statusText=``,r.headers=n,r.body=null,r.type=`default`,r.url=``,r.redirected=!1,r}}h.Response=I,Object.defineProperties(I.prototype,{arrayBuffer:{value:k(`__builtin_response_array_buffer`),writable:!0,configurable:!0},json:{value:k(`__builtin_response_json`),writable:!0,configurable:!0},text:{value:k(`__builtin_response_text`),writable:!0,configurable:!0}});class L{constructor(){u()}get locked(){return!1}cancel(){u()}getReader(){u()}pipeThrough(){u()}pipeTo(){u()}tee(){u()}values(){u()}static from(){u()}[Symbol.asyncIterator](){u()}}h.ReadableStream=L;class R{constructor(){u()}get locked(){return!1}abort(){u()}close(){u()}getWriter(){u()}}h.WritableStream=R;class te{readable;writable;constructor(){u()}}h.TransformStream=te,h.console=globalThis.console;let ne=Symbol.for(`@vercel/request-context`);h[ne]=globalThis[ne];let re=nt(t.workflowName)?.moduleSpecifier||t.workflowName;ro(e,re,m);let z=ro(`globalThis.__private_workflows?.get(${JSON.stringify(t.workflowName)})`,re,m);if(typeof z!=`function`)throw new Ft(t.workflowName);let B=[];D.promiseQueue=D.promiseQueue.then(async()=>{let e=await a.prepareWorkflowInput(t);B=await O(t.input,t.runId,r,h,{},e)}),await D.promiseQueue;let ae=(async()=>await z(...B))(),oe=async e=>{throw K.is(e)||Z.is(e)?(v.type===`running`&&(v={type:`replay`}),e):(v={type:`completed`},await co(t.runId,D.invocationsQueue,h,t,`failed`,o),e)},se=async e=>{let n;try{n=await Promise.race([ae,e.promise])}catch(e){return v.type===`suspended`&&e===v.suspension?{type:`suspended`,suspension:v.suspension,session:le}:oe(e)}v={type:`completed`};try{let e=await We(n,t.runId,r,h,!1,(t.specVersion??0)>=5);return await co(t.runId,D.invocationsQueue,h,t,`completed`,o),{type:`completed`,output:e,resultType:typeof n}}catch(e){return oe(e)}},le={workflowRun:t,argumentCount:B.length,async resume(e){switch(v.type){case`suspended`:{let t=T.events;if(!(e.length>t.length&&t.every((t,n)=>t.eventId===e[n].eventId)))return v={type:`replay`},{type:`replay`};let n=Zt();return v={type:`running`,interruption:n},D.suspensionGeneration++,T.append(e.slice(t.length)),se(n)}case`replay`:return{type:`replay`};case`completed`:case`running`:throw new q(`Cannot resume ${v.type} workflow "${t.runId}"`)}}};return{session:le,execution:se(_)}}function ho(e){let t=ur();return t===void 0?e:e===void 0?t:Math.min(e,t)}function go({world:e,runInput:t,runId:n,runLogger:r}){let i=t?.environment;if(!i)return!1;let a=e.getEnvironment?.();return!a||a===i?!1:(r.error(`Refusing to run this workflow: it was created in the "${i}" environment but this deployment runs in "${a}". Executing it here would create a second copy of the same run id in both environments — one pending forever, one running — so the queue message is being discarded without executing and without retrying. The client that called start() wrote the run to its own environment but addressed the queue message to a deployment in another one. Check that the environment that client authenticates as (WORKFLOW_VERCEL_ENV for CLI and CI clients, or the OIDC token's environment inside a deployment) matches the environment of the deployment it targets. The run it created is still pending in "${i}" and will not run.`,{workflowRunId:n,creatorEnvironment:i,currentEnvironment:a,pinnedDeploymentId:t?.deploymentId}),!0)}async function _o({world:e,runInput:t,runId:n,runLogger:r}){let i=t?.deploymentId;if(!i)return;let a;try{a=await e.getDeploymentId()}catch{return}!a||a===i||r.error(`Queue message was delivered to a deployment it was not pinned to. The run was created targeting a different deployment, so this invocation may be replaying against code the run was not started on. Continuing — this is expected if the Workflow SDK version changed mid-run in local development, where the deployment id is derived from that version.`,{workflowRunId:n,pinnedDeploymentId:i,currentDeploymentId:a})}function vo(e){return q.is(e)?X.RUNTIME_ERROR:xe(e)?X.WORLD_CONTRACT_ERROR:null}async function yo({world:e,workflowRun:t,runId:n,requestId:r,err:i,errorCode:a,logMessage:o}){w.error(o,{workflowRunId:n,errorCode:a,error:i instanceof Error?i.message:String(i)});try{let o=Ee(e,t??n);await e.events.create(n,{eventType:`run_failed`,specVersion:5,eventData:{error:await Ct(i,n,await o(),globalThis,(t?.specVersion??0)>=5),errorCode:a}},{requestId:r})}catch(e){if(Q.is(e)||J.is(e))return;if(xe(e)){w.error(`Fatal world contract error while recording workflow failure`,{workflowRunId:n,errorCode:X.WORLD_CONTRACT_ERROR,error:e instanceof Error?e.message:String(e)});return}throw e}}function bo(e,t){let n=e.find(e=>e.runId===t&&(e.eventType===`run_completed`||e.eventType===`run_failed`||e.eventType===`run_cancelled`));return n?(w.debug(`Run reached terminal event, exiting`,{workflowRunId:t,eventType:n.eventType,eventId:n.eventId}),!0):!1}function xo(e,t){let n=0;for(let r of e)t.has(r)||n++;return n}function So(e,t){return e?.[un]??t}function Co(e){let t=new Set,n=new Set;for(let r of e)r.eventType===`hook_disposed`?t.add(r.correlationId):r.eventType===`wait_completed`&&n.add(r.correlationId);let r=!1,i=!1;for(let a of e)if(a.eventType===`hook_created`&&!t.has(a.correlationId)?r=!0:a.eventType===`wait_created`&&!n.has(a.correlationId)&&(i=!0),r&&i)break;return{openHook:r,openWait:i}}function wo(e,t,n){if(!mr()||!t||e.steps.length===0||!e.steps.every(e=>e.type===`step`))return!1;let{openHook:r,openWait:i}=n.value;return!r&&!i}async function To(e,t){let n=process.env.WORKFLOW_V2_TIMEOUT_MS;if(n!==void 0&&n!==``){let e=Number(n);if(Number.isFinite(e)&&e>0)return e}let r=await e.getRuntimeDeadline?.();if(r!==void 0){let e=r.getTime();if(!Number.isNaN(e)){let n=Math.floor(e-t);if(n>=(0,Gn.default)(`25m`))return(0,Gn.default)(`10m`);if(n>=(0,Gn.default)(`10m`))return(0,Gn.default)(`5m`)}}return(0,Gn.default)(`2m`)}function Eo(e,t){tn(t?.basePath);let n=_n(t?.namespace),i=vn(`workflow`,n),o=t=>t.createQueueHandler(i,async(o,s)=>{let c=Me(o);if(c){await et(c,t.specVersion);return}let{runId:l,traceCarrier:u,requestedAt:f,stepId:p,stepName:m,replayDivergence:h,preconditionReinvocations:g,deploymentMismatchRetryCount:_,runInput:v,hookInput:y}=gn.parse(o),b=$e(u)?u:void 0,{requestId:x}=s,S=s.queueName.slice(i.length),C=w.forRun(l,S),T=$n();if(s.attempt>T){let e=Jn(void 0,X.MAX_DELIVERIES_EXCEEDED);C.error(`Workflow handler exceeded max deliveries (${s.attempt}/${T})`,{attempt:s.attempt,errorCode:e.errorCode,errorAttribution:e.attribution});try{let e=await Lr(),t=Ee(e,l),n=new Y(`Workflow exceeded maximum queue deliveries (${s.attempt}/${T})`);await e.events.create(l,{eventType:`run_failed`,specVersion:5,eventData:{error:await Ct(n,l,await t()),errorCode:X.MAX_DELIVERIES_EXCEEDED}},{requestId:x})}catch(e){if(Q.is(e)||J.is(e))return;C.error(`Failed to mark run as failed after ${s.attempt} delivery attempts. A persistent error is preventing the run from being terminated. The run will remain in its current state until manually resolved. This is most likely due to a persistent outage of the workflow backend or a bug in the workflow runtime and should be reported to the Workflow team.`,{attempt:s.attempt,errorName:e instanceof Error?e.name:`UnknownError`,errorMessage:e instanceof Error?e.message:String(e),errorStack:e instanceof Error?e.stack:void 0})}return}let E=_t(),D=()=>r(E,b),O=await L(E,b),k=new Br,A=E===`continuous`?b:void 0,j=await je(`CONSUMER`);return await rt(A,async()=>await pt({workflowRunId:l,workflowName:S},async()=>{let t=await W(`workflow.route.get_world`,async()=>Lr());if(!go({world:t,runInput:v,runId:l,runLogger:C}))return await _o({world:t,runInput:v,runId:l,runLogger:C}),W(`workflow.execute ${Te(S)}`,{kind:j,links:O},async r=>{r?.setAttributes({...be(S),...tt(`execute_v2`),...B(`vercel-queue`),...re(s.queueName),...d(s.messageId),...wt(`process`),...Be({requestedAt:f}),...Ze(l),...Se(!!b),...Ot(E)});let i=Date.now(),o=await To(t,i),c=0,u=h?new Hr(h.count):Hr.inert(),T=(e,n)=>u.withEventCreate(n,n=>t.events.create(l,e,n)),O=null,A=null,j=null,M,N,P=-1,F,I,L=!1,ee,R,te=0,ne,z=pr()&&v!==void 0&&s.attempt===1&&p===void 0&&!h;r?.setAttributes(Tt(z));let V,ie=async()=>{if(V)try{await V}catch{}},ae=new Set,H=e=>{ae.size>0&&w.error(`Invariant violation: acking the workflow message while owned inline steps are still executing — crash recovery for these steps is broken`,{workflowRunId:l,ackPath:e,stepIds:[...ae]})},oe=async()=>({runId:l,traceCarrier:await D(),requestedAt:new Date}),ce=async(e,r)=>{if(H(`reinvoke`),!z)return{timeoutSeconds:e};await Re(t,ye(S,n),{...await oe(),...r},e>0?{delaySeconds:e}:void 0)},le=0,ue=null,de=e=>{let t=ue;if(!t)return;ue=null;let n=new Set(e.map(e=>e.eventId)),r=xo(n,t.ids),i=xo(t.ids,n),a=i>0?`shrank`:r>0?`grew`:`unchanged`;w.warn(`Restarted replay reloaded its event log after a stale-snapshot rejection`,{workflowRunId:l,outcome:a,added:r,dropped:i,eventsBefore:t.ids.size,eventsAfter:n.size,preconditionRestarts:t.restart,reason:t.reason,source:t.source,loopIteration:c})},U=(e,t,{allowDelta:n=!0}={})=>{if(le>=vr())return!1;le++,G=null;let i=n&&le===1?it(t,l):null,a=!!(i&&O);return ue=O?{ids:new Set(O.map(e=>e.eventId)),restart:le,reason:e,source:a?`inline-delta`:`full-reload`}:null,a?j=i:(O=null,A=null,F=void 0,I=void 0,L=!1,j=null,W.resetScan()),w.warn(`Event creation rejected as stale; restarting replay in-process`,{workflowRunId:l,reason:e,loopIteration:c,preconditionRestarts:le,source:a?`inline-delta`:`full-reload`}),r?.setAttributes({"workflow.precondition_restarts":le}),!0},pe=async(e,t)=>{let n=(g??0)+1,i=yr();return n>i?{reinvoked:!1,error:new q(`Event creation was rejected as stale after ${i} re-invocations of ${vr()} in-process replay restarts each: this run cannot observe its own event log completely enough to make progress. Last rejection (${e}): ${t instanceof Error?t.message:String(t)}`,{cause:t})}:(w.warn(`Event creation rejected as stale after in-process restarts; re-invoking run for a fresh replay`,{workflowRunId:l,reason:e,loopIteration:c,preconditionReinvocations:n,maxReinvocations:i}),r?.setAttributes({"workflow.precondition_reinvocations":n}),{reinvoked:!0,result:await ce(br(),{preconditionReinvocations:n})})},me=async(e,i,a)=>{let{outcome:o,spanAttributes:s}=await Er({world:t,run:e,requestId:x,retryCount:_,beforeStop:a,isDeploymentUnavailableError:t.isDeploymentUnavailableError,reenqueue:async({deploymentId:e,specVersion:r,deploymentMismatchRetryCount:a,delaySeconds:o})=>{await Re(t,ye(S,n),{...await i(),deploymentMismatchRetryCount:a},{deploymentId:e,specVersion:r,delaySeconds:o})}});return s&&r?.setAttributes(s),o};if(p&&m)try{let e=await t.runs.get(l,{resolveData:`none`});if(e.status!==`running`){w.debug(`Run already finished, skipping background step`,{workflowRunId:l,status:e.status});return}if(await me(e,async()=>({...await oe(),stepId:p,stepName:m}))!==`continue`)return;let r=e.startedAt?+e.startedAt:Date.now(),i=s.attempt,a=Jt(m)?.maxRetries??3;if(s.attempt>a+1){let e=await vt(l);O=e.events,A=e.cursor,i=Cr(O,p,{type:`totalAttempts`})+1}k.pause();let o;try{o=await fi(l,p,()=>oi({world:t,workflowRunId:l,workflowDeploymentId:e.deploymentId,workflowName:S,workflowStartedAt:r,rootRunId:So(e.attributes,l),stepId:p,stepName:m,runSpecVersion:e.specVersion,authoritativeAttempt:i}))}finally{k.resume()}if(o.type===`retry`||o.type===`throttled`)return{timeoutSeconds:o.timeoutSeconds};if(o.type===`completed`&&o.hasPendingOps){await Re(t,ye(S,n),{runId:l,traceCarrier:await D(),requestedAt:new Date});return}if(o.type===`completed`||o.type===`failed`||o.type===`skipped`){let n=await vt(l);O=n.events,A=n.cursor;let i=new Set,a=new Set;for(let e of O)e.eventType===`step_created`?i.add(e.correlationId):(e.eventType===`step_completed`||e.eventType===`step_failed`)&&a.add(e.correlationId);let o=new Set;for(let e of i)a.has(e)||o.add(e);if(o.size>0)if(hr()&&ui(O,o,s.messageId))w.debug(`Background step done; falling through to recover an inline step owned by this message`,{workflowRunId:l});else{w.debug(`Background step done but other steps pending, returning`,{workflowRunId:l});return}w.debug(`All parallel steps done, replaying inline after background step`,{workflowRunId:l});let c=O.find(e=>e.eventType===`run_created`),u;if(c)u=c.eventData.input;else{if(!bn(e.specVersion))throw new q(`Workflow run "${l}" has no "run_created" event`);let n=await t.runs.get(l,{resolveData:`all`});if(n.status!==`running`)return;u=n.input}M={...e,input:u,status:`running`,output:void 0,error:void 0,completedAt:void 0},P=r}else return}catch(e){let n=vo(e);if(!n)throw e;await yo({world:t,workflowRun:M,runId:l,requestId:x,err:e,errorCode:n,logMessage:`Fatal error while preparing background workflow step`});return}let he=!1;if(!M&&y&&y.resumeId!==void 0&&y.payloadDigest!==void 0){let e=y,t;try{t=new Date(dn(e.resumeId))}catch{t=void 0}try{r?.addEvent(`workflow.hook_received.create.start`,{"workflow.hook_received.preload_events":!0});let n=await T({eventType:`hook_received`,specVersion:5,correlationId:e.hookId,eventData:{token:e.token,payload:e.payload}},{requestId:x,occurredAt:t,resumeId:e.resumeId,resumePayloadDigest:e.payloadDigest,preloadEvents:!0});if(he=!0,n.run!==void 0&&n.run.startedAt!==void 0&&n.event!==void 0&&n.events!==void 0&&n.events.length>0&&n.cursor!=null&&n.hasMore===!1&&typeof n.maxEvents==`number`&&n.events.some(e=>e.eventType===`run_created`)&&n.events.some(e=>e.eventType===`run_started`)&&n.events.some(t=>t.eventType===`hook_received`&&t.resumeId===e.resumeId)&&n.run?.startedAt&&n.events){let e=n.events.find(e=>e.runId===l&&(e.eventType===`run_completed`||e.eventType===`run_failed`||e.eventType===`run_cancelled`));if(e){r?.setAttributes({...Ie(e.eventType===`run_completed`?`completed`:e.eventType===`run_failed`?`failed`:`cancelled`),...ve(`hook_received_stream`)}),w.info(`Run already finished during lazy hook setup, skipping`,{workflowRunId:l,eventType:e.eventType});return}M=n.run,N=ho(n.maxEvents),R=Date.now(),F=n.events,I=n.cursor,L=!0,P=+n.run.startedAt,r?.setAttributes({...Ie(n.run.status),..._e(P),...ve(`hook_received_stream`)})}else r?.setAttributes(ve(`hook_received_fallback`))}catch(e){if(Ut.is(e)||J.is(e)){w.info(`Run already finished during lazy hook setup, skipping`,{workflowRunId:l,message:e.message});return}throw e}}if(!M){let e={eventType:`run_started`,specVersion:v?.specVersion??5,...v?{eventData:{input:v.input,deploymentId:v.deploymentId,workflowName:v.workflowName,executionContext:v.executionContext,attributes:v.attributes,allowReservedAttributes:v.allowReservedAttributes}}:{}},n=e=>{r?.addEvent(`workflow.run_started.create.start`,{"workflow.run_started.skip_preload":e})};if(z&&v){n(!0);let t=T(e,{requestId:x,skipPreload:!0});V=t,t.then(e=>{let t=ho(e?.maxEvents);t!==void 0&&(N=t)},()=>{}),t.catch(()=>{}),F=[];let i=new Date;M={runId:l,status:`running`,deploymentId:v.deploymentId,workflowName:v.workflowName,specVersion:v.specVersion,executionContext:v.executionContext,input:v.input,attributes:v.attributes??{},startedAt:i,createdAt:i,updatedAt:i},P=+i,R=+i,r?.setAttributes({...Ie(`running`),..._e(P)})}else{try{n(!1);let t=await T(e,{requestId:x});if(!t.run)throw new q(`Event creation for 'run_started' did not return the run entity for run "${l}"`);if(M=t.run,N=ho(t.maxEvents),R=Date.now(),t.events&&t.events.length>0&&t.hasMore!==!0&&(F=t.events,I=t.cursor),!M.startedAt)throw new q(`Workflow run "${l}" has no "startedAt" timestamp`)}catch(e){if(Q.is(e)||J.is(e)){w.info(`Run already finished during setup, skipping`,{workflowRunId:l,message:e.message});return}else{let n=vo(e);if(!n)throw e;await yo({world:t,workflowRun:M,runId:l,requestId:x,err:e,errorCode:n,logMessage:`Fatal runtime error during workflow setup`});return}}if(P=+M.startedAt,r?.setAttributes({...Ie(M.status),..._e(P)}),M.status!==`running`){w.info(`Workflow already completed or failed, skipping`,{workflowRunId:l,status:M.status});return}}}if(await me(M,async()=>({...await oe(),...y?{hookInput:y}:{}}),ie)!==`continue`)return;if(y&&!he&&!(y.resumeId!==void 0&&F?.some(e=>e.eventType===`hook_received`&&e.resumeId===y.resumeId))){let e;try{e=y.resumeId===void 0?void 0:new Date(dn(y.resumeId))}catch{e=void 0}let n;try{let i=await t.events.create(l,{eventType:`hook_received`,specVersion:5,correlationId:y.hookId,eventData:{token:y.token,payload:y.payload}},{requestId:x,occurredAt:e,resumeId:y.resumeId,resumePayloadDigest:y.payloadDigest});r?.setAttributes(Le(!0));let a=i.event;n=a?{...a,eventData:{token:y.token,payload:y.payload}}:void 0}catch(e){if(Ut.is(e)||J.is(e))return;throw e}F&&n?Ce(F,n):(F=void 0,I=void 0,L=!1)}let ge=await Ee(t,M)(),W=new Zn(ge),G=null;for(;;){if(c++,k.isExhausted()){await Vr({runId:l,workflowName:S,requestId:x,attempt:s.attempt,limitMs:k.configuredLimitMs});return}if(Date.now()-i>=o){w.info(`V2 timeout reached, re-scheduling workflow`,{workflowRunId:l,loopIteration:c,elapsedMs:Date.now()-i}),await Re(t,ye(S,n),{runId:l,traceCarrier:await D(),requestedAt:new Date});return}let d=0,f=null;try{if(En(M)){w.debug(`Using QuickJS VM engine`,{workflowRunId:l,loopIteration:c}),await ie();let{runWorkflowWithQuickJS:t}=await import(`../../_chunks/workflow/_eve-core-quickjs-entrypoint-stub-qIV0OaFz.js`),i=await t({workflowCode:e,workflowName:S,workflowRun:M,preloadedEvents:F,preloadedEventsComplete:L,runInput:v,parentSpan:r,maxEventsLimit:N,namespace:n,nextTraceCarrier:D,deliveryAttempt:s.attempt,ownerMessageId:s.messageId});return i?.timeoutSeconds===void 0?void 0:await ce(i.timeoutSeconds)}let i;if(j&&O){let e=j;j=null,ct(O,e.events),A=e.cursor??A,i=O}else if(O===null)if(F)i=F,A=I??null;else{let e=await vt(l);i=e.events,A=e.cursor}else if(A){let e=await vt(l,A);ct(O,e.events),A=e.cursor??A,i=O}else if(F){w.debug(`No cursor after preloaded-events first iteration; doing full reload to pick up cursor.`,{workflowRunId:l});let e=await vt(l);O=e.events,A=e.cursor,i=O}else{w.warn(`Event cursor missing after initial load — falling back to full reload. This indicates a bug in the World implementation.`,{workflowRunId:l});let e=await vt(l);O=e.events,A=e.cursor,i=O}if(O=i,de(i),bo(i,l))return;let a=Date.now(),o=new Set(i.filter(e=>e.eventType===`wait_completed`).map(e=>e.correlationId)),p=i.filter(e=>e.eventType===`wait_created`&&e.correlationId!==void 0&&!o.has(e.correlationId)&&a>=e.eventData.resumeAt.getTime()).map(e=>({eventType:`wait_completed`,specVersion:5,correlationId:e.correlationId,eventData:{resumeAt:e.eventData.resumeAt}}));for(let e of p)try{await T(e,{requestId:x,...Xe(i,A)})}catch(t){if(Q.is(t)){w.info(`Wait already completed, skipping`,{workflowRunId:l,correlationId:e.correlationId});continue}throw t}if(p.length>0)if(A){let e=await vt(l,A),t=new Set(e.events.filter(e=>e.eventType===`wait_completed`).map(e=>e.correlationId));if(p.every(e=>t.has(e.correlationId)))ct(i,e.events),A=e.cursor??A;else{let e=await vt(l);i=e.events,A=e.cursor}}else{let e=await vt(l);i=e.events,A=e.cursor}if(bo(i,l))return;if(N!==void 0&&i.length>=N)throw new Wt(i.length,N);O=i,ee??=i.every(e=>e.eventType===`run_created`||e.eventType===`run_started`||e.eventType===`attr_set`),f=A,w.debug(`Starting workflow execution`,{workflowRunId:l,loopIteration:c,eventCount:i.length,executionMode:G?`retained`:`replay`}),d=Date.now();let m=W.prewarm(M,i),h=G?await uo(G,i):{type:`replay`};if(h.type===`replay`&&(G=null,h=await lo({workflowCode:e,workflowRun:M,events:i,encryptionKey:ge,replayPayloadCache:W,runReadyBarrier:V,worldCapabilities:t.capabilities})),await m,h.type===`suspended`)throw G=h.session,h.suspension;let g=h.output;w.debug(`Workflow execution completed`,{workflowRunId:l,loopIteration:c,replayMs:Date.now()-d,executionMode:G?`retained`:`replay`}),u.activate();try{await ie(),await T({eventType:`run_completed`,specVersion:5,eventData:{output:g}},{requestId:x,...Xe(i,A)})}catch(e){if(Q.is(e)||J.is(e)){w.info(`Tried completing workflow run, but run has already finished.`,{workflowRunId:l,message:e.message});return}throw e}r?.setAttributes({...Ie(`completed`)});return}catch(i){if(K.is(i)){u.activate();let e=Date.now()-d;w.debug(`Workflow suspended`,{workflowRunId:l,loopIteration:c,replayMs:e,steps:i.stepCount,hooks:i.hookCount,waits:i.waitCount});let o=se(i.stepCount,i.hookCount,i.waitCount);o&&w.debug(o);let p=Date.now();if(!O)throw Error(`Invariant violation: workflow suspended before its event log was loaded`);let m={events:O,cursor:A},h;try{h=await mi({suspension:i,world:t,run:M,span:r,requestId:x,eventLog:m,runReadyBarrier:V,replayRecoveryReporter:u})}catch(e){if(zt.is(e)){if(U(`suspension-create`,e))continue;let t=await pe(`suspension-create`,e);if(t.reinvoked)return t.result;throw t.error}if(!Y.is(e))throw e;let t=xt(e);w.error(`Non-retryable error while committing workflow suspension; failing run`,{workflowRunId:l,errorCode:t,errorName:e.name,errorMessage:e.message});try{await ie(),await T({eventType:`run_failed`,specVersion:5,eventData:{error:await Ct(e,l,ge,globalThis,(M?.specVersion??0)>=5),errorCode:t}},{requestId:x})}catch(e){if(Q.is(e)||J.is(e)){w.info(`Tried failing workflow run, but run has already finished.`,{workflowRunId:l,message:e.message});return}throw e}r?.setAttributes({...Ie(`failed`),...a(t),...ht(e.name),...ke(e.message),...Oe(e.name)});return}A=m.cursor;let g=O,_=Yt(()=>Co(g));if(G&&!wo(i,h.retainedStepInputsSafe,_)&&(G=null),te+=h.hookCreationMs,h.hasAttributeEvents&&ne===void 0&&(ne=te),w.debug(`Suspension handled`,{workflowRunId:l,suspensionMs:Date.now()-p,pendingSteps:h.pendingSteps.length,timeoutSeconds:h.waitTimeout?.seconds,hasHookConflict:h.hasHookConflict,hasAwaitedHookCreation:h.hasAwaitedHookCreation,hasAttributeEvents:h.hasAttributeEvents}),h.hasHookConflict)return await ce(0);if(h.hasAttributeEvents)continue;let v=h.pendingSteps,y=h.lazyInlineSteps,b=new Set(y.map(e=>e.correlationId)),C=await D(),E=[],N=hr(),F=Date.now(),I=[],L=0;for(let e of v){if(b.has(e.correlationId))continue;let r=N&&si(e);if(r&&e.ownerMessageId===s.messageId){I.push(e);continue}let i=r?ci(e,F):0;if(i>0){L++,w.debug(`Pending step is inline-owned by a live invocation; ensuring delayed backstop wake instead of immediate requeue`,{workflowRunId:l,stepId:e.correlationId,ownerMessageId:e.ownerMessageId,backstopDelaySeconds:i}),E.push(Re(t,ye(S,n),{runId:l,traceCarrier:C,requestedAt:new Date},{delaySeconds:i,idempotencyKey:li(e)}));continue}E.push(Re(t,ye(S,n),{runId:l,stepId:e.correlationId,stepName:e.stepName,traceCarrier:C,requestedAt:new Date},{idempotencyKey:e.correlationId}))}h.waitTimeout&&E.push(Re(t,ye(S,n),{runId:l,traceCarrier:C,requestedAt:new Date},vi(h.waitTimeout.seconds,h.waitTimeout.correlationId))),await Promise.all(E);let re=[...y.map(e=>({correlationId:e.correlationId,stepName:e.stepName,lazyStepInput:e.dehydratedInput})),...I.map(e=>({correlationId:e.correlationId,stepName:e.stepName}))];if((L>0||I.length>0)&&r?.setAttributes({...I.length>0?dt(I.length):{},...L>0?fe(L):{}}),I.length>0&&w.warn(`Re-executing inline steps owned by this queue message — a previous delivery crashed mid-body and this redelivery is recovering them`,{workflowRunId:l,stepIds:I.map(e=>e.correlationId)}),re.length===0)return h.hasAwaitedHookCreation?await ce(0):void 0;let B=_.value,H=qe()&&t.capabilities?.preconditionGuard===!0,oe=typeof f==`string`&&i.stepCount===1&&i.waitCount===0&&v.length===1&&y.length===1&&I.length===0&&!h.waitTimeout&&!B.openWait&&(H||i.hookCount===0&&!B.openHook),le=H&&(B.openHook||i.hookCount>0||h.hasHookEvents),ue=z&&!h.hasAttributeEvents&&!h.waitTimeout&&!h.hasHookEvents&&!h.hasAwaitedHookCreation&&!B.openHook&&!B.openWait,de=ri({events:O,invocationStartedClean:ee===!0,runCreatedAtMs:Wr(l)??(z?void 0:+M.createdAt),runStartedReceivedAtMs:R,replayMs:e,preStepBlockingMs:te,preStepBlockingBeforeAttrMs:ne,suspensionHasWaits:i.waitCount>0||h.waitTimeout!==void 0,suspensionCreatedHooks:i.hookCount>0||h.hasHookEvents,turbo:z}),me=Xe(O,f);k.pause();let he,_e=re.map((e,n)=>{let r=()=>oi({world:t,workflowRunId:l,workflowDeploymentId:M.deploymentId,workflowName:S,workflowStartedAt:P,rootRunId:So(M.attributes,l),stepId:e.correlationId,stepName:e.stepName,runSpecVersion:M.specVersion,authoritativeAttempt:e.lazyStepInput===void 0?Cr(O,e.correlationId,{type:`ownedBy`,messageId:s.messageId})+1:1,lazyStepInput:e.lazyStepInput,ownerMessageId:s.messageId,forceOptimisticStart:ue,suppressOptimisticStart:le,runReadyBarrier:V,preconditionSnapshot:me,...n===0&&e.lazyStepInput!==void 0&&de?{latencyTracking:de}:{},...oe&&f?{inlineDeltaSinceCursor:f}:{},replayRecoveryReporter:u});return ae.add(e.correlationId),(e.lazyStepInput===void 0?fi(l,e.correlationId,r):r()).finally(()=>ae.delete(e.correlationId))});try{he=await Promise.all(_e)}catch(e){if(zt.is(e)){if(U(`inline-claim`,e,{allowDelta:!(await Promise.allSettled(_e)).some(e=>e.status===`fulfilled`&&(e.value.type===`completed`||e.value.type===`failed`||e.value.type===`retry`))}))continue;let t=await pe(`inline-claim`,e);if(t.reinvoked)return t.result;throw t.error}throw e}finally{k.resume()}let ve=[],be=!1,W;for(let e=0;e<re.length;e++){let t=he[e],n=re[e];t.type===`retry`?ve.push({step:n,delaySeconds:t.timeoutSeconds}):t.type===`throttled`?W=Math.max(W??0,t.timeoutSeconds):t.type===`completed`&&t.hasPendingOps&&(be=!0)}if(W!==void 0)return await ce(W);if(ve.length>0){let e=await D();await Promise.all(ve.map(({step:r,delaySeconds:i})=>Re(t,ye(S,n),{runId:l,stepId:r.correlationId,stepName:r.stepName,traceCarrier:e,requestedAt:new Date},{delaySeconds:i,idempotencyKey:r.correlationId})))}if(be){w.debug(`Breaking loop: inline step has pending ops`,{workflowRunId:l,loopIteration:c}),await Re(t,ye(S,n),{runId:l,traceCarrier:await D(),requestedAt:new Date});return}if(ve.length>0)return;if(re.length===1){let e=he[0];e.type===`completed`&&e.inlineDelta&&!e.inlineDelta.hasMore&&(j={events:e.inlineDelta.events,cursor:e.inlineDelta.cursor})}}else{let o=i;if(zt.is(i)){if(U(`replay-write`,i))continue;let e=await pe(`replay-write`,i);if(e.reinvoked)return e.result;o=e.error}if(Dt(i))throw C.warn(`Transient world error during replay; redelivering via queue instead of failing the run`,{errorName:i instanceof Error?i.name:`UnknownError`,errorMessage:i instanceof Error?i.message:String(i),deliveryAttempt:s.attempt}),i;let c;if(Z.is(i)){let e=(h?.count??0)+1,r=_r();if(e<=r){C.warn(`Workflow replay diverged; queueing a recovery replay before declaring the event log corrupted`,{errorCode:X.REPLAY_DIVERGENCE,divergenceEventId:i.eventId,priorDivergenceEventId:h?.eventId,divergenceCount:e,deliveryAttempt:s.attempt,maxRecoveryReplays:r,errorMessage:i.message}),await Re(t,ye(S,n),{runId:l,traceCarrier:await D(),requestedAt:new Date,replayDivergence:{eventId:i.eventId,count:e}});return}c=e,o=new Gt(`Workflow replay diverged ${e} times after ${r} recovery replays; latest divergent event was ${i.eventId}. Last divergence: ${i.message}`,{cause:i})}else d>0&&u.activate();o instanceof Error&&r?.recordException?.(o);let f=await Zr(o),p=f.name||Gr(o),m=f.message,g=f.stack||Kr(o);if(g){let t=nt(S)?.moduleSpecifier||S;g=Sa(g,t,e)}let _=xt(o);w.error(`Error while running workflow`,{workflowRunId:l,errorCode:_,errorName:p,errorStack:g}),Rn.isNativeError(o)&&g&&(o.stack=g);try{await ie(),await T({eventType:`run_failed`,specVersion:5,eventData:{error:await Ct(o,l,ge,globalThis,(M?.specVersion??0)>=5),errorCode:_}},{requestId:x,...c===void 0?{}:{replayDivergenceCount:c}})}catch(e){if(Q.is(e)||J.is(e)){w.info(`Tried failing workflow run, but run has already finished.`,{workflowRunId:l,message:e.message});return}if(xe(e)){w.error(`Fatal world contract error while recording workflow failure`,{workflowRunId:l,errorCode:X.WORLD_CONTRACT_ERROR,error:e instanceof Error?e.message:String(e)});return}throw e}r?.setAttributes({...Ie(`failed`),...a(_),...ht(p),...ke(m),...Oe(p)});return}}}})}))}),s,c=0,l=Date.now(),u=typeof t?.routeModuleBodyStartedAt==`number`?l-t.routeModuleBodyStartedAt:void 0;return Fe(async e=>{c+=1;let t=s!==void 0;return W(`workflow.route.flow`,{kind:await je(`SERVER`),attributes:{...at(`flow`),...Pe(Qn),...yt(t),...De(c),...Je(Date.now()-l),...u===void 0?{}:Ne(u),...kt(e.method),...Et(`/.well-known/workflow/v1/flow`)}},async t=>{s||=await W(`workflow.route.init`,async()=>{let e=await W(`workflow.route.get_world_handlers`,async()=>Ir());return o(e)});let n=await s(e);return n instanceof Response&&t?.setAttributes(G(n.status)),n})})}export{Nn as Run,K as WorkflowSuspension,jn as cancelRun,Dn as cancelRuns,Fr as createWorld,Nr as createWorldFromModule,Cn as getHookByToken,kn as getRun,Lr as getWorld,Ir as getWorldHandlers,ut as healthCheck,wn as listStreams,An as readStream,Mn as recreateRunFromExisting,Tn as reenqueueRun,xn as resumeHook,Sn as resumeWebhook,Rr as setWorld,Pn as start,On as wakeUpRun,Eo as workflowEntrypoint};
@@ -0,0 +1,9 @@
1
+ /**
2
+ * VM-compatible devalue codec.
3
+ *
4
+ * Same as codec-devalue.ts but uses VM-compatible reducers/revivers
5
+ * (no Node.js Buffer, no node:util). Safe to bundle into the QuickJS VM.
6
+ */
7
+ import type { Codec } from './codec.js';
8
+ export declare const devalueVmCodec: Codec;
9
+ //# sourceMappingURL=codec-devalue-vm.d.ts.map
@@ -0,0 +1,20 @@
1
+ /**
2
+ * VM-compatible copy: identical semantics to class.ts before the host-side
3
+ * hardening (#3257) made that module depend on `serialization/hardened.ts`
4
+ * (which imports `node:util` and captures host intrinsics — meaningless
5
+ * and unbundleable inside the QuickJS VM, where the codec already runs in
6
+ * the guest realm). The host/guest boundary hardening for the QuickJS
7
+ * engine lands with the host-side serde (#3263), which retires this
8
+ * bundle entirely. Wire format is identical to the hardened host version.
9
+ */
10
+ /**
11
+ * Reducers and revivers for custom class serialization.
12
+ *
13
+ * Handles:
14
+ * - Class: class constructors with a `classId` property
15
+ * - Instance: instances of classes with custom WORKFLOW_SERIALIZE/DESERIALIZE methods
16
+ */
17
+ import type { Reducers, Revivers } from '../types.js';
18
+ export declare function getClassReducers(): Partial<Reducers>;
19
+ export declare function getClassRevivers(global?: Record<string, any>): Partial<Revivers>;
20
+ //# sourceMappingURL=class-vm.d.ts.map
@@ -0,0 +1,15 @@
1
+ /**
2
+ * VM-compatible common reducers and revivers.
3
+ *
4
+ * Identical to common.ts but without Node.js dependencies:
5
+ * - Uses native `btoa` / `atob` (provided by quickjs-wasi's base64
6
+ * extension, see `quickjs-assets.generated.ts`) instead of Buffer
7
+ * or pure-JS base64.
8
+ * - Uses `instanceof Error` instead of `types.isNativeError()`.
9
+ *
10
+ * This module is safe to bundle into the QuickJS WASM VM.
11
+ */
12
+ import type { Reducers, Revivers } from '../types.js';
13
+ export declare function getCommonReducers(): Partial<Reducers>;
14
+ export declare function getCommonRevivers(): Partial<Revivers>;
15
+ //# sourceMappingURL=common-vm.d.ts.map