eve 0.52.4 → 0.53.0

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 (149) hide show
  1. package/CHANGELOG.md +28 -0
  2. package/dist/src/cli/commands/init-agent-workspace.d.ts +2 -0
  3. package/dist/src/cli/commands/init-agent-workspace.js +1 -1
  4. package/dist/src/cli/commands/init-install.d.ts +8 -0
  5. package/dist/src/cli/commands/init-install.js +1 -0
  6. package/dist/src/cli/commands/init.d.ts +3 -4
  7. package/dist/src/cli/commands/init.js +1 -1
  8. package/dist/src/cli/dev/tui/message-queue.js +1 -1
  9. package/dist/src/cli/dev/tui/terminal-renderer.js +12 -12
  10. package/dist/src/cli/run.js +2 -2
  11. package/dist/src/cli/telemetry/index.d.ts +3 -0
  12. package/dist/src/cli/telemetry/index.js +1 -1
  13. package/dist/src/compiled/.vendor-stamp.json +17 -16
  14. package/dist/src/compiled/@ai-sdk/anthropic/index.d.ts +23 -2
  15. package/dist/src/compiled/@ai-sdk/anthropic/index.js +2 -4
  16. package/dist/src/compiled/@ai-sdk/google/index.d.ts +145 -33
  17. package/dist/src/compiled/@ai-sdk/google/index.js +10 -7
  18. package/dist/src/compiled/@ai-sdk/mcp/index.d.ts +176 -7
  19. package/dist/src/compiled/@ai-sdk/mcp/index.js +1 -1
  20. package/dist/src/compiled/@ai-sdk/openai/index.d.ts +71 -40
  21. package/dist/src/compiled/@ai-sdk/openai/index.js +8 -8
  22. package/dist/src/compiled/@ai-sdk/otel/index.js +1 -1
  23. package/dist/src/compiled/@ai-sdk/provider/index.d.ts +225 -3
  24. package/dist/src/compiled/@ai-sdk/provider-utils/index.d.ts +220 -151
  25. package/dist/src/compiled/@workflow/core/create-hook.d.ts +3 -0
  26. package/dist/src/compiled/@workflow/core/index.js +2 -2
  27. package/dist/src/compiled/@workflow/core/private.js +1 -1
  28. package/dist/src/compiled/@workflow/core/runtime/resume-hook.d.ts +59 -7
  29. package/dist/src/compiled/@workflow/core/runtime/run.d.ts +42 -0
  30. package/dist/src/compiled/@workflow/core/runtime/start.d.ts +31 -1
  31. package/dist/src/compiled/@workflow/core/runtime.d.ts +2 -2
  32. package/dist/src/compiled/@workflow/core/runtime.js +2 -2
  33. package/dist/src/compiled/@workflow/core/serialization.d.ts +22 -0
  34. package/dist/src/compiled/@workflow/core/version.d.ts +1 -1
  35. package/dist/src/compiled/@workflow/core/workflow.js +1 -1
  36. package/dist/src/compiled/@workflow/errors/index.d.ts +37 -3
  37. package/dist/src/compiled/@workflow/errors/index.js +1 -1
  38. package/dist/src/compiled/@workflow/world/attributes-validation.d.ts +68 -0
  39. package/dist/src/compiled/@workflow/world/index.d.ts +1 -1
  40. package/dist/src/compiled/@workflow/world/interfaces.d.ts +21 -0
  41. package/dist/src/compiled/@workflow/world-local/index.js +5 -5
  42. package/dist/src/compiled/@workflow/world-vercel/index.js +3 -3
  43. package/dist/src/compiled/_chunks/workflow/attribute-changes-C6H-fRVP.js +20 -0
  44. package/dist/src/compiled/_chunks/workflow/dist-DDeH-1ER.js +40 -0
  45. package/dist/src/compiled/_chunks/workflow/dist-DhncQSl7.js +74 -0
  46. package/dist/src/compiled/_chunks/workflow/{dist-BIO9Inoc.js → dist-xTushGCp.js} +1 -1
  47. package/dist/src/compiled/_chunks/workflow/frames-DsEqSDes.js +3 -0
  48. package/dist/src/compiled/_chunks/workflow/{private-aXEeo0fU.js → private-CFJkQA7R.js} +1 -1
  49. package/dist/src/compiled/_chunks/workflow/resume-hook-BRDLAb67.js +1 -0
  50. package/dist/src/compiled/_chunks/workflow/run-BM2OFphk.js +1 -0
  51. package/dist/src/compiled/_chunks/workflow/sleep-6cG0F99-.js +1 -0
  52. package/dist/src/compiled/_chunks/workflow/{ws-transport-M7uk8HV8.js → ws-transport-DuK82LLz.js} +1 -1
  53. package/dist/src/compiler/extension-compatibility.d.ts +7 -6
  54. package/dist/src/compiler/extension-compatibility.js +1 -1
  55. package/dist/src/compiler/manifest.js +1 -1
  56. package/dist/src/compiler/normalize-agent-config.js +1 -1
  57. package/dist/src/compiler/normalize-manifest-helpers.js +1 -1
  58. package/dist/src/context/dynamic-model-lifecycle.js +1 -1
  59. package/dist/src/context/keys.d.ts +11 -2
  60. package/dist/src/context/keys.js +1 -1
  61. package/dist/src/evals/mock-model.js +1 -1
  62. package/dist/src/evals/runner/run-evals.d.ts +1 -1
  63. package/dist/src/evals/runner/run-evals.js +1 -1
  64. package/dist/src/execution/activity-cohort.d.ts +20 -0
  65. package/dist/src/execution/activity-cohort.js +1 -0
  66. package/dist/src/execution/authorization-callback-match.d.ts +1 -0
  67. package/dist/src/execution/authorization-callback-match.js +1 -1
  68. package/dist/src/execution/cancelled-model-call-batch.d.ts +15 -0
  69. package/dist/src/execution/cancelled-model-call-batch.js +1 -0
  70. package/dist/src/execution/coordination-dispatch-shared.js +1 -1
  71. package/dist/src/execution/model-call-batching.d.ts +11 -0
  72. package/dist/src/execution/model-call-batching.js +1 -0
  73. package/dist/src/execution/parked-delivery-wait.js +1 -1
  74. package/dist/src/execution/session-activity-projection.d.ts +2 -0
  75. package/dist/src/execution/session-activity-projection.js +1 -1
  76. package/dist/src/execution/skills/instructions.js +1 -1
  77. package/dist/src/execution/tools/sleep-workflow.js +1 -1
  78. package/dist/src/execution/tools/subagent/invoke-agent.d.ts +5 -5
  79. package/dist/src/execution/tools/subagent/invoke-agent.js +1 -1
  80. package/dist/src/execution/tools/subagent/start.js +1 -1
  81. package/dist/src/execution/tools/workflow/body.js +1 -1
  82. package/dist/src/execution/turn-workflow.js +1 -1
  83. package/dist/src/execution/wire/session-inbox-resume.js +1 -1
  84. package/dist/src/execution/workflow-steps.d.ts +1 -1
  85. package/dist/src/execution/workflow-steps.js +1 -1
  86. package/dist/src/harness/approval-delivery-coordinator.js +1 -1
  87. package/dist/src/harness/authorization.d.ts +1 -0
  88. package/dist/src/harness/authorization.js +1 -1
  89. package/dist/src/harness/compaction.js +1 -1
  90. package/dist/src/harness/current-messages.d.ts +8 -2
  91. package/dist/src/harness/current-messages.js +1 -1
  92. package/dist/src/harness/hitl/approval-input-requests.js +1 -1
  93. package/dist/src/harness/input-requests.js +1 -1
  94. package/dist/src/harness/pending-input-batches.d.ts +4 -0
  95. package/dist/src/harness/pending-input-batches.js +1 -1
  96. package/dist/src/harness/tool-loop.js +2 -2
  97. package/dist/src/harness/turn-client-context.d.ts +1 -1
  98. package/dist/src/internal/application/package.js +1 -1
  99. package/dist/src/internal/authored-definition/core.js +1 -1
  100. package/dist/src/internal/authored-package-boundary.js +1 -1
  101. package/dist/src/internal/mock-model-identity.d.ts +2 -0
  102. package/dist/src/internal/mock-model-identity.js +1 -0
  103. package/dist/src/internal/nitro/routes/agent-info/build-agent-info-response.js +1 -1
  104. package/dist/src/internal/workflow-bundle/authored-workflow-directives.js +1 -1
  105. package/dist/src/public/tools/index.d.ts +1 -0
  106. package/dist/src/public/tools/index.js +1 -1
  107. package/dist/src/runtime/resolve-agent.js +1 -1
  108. package/dist/src/self-modification/agent.d.ts +2 -2
  109. package/dist/src/self-modification/agent.js +1 -1
  110. package/dist/src/self-modification/config.d.ts +15 -0
  111. package/dist/src/self-modification/config.js +1 -1
  112. package/dist/src/self-modification/extension/extension.d.ts +3 -0
  113. package/dist/src/self-modification/extension/extension.js +1 -1
  114. package/dist/src/self-modification/setup.d.ts +3 -0
  115. package/dist/src/self-modification/setup.js +25 -4
  116. package/dist/src/setup/integrations/self-modification/setup.js +1 -1
  117. package/dist/src/setup/scaffold/create/add-to-project.js +1 -1
  118. package/dist/src/setup/scaffold/create/project.js +2 -2
  119. package/dist/src/setup/scaffold/update/web-options.js +1 -1
  120. package/dist/src/shared/agent-definition.d.ts +11 -2
  121. package/dist/src/tasks/delivery-context.d.ts +2 -2
  122. package/dist/src/tasks/delivery-context.js +2 -18
  123. package/dist/src/tasks/delivery-policy.js +1 -1
  124. package/dist/src/tools/durable-callbacks.d.ts +18 -1
  125. package/dist/src/tools/durable-callbacks.js +1 -1
  126. package/dist/src/tools/workflow-definition.d.ts +38 -4
  127. package/docs/agent-config.md +44 -8
  128. package/docs/channels/overview.mdx +2 -0
  129. package/docs/channels/slack.mdx +2 -0
  130. package/docs/concepts/execution-model-and-durability.mdx +20 -2
  131. package/docs/evals/running.mdx +3 -1
  132. package/docs/guides/dev-tui.md +11 -11
  133. package/docs/guides/dynamic-capabilities.md +36 -1
  134. package/docs/guides/instrumentation.md +3 -2
  135. package/docs/instructions.mdx +1 -1
  136. package/docs/reference/cli.md +1 -1
  137. package/docs/reference/telemetry.md +1 -1
  138. package/docs/reference/typescript-api.md +36 -35
  139. package/docs/subagents/index.mdx +1 -1
  140. package/docs/tools/overview.mdx +4 -2
  141. package/docs/tools/workflows.mdx +15 -10
  142. package/package.json +17 -17
  143. package/dist/src/compiled/_chunks/workflow/attribute-changes-DpruylJZ.js +0 -20
  144. package/dist/src/compiled/_chunks/workflow/dist-ChzQSWQA.js +0 -65
  145. package/dist/src/compiled/_chunks/workflow/dist-veFIAdWV.js +0 -40
  146. package/dist/src/compiled/_chunks/workflow/frames-DKxlMf3X.js +0 -3
  147. package/dist/src/compiled/_chunks/workflow/resume-hook-DWDi_wCN.js +0 -1
  148. package/dist/src/compiled/_chunks/workflow/run-vsAdI41O.js +0 -1
  149. package/dist/src/compiled/_chunks/workflow/sleep-BKxoNDRv.js +0 -1
@@ -1,5 +1,5 @@
1
- import{i as e,t}from"../../_chunks/workflow/rolldown-runtime-DPpTSio4.js";import{t as n}from"../../_chunks/workflow/debug-log-CVPstO1D.js";import{C as r,Di as i,E as a,Fr as o,G as s,Il as c,J as l,Jr as u,L as d,Ln as f,O as p,Q as m,R as h,U as g,W as _,X as v,Y as y,Z as b,_ as x,a as S,at as C,c as ee,ct as te,d as ne,dt as re,f as ie,ft as ae,k as w,l as oe,lt as se,m as ce,n as le,o as ue,q as de,r as fe,u as pe,v as T,x as me,y as E,z as he}from"../../_chunks/workflow/dist-veFIAdWV.js";import{A as D,O as ge,d as O,f as _e,o as k,r as A,y as ve}from"../../_chunks/workflow/dist-BIO9Inoc.js";import{i as ye,n as j,r as M,t as N}from"../../_chunks/workflow/workflow-routes-CwqB063q.js";import{a as P,i as F,n as be,r as xe,t as Se}from"../../_chunks/workflow/signal-exit-Dsy-TT0V.js";import{createHash as I}from"node:crypto";import{promisify as Ce}from"node:util";import{fileURLToPath as we}from"node:url";import{promises as L}from"node:fs";import R,{access as Te,constants as z,mkdir as Ee,readFile as De,readdir as Oe,readlink as ke,rm as Ae,unlink as je,writeFile as Me}from"node:fs/promises";import B from"node:path";import{tmpdir as Ne}from"node:os";import{execFile as Pe}from"node:child_process";import{setTimeout as Fe}from"node:timers/promises";import Ie from"node:assert";import{EventEmitter as Le}from"node:events";var Re=class extends D{dataDir;constructor(e,t){super(`[workflow] The local (filesystem) world cannot create its data directory "${e}" (${t}). Workflow runs cannot be stored, so every run will fail before its first step. If this is a Vercel deployment, its filesystem is read-only and the local world cannot work there. The world is selected from the environment when the process starts: the Vercel world is used when VERCEL_DEPLOYMENT_ID is set, unless WORKFLOW_TARGET_WORLD says otherwise. Unset WORKFLOW_TARGET_WORLD in this deployment, or set WORKFLOW_TARGET_WORLD=vercel, to use the Vercel world. Otherwise point WORKFLOW_LOCAL_DATA_DIR at a writable directory.`,{code:t}),this.name=`UnwritableDataDirError`,this.dataDir=e}static is(e){return e instanceof Error&&e.name===`UnwritableDataDirError`}};const ze=new Set([`EROFS`,`EACCES`,`EPERM`]);function Be(e){return e!==void 0&&ze.has(e)}const Ve=c(`@workflow/world-local//buildTargetWarnings`,1,()=>({warnedAboutVercelDeployment:!1}));function He(e){if(Ve.warnedAboutVercelDeployment||!process.env.VERCEL_DEPLOYMENT_ID)return;let t=B.resolve(e),n=Ne();t===n||t.startsWith(`${n}${B.sep}`)||(Ve.warnedAboutVercelDeployment=!0,console.warn(`[workflow] Warning: the local (filesystem) world is running inside a Vercel deployment, writing to ${t}. That filesystem is read-only, so workflow runs will fail before their first step. The world is selected from the environment when the process starts: the Vercel world is used when VERCEL_DEPLOYMENT_ID is set, unless WORKFLOW_TARGET_WORLD says otherwise. Unset WORKFLOW_TARGET_WORLD in this deployment, or set WORKFLOW_TARGET_WORLD=vercel, to use the Vercel world.`))}function Ue(e,t=10){let n=parseInt(e,t);if(!Number.isNaN(n)&&n>=0&&n<=65535)return n}function We(e,t){let n=[],r=e.trim().split(`
2
- `);for(let e of r){let r=e.trim().split(/\s+/);if(r.length<5||r[0]?.toUpperCase()!==`TCP`)continue;let[,i,,a,o]=r;if(a?.toUpperCase()!==`LISTENING`||o!==t.toString())continue;let s=i.lastIndexOf(`:`);if(s===-1)continue;let c=Ue(i.slice(s+1));c!==void 0&&n.push(c)}return n}const Ge=Ce(Pe);function Ke(e,t=10){let n=parseInt(e,t);if(!Number.isNaN(n)&&n>=0&&n<=65535)return n}const qe=((e,t)=>e.join(t))([``,`proc`],`/`);async function Je(e){let t=[`${qe}/net/tcp`,`${qe}/net/tcp6`],n=[],r=new Set,i=`${qe}/${e}/fd`;try{let e=(await Oe(i)).sort((e,t)=>Number.parseInt(e,10)-Number.parseInt(t,10)),t=await Promise.allSettled(e.map(async e=>(await ke(`${i}/${e}`)).match(/^socket:\[(\d+)\]$/)?.[1]??null));for(let e of t)e.status===`fulfilled`&&e.value&&(n.push(e.value),r.add(e.value))}catch{return[]}if(n.length===0)return[];let a=new Map;for(let e of t)try{let t=(await De(e,`utf8`)).split(`
3
- `).slice(1);for(let e of t){if(!e.trim())continue;let t=e.trim().split(/\s+/);if(t.length<10)continue;let n=t[1],i=t[3],o=t[9];if(!n||i!==`0A`||!o||!r.has(o))continue;let s=n.indexOf(`:`);if(s===-1)continue;let c=n.slice(s+1);if(!c)continue;let l=Ke(c,16);l!==void 0&&a.set(o,l)}}catch{}let o=[];for(let e of n){let t=a.get(e);t!==void 0&&o.push(t)}return o}async function Ye(e){try{let{stdout:t}=await Ge(`lsof`,[`-a`,`-i`,`-P`,`-n`,`-p`,e.toString()]),n=[],r=t.split(`
4
- `);for(let e of r)if(e.includes(`LISTEN`)){let t=e.trim().split(/\s+/)[8];if(t){let e=t.lastIndexOf(`:`);if(e!==-1){let r=Ke(t.slice(e+1));r!==void 0&&n.push(r)}}}return n}catch{return[]}}async function Xe(e){try{let{stdout:t}=await Ge(`cmd`,[`/c`,`netstat -ano -p tcp | findstr LISTENING`]);return We(t,e)}catch{return[]}}async function Ze(){let{pid:e,platform:t}=process;try{switch(t){case`linux`:return await Je(e);case`darwin`:return await Ye(e);case`win32`:return await Xe(e);default:return[]}}catch(e){return n(`[getAllPorts] Detection failed:`,e),[]}}const Qe=`${N}/flow?__health`;async function $e(e,t={}){let{endpoint:n=Qe,timeout:r=500}=t,i=new AbortController,a=setTimeout(()=>i.abort(),r);try{return(await fetch(`http://localhost:${e}${n}`,{method:`HEAD`,signal:i.signal})).status===200}catch{return!1}finally{clearTimeout(a)}}async function et(e){let t=await Ze();if(t.length===0)return;if(t.length===1)return t[0];let r=(await Promise.all(t.map(async t=>({port:t,isWorkflow:await $e(t,e)})))).find(e=>e.isWorkflow);return r?r.port:(n(`[getWorkflowPort] Probing failed, falling back to first port:`,t[0]),t[0])}function tt(e){let t={get value(){let n=e();return Object.defineProperty(t,"value",{value:n}),n}};return t}const nt=()=>process.env.WORKFLOW_LOCAL_DATA_DIR||`.workflow-data`,rt=()=>process.env.WORKFLOW_LOCAL_BASE_URL,it=tt(()=>({dataDir:nt(),baseUrl:rt()}));function at(e){if(e.recoverActiveRuns!==void 0)return e.recoverActiveRuns;let t=process.env.WORKFLOW_LOCAL_RECOVER_ACTIVE_RUNS?.toLowerCase();return t!==`0`&&t!==`false`}function ot(e){return e.baseUrl??process.env.WORKFLOW_LOCAL_BASE_URL??j(`http://localhost`)}async function st(e){if(e.baseUrl)return e.baseUrl;if(process.env.WORKFLOW_LOCAL_BASE_URL)return process.env.WORKFLOW_LOCAL_BASE_URL;if(typeof e.port==`number`)return j(`http://localhost:${e.port}`);if(process.env.PORT)return j(`http://localhost:${process.env.PORT}`);let t=await et({endpoint:M()});if(t)return j(`http://localhost:${t}`);throw Error(`Unable to resolve base URL for workflow queue.`)}const V=c(`@workflow/world-local//fs`,1,()=>({ulid:ue(()=>Math.random()),createdFilesCache:new Set,createdDirectoriesCache:new Set}));function ct(e){let t=typeof e==`string`?e:String(e);return t.length>48?`${t.slice(0,48)}…`:t}var lt=class extends D{constructor(e,t){super(`Unsafe ${e} "${ct(t)}": must not be empty, contain ".", "/", "\\", or null bytes`),this.name=`UnsafeEntityIdError`}static is(e){return e instanceof Error&&e.name===`UnsafeEntityIdError`}};function H(e,t){if(t.length===0||t.startsWith(`.`)||t.includes(`/`)||t.includes(`\\`)||t.includes(`\0`)||t.includes(`.`))throw new lt(e,t)}function U(e,...t){let n=B.resolve(e),r=B.resolve(e,...t);if(r!==n&&!r.startsWith(n+B.sep))throw new lt(`path`,t.join(`/`));return r}const ut=process.platform===`win32`;async function W(e,t=5){if(!ut)return e();let n=[`EPERM`,`EBUSY`,`EACCES`];for(let r=0;r<=t;r++)try{return await e()}catch(e){if(!(r<t&&n.includes(e.code)))throw e;let i=10*2**r+Math.random()*10;await new Promise(e=>setTimeout(e,i))}throw Error(`Retry loop exited unexpectedly`)}function dt(){V.createdFilesCache.clear(),V.createdDirectoriesCache.clear()}const ft=/\.[a-zA-Z][a-zA-Z0-9-]*$/;function G(e){return e.replace(ft,``)}function pt(e,t){return e.endsWith(`.${t}`)}function mt(e){return!ft.test(e)}function K(e,t,n,r){return H(`fileId`,n),r!==void 0&&H(`tag`,r),U(e,t,r?`${n}.${r}.json`:`${n}.json`)}async function q(e,t,n,r,i){if(H(`fileId`,n),i!==void 0&&H(`tag`,i),i){let a=await X(U(e,t,`${n}.${i}.json`),r);if(a!==null)return a}return X(U(e,t,`${n}.json`),r)}async function ht(e,t){let n=`.${t}.json`;try{return(await L.readdir(e)).filter(e=>e.endsWith(n))}catch(e){if(e.code===`ENOENT`)return[];throw e}}async function gt(e,t,n){let r=`.${t}${n}`;try{return(await L.readdir(e)).filter(e=>e.endsWith(r))}catch(e){if(e.code===`ENOENT`)return[];throw e}}async function _t(e){let t=B.resolve(e);if(!V.createdDirectoriesCache.has(t))try{await L.mkdir(t,{recursive:!0}),V.createdDirectoriesCache.add(t)}catch(e){let n=e.code;if(Be(n)&&!await vt(t))throw new Re(t,n)}}async function vt(e){try{return(await L.stat(e)).isDirectory()}catch{return!1}}async function yt(e,t){await _t(e);try{return await t()}catch(n){if(n.code!==`ENOENT`)throw n;return V.createdDirectoriesCache.delete(B.resolve(e)),await _t(e),t()}}function J(e,t){return t instanceof Uint8Array?{__type:`Uint8Array`,data:Buffer.from(t).toString(`base64`)}:t}function bt(e,t){return typeof t==`object`&&t&&t.__type===`Uint8Array`&&typeof t.data==`string`?new Uint8Array(Buffer.from(t.data,`base64`)):t}async function Y(e,t,n){return xt(e,JSON.stringify(t,J,2),n)}async function xt(e,t,n){if(!n?.overwrite){if(V.createdFilesCache.has(e))throw new A(`File ${e} already exists and 'overwrite' is false`);try{throw await L.access(e),V.createdFilesCache.add(e),new A(`File ${e} already exists and 'overwrite' is false`)}catch(e){if(e.code!==`ENOENT`)throw e}}let r=`${e}.tmp.${V.ulid()}`,i=!1;try{await yt(B.dirname(e),async()=>{await L.writeFile(r,t),i=!0,await W(()=>L.rename(r,e))}),V.createdFilesCache.add(e)}catch(e){throw i&&await W(()=>L.unlink(r),3).catch(()=>{}),e}}async function X(e,t){try{let n=await L.readFile(e,`utf-8`);return t.parse(JSON.parse(n,bt))}catch(e){if(e.code===`ENOENT`)return null;throw e}}async function St(e){return await L.readFile(e)}async function Ct(e){let t=await L.open(e,`r`);try{let e=Buffer.allocUnsafe(1),{bytesRead:n}=await t.read(e,0,1,0);return n===0?void 0:e[0]}finally{await t.close()}}async function Z(e){try{await W(()=>L.unlink(e))}catch(e){if(e.code!==`ENOENT`)throw e}}async function Q(e,t){let n=`${e}.tmp.${V.ulid()}`,r=!1;try{return await yt(B.dirname(e),async()=>{await L.writeFile(n,t,{flag:`wx`}),r=!0;try{return await W(()=>L.link(n,e)),!0}catch(e){if(e.code===`EEXIST`)return!1;throw e}})}finally{r&&await W(()=>L.unlink(n),3).catch(()=>{})}}async function wt(e,t){try{return await yt(B.dirname(t),()=>W(()=>L.link(e,t))),`linked`}catch(e){if(e.code===`EEXIST`)return`exists`;if(e.code===`ENOENT`)return`missing`;throw e}}async function Tt(e){return Et(e,`.json`)}async function Et(e,t){try{return(await L.readdir(e)).filter(e=>e.endsWith(t)).map(e=>e.slice(0,-t.length))}catch(e){if(e.code===`ENOENT`)return[];throw e}}const Dt=`key:`;function Ot(e){if(!e)return null;if(e.startsWith(`key:`))return{timestamp:new Date(0),id:null,sortKey:e.slice(4)};let t=e.split(`|`);return{timestamp:new Date(t[0]),id:t[1]||null,sortKey:null}}function kt(e,t,n){return n?`${Dt}${n}`:t?`${e.toISOString()}|${t}`:e.toISOString()}async function At(e){let{directory:t,schema:n,cachedItems:r,filePrefix:a,fileIdFilter:o,filter:s,sortOrder:c=`desc`,limit:l=20,cursor:u,getCreatedAt:d,getId:f,getSortKey:p,getSortKeyFromFileId:m}=e;a!==void 0&&H(`filePrefix`,a);let h=B.resolve(t),g=await Tt(h),_=a?g.filter(e=>e.startsWith(a)):g,v=o?_.filter(o):_,y=Ot(u),b=v;if(y?.sortKey&&m){let e=y.sortKey;b=v.filter(t=>{let n=m(t);if(n===null)return!0;let r=n.localeCompare(e);return c===`desc`?r<0:r>0})}else y&&!y.sortKey&&(b=v.filter(e=>{let t=d(`${e}.json`);if(t){let e=y.timestamp.getTime(),n=t.getTime();return y.id?c===`desc`?n<=e:n>=e:c===`desc`?n<e:n>e}return!0}));let x=[];for(let e=0;e<b.length;e+=32){let t=b.slice(e,e+32),a=await Promise.all(t.map(async e=>{let t=B.join(h,`${e}.json`),a;try{let e=r?.get(t);a=e===void 0?await X(t,n):structuredClone(e)}catch(t){if(t instanceof i)return console.warn(`Skipping item ${e} due to malformed JSON: ${t.message}`),null;throw t}return a&&s&&!await s(a)?null:a}));for(let e of a){if(!e)continue;let t=p?.(e)??null;if(y?.sortKey){if(t){let e=t.localeCompare(y.sortKey);if(c===`desc`?e>=0:e<=0)continue}x.push(e);continue}if(y){let t=e.createdAt.getTime(),n=y.timestamp.getTime();if(c===`desc`){if(t>n||t===n&&y.id&&f&&f(e)>=y.id)continue}else if(t<n||t===n&&y.id&&f&&f(e)<=y.id)continue}x.push(e)}}x.sort((e,t)=>{if(p){let n=p(e),r=p(t);if(n!==null&&r!==null)return c===`asc`?n.localeCompare(r):r.localeCompare(n)}let n=e.createdAt.getTime(),r=t.createdAt.getTime(),i=c===`asc`?n-r:r-n;if(i===0&&f){let n=f(e),r=f(t);return c===`asc`?n.localeCompare(r):r.localeCompare(n)}return i});let S=x.length>l,C=S?x.slice(0,l):x;return{data:C,cursor:C.length>0?kt(C[C.length-1].createdAt,f?.(C[C.length-1]),p?.(C[C.length-1])):null,hasMore:S}}const jt=c(`@workflow/world-local//packageInfo`,1,()=>({cached:null}));function Mt(){return typeof import.meta.url==`string`&&import.meta.url?B.dirname(we(import.meta.url)):null}async function Nt(){if(jt.cached)return jt.cached;let e=Mt();if(e)try{let t=await De(B.join(e,`../package.json`),`utf-8`);return jt.cached=JSON.parse(t),jt.cached}catch{}return jt.cached={name:`@workflow/world-local`,version:`5.0.0-beta.42`},jt.cached}const Pt=`version.txt`;var Ft=class extends Error{dataDir;code;constructor(e,t,n){super(e),this.name=`DataDirAccessError`,this.dataDir=t,this.code=n}},It=class extends Error{oldVersion;newVersion;suggestedVersion;constructor(e,t,n,r){super(e),this.name=`DataDirVersionError`,this.oldVersion=t,this.newVersion=n,this.suggestedVersion=r}};function Lt(e){let t=e.match(/^(\d+)\.(\d+)\.(\d+)(?:-(.+))?$/);if(!t)throw Error(`Invalid version string: "${e}"`);return{major:parseInt(t[1],10),minor:parseInt(t[2],10),patch:parseInt(t[3],10),prerelease:t[4],raw:e}}function $(e){let t=`${e.major}.${e.minor}.${e.patch}`;return e.prerelease?`${t}-${e.prerelease}`:t}function Rt(e){let t=e.trim(),n=t.lastIndexOf(`@`);if(n<=0)throw Error(`Invalid version file content: "${e}"`);return{packageName:t.substring(0,n),version:Lt(t.substring(n+1))}}function zt(e,t){return`${e}@${$(t)}`}function Bt(e,t){console.log(`[world-local] Upgrading from version ${$(e)} to ${$(t)}`)}async function Vt(e){let t=B.resolve(e);try{await Ee(t,{recursive:!0})}catch(e){let n=e;if(n.code!==`EEXIST`)throw new Ft(`Failed to create data directory "${t}": ${n.message}`,t,n.code)}try{await Te(t,z.R_OK)}catch(e){let n=e;throw new Ft(`Data directory "${t}" is not readable: ${n.message}`,t,n.code)}let n=B.join(t,`.workflow-write-test-${Date.now()}`);try{await Me(n,``),await je(n).catch(e=>{if(e.code!==`ENOENT`)throw e})}catch(e){let n=e;throw new Ft(`Data directory "${t}" is not writable: ${n.message}`,t,n.code)}}async function Ht(e){let t=B.join(B.resolve(e),Pt);try{return Rt(await De(t,`utf-8`))}catch(e){if(e.code===`ENOENT`)return null;throw e}}async function Ut(e,t){let n=B.join(B.resolve(e),Pt),r=zt((await Nt()).name,t);await Me(n,r)}function Wt(e,t){return t||$(e)}async function Gt(e){await Vt(e);let t=await Nt(),n=Lt(t.version),r=await Ht(e);if(r===null){await Ut(e,n);return}let{version:i}=r;if($(i)!==$(n))try{Bt(i,n),await Ut(e,n)}catch(e){let r=Wt(i,e instanceof It?e.suggestedVersion:void 0);throw console.error(`[world-local] Failed to upgrade data directory from version ${$(i)} to ${$(n)}:`,e instanceof Error?e.message:e),console.error(`[world-local] Data is not compatible with the current version. Please downgrade to ${t.name}@${r}`),e}}const Kt=c(`@workflow/world-local//telemetry`,1,()=>({apiPromise:null,tracerPromise:null}));async function qt(){return Kt.apiPromise||=import(`../../@opentelemetry/api/index.js`).catch(()=>null),Kt.apiPromise}async function Jt(){return Kt.tracerPromise||=qt().then(e=>e?e.trace.getTracer(`workflow`):null),Kt.tracerPromise}async function Yt(e,...t){let[n,r]=await Promise.all([Jt(),qt()]),{fn:i,opts:a}=typeof t[0]==`function`?{fn:t[0],opts:{}}:{fn:t[1],opts:t[0]};if(!i)throw Error(`Function to trace must be provided`);return!n||!r?await i():n.startActiveSpan(e,a,async e=>{try{let t=await i(e);return e.setStatus({code:r.SpanStatusCode.OK}),t}catch(t){throw e.setStatus({code:r.SpanStatusCode.ERROR,message:t.message}),t}finally{e.end()}})}async function Xt(e){let t=await qt();if(t)return t.SpanKind[e]}function Zt(...e){return t=>Object.fromEntries(e.map(e=>[e,t]))}const Qt=Zt(`peer.service`),$t=Zt(`rpc.system`),en=Zt(`rpc.service`),tn=Zt(`rpc.method`),nn=Zt(`workflow.run.id`),rn=Zt(`step.id`),an={peerService:`world-local`,rpcSystem:`local`,rpcService:`world-local`},on={"world.runs.get":0,"world.runs.experimentalSetAttributes":0,"world.steps.get":0,"world.events.create":0,"world.events.get":0},sn=new Set([`world.steps.list`,`world.events.list`,`world.hooks.list`]);function cn(e){if(e.length>=2&&typeof e[1]==`object`&&e[1]!==null){let t=e[1];if(typeof t.eventType==`string`)return t.eventType}}function ln(e,t){return typeof e[t]==`string`?e[t]:void 0}function un(e){if(typeof e!=`object`||!e)return;let t=e.runId;return typeof t==`string`?t:void 0}function dn(e){if(typeof e!=`object`||!e)return;let t=e;if(typeof t.runId==`string`)return t.runId;for(let e of[`run`,`step`,`hook`,`wait`]){let n=t[e];if(typeof n==`object`&&n){let e=n.runId;if(typeof e==`string`)return e}}}function fn(e,t,n){let r=`${e}.${t}`,i={},a=on[r],o=a===void 0?sn.has(r)?un(n[0]):void 0:ln(n,a);if(o&&Object.assign(i,nn(o)),r===`world.steps.get`){let e=ln(n,1);e&&Object.assign(i,rn(e))}return i}function pn(e,t){let n={};for(let r of Object.keys(t))if(typeof t[r]!=`function`)n[r]=t[r];else{let i=t[r],a=String(r);n[r]=async(...t)=>{let n=`${e}.${a}`;if(e===`world.events`&&a===`create`){let r=cn(t);r&&(n=`${e}.${a} ${r}`)}return Yt(n,{kind:await Xt(`INTERNAL`)},async r=>{r?.setAttributes({...Qt(an.peerService),...$t(an.rpcSystem),...en(an.rpcService),...tn(n),...fn(e,a,t)});let o=await i(...t),s=dn(o);return s&&r?.setAttributes(nn(s)),o})}}return n}var mn=t((t=>{var n=t&&t.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.RateLimit=t.Sema=void 0;let r=n(e(`events`));function i(e,t,n,r,i){for(let a=0;a<i;++a)n[a+r]=e[a+t],e[a+t]=void 0}function a(e){return e>>>=0,--e,e|=e>>1,e|=e>>2,e|=e>>4,e|=e>>8,e|=e>>16,e+1}function o(e){return a(Math.min(Math.max(16,e),1073741824))}var s=class{constructor(e){this._capacity=o(e),this._length=0,this._front=0,this.arr=[]}push(e){let t=this._length;this.checkCapacity(t+1);let n=this._front+t&this._capacity-1;return this.arr[n]=e,this._length=t+1,t+1}pop(){let e=this._length;if(e===0)return;let t=this._front+e-1&this._capacity-1,n=this.arr[t];return this.arr[t]=void 0,this._length=e-1,n}shift(){let e=this._length;if(e===0)return;let t=this._front,n=this.arr[t];return this.arr[t]=void 0,this._front=t+1&this._capacity-1,this._length=e-1,n}get length(){return this._length}checkCapacity(e){this._capacity<e&&this.resizeTo(o(this._capacity*1.5+16))}resizeTo(e){let t=this._capacity;this._capacity=e;let n=this._front,r=this._length;if(n+r>t){let e=n+r&t-1;i(this.arr,0,this.arr,t,e)}}},c=class extends r.default{};function l(e){return typeof e==`function`}function u(){return`1`}var d=class{constructor(e,{initFn:t=u,pauseFn:n,resumeFn:r,capacity:i=10}={}){if(l(n)!==l(r))throw Error(`pauseFn and resumeFn must be both set for pausing`);this.nrTokens=e,this.free=new s(e),this.waiting=new s(i),this.releaseEmitter=new c,this.noTokens=t===u,this.pauseFn=n,this.resumeFn=r,this.paused=!1,this.releaseEmitter.on(`release`,e=>{let t=this.waiting.shift();t?t.resolve(e):(this.resumeFn&&this.paused&&(this.paused=!1,this.resumeFn()),this.free.push(e))});for(let n=0;n<e;n++)this.free.push(t())}tryAcquire(){return this.free.pop()}async acquire(){let e=this.tryAcquire();return e===void 0?new Promise((e,t)=>{this.pauseFn&&!this.paused&&(this.paused=!0,this.pauseFn()),this.waiting.push({resolve:e,reject:t})}):e}release(e){this.releaseEmitter.emit(`release`,this.noTokens?`1`:e)}drain(){let e=Array(this.nrTokens);for(let t=0;t<this.nrTokens;t++)e[t]=this.acquire();return Promise.all(e)}nrWaiting(){return this.waiting.length}};t.Sema=d;function f(e,{timeUnit:t=1e3,uniformDistribution:n=!1}={}){let r=new d(n?1:e),i=n?t/e:t;return async function(){await r.acquire(),setTimeout(()=>r.release(),i)}}t.RateLimit=f}))(),hn=be(),gn=class{contentType=`application/json`;serialize(e){return Buffer.from(JSON.stringify(e,J))}async deserialize(e){let t=[],n=e.getReader();for(;;){let{done:e,value:r}=await n.read();if(e)break;r&&t.push(r)}let r=Buffer.concat(t).toString();return JSON.parse(r,bt)}};const _n=parseInt(process.env.WORKFLOW_LOCAL_QUEUE_MAX_VISIBILITY??`0`,10)||1/0,vn=2147483647,yn=parseInt(process.env.WORKFLOW_LOCAL_QUEUE_CONCURRENCY??`0`,10)||1e3;function bn(e,t){let n=process.env[e];if(n===void 0||n===``)return t;let r=Number.parseInt(n,10);return Number.isFinite(r)&&r>=0?r:t}function xn(){return{bodyTimeout:bn(`WORKFLOW_LOCAL_BODY_TIMEOUT_MS`,3e4),connections:1e3,headersTimeout:bn(`WORKFLOW_LOCAL_HEADERS_TIMEOUT_MS`,3e4),keepAliveTimeout:3e4}}const Sn=`Cannot perform ArrayBuffer.prototype.slice on a detached ArrayBuffer`;function Cn(e){let t=e,n=new Set;for(;t&&typeof t==`object`&&!n.has(t);){if(n.add(t),`message`in t&&typeof t.message==`string`&&t.message.includes(Sn))return!0;t=`cause`in t?t.cause:void 0}return!1}function wn(e){let t=xn(),i=T()?xe({maxSockets:t.connections,keepAliveMs:t.keepAliveTimeout}):void 0,s=i?void 0:new hn.Agent(t),c=new gn,l=ue(),u=new mn.Sema(yn),d=new AbortController,f=d.signal,p=new Map,m=new Map,h=async(r,o,d)=>{let h=[];if(d?.idempotencyKey){let e=p.get(d.idempotencyKey);if(e)return{messageId:e}}let g=c.serialize(o),{prefix:_}=a(r),v=me.parse(`msg_${l()}`),y=o,b=y.runId??void 0,x=y.stepId??void 0;if(d?.idempotencyKey){let e=d.idempotencyKey;p.set(e,v),h.push(()=>{p.delete(e)})}return(async()=>{if(d?.delaySeconds&&d.delaySeconds>0){let e=Math.min(d.delaySeconds*1e3,vn);await Fe(e,void 0,{signal:f})}u.tryAcquire()||(n(`[world-local]: concurrency limit (${yn}) reached, waiting for queue to free up`),await u.acquire());let a=0;try{for(let n=0;n<256;n++){let o={...d?.headers,"content-type":`application/json`,"x-vqs-queue-name":r,"x-vqs-message-id":v,"x-vqs-message-attempt":String(a+1)},c=m.get(_),l,u;try{if(c)l=await c(new Request(ye(ot(e),{type:`flow`}),{method:`POST`,headers:o,body:g}));else{let n=await st(e),r=ye(n,{type:`flow`});l=i?await P(r,{method:`POST`,headers:new Headers(o),body:g,agents:i,signal:f,headersTimeoutMs:t.headersTimeout,bodyTimeoutMs:t.bodyTimeout}):await fetch(r,{method:`POST`,duplex:`half`,dispatcher:s,headers:o,body:g,signal:f})}a++,u=await l.text()}catch(e){let t=e?.name;if(f.aborted||t===`AbortError`||t===`ResponseAborted`)return;if(Cn(e))throw e;console.error(`[world-local] Queue delivery failed at the transport (loop ${n+1}), retrying`,{queueName:r,messageId:v,...b&&{runId:b},...x&&{stepId:x},error:String(e)}),await Fe(5e3,void 0,{signal:f});continue}if(l.ok){try{let e=Number(JSON.parse(u).timeoutSeconds);if(Number.isFinite(e)&&e>=0){if(e>0){let t=Math.min(e*1e3,vn);await Fe(t,void 0,{signal:f})}continue}}catch{}return}console.error(`[world-local] Queue message failed (attempt ${a}, HTTP ${l.status})`,{queueName:r,messageId:v,...b&&{runId:b},...x&&{stepId:x},handlerError:u}),await Fe(5e3,void 0,{signal:f})}console.error(`[world-local] Queue message exhausted safety limit (256 attempts)`,{queueName:r,messageId:v,...b&&{runId:b},...x&&{stepId:x}})}finally{u.release()}})().catch(e=>{e?.name!==`AbortError`&&e?.name!==`ResponseAborted`&&(Cn(e)?console.error(`[local world] Queue operation failed: detected "${Sn}". This usually means a Next.js proxy/middleware consumed Workflow's internal request before the executor could read it. Exclude \`/.well-known/workflow/*\` from your matcher. See https://workflow-sdk.dev/docs/getting-started/next#configure-proxy-handler`,{queueName:r,messageId:v,...b&&{runId:b},...x&&{stepId:x},originalError:e}):console.error(`[local world] Queue operation failed:`,e))}).finally(()=>{for(let e of h)e()}),{messageId:v}},g=o({"x-vqs-queue-name":r,"x-vqs-message-id":me,"x-vqs-message-attempt":ae()});return{queue:h,createQueueHandler:(e,t)=>async n=>{let r=g.safeParse(Object.fromEntries(n.headers));if(!r.success||!n.body)return Response.json({error:n.body?`Missing required headers`:`Missing request body`},{status:400});let i=r.data[`x-vqs-queue-name`],a=r.data[`x-vqs-message-id`],o=r.data[`x-vqs-message-attempt`];if(!i.startsWith(e))return Response.json({error:`Unhandled queue`},{status:400});let s=await new gn().deserialize(n.body);try{let e=await t(s,{attempt:o,queueName:i,messageId:a}),n=null;return typeof e?.timeoutSeconds==`number`&&(n=Math.min(e.timeoutSeconds,_n)),n==null?Response.json({ok:!0}):Response.json({timeoutSeconds:n})}catch(e){return Response.json(String(e),{status:500})}},getDeploymentId:async()=>`dpl_local@${(await Nt()).version}`,registerHandler(e,t){m.set(e,t)},async close(){f.aborted||(d.abort(),i&&F(i),await s?.close())}}}var Tn=t(((t,n)=>{var r=e(`constants`),i=process.cwd,a=null,o=process.env.GRACEFUL_FS_PLATFORM||process.platform;process.cwd=function(){return a||=i.call(process),a};try{process.cwd()}catch{}if(typeof process.chdir==`function`){var s=process.chdir;process.chdir=function(e){a=null,s.call(process,e)},Object.setPrototypeOf&&Object.setPrototypeOf(process.chdir,s)}n.exports=c;function c(e){r.hasOwnProperty(`O_SYMLINK`)&&process.version.match(/^v0\.6\.[0-2]|^v0\.5\./)&&t(e),e.lutimes||n(e),e.chown=s(e.chown),e.fchown=s(e.fchown),e.lchown=s(e.lchown),e.chmod=i(e.chmod),e.fchmod=i(e.fchmod),e.lchmod=i(e.lchmod),e.chownSync=c(e.chownSync),e.fchownSync=c(e.fchownSync),e.lchownSync=c(e.lchownSync),e.chmodSync=a(e.chmodSync),e.fchmodSync=a(e.fchmodSync),e.lchmodSync=a(e.lchmodSync),e.stat=l(e.stat),e.fstat=l(e.fstat),e.lstat=l(e.lstat),e.statSync=u(e.statSync),e.fstatSync=u(e.fstatSync),e.lstatSync=u(e.lstatSync),e.chmod&&!e.lchmod&&(e.lchmod=function(e,t,n){n&&process.nextTick(n)},e.lchmodSync=function(){}),e.chown&&!e.lchown&&(e.lchown=function(e,t,n,r){r&&process.nextTick(r)},e.lchownSync=function(){}),o===`win32`&&(e.rename=typeof e.rename==`function`?(function(t){function n(n,r,i){var a=Date.now(),o=0;t(n,r,function s(c){if(c&&(c.code===`EACCES`||c.code===`EPERM`||c.code===`EBUSY`)&&Date.now()-a<6e4){setTimeout(function(){e.stat(r,function(e,a){e&&e.code===`ENOENT`?t(n,r,s):i(c)})},o),o<100&&(o+=10);return}i&&i(c)})}return Object.setPrototypeOf&&Object.setPrototypeOf(n,t),n})(e.rename):e.rename),e.read=typeof e.read==`function`?(function(t){function n(n,r,i,a,o,s){var c;if(s&&typeof s==`function`){var l=0;c=function(u,d,f){if(u&&u.code===`EAGAIN`&&l<10)return l++,t.call(e,n,r,i,a,o,c);s.apply(this,arguments)}}return t.call(e,n,r,i,a,o,c)}return Object.setPrototypeOf&&Object.setPrototypeOf(n,t),n})(e.read):e.read,e.readSync=typeof e.readSync==`function`?(function(t){return function(n,r,i,a,o){for(var s=0;;)try{return t.call(e,n,r,i,a,o)}catch(e){if(e.code===`EAGAIN`&&s<10){s++;continue}throw e}}})(e.readSync):e.readSync;function t(e){e.lchmod=function(t,n,i){e.open(t,r.O_WRONLY|r.O_SYMLINK,n,function(t,r){if(t){i&&i(t);return}e.fchmod(r,n,function(t){e.close(r,function(e){i&&i(t||e)})})})},e.lchmodSync=function(t,n){var i=e.openSync(t,r.O_WRONLY|r.O_SYMLINK,n),a=!0,o;try{o=e.fchmodSync(i,n),a=!1}finally{if(a)try{e.closeSync(i)}catch{}else e.closeSync(i)}return o}}function n(e){r.hasOwnProperty(`O_SYMLINK`)&&e.futimes?(e.lutimes=function(t,n,i,a){e.open(t,r.O_SYMLINK,function(t,r){if(t){a&&a(t);return}e.futimes(r,n,i,function(t){e.close(r,function(e){a&&a(t||e)})})})},e.lutimesSync=function(t,n,i){var a=e.openSync(t,r.O_SYMLINK),o,s=!0;try{o=e.futimesSync(a,n,i),s=!1}finally{if(s)try{e.closeSync(a)}catch{}else e.closeSync(a)}return o}):e.futimes&&(e.lutimes=function(e,t,n,r){r&&process.nextTick(r)},e.lutimesSync=function(){})}function i(t){return t&&function(n,r,i){return t.call(e,n,r,function(e){d(e)&&(e=null),i&&i.apply(this,arguments)})}}function a(t){return t&&function(n,r){try{return t.call(e,n,r)}catch(e){if(!d(e))throw e}}}function s(t){return t&&function(n,r,i,a){return t.call(e,n,r,i,function(e){d(e)&&(e=null),a&&a.apply(this,arguments)})}}function c(t){return t&&function(n,r,i){try{return t.call(e,n,r,i)}catch(e){if(!d(e))throw e}}}function l(t){return t&&function(n,r,i){typeof r==`function`&&(i=r,r=null);function a(e,t){t&&(t.uid<0&&(t.uid+=4294967296),t.gid<0&&(t.gid+=4294967296)),i&&i.apply(this,arguments)}return r?t.call(e,n,r,a):t.call(e,n,a)}}function u(t){return t&&function(n,r){var i=r?t.call(e,n,r):t.call(e,n);return i&&(i.uid<0&&(i.uid+=4294967296),i.gid<0&&(i.gid+=4294967296)),i}}function d(e){return!(e&&e.code!==`ENOSYS`&&(process.getuid&&process.getuid()===0||e.code!==`EINVAL`&&e.code!==`EPERM`))}}})),En=t(((t,n)=>{var r=e(`stream`).Stream;n.exports=i;function i(e){return{ReadStream:t,WriteStream:n};function t(n,i){if(!(this instanceof t))return new t(n,i);r.call(this);var a=this;this.path=n,this.fd=null,this.readable=!0,this.paused=!1,this.flags=`r`,this.mode=438,this.bufferSize=65536,i||={};for(var o=Object.keys(i),s=0,c=o.length;s<c;s++){var l=o[s];this[l]=i[l]}if(this.encoding&&this.setEncoding(this.encoding),this.start!==void 0){if(typeof this.start!=`number`)throw TypeError(`start must be a Number`);if(this.end===void 0)this.end=1/0;else if(typeof this.end!=`number`)throw TypeError(`end must be a Number`);if(this.start>this.end)throw Error(`start must be <= end`);this.pos=this.start}if(this.fd!==null){process.nextTick(function(){a._read()});return}e.open(this.path,this.flags,this.mode,function(e,t){if(e){a.emit(`error`,e),a.readable=!1;return}a.fd=t,a.emit(`open`,t),a._read()})}function n(t,i){if(!(this instanceof n))return new n(t,i);r.call(this),this.path=t,this.fd=null,this.writable=!0,this.flags=`w`,this.encoding=`binary`,this.mode=438,this.bytesWritten=0,i||={};for(var a=Object.keys(i),o=0,s=a.length;o<s;o++){var c=a[o];this[c]=i[c]}if(this.start!==void 0){if(typeof this.start!=`number`)throw TypeError(`start must be a Number`);if(this.start<0)throw Error(`start must be >= zero`);this.pos=this.start}this.busy=!1,this._queue=[],this.fd===null&&(this._open=e.open,this._queue.push([this._open,this.path,this.flags,this.mode,void 0]),this.flush())}}})),Dn=t(((e,t)=>{t.exports=r;var n=Object.getPrototypeOf||function(e){return e.__proto__};function r(e){if(typeof e!=`object`||!e)return e;if(e instanceof Object)var t={__proto__:n(e)};else var t=Object.create(null);return Object.getOwnPropertyNames(e).forEach(function(n){Object.defineProperty(t,n,Object.getOwnPropertyDescriptor(e,n))}),t}})),On=t(((t,n)=>{var r=e(`fs`),i=Tn(),a=En(),o=Dn(),s=e(`util`),c,l;typeof Symbol==`function`&&typeof Symbol.for==`function`?(c=Symbol.for(`graceful-fs.queue`),l=Symbol.for(`graceful-fs.previous`)):(c=`___graceful-fs.queue`,l=`___graceful-fs.previous`);function u(){}function d(e,t){Object.defineProperty(e,c,{get:function(){return t}})}var f=u;s.debuglog?f=s.debuglog(`gfs4`):/\bgfs4\b/i.test(process.env.NODE_DEBUG||``)&&(f=function(){var e=s.format.apply(s,arguments);e=`GFS4: `+e.split(/\n/).join(`
5
- GFS4: `),console.error(e)}),r[c]||(d(r,global[c]||[]),r.close=(function(e){function t(t,n){return e.call(r,t,function(e){e||g(),typeof n==`function`&&n.apply(this,arguments)})}return Object.defineProperty(t,l,{value:e}),t})(r.close),r.closeSync=(function(e){function t(t){e.apply(r,arguments),g()}return Object.defineProperty(t,l,{value:e}),t})(r.closeSync),/\bgfs4\b/i.test(process.env.NODE_DEBUG||``)&&process.on(`exit`,function(){f(r[c]),e(`assert`).equal(r[c].length,0)})),global[c]||d(global,r[c]),n.exports=p(o(r)),process.env.TEST_GRACEFUL_FS_GLOBAL_PATCH&&!r.__patched&&(n.exports=p(r),r.__patched=!0);function p(e){i(e),e.gracefulify=p,e.createReadStream=te,e.createWriteStream=ne;var t=e.readFile;e.readFile=n;function n(e,n,r){return typeof n==`function`&&(r=n,n=null),i(e,n,r);function i(e,n,r,a){return t(e,n,function(t){t&&(t.code===`EMFILE`||t.code===`ENFILE`)?m([i,[e,n,r],t,a||Date.now(),Date.now()]):typeof r==`function`&&r.apply(this,arguments)})}}var r=e.writeFile;e.writeFile=o;function o(e,t,n,i){return typeof n==`function`&&(i=n,n=null),a(e,t,n,i);function a(e,t,n,i,o){return r(e,t,n,function(r){r&&(r.code===`EMFILE`||r.code===`ENFILE`)?m([a,[e,t,n,i],r,o||Date.now(),Date.now()]):typeof i==`function`&&i.apply(this,arguments)})}}var s=e.appendFile;s&&(e.appendFile=c);function c(e,t,n,r){return typeof n==`function`&&(r=n,n=null),i(e,t,n,r);function i(e,t,n,r,a){return s(e,t,n,function(o){o&&(o.code===`EMFILE`||o.code===`ENFILE`)?m([i,[e,t,n,r],o,a||Date.now(),Date.now()]):typeof r==`function`&&r.apply(this,arguments)})}}var l=e.copyFile;l&&(e.copyFile=u);function u(e,t,n,r){return typeof n==`function`&&(r=n,n=0),i(e,t,n,r);function i(e,t,n,r,a){return l(e,t,n,function(o){o&&(o.code===`EMFILE`||o.code===`ENFILE`)?m([i,[e,t,n,r],o,a||Date.now(),Date.now()]):typeof r==`function`&&r.apply(this,arguments)})}}var d=e.readdir;e.readdir=h;var f=/^v[0-5]\./;function h(e,t,n){typeof t==`function`&&(n=t,t=null);var r=f.test(process.version)?function(e,t,n,r){return d(e,i(e,t,n,r))}:function(e,t,n,r){return d(e,t,i(e,t,n,r))};return r(e,t,n);function i(e,t,n,i){return function(a,o){a&&(a.code===`EMFILE`||a.code===`ENFILE`)?m([r,[e,t,n],a,i||Date.now(),Date.now()]):(o&&o.sort&&o.sort(),typeof n==`function`&&n.call(this,a,o))}}}if(process.version.substr(0,4)===`v0.8`){var g=a(e);x=g.ReadStream,C=g.WriteStream}var _=e.ReadStream;_&&(x.prototype=Object.create(_.prototype),x.prototype.open=S);var v=e.WriteStream;v&&(C.prototype=Object.create(v.prototype),C.prototype.open=ee),Object.defineProperty(e,"ReadStream",{get:function(){return x},set:function(e){x=e},enumerable:!0,configurable:!0}),Object.defineProperty(e,"WriteStream",{get:function(){return C},set:function(e){C=e},enumerable:!0,configurable:!0});var y=x;Object.defineProperty(e,"FileReadStream",{get:function(){return y},set:function(e){y=e},enumerable:!0,configurable:!0});var b=C;Object.defineProperty(e,"FileWriteStream",{get:function(){return b},set:function(e){b=e},enumerable:!0,configurable:!0});function x(e,t){return this instanceof x?(_.apply(this,arguments),this):x.apply(Object.create(x.prototype),arguments)}function S(){var e=this;ie(e.path,e.flags,e.mode,function(t,n){t?(e.autoClose&&e.destroy(),e.emit(`error`,t)):(e.fd=n,e.emit(`open`,n),e.read())})}function C(e,t){return this instanceof C?(v.apply(this,arguments),this):C.apply(Object.create(C.prototype),arguments)}function ee(){var e=this;ie(e.path,e.flags,e.mode,function(t,n){t?(e.destroy(),e.emit(`error`,t)):(e.fd=n,e.emit(`open`,n))})}function te(t,n){return new e.ReadStream(t,n)}function ne(t,n){return new e.WriteStream(t,n)}var re=e.open;e.open=ie;function ie(e,t,n,r){return typeof n==`function`&&(r=n,n=null),i(e,t,n,r);function i(e,t,n,r,a){return re(e,t,n,function(o,s){o&&(o.code===`EMFILE`||o.code===`ENFILE`)?m([i,[e,t,n,r],o,a||Date.now(),Date.now()]):typeof r==`function`&&r.apply(this,arguments)})}}return e}function m(e){f(`ENQUEUE`,e[0].name,e[1]),r[c].push(e),_()}var h;function g(){for(var e=Date.now(),t=0;t<r[c].length;++t)r[c][t].length>2&&(r[c][t][3]=e,r[c][t][4]=e);_()}function _(){if(clearTimeout(h),h=void 0,r[c].length!==0){var e=r[c].shift(),t=e[0],n=e[1],i=e[2],a=e[3],o=e[4];if(a===void 0)f(`RETRY`,t.name,n),t.apply(null,n);else if(Date.now()-a>=6e4){f(`TIMEOUT`,t.name,n);var s=n.pop();typeof s==`function`&&s.call(null,i)}else{var l=Date.now()-o,u=Math.max(o-a,1);l>=Math.min(u*1.2,100)?(f(`RETRY`,t.name,n),t.apply(null,n.concat([a]))):r[c].push(e)}h===void 0&&(h=setTimeout(_,0))}}})),kn=t(((e,t)=>{function n(e,t){typeof t==`boolean`&&(t={forever:t}),this._originalTimeouts=JSON.parse(JSON.stringify(e)),this._timeouts=e,this._options=t||{},this._maxRetryTime=t&&t.maxRetryTime||1/0,this._fn=null,this._errors=[],this._attempts=1,this._operationTimeout=null,this._operationTimeoutCb=null,this._timeout=null,this._operationStart=null,this._options.forever&&(this._cachedTimeouts=this._timeouts.slice(0))}t.exports=n,n.prototype.reset=function(){this._attempts=1,this._timeouts=this._originalTimeouts},n.prototype.stop=function(){this._timeout&&clearTimeout(this._timeout),this._timeouts=[],this._cachedTimeouts=null},n.prototype.retry=function(e){if(this._timeout&&clearTimeout(this._timeout),!e)return!1;var t=new Date().getTime();if(e&&t-this._operationStart>=this._maxRetryTime)return this._errors.unshift(Error(`RetryOperation timeout occurred`)),!1;this._errors.push(e);var n=this._timeouts.shift();if(n===void 0){if(this._cachedTimeouts)this._errors.splice(this._errors.length-1,this._errors.length),this._timeouts=this._cachedTimeouts.slice(0),n=this._timeouts.shift();else return!1}var r=this,i=setTimeout(function(){r._attempts++,r._operationTimeoutCb&&(r._timeout=setTimeout(function(){r._operationTimeoutCb(r._attempts)},r._operationTimeout),r._options.unref&&r._timeout.unref()),r._fn(r._attempts)},n);return this._options.unref&&i.unref(),!0},n.prototype.attempt=function(e,t){this._fn=e,t&&(t.timeout&&(this._operationTimeout=t.timeout),t.cb&&(this._operationTimeoutCb=t.cb));var n=this;this._operationTimeoutCb&&(this._timeout=setTimeout(function(){n._operationTimeoutCb()},n._operationTimeout)),this._operationStart=new Date().getTime(),this._fn(this._attempts)},n.prototype.try=function(e){console.log(`Using RetryOperation.try() is deprecated`),this.attempt(e)},n.prototype.start=function(e){console.log(`Using RetryOperation.start() is deprecated`),this.attempt(e)},n.prototype.start=n.prototype.try,n.prototype.errors=function(){return this._errors},n.prototype.attempts=function(){return this._attempts},n.prototype.mainError=function(){if(this._errors.length===0)return null;for(var e={},t=null,n=0,r=0;r<this._errors.length;r++){var i=this._errors[r],a=i.message,o=(e[a]||0)+1;e[a]=o,o>=n&&(t=i,n=o)}return t}})),An=t((e=>{var t=kn();e.operation=function(n){return new t(e.timeouts(n),{forever:n&&n.forever,unref:n&&n.unref,maxRetryTime:n&&n.maxRetryTime})},e.timeouts=function(e){if(e instanceof Array)return[].concat(e);var t={retries:10,factor:2,minTimeout:1e3,maxTimeout:1/0,randomize:!1};for(var n in e)t[n]=e[n];if(t.minTimeout>t.maxTimeout)throw Error(`minTimeout is greater than maxTimeout`);for(var r=[],i=0;i<t.retries;i++)r.push(this.createTimeout(i,t));return e&&e.forever&&!r.length&&r.push(this.createTimeout(i,t)),r.sort(function(e,t){return e-t}),r},e.createTimeout=function(e,t){var n=t.randomize?Math.random()+1:1,r=Math.round(n*t.minTimeout*t.factor**+e);return r=Math.min(r,t.maxTimeout),r},e.wrap=function(t,n,r){if(n instanceof Array&&(r=n,n=null),!r)for(var i in r=[],t)typeof t[i]==`function`&&r.push(i);for(var a=0;a<r.length;a++){var o=r[a],s=t[o];t[o]=function(r){var i=e.operation(n),a=Array.prototype.slice.call(arguments,1),o=a.pop();a.push(function(e){i.retry(e)||(e&&(arguments[0]=i.mainError()),o.apply(this,arguments))}),i.attempt(function(){r.apply(t,a)})}.bind(t,s),t[o].options=n}}})),jn=t(((e,t)=>{t.exports=An()})),Mn=t(((e,t)=>{let n=Symbol();function r(e,t,r){let i=t[n];if(i)return t.stat(e,(e,t)=>{if(e)return r(e);r(null,t.mtime,i)});let a=new Date(Math.ceil(Date.now()/1e3)*1e3+5);t.utimes(e,a,a,i=>{if(i)return r(i);t.stat(e,(e,i)=>{if(e)return r(e);let a=i.mtime.getTime()%1e3==0?`s`:`ms`;Object.defineProperty(t,n,{value:a}),r(null,i.mtime,a)})})}function i(e){let t=Date.now();return e===`s`&&(t=Math.ceil(t/1e3)*1e3),new Date(t)}t.exports.probe=r,t.exports.getMtime=i})),Nn=t(((t,n)=>{let r=e(`path`),i=On(),a=jn(),o=Se(),s=Mn(),c={};function l(e,t){return t.lockfilePath||`${e}.lock`}function u(e,t,n){if(!t.realpath)return n(null,r.resolve(e));t.fs.realpath(e,n)}function d(e,t,n){let r=l(e,t);t.fs.mkdir(r,i=>{if(!i)return s.probe(r,t.fs,(e,i,a)=>{if(e)return t.fs.rmdir(r,()=>{}),n(e);n(null,i,a)});if(i.code!==`EEXIST`)return n(i);if(t.stale<=0)return n(Object.assign(Error(`Lock file is already being held`),{code:`ELOCKED`,file:e}));t.fs.stat(r,(r,i)=>{if(r)return r.code===`ENOENT`?d(e,{...t,stale:0},n):n(r);if(!f(i,t))return n(Object.assign(Error(`Lock file is already being held`),{code:`ELOCKED`,file:e}));p(e,t,r=>{if(r)return n(r);d(e,{...t,stale:0},n)})})})}function f(e,t){return e.mtime.getTime()<Date.now()-t.stale}function p(e,t,n){t.fs.rmdir(l(e,t),e=>{if(e&&e.code!==`ENOENT`)return n(e);n()})}function m(e,t){let n=c[e];n.updateTimeout||(n.updateDelay=n.updateDelay||t.update,n.updateTimeout=setTimeout(()=>{n.updateTimeout=null,t.fs.stat(n.lockfilePath,(r,i)=>{let a=n.lastUpdate+t.stale<Date.now();if(r)return r.code===`ENOENT`||a?h(e,n,Object.assign(r,{code:`ECOMPROMISED`})):(n.updateDelay=1e3,m(e,t));if(n.mtime.getTime()!==i.mtime.getTime())return h(e,n,Object.assign(Error(`Unable to update lock within the stale threshold`),{code:`ECOMPROMISED`}));let o=s.getMtime(n.mtimePrecision);t.fs.utimes(n.lockfilePath,o,o,r=>{let i=n.lastUpdate+t.stale<Date.now();if(!n.released){if(r)return r.code===`ENOENT`||i?h(e,n,Object.assign(r,{code:`ECOMPROMISED`})):(n.updateDelay=1e3,m(e,t));n.mtime=o,n.lastUpdate=Date.now(),n.updateDelay=null,m(e,t)}})})},n.updateDelay),n.updateTimeout.unref&&n.updateTimeout.unref())}function h(e,t,n){t.released=!0,t.updateTimeout&&clearTimeout(t.updateTimeout),c[e]===t&&delete c[e],t.options.onCompromised(n)}function g(e,t,n){t={stale:1e4,update:null,realpath:!0,retries:0,fs:i,onCompromised:e=>{throw e},...t},t.retries=t.retries||0,t.retries=typeof t.retries==`number`?{retries:t.retries}:t.retries,t.stale=Math.max(t.stale||0,2e3),t.update=t.update==null?t.stale/2:t.update||0,t.update=Math.max(Math.min(t.update,t.stale/2),1e3),u(e,t,(e,r)=>{if(e)return n(e);let i=a.operation(t.retries);i.attempt(()=>{d(r,t,(e,a,o)=>{if(i.retry(e))return;if(e)return n(i.mainError());let s=c[r]={lockfilePath:l(r,t),mtime:a,mtimePrecision:o,options:t,lastUpdate:Date.now()};m(r,t),n(null,e=>{if(s.released)return e&&e(Object.assign(Error(`Lock is already released`),{code:`ERELEASED`}));_(r,{...t,realpath:!1},e)})})})})}function _(e,t,n){t={fs:i,realpath:!0,...t},u(e,t,(e,r)=>{if(e)return n(e);let i=c[r];if(!i)return n(Object.assign(Error(`Lock is not acquired/owned by you`),{code:`ENOTACQUIRED`}));i.updateTimeout&&clearTimeout(i.updateTimeout),i.released=!0,delete c[r],p(r,t,n)})}function v(e,t,n){t={stale:1e4,realpath:!0,fs:i,...t},t.stale=Math.max(t.stale||0,2e3),u(e,t,(e,r)=>{if(e)return n(e);t.fs.stat(l(r,t),(e,r)=>e?e.code===`ENOENT`?n(null,!1):n(e):n(null,!f(r,t)))})}function y(){return c}o(()=>{for(let e in c){let t=c[e].options;try{t.fs.rmdirSync(l(e,t))}catch{}}}),n.exports.lock=g,n.exports.unlock=_,n.exports.check=v,n.exports.getLocks=y})),Pn=t(((e,t)=>{let n=On();function r(e){let t=[`mkdir`,`realpath`,`stat`,`rmdir`,`utimes`],n={...e};return t.forEach(t=>{n[t]=(...n)=>{let r=n.pop(),i;try{i=e[`${t}Sync`](...n)}catch(e){return r(e)}r(null,i)}}),n}function i(e){return(...t)=>new Promise((n,r)=>{t.push((e,t)=>{e?r(e):n(t)}),e(...t)})}function a(e){return(...t)=>{let n,r;if(t.push((e,t)=>{n=e,r=t}),e(...t),n)throw n;return r}}function o(e){if(e={...e},e.fs=r(e.fs||n),typeof e.retries==`number`&&e.retries>0||e.retries&&typeof e.retries.retries==`number`&&e.retries.retries>0)throw Object.assign(Error(`Cannot use retries with the sync api`),{code:`ESYNC`});return e}t.exports={toPromise:i,toSync:a,toSyncOptions:o}})),Fn=t(((e,t)=>{let n=Nn(),{toPromise:r,toSync:i,toSyncOptions:a}=Pn();async function o(e,t){let i=await r(n.lock)(e,t);return r(i)}function s(e,t){let r=i(n.lock)(e,a(t));return i(r)}function c(e,t){return r(n.unlock)(e,t)}function l(e,t){return i(n.unlock)(e,a(t))}function u(e,t){return r(n.check)(e,t)}function d(e,t){return i(n.check)(e,a(t))}t.exports=o,t.exports.lock=o,t.exports.unlock=c,t.exports.lockSync=s,t.exports.unlockSync=l,t.exports.check=u,t.exports.checkSync=d}))();function In(e){return I(`sha256`).update(e).digest(`hex`)}function Ln(e,t,n){return U(e,`.locks`,`hooks`,n?`${t}.disposed.${n}`:`${t}.disposed`)}async function Rn(e,t,n){let r=[Ln(e,t)];n&&r.push(Ln(e,t,n));for(let e of r)try{return await R.access(e),!0}catch{}return!1}function zn(e,t,n){return U(e,`.locks`,`runs`,n?`${t}.terminal.${n}`:`${t}.terminal`)}async function Bn(e,t,n){let r=[zn(e,t)];n&&r.push(zn(e,t,n));for(let e of r)try{return await R.access(e),!0}catch(e){if(e.code!==`ENOENT`)throw e}return!1}function Vn(e,t,n){return U(e,`.locks`,`runs`,n?`${t}.pending.${n}`:`${t}.pending`)}function Hn(e,t,n,r){return B.join(Vn(e,t,r),`${n}.json`)}async function Un(e,t,n){let r=[Vn(e,t)];n&&r.push(Vn(e,t,n));for(let e of r){let t;try{t=await R.readdir(e)}catch(e){if(e.code===`ENOENT`)continue;throw e}for(let n of t)try{await W(()=>R.unlink(B.join(e,n)))}catch(e){if(e.code!==`ENOENT`)throw e}await R.rmdir(e).catch(()=>{})}}async function Wn(e,t,n){let r=await Gn(e,t,n),i=Date.now();if(r.maxId)try{let e=S(r.maxId.replace(/^evnt_/,``));i<=e&&(i=e+1)}catch{}return{eventId:`evnt_${er(i)}`,createdAt:new Date(i)}}async function Gn(e,t,n){let r=[];try{r=await R.readdir(B.join(e,`events`))}catch(e){if(e.code!==`ENOENT`)throw e}let i=`${t}-`,a=[],o=null,s=0,c=!1,l=0;for(let e of r){if(!e.startsWith(i)||!e.endsWith(`.json`))continue;let t=e.slice(0,-5);if(!mt(t)&&!(n&&pt(t,n)))continue;let r=G(t).slice(i.length);l+=1,a.push(r),(!o||r>o)&&(o=r);let u=ne(r);u!==null&&(c=!0,u>s&&(s=u))}return{maxId:o,usesSlots:c,maxSlot:s,count:l,ids:a}}function Kn(e,t){return B.join(e,`hooks`,`tokens`,`${In(t)}.json`)}const qn=o({hookId:u().optional(),runId:u(),eventId:u().optional(),tokenRetentionUntil:re().optional()});async function Jn(e){try{return await X(e,qn)}catch(e){if(e instanceof SyntaxError||e instanceof i)return null;throw e}}async function Yn(e,t,n){let r=Kn(e,t);await R.mkdir(B.dirname(r),{recursive:!0});let i=new AbortController,a;try{a=await(0,Fn.lock)(r,{realpath:!1,stale:3e4,update:1e3,retries:{retries:350,factor:1,minTimeout:100,maxTimeout:100},onCompromised(e){i.abort(new D(`Hook token claim lock was compromised`,{cause:e}))}})}catch(e){throw new D(`Could not acquire Hook token claim lock`,{cause:e})}let o;try{o=await n(i.signal),i.signal.throwIfAborted()}catch(e){throw i.signal.aborted||await a().catch(()=>{}),e}try{await a()}catch(e){throw new D(`Could not release Hook token claim lock`,{cause:e})}return o}function Xn(e,t,n){let r=I(`sha256`).update(`${t}\x00${n}`).digest(`hex`);return B.join(e,`hooks`,`resumes`,`${r}.json`)}async function Zn(e,t,n,r){await Yn(e,t,async i=>{let a=Kn(e,t),o=await Jn(a);o&&o.runId===n&&o.hookId===r&&(i.throwIfAborted(),await Z(a))})}function Qn(e,t,n,r){let i=I(`sha256`).update(`${t}\x00${n}\x00${r}`).digest(`hex`);return B.join(e,`hooks`,`tokens`,`${i}.recovery.json`)}const $n=c(`@workflow/world-local//storageMonotonicUlid`,1,()=>({next:ue(()=>Math.random())})),er=e=>$n.next(e),tr=e=>{let t=RegExp(`^${e}_`,`g`);return n=>{let r=G(n.replace(/\.json$/,``))+`.json`,i=r.indexOf(`-`);if(i===-1){let e=r.replace(/\.json$/,``).replace(t,``);return le(e)}if(e===`step`)return null;let a=r.substring(i+1).replace(/\.json$/,``).replace(t,``);return le(a)}},nr=o({runId:u()}),rr=o({hookId:u(),tag:u().optional()});function ir(e,t){return U(e,`hooks`,`token-index`,In(t))}function ar(e,t){return H(`hookId`,t),U(e,`hooks`,`id-index`,t)}function or(e){return U(e,`hooks`,`by-run`)}function sr(e){let t=G(e);return t===e?void 0:e.slice(t.length+1)}function cr(e,t){return t?mt(e)||pt(e,t):mt(e)}async function lr(e){try{return await X(e,s)}catch(e){if(e instanceof SyntaxError||e instanceof i)return null;throw e}}async function ur(e,t,n,r,i,a){H(`runId`,n),H(`eventId`,i),a!==void 0&&H(`tag`,a);let o=a?`${i}.${a}.json`:`${i}.json`,s=JSON.stringify({runId:n});await Promise.all([Q(B.join(ir(e,t),o),s),Q(B.join(ar(e,r),o),s)])}function dr(e,t,n,r){return K(e,`hooks/by-run`,`${t}-${n}`,r)}async function fr(e,t,n,r){await Q(dr(e,t,n,r),JSON.stringify(r?{hookId:n,tag:r}:{hookId:n}))}async function pr(e,t,n,r){await Z(dr(e,t,n,r)),r&&await Z(dr(e,t,n))}async function mr(e,t){H(`runId`,t);let n=or(e),r=`${t}-`,a=[];for(let e of await Tt(n)){if(!e.startsWith(r))continue;let t=null;try{t=await X(B.join(n,`${e}.json`),rr)}catch(e){if(!(e instanceof SyntaxError||e instanceof i))throw e}a.push({fileId:e,hookId:t?.hookId??null,tag:t?.tag})}return a}async function hr(e,t){await Z(B.join(or(e),`${t}.json`))}const gr=c(`@workflow/world-local//hookIndexEnsureCache`,1,()=>({ensuredBasedirs:new Map}));function _r(){gr.ensuredBasedirs.clear()}async function vr(e){let t=B.resolve(e),n=gr.ensuredBasedirs.get(t);return n||(n=br(t).catch(e=>{throw gr.ensuredBasedirs.delete(t),e}),gr.ensuredBasedirs.set(t,n)),n}async function yr(e,t,n){for(let r=0;r<e.length;r+=t)await Promise.all(e.slice(r,r+t).map(n))}async function br(e){let t=B.join(e,`hooks`,`.hook-index-complete`);try{await R.access(t);return}catch{}let n=B.join(e,`events`);await yr(await Tt(n),32,async t=>{let r=await lr(B.join(n,`${t}.json`));if(!r||r.eventType!==`hook_created`||typeof r.correlationId!=`string`)return;let i=r.eventData?.token;if(typeof i==`string`)try{await ur(e,i,r.runId,r.correlationId,r.eventId,sr(t))}catch{}});let r=B.join(e,`hooks`);await yr(await Tt(r),32,async t=>{let n=null;try{n=await X(B.join(r,`${t}.json`),E)}catch(e){if(!(e instanceof SyntaxError||e instanceof i))throw e}if(n)try{await fr(e,n.runId,n.hookId,sr(t))}catch{}}),await Q(t,``)}async function xr(e,t,n,r){await vr(e);let a;try{a=t.kind===`token`?ir(e,t.token):ar(e,t.hookId)}catch{return null}let o=(await Tt(a)).filter(e=>cr(e,r)).sort((e,t)=>G(t).localeCompare(G(e)));for(let t of o){let r=null;try{r=await X(B.join(a,`${t}.json`),nr)}catch(e){if(!(e instanceof SyntaxError||e instanceof i))throw e}if(!r)continue;let o=G(t),s;try{s=K(e,`events`,`${r.runId}-${o}`,sr(t))}catch{continue}let c=await lr(s);if(c&&c.eventType===`hook_created`&&typeof c.correlationId==`string`&&n(c))return c}return null}function Sr(e,t){return t===`none`?{...e,input:void 0,output:void 0}:e}function Cr(e,t){return t===`none`?{...e,input:void 0,output:void 0}:e}function wr(e,t){if(t===`none`){let{metadata:t,...n}=e;return n}return e}function Tr(e){if(e.eventType!==`hook_created`)return;let t=e.eventData.token;return typeof t==`string`?t:void 0}function Er(e){let{token:t,metadata:n,isWebhook:r,isSystem:i,tokenRetentionUntil:a}=e.eventData;return{runId:e.runId,hookId:e.correlationId,token:t,metadata:n,ownerId:`local-owner`,projectId:`local-project`,environment:`local`,createdAt:e.createdAt,specVersion:e.specVersion,isWebhook:r??!0,isSystem:i??!1,tokenRetentionUntil:a}}function Dr(e,t){return e.eventType===`hook_created`&&typeof e.correlationId==`string`&&t(e)}async function Or(e,t,n){let r=await q(e,`runs`,t,g,n);return r?_(r.status):!1}async function kr(e,t,n,r){let i=await xr(e,t,e=>Dr(e,n),r);if(!i||!Dr(i,n))return null;if(await Or(e,i.runId,r)){let e=i.eventData.tokenRetentionUntil;if(!e||e.getTime()<=Date.now())return null}return await Rn(e,i.correlationId,r)?null:i}async function Ar(e,t,n){let r=Er(t);return await Q(Kn(e,r.token),JSON.stringify({token:r.token,hookId:r.hookId,runId:r.runId,eventId:t.eventId,tokenRetentionUntil:t.eventData.tokenRetentionUntil})),await fr(e,r.runId,r.hookId,n),await Q(K(e,`hooks`,r.hookId,n),JSON.stringify(r,J,2)),r}async function jr(e,t,n){let r=await kr(e,{kind:`token`,token:t},e=>Tr(e)===t,n);return r?Ar(e,r,n):null}async function Mr(e,t,n){let r=await kr(e,{kind:`id`,hookId:t},e=>e.correlationId===t,n);return r?Ar(e,r,n):null}function Nr(e,t){async function n(n){return await Rn(e,n.hookId,t)?!1:n.tokenRetentionUntil&&n.tokenRetentionUntil.getTime()>Date.now()?!0:!await Or(e,n.runId,t)}async function r(r){let i=await Jn(Kn(e,r));if(i?.hookId){try{let a=await q(e,`hooks`,i.hookId,E,t);if(a?.token===r){if(!await n(a))throw new k(r);return{...a,isWebhook:a.isWebhook??!0}}}catch(e){if(!lt.is(e))throw e}return null}let a=B.join(e,`hooks`),o=await Tt(a);for(let e of o){let t=await X(B.join(a,`${e}.json`),E);if(t?.token===r){if(!await n(t))throw new k(r);return{...t,isWebhook:t.isWebhook??!0}}}return null}async function i(r,i){H(`hookId`,r);let a=await q(e,`hooks`,r,E,t);if(a&&!await n(a))throw new k(r);let o=a??await Mr(e,r,t);if(!o)throw new k(r);let s=i?.resolveData||`all`;return wr({...o,isWebhook:o.isWebhook??!0},s)}async function a(n){let i=await r(n)??await jr(e,n,t);if(!i)throw new k(n);return i}async function o(t){let r=B.join(e,`hooks`),i=t.resolveData||`all`,a=await At({directory:r,schema:E,sortOrder:t.pagination?.sortOrder??`asc`,limit:t.pagination?.limit,cursor:t.pagination?.cursor,filePrefix:void 0,filter:async e=>t.runId&&e.runId!==t.runId?!1:n(e),getCreatedAt:()=>null,getId:e=>e.hookId});return{...a,data:a.data.map(e=>wr(e,i))}}return{get:i,getByToken:a,list:o}}async function Pr(e,t){await vr(e);for(let n of await mr(e,t)){if(n.hookId){let r=null,a=null;try{a=K(e,`hooks`,n.hookId,n.tag),r=await X(a,E)}catch(e){if(!lt.is(e)&&!(e instanceof SyntaxError||e instanceof i))throw e}if(r&&a&&r.runId===t){if(r.tokenRetentionUntil&&r.tokenRetentionUntil.getTime()>Date.now())continue;await Zn(e,r.token,r.runId,r.hookId),await Z(Qn(e,r.token,r.runId,r.hookId)),await Z(a)}}await hr(e,n.fileId)}}const Fr=new Le;Fr.setMaxListeners(0);function Ir(){return p(`WORKFLOW_LOCAL_RUN_STATUS_POLL_INTERVAL_MS`,100,{integer:!0,min:1})}function Lr(e){Fr.emit(`run:${e}`)}function Rr(e,t,n){return t<=0||n?.aborted?Promise.resolve():new Promise(r=>{let i=`run:${e}`,a=!1,o=()=>{a||(a=!0,clearTimeout(s),Fr.off(i,o),n?.removeEventListener(`abort`,o),r())},s=setTimeout(o,t);Fr.once(i,o),n?.addEventListener(`abort`,o,{once:!0})})}async function zr(e,t,n,r,i,a){if(_(a.status)||await Bn(e,t))throw new O(`Workflow run "${t}" is already in a terminal state`);let o=Hn(e,t,n);await Q(o,r);try{if(await Bn(e,t)||await wt(o,i)!==`linked`)throw new O(`Workflow run "${t}" is already in a terminal state`)}finally{await R.unlink(o).catch(()=>{})}}async function Br(e,t,n,r,i){H(`runId`,t);let a=i?.resolveData??`all`;switch(n.eventType){case`run_cancelled`:{await Q(zn(e,t),``),await Un(e,t);let n=new Date,i={runId:r.runId,deploymentId:r.deploymentId,workflowName:r.workflowName,specVersion:r.specVersion,executionContext:r.executionContext,input:r.input,createdAt:r.createdAt,expiredAt:r.expiredAt,startedAt:r.startedAt,status:`cancelled`,output:void 0,error:void 0,completedAt:n,updatedAt:n,attributes:r.attributes};return await Y(U(e,`runs`,`${t}.json`),i,{overwrite:!0}),Lr(t),await Pr(e,t),{event:void 0,run:Sr(i,a)}}case`wait_completed`:case`hook_received`:{let i=`evnt_${er()}`,o=new Date,s={...n,runId:t,eventId:i,createdAt:o,specVersion:7},c=U(e,`events`,`${`${t}-${i}`}.json`);return n.eventType===`hook_received`?await zr(e,t,i,JSON.stringify(s,J,2),c,r):await Y(c,s),{event:m(s,a)}}default:throw Error(`Event type '${n.eventType}' not supported for legacy runs (specVersion: ${r.specVersion||`undefined`}). Please upgrade 'workflow' package.`)}}const Vr=c(`@workflow/world-local//runFileLocks`,1,()=>({byKey:new Map}));function Hr(e,t){let n=Vr.byKey.get(e),r={},i=(async()=>{n&&await n.catch(()=>void 0);try{return await t()}finally{Vr.byKey.get(e)===r.task&&Vr.byKey.delete(e)}})();return r.task=i,Vr.byKey.set(e,i),i}function Ur(e,t){let n=(async(n,r)=>{H(`runId`,n);let i=await q(e,`runs`,n,g,t);if(!i)throw new ge(n);return Sr(i,r?.resolveData??`all`)});return{get:n,waitForTerminalStatus:(async(e,t)=>{let r=Date.now()+(t?.timeoutMs??0);for(;;){let i=await n(e,t);if(_(i.status))return i;let a=r-Date.now();if(a<=0||t?.signal?.aborted)return i;await Rr(e,Math.min(a,Ir()),t?.signal)}}),getMany:(async(e,t)=>{let r=[...new Set(e)],i=await Promise.all(r.map(async e=>{try{return await n(e,t)}catch(e){if(e instanceof ge)return null;throw e}})),a=new Map(r.map((e,t)=>[e,i[t]]));return e.map(e=>a.get(e)??null)}),list:(async t=>{let n=t?.resolveData??`all`,r=await At({directory:B.join(e,`runs`),schema:g,fileIdFilter:t?.fileIdFilter,filter:e=>!(t?.workflowName&&e.workflowName!==t.workflowName||t?.status&&e.status!==t.status),sortOrder:t?.pagination?.sortOrder??`desc`,limit:t?.pagination?.limit??200,cursor:t?.pagination?.cursor,getCreatedAt:tr(`wrun`),getId:e=>e.runId});return n===`none`?{...r,data:r.data.map(e=>({...e,input:void 0,output:void 0}))}:r}),experimentalSetAttributes:async(n,r,i)=>(H(`runId`,n),Hr(n,async()=>{let a=await q(e,`runs`,n,g,t);if(!a)throw new ge(n);try{se(r,{existingKeys:Object.keys(a.attributes??{}),allowReservedAttributes:i?.allowReservedAttributes})}catch(e){throw e instanceof C,e}let o=te(a.attributes,r),s={...a,attributes:o,updatedAt:new Date};return await Y(K(e,`runs`,n,t),s,{overwrite:!0}),{attributes:o}}))}}const Wr=864e5;function Gr(){let e=Number(process.env.WORKFLOW_LOCAL_HOOK_RETENTION_LIMIT_DAYS??30);if(!Number.isFinite(e)||e<=0)throw new D(`WORKFLOW_LOCAL_HOOK_RETENTION_LIMIT_DAYS must be a positive number`,{status:400});return e*Wr}const Kr=o({eventId:u()}),qr=o({runId:u(),resumeId:u(),hookId:u(),eventId:u(),payloadDigest:u().optional()});function Jr(e,t){return e.eventType===`hook_received`&&e.correlationId===t.hookId&&(e.resumeId===void 0||e.resumeId===t.resumeId)}async function Yr(e,t,n,r){let i=await Gn(e,t,r);for(let a of i.ids){let i=await q(e,`events`,`${t}-${a}`,s,r);if(i&&i.resumeId===n.resumeId&&Jr(i,n))return i}return null}async function Xr(e,t,n){if(t.hookId&&await Rn(e,t.hookId,n))return!0;let r=await q(e,`runs`,t.runId,g,n);return r?_(r.status)?!t.tokenRetentionUntil||t.tokenRetentionUntil.getTime()<=Date.now():!1:!0}async function Zr(e){try{return await X(e,Kr)}catch(e){if(e instanceof SyntaxError||e instanceof i)return null;throw e}}function Qr(e){return ie(e.eventId)?e.eventId:null}function $r(e,t){let n=G(t).slice(e.length+1);return ie(n)?n:null}async function ei(e,t,n){return(await At({directory:B.join(e,`events`),schema:s,filePrefix:`${t}-`,filter:e=>e.eventType===`hook_created`&&e.correlationId===n,limit:1,getCreatedAt:tr(`evnt`),getId:e=>e.eventId})).data[0]?.eventId??null}async function ti(e,t,n,r,i){let a=await q(e,`events`,`${t}-${r}`,s,i);if(!a||a.eventType!==`hook_created`||a.correlationId!==n||await q(e,`hooks`,n,E,i))return;let o=Er(a);await ur(e,o.token,t,n,r,i),await fr(e,t,n,i),await Q(K(e,`hooks`,n,i),JSON.stringify(o,J,2))}async function ni(e,t,n,r,i){let a=Qn(e,t,n,r);return await Q(a,JSON.stringify({eventId:i}))?i:(await Zr(a))?.eventId??null}function ri(e,t,n){let r=e.get(t),i={},a=(async()=>{r&&await r.catch(()=>void 0);try{return await n()}finally{e.get(t)===i.task&&e.delete(t)}})();return i.task=a,e.set(t,a),a}async function ii(e,t){let n=B.join(e,`waits`),r=await Tt(n);for(let e of r)e.startsWith(`${t}-`)&&await Z(B.join(n,`${e}.json`))}async function ai(e,t,n,r){return Hr(t,async()=>{let i=await X(K(e,`runs`,t,n),g),a={...r,attributes:i?.attributes??r.attributes};return await Y(K(e,`runs`,t,n),a,{overwrite:!0}),_(a.status)&&Lr(t),a})}function oi(e,t){let n=Gr(),r=4194304,i=new Map,a=new Map,o=new Map,c=0;function u(e){let t=i.get(e);if(!t)return;i.delete(e),c-=a.get(e)??0,a.delete(e);let n=o.get(t.runId);n?.delete(e),n?.size===0&&o.delete(t.runId)}function f(e){for(let t of o.get(e)??[])u(t)}function p(){i.clear(),a.clear(),o.clear(),c=0,x.clear()}let x=new Map;function S(e){return t?`${e}.${t}`:e}async function C(n,r){let i=`${n}-${ce(r)}`;for(let n of t?[K(e,`events`,i,t),K(e,`events`,i)]:[K(e,`events`,i)])try{return await R.stat(n),!0}catch(e){if(e.code!==`ENOENT`)throw e}return!1}async function re(n,r){let i=S(n),a=x.get(i);if(a===void 0||r?.rescan){let r=await Gn(e,n,t);a===void 0?(a=r.count>0&&!r.usesSlots?null:{published:r.maxSlot},x.set(i,a)):a!==null&&(a.published=Math.max(a.published,r.maxSlot))}if(a===null)return null;let o=Math.max(a.published+1,1,r?.atLeast??1);for(;await C(n,o);)a.published=Math.max(a.published,o),o+=1;return o}function ae(e,t){let n=ne(t);if(n===null)return;let r=x.get(S(e));r&&(r.published=Math.max(r.published,n))}async function oe(e){let t=await re(e);return t===null?`evnt_${er()}`:ce(t)}async function ue(n){let r=await re(n,{rescan:!0});return r===null?Wn(e,n,t):{eventId:ce(r),createdAt:new Date}}function T(e,t,n){if(n>r)return;for(;i.size>0&&(i.size>=1e3||c+n>r);){let e=i.keys().next().value;u(e)}i.set(e,t),a.set(e,n),c+=n;let s=o.get(t.runId)??new Set;s.add(e),o.set(t.runId,s)}function me(e,t,n){if(b(e.eventType)){f(e.runId);return}let i=Buffer.byteLength(n);if(i>r)return;let a=s.safeParse(JSON.parse(n,bt));a.success&&T(t,a.data,i)}async function ye(n){let r=n;for(let n=0;;n++){let i=K(e,`events`,`${r.runId}-${r.eventId}`,t),a=JSON.stringify(r,J,2),o=ne(r.eventId);if(o===null)return await xt(i,a),me(r,i,a),r;if(await Q(i,a))return ae(r.runId,r.eventId),me(r,i,a),r;let s=await re(r.runId,{rescan:n>0&&n%8==0,atLeast:o+1});Ie(s!==null),r={...r,eventId:ce(s)}}}let j=(t,n)=>At({directory:B.join(e,`events`),schema:s,cachedItems:i,filePrefix:`${t}-`,sortOrder:n.sortOrder??`asc`,limit:n.limit,cursor:n.cursor,getCreatedAt:tr(`evnt`),getId:e=>e.eventId,getSortKey:Qr,getSortKeyFromFileId:e=>$r(t,e)}),M=new Map,N=new Map,P={clearCache:p,async create(r,i,a){if(i.eventType===`hook_created`&&i.eventData.tokenRetentionUntil!==void 0&&i.eventData.tokenRetentionUntil.getTime()>Date.now()+n)throw new D(`Hook minimum retention cannot exceed ${n/Wr} days in the Local World.`,{status:400});if(r!=null&&r!==``&&H(`runId`,r),`correlationId`in i&&typeof i.correlationId==`string`&&H(`correlationId`,i.correlationId),v(i.eventType)&&r&&i.correlationId){let e=t?`${r}-${i.correlationId}.${t}`:`${r}-${i.correlationId}`;return ri(M,e,o)}if(y(i.eventType)&&r&&i.correlationId){let e=t?`${r}-${i.correlationId}.hook.${t}`:`${r}-${i.correlationId}.hook`;return ri(N,e,o)}return o();async function o(){let n=``,o=!1,c=null,u=new Date,f;if(i.eventType===`run_created`&&(!r||r===``))f=`wrun_${er()}`;else if(r)f=r;else throw Error(`runId is required for non-run_created events`);if(i.eventType===`run_created`&&r&&r!==``){let e=fe(f,`wrun_`);if(e)throw new D(e)}let p=i.specVersion??7,y=null;if(i.eventType!==`run_created`&&![`step_completed`,`step_retrying`].includes(i.eventType)&&(y=await q(e,`runs`,f,g,t),i.eventType===`run_started`&&!y&&`eventData`in i&&i.eventData)){let n=i.eventData;if(n.deploymentId&&n.workflowName&&n.input!==void 0){se(Object.entries(n.attributes??{}).map(([e,t])=>({key:e,value:t})),{allowReservedAttributes:n.allowReservedAttributes===!0});let r={runId:f,deploymentId:n.deploymentId,status:`pending`,workflowName:n.workflowName,specVersion:p,executionContext:n.executionContext,input:n.input,output:void 0,error:void 0,startedAt:void 0,completedAt:void 0,attributes:n.attributes??{},encryptionPublicKey:n.encryptionPublicKey,createdAt:u,updatedAt:u};if(await Q(K(e,`runs`,f,t),JSON.stringify(r,J))){let e=await oe(f);await ye({eventType:`run_created`,runId:f,eventId:e,createdAt:u,specVersion:p,eventData:{deploymentId:n.deploymentId,workflowName:n.workflowName,input:n.input,executionContext:n.executionContext,attributes:n.attributes,allowReservedAttributes:n.allowReservedAttributes,encryptionPublicKey:n.encryptionPublicKey}}),y=r}else y=await q(e,`runs`,f,g,t)}}if(n=await oe(f),!y&&(i.eventType===`run_failed`||i.eventType===`attr_set`||i.eventType===`run_started`))throw new ge(f);if(y){if(pe(y.specVersion))throw new _e(y.specVersion,7);if(ee(y.specVersion))return Br(e,f,i,y,a)}let x=de(i),S=x&&i.eventType===`step_started`;if(y&&_(y.status)){if(i.eventType===`run_cancelled`&&y.status===`cancelled`){let e=await ye({...i,runId:f,eventId:n,createdAt:u,specVersion:p}),t=a?.resolveData??`all`;return{event:m(e,t),run:y,...y?{maxEvents:w()}:{}}}if(i.eventType===`run_started`)throw new O(`Workflow run "${f}" is already in terminal state "${y.status}"`);if(b(i.eventType))throw new A(`Cannot transition run from terminal state "${y.status}"`);if(x)throw new A(`Cannot create new entities on run in terminal state "${y.status}"`);if(i.eventType===`attr_set`)throw new A(`Cannot set attributes on run in terminal state "${y.status}"`)}let C=null;if(v(i.eventType)&&i.eventType!==`step_created`&&i.correlationId){if(C=await q(e,`steps`,`${f}-${i.correlationId}`,h,t),!C&&!S)throw new D(`Step "${i.correlationId}" not found`);if(S&&C)throw new A(`Step "${i.correlationId}" already created`);if(C){if(he(C.status))throw new A(`Cannot modify step in terminal state "${C.status}"`);if(y&&_(y.status)&&C.status!==`running`)throw new O(`Cannot modify non-running step on run in terminal state "${y.status}"`)}}if(l(i.eventType)&&i.correlationId){if(i.eventType===`hook_received`&&a?.resumeId){let n=await X(Xn(e,f,a.resumeId),qr);if(n&&n.hookId===i.correlationId&&(!a.resumePayloadDigest||!n.payloadDigest||n.payloadDigest===a.resumePayloadDigest)){let r=await q(e,`events`,`${f}-${n.eventId}`,s,t),i=r&&Jr(r,n)?r:await Yr(e,f,n,t);if(i)return{event:i}}}if(i.eventType===`hook_received`&&await Rn(e,i.correlationId,t)||!await q(e,`hooks`,i.correlationId,E,t))throw new k(i.correlationId);if(i.eventType===`hook_received`&&a?.resumeId){let r=Xn(e,f,a.resumeId),l=async r=>{if(r.hookId!==i.correlationId)throw new A(`hook_received resumeId "${a.resumeId}" already recorded for a different hook`);if(a.resumePayloadDigest&&r.payloadDigest&&r.payloadDigest!==a.resumePayloadDigest)throw new A(`hook_received resumeId "${a.resumeId}" already recorded with a different payload`);let l=await q(e,`events`,`${f}-${r.eventId}`,s,t);if(l&&Jr(l,r))return{event:l};let u=await Yr(e,f,r,t);return u?{event:u}:(c=r.eventId,l||(n=r.eventId,o=!0),null)},u=await X(r,qr);if(u){let e=await l(u);if(e)return e}else if(o=!ie(n),c=n,!await Q(r,JSON.stringify({runId:f,resumeId:a.resumeId,hookId:i.correlationId,eventId:n,...a.resumePayloadDigest?{payloadDigest:a.resumePayloadDigest}:{}}))){c=null;let e=await X(r,qr);if(e){let t=await l(e);if(t)return t}}}}let T={...i,runId:f,eventId:n,createdAt:u,specVersion:p,...i.eventType===`hook_received`&&a?.resumeId?{resumeId:a.resumeId}:{}};if(i.eventType===`run_started`&&`eventData`in T&&delete T.eventData,S&&T.eventType===`step_started`&&T.eventData){let{input:e,...t}=T.eventData;T={...T,eventData:t}}let M,N,P,F,be=!1,xe;if(b(i.eventType)&&y){await Q(zn(e,f,t),``),await Un(e,f,t);let r=await ue(f);n=r.eventId,T={...T,eventId:n,createdAt:r.createdAt}}if(i.eventType===`run_created`&&`eventData`in i){let n=i.eventData;if(se(Object.entries(n.attributes??{}).map(([e,t])=>({key:e,value:t})),{allowReservedAttributes:n.allowReservedAttributes===!0}),M={runId:f,deploymentId:n.deploymentId,status:`pending`,workflowName:n.workflowName,specVersion:p,executionContext:n.executionContext,input:n.input,output:void 0,error:void 0,startedAt:void 0,completedAt:void 0,attributes:n.attributes??{},encryptionPublicKey:n.encryptionPublicKey,createdAt:u,updatedAt:u},!await Q(K(e,`runs`,f,t),JSON.stringify(M,J,2)))throw new A(`Workflow run "${f}" already exists`)}else if(i.eventType===`run_started`){if(y){if(y.status===`running`){if(a?.skipPreload)return{run:y,maxEvents:w()};let e=await j(f,{limit:w()});return{run:y,events:e.data,cursor:e.cursor,hasMore:e.hasMore,maxEvents:w()}}M=await ai(e,f,t,{runId:y.runId,deploymentId:y.deploymentId,workflowName:y.workflowName,specVersion:y.specVersion,executionContext:y.executionContext,input:y.input,createdAt:y.createdAt,expiredAt:y.expiredAt,status:`running`,output:void 0,error:void 0,completedAt:void 0,startedAt:y.startedAt??u,updatedAt:u,attributes:y.attributes,encryptionPublicKey:y.encryptionPublicKey})}}else if(i.eventType===`run_completed`&&`eventData`in i){let n=i.eventData;y&&(M=await ai(e,f,t,{runId:y.runId,deploymentId:y.deploymentId,workflowName:y.workflowName,specVersion:y.specVersion,executionContext:y.executionContext,input:y.input,createdAt:y.createdAt,expiredAt:y.expiredAt,startedAt:y.startedAt,status:`completed`,output:n.output,error:void 0,completedAt:u,updatedAt:u,attributes:y.attributes,encryptionPublicKey:y.encryptionPublicKey}),await Promise.all([Pr(e,f),ii(e,f)]))}else if(i.eventType===`run_failed`&&`eventData`in i){let n=i.eventData;y&&(M=await ai(e,f,t,{runId:y.runId,deploymentId:y.deploymentId,workflowName:y.workflowName,specVersion:y.specVersion,executionContext:y.executionContext,input:y.input,createdAt:y.createdAt,expiredAt:y.expiredAt,startedAt:y.startedAt,status:`failed`,output:void 0,error:n.error,errorCode:n.errorCode,completedAt:u,updatedAt:u,attributes:y.attributes,encryptionPublicKey:y.encryptionPublicKey}),await Promise.all([Pr(e,f),ii(e,f)]))}else if(i.eventType===`run_cancelled`)y&&(M=await ai(e,f,t,{runId:y.runId,deploymentId:y.deploymentId,workflowName:y.workflowName,specVersion:y.specVersion,executionContext:y.executionContext,input:y.input,createdAt:y.createdAt,expiredAt:y.expiredAt,startedAt:y.startedAt,status:`cancelled`,output:void 0,error:void 0,completedAt:u,updatedAt:u,attributes:y.attributes,encryptionPublicKey:y.encryptionPublicKey}),await Promise.all([Pr(e,f),ii(e,f)]));else if(i.eventType===`attr_set`&&y)M=await Hr(f,async()=>{let n=await X(K(e,`runs`,f,t),g);if(!n)throw new ge(f);if(se(i.eventData.changes,{existingKeys:Object.keys(n.attributes),allowReservedAttributes:i.eventData.allowReservedAttributes===!0}),i.correlationId&&i.eventData.writer.type===`workflow`&&!await Q(U(e,`.locks`,`attributes`,t?`${f}-${i.correlationId}.created.${t}`:`${f}-${i.correlationId}.created`),``))throw new A(`Attribute event "${i.correlationId}" already exists`);let r={...n,attributes:te(n.attributes,i.eventData.changes),updatedAt:u};return await Y(K(e,`runs`,f,t),r,{overwrite:!0}),r});else if(i.eventType===`step_created`&&`eventData`in i){if(!await Q(U(e,`.locks`,`steps`,t?`${f}-${i.correlationId}.created.${t}`:`${f}-${i.correlationId}.created`),``))throw new A(`Step "${i.correlationId}" already created`);let n=i.eventData;N={runId:f,stepId:i.correlationId,stepName:n.stepName,status:`pending`,input:n.input,output:void 0,error:void 0,attempt:0,startedAt:void 0,completedAt:void 0,createdAt:u,updatedAt:u,specVersion:p},await Y(K(e,`steps`,`${f}-${i.correlationId}`,t),N)}else if(i.eventType===`step_started`){if(!C&&S){let n=i.eventData;if(await Q(U(e,`.locks`,`steps`,t?`${f}-${i.correlationId}.created.${t}`:`${f}-${i.correlationId}.created`),``)){let r={runId:f,stepId:i.correlationId,stepName:n.stepName,status:`pending`,input:n.input,output:void 0,error:void 0,attempt:0,startedAt:void 0,completedAt:void 0,createdAt:u,updatedAt:u,specVersion:p};await Y(K(e,`steps`,`${f}-${i.correlationId}`,t),r);let a=await oe(f);await ye({eventType:`step_created`,runId:f,eventId:a,createdAt:u,specVersion:p,correlationId:i.correlationId,eventData:{stepName:n.stepName,input:n.input}}),C=r,be=!0}else throw new A(`Step "${i.correlationId}" already created`)}if(C){if(C.retryAfter&&C.retryAfter.getTime()>Date.now())throw new ve(`Cannot start step "${i.correlationId}": retryAfter timestamp has not been reached yet`,{retryAfter:Math.ceil((C.retryAfter.getTime()-Date.now())/1e3)});let n=`${f}-${i.correlationId}`,r=await q(e,`steps`,n,h,t);if(r&&he(r.status))throw new A(`Cannot modify step in terminal state "${r.status}"`);N={...C,status:`running`,startedAt:C.startedAt??u,attempt:C.attempt+1,retryAfter:void 0,updatedAt:u},await Y(K(e,`steps`,n,t),N,{overwrite:!0})}}else if(i.eventType===`step_completed`&&`eventData`in i){let n=i.eventData;if(C){let r=`${f}-${i.correlationId}`;if(!await Q(U(e,`.locks`,`steps`,t?`${r}.terminal.${t}`:`${r}.terminal`),``))throw new A(`Cannot modify step in terminal state`);N={...C,status:`completed`,output:n.result,completedAt:u,updatedAt:u},await Y(K(e,`steps`,r,t),N,{overwrite:!0})}}else if(i.eventType===`step_failed`&&`eventData`in i){let n=i.eventData;if(C){let r=`${f}-${i.correlationId}`;if(!await Q(U(e,`.locks`,`steps`,t?`${r}.terminal.${t}`:`${r}.terminal`),``))throw new A(`Cannot modify step in terminal state`);N={...C,status:`failed`,error:n.error,completedAt:u,updatedAt:u},await Y(K(e,`steps`,r,t),N,{overwrite:!0})}}else if(i.eventType===`step_retrying`&&`eventData`in i){let n=i.eventData;if(C){let r=`${f}-${i.correlationId}`;N={...C,status:`pending`,error:n.error,retryAfter:n.retryAfter,updatedAt:u},await Y(K(e,`steps`,r,t),N,{overwrite:!0})}}else if(i.eventType===`hook_created`&&`eventData`in i){let r=i.eventData,s=Kn(e,r.token),c=JSON.stringify({token:r.token,hookId:i.correlationId,runId:f,eventId:n,tokenRetentionUntil:r.tokenRetentionUntil}),l=await Yn(e,r.token,async n=>{let a=await Jn(s);return a||=(n.throwIfAborted(),await Z(s),await jr(e,r.token,t),await Jn(s)),a?a.runId===f&&a.hookId===i.correlationId?{status:`owned`,claim:a}:await Xr(e,a,t)?(n.throwIfAborted(),await Z(s),a.hookId&&(await Z(K(e,`hooks`,a.hookId,t)),await Z(Qn(e,r.token,a.runId,a.hookId)),await pr(e,a.runId,a.hookId,t)),n.throwIfAborted(),Ie(await Q(s,c)),{status:`claimed`}):{status:`conflict`,claim:a}:(n.throwIfAborted(),Ie(await Q(s,c)),{status:`claimed`})});if(l.status===`owned`){let a=l.claim,s;if(a.eventId)s=a.eventId;else{let a=await ei(e,f,i.correlationId);if(a!==null)throw await ti(e,f,i.correlationId,a,t),new A(`Hook "${i.correlationId}" already created`);let o=await ni(e,r.token,f,i.correlationId,n);if(o===null)throw new A(`Hook "${i.correlationId}" already created`);s=o}n=s,o=!0;let c=le(n.replace(/^evnt_/,``))??u;T={...i,eventData:{...i.eventData,tokenRetentionUntil:a.tokenRetentionUntil},runId:f,eventId:n,createdAt:c,specVersion:p}}if(l.status===`conflict`){let e=l.claim,t=await ye({eventType:`hook_conflict`,correlationId:i.correlationId,eventData:{token:r.token,conflictingRunId:e.runId},runId:f,eventId:n,createdAt:u,specVersion:p}),o=a?.resolveData??`all`,s=typeof a?.sinceCursor==`string`?await j(f,{sortOrder:`asc`,cursor:a.sinceCursor}):void 0,c={event:m(t,o),run:M,step:N,hook:void 0};return s?{...c,events:o===`none`?s.data.map(e=>m(e,o)):s.data,cursor:s.cursor,hasMore:s.hasMore}:c}let d=T.eventData;P={runId:f,hookId:i.correlationId,token:d.token,metadata:d.metadata,ownerId:`local-owner`,projectId:`local-project`,environment:`local`,createdAt:T.createdAt,specVersion:p,isWebhook:d.isWebhook??!1,isSystem:d.isSystem??!1,tokenRetentionUntil:d.tokenRetentionUntil},xe=l.status===`owned`?{overwrite:!0}:void 0,await ur(e,r.token,f,i.correlationId,n,t)}else if(i.eventType===`hook_disposed`){if(!await Q(Ln(e,i.correlationId,t),``))throw new A(`Hook "${i.correlationId}" already disposed`);let n=K(e,`hooks`,i.correlationId,t),r=await q(e,`hooks`,i.correlationId,E,t);r&&(await Zn(e,r.token,r.runId,r.hookId),await Z(Qn(e,r.token,r.runId,r.hookId))),await Z(n),await pr(e,f,i.correlationId,t)}else if(i.eventType===`wait_created`&&`eventData`in i){let n=`${f}-${i.correlationId}`;if(!await Q(U(e,`.locks`,`waits`,t?`${n}.created.${t}`:`${n}.created`),``))throw new A(`Wait "${i.correlationId}" already exists`);let r=i.eventData;F={waitId:n,runId:f,status:`waiting`,resumeAt:r.resumeAt,completedAt:void 0,createdAt:u,updatedAt:u,specVersion:p},await Y(K(e,`waits`,n,t),F)}else if(i.eventType===`wait_completed`){let n=`${f}-${i.correlationId}`,r=U(e,`.locks`,`waits`,t?`${n}.completed.${t}`:`${n}.completed`);if(!await Q(r,``))throw new A(`Wait "${i.correlationId}" already completed`);let a=await q(e,`waits`,n,d,t);if(!a)throw await R.unlink(r).catch(()=>{}),new D(`Wait "${i.correlationId}" not found`);F={...a,status:`completed`,completedAt:u,updatedAt:u},await Y(K(e,`waits`,n,t),F,{overwrite:!0})}if(i.eventType===`hook_received`&&i.correlationId&&await Rn(e,i.correlationId,t))throw new k(i.correlationId);let Se=K(e,`events`,`${f}-${n}`,t),I=JSON.stringify(T,J,2),Ce=async r=>{let i=ne(n);if(o||i===null)return!1;let a=await re(f,{rescan:r>0&&r%8==0,atLeast:i+1});return a!==null&&(n=ce(a),T={...T,eventId:n},Se=K(e,`events`,`${f}-${n}`,t),I=JSON.stringify(T,J,2),!0)},we=!1;for(let r=0;;r++){if(i.eventType===`hook_received`){let r=await Bn(e,f,t),i=r?null:await q(e,`runs`,f,g,t);if(r||i&&_(i.status))throw new O(`Workflow run "${f}" is already in a terminal state`);let a=Hn(e,f,`${n}.${er()}`,t);if(!await Q(a,I))throw new D(`Failed to stage event "${n}" for run "${f}": staging path already exists`);try{if(await Bn(e,f,t))throw new O(`Workflow run "${f}" is already in a terminal state`);let n=await wt(a,Se);if(n===`missing`)throw new O(`Workflow run "${f}" is already in a terminal state`);we=n===`linked`}finally{await Z(a).catch(()=>{})}}else we=await Q(Se,I);if(we){ae(f,n);break}if(i.eventType===`hook_received`&&a?.resumeId){let r=await q(e,`events`,`${f}-${n}`,s,t);if(r&&Jr(r,{runId:f,resumeId:a.resumeId,hookId:i.correlationId,eventId:n}))return{event:r}}if(!await Ce(r))break}if(!we)throw i.eventType===`hook_created`&&i.correlationId&&await ti(e,f,i.correlationId,n,t),new A(`Event "${n}" already exists for run "${f}"`);me(T,Se,I),i.eventType===`hook_received`&&a?.resumeId&&c!==null&&c!==n&&await xt(Xn(e,f,a.resumeId),JSON.stringify({runId:f,resumeId:a.resumeId,hookId:i.correlationId,eventId:n,...a.resumePayloadDigest?{payloadDigest:a.resumePayloadDigest}:{}}),{overwrite:!0}),P&&i.eventType===`hook_created`&&(await fr(e,P.runId,P.hookId,t),await Y(K(e,`hooks`,P.hookId,t),P,xe));let L=a?.resolveData??`all`,Te=m(T,L),z;if(i.eventType===`run_started`&&M&&!a?.skipPreload&&(z=await j(f,{limit:w()})),typeof a?.sinceCursor==`string`){let e=await j(f,{sortOrder:`asc`,cursor:a.sinceCursor});z=L===`none`?{...e,data:e.data.map(e=>m(e,L))}:e}let Ee={event:Te,run:M,step:N,hook:P,wait:F,...be?{stepCreated:!0}:{},...M?{maxEvents:w()}:{}};return z?{...Ee,events:z.data,cursor:z.cursor,hasMore:z.hasMore}:Ee}},async get(n,r,i){H(`runId`,n),H(`eventId`,r);let a=await q(e,`events`,`${n}-${r}`,s,t);if(!a)throw Error(`Event ${r} in run ${n} not found`);let o=i?.resolveData??`all`;return m(a,o)},async list(e){let{runId:t}=e;H(`runId`,t);let n=e.resolveData??`all`,r=await j(t,{...e.pagination,limit:e.pagination?.limit??w()});return n===`none`?{...r,data:r.data.map(e=>m(e,n))}:r},async listByCorrelationId(t){let n=t.correlationId;H(`correlationId`,n),H(`runId`,t.runId);let r=t.resolveData??`all`,a=await At({directory:B.join(e,`events`),schema:s,cachedItems:i,filePrefix:`${t.runId}-`,filter:e=>e.correlationId===n,sortOrder:t.pagination?.sortOrder??`asc`,limit:t.pagination?.limit,cursor:t.pagination?.cursor,getCreatedAt:tr(`evnt`),getId:e=>e.eventId,getSortKey:Qr,getSortKeyFromFileId:e=>$r(t.runId,e)});return r===`none`?{...a,data:a.data.map(e=>m(e,r))}:a}};async function F(e,t,n){if(!e.event)return e;let r=ne(e.event.eventId);if(r===null||t<1||r<=t+1)return e;let i=r-t-1,a=await P.list({runId:e.event.runId,pagination:{cursor:`${Dt}${ce(t)}`,limit:i,sortOrder:`asc`},resolveData:n}),o=e.event.eventId,s=a.data.filter(e=>e.eventId<o);return{...e,events:s,cursor:null,hasMore:s.length<r-t-1}}let be=(async(e,t,n)=>{if(n?.eventCount===void 0)return P.create(e,t,n);let r=n.resolveData??`all`,i=await P.create(e,t,n);return typeof n.sinceCursor==`string`?i:F(i,n.eventCount,r)});return{...P,create:be}}function si(e,t){return{get:(async(n,r,i)=>{H(`runId`,n),H(`stepId`,r);let a=await q(e,`steps`,`${n}-${r}`,h,t);if(!a)throw Error(`Step ${r} in run ${n} not found`);return Cr(a,i?.resolveData??`all`)}),list:(async t=>{H(`runId`,t.runId);let n=t.resolveData??`all`,r=await At({directory:B.join(e,`steps`),schema:h,filePrefix:`${t.runId}-`,sortOrder:t.pagination?.sortOrder??`desc`,limit:t.pagination?.limit,cursor:t.pagination?.cursor,getCreatedAt:tr(`step`),getId:e=>e.stepId});return n===`none`?{...r,data:r.data.map(e=>({...e,input:void 0,output:void 0}))}:r})}}function ci(e,t){let n=Ur(e,t),r=si(e,t),i=oi(e,t),a=Nr(e,t);return{runs:pn(`world.runs`,n),steps:pn(`world.steps`,r),events:pn(`world.events`,i),hooks:pn(`world.hooks`,a),clearCache:()=>i.clearCache()}}const li=c(`@workflow/world-local//streamerMonotonicUlid`,1,()=>({next:ue(()=>Math.random())})),ui=e=>li.next(e),di=o({streams:f(u())});function fi(e){return e===1}function pi(e){let t=Buffer.from([+!!e.eof]);return Buffer.concat([t,e.chunk])}function mi(e){return fi(e[0])}function hi(e){return{eof:mi(e),chunk:Buffer.from(e.subarray(1))}}async function gi(e){try{return await R.readdir(e)}catch(e){if(e.code===`ENOENT`)return[];throw e}}function _i(e,t,n,r=n,i=()=>!0){for(let a of t){if(!a.endsWith(n))continue;let t=a.slice(0,-n.length);i(t)&&e.set(t,r)}}function vi(e,t){return H(`streamName`,t),B.join(e,t)}async function yi(e,t,n){let r=vi(e,t),i=await gi(r),a=new Map;return _i(a,i,`.json`),_i(a,i,`.bin`,`.bin`,n?e=>!e.endsWith(`.${n}`):void 0),n&&_i(a,i,`.${n}.bin`),{files:[...a.keys()].sort(),extMap:a,dir:r}}function bi(e,t){let n=t?`.${t}`:``,r=new Le,i=new Set;async function a(n,r){H(`runId`,n),H(`streamName`,r);let a=`${n}:${r}`;if(i.has(a))return;let o=K(e,`streams/runs`,n,t),s=(await q(e,`streams/runs`,n,di,t))?.streams??[];s.includes(r)||(s.push(r),await Y(o,{streams:s},{overwrite:!0})),i.add(a)}function o(e){return typeof e==`string`?Buffer.from(new TextEncoder().encode(e)):e instanceof Buffer?e:Buffer.from(e)}return{streams:{async write(t,i,s){let c=`chnk_${ui()}`;await a(await t,i);let l=o(s),u=pi({chunk:l,eof:!1});await xt(B.join(vi(B.join(e,`streams`,`chunks`),i),`${c}${n}.bin`),u);let d=Uint8Array.from(l);r.emit(`chunk:${i}`,{streamName:i,chunkData:d,chunkId:c})},async writeMulti(t,i,s){if(s.length===0)return;let c=s.map(()=>`chnk_${ui()}`);await a(await t,i);let l=s.map(e=>o(e)).map(async(t,r)=>{let a=c[r],o=pi({chunk:t,eof:!1});return await xt(B.join(vi(B.join(e,`streams`,`chunks`),i),`${a}${n}.bin`),o),{chunkId:a,chunkData:Uint8Array.from(t)}});for(let e of l){let{chunkId:t,chunkData:n}=await e;r.emit(`chunk:${i}`,{streamName:i,chunkData:n,chunkId:t})}},async close(t,i){let o=`chnk_${ui()}`;await a(await t,i),await xt(B.join(vi(B.join(e,`streams`,`chunks`),i),`${o}${n}.bin`),pi({chunk:Buffer.from([]),eof:!0})),r.emit(`close:${i}`,{streamName:i})},async list(n){return H(`runId`,n),(await q(e,`streams/runs`,n,di,t))?.streams??[]},async getChunks(n,r,i){let a=i?.limit??100,{files:o,extMap:s,dir:c}=await yi(B.join(e,`streams`,`chunks`),r,t),l=0;if(i?.cursor)try{l=JSON.parse(Buffer.from(i.cursor,`base64`).toString(`utf-8`)).i}catch{l=0}let u=!1,d=[],f=0;for(let e of o){let t=s.get(e)??`.bin`,n=B.join(c,`${e}${t}`);if(f<l){if(fi(await Ct(n))){u=!0;break}f++;continue}if(d.length>=a){fi(await Ct(n))?u=!0:f++;break}let r=hi(await St(n));if(r.eof){u=!0;break}d.push({index:f,data:Uint8Array.from(r.chunk)}),f++}let p=!u&&f>l+d.length,m=l+d.length;return{data:d,cursor:p?Buffer.from(JSON.stringify({i:m})).toString(`base64`):null,hasMore:p,done:u}},async getInfo(n,r){let{files:i,extMap:a,dir:o}=await yi(B.join(e,`streams`,`chunks`),r,t),s=!1,c=0;for(let e of i){let t=a.get(e)??`.bin`;if(fi(await Ct(B.join(o,`${e}${t}`)))){s=!0;break}c++}return{tailIndex:c-1,done:s}},async get(n,i,a=0){let o=B.join(e,`streams`,`chunks`),s=()=>{},c=null,l=!1;return new ReadableStream({async start(e){let n=new Set,u=[],d=!0,f=!1,p=t=>{if(t.chunkData.byteLength===0){n.add(t.chunkId);return}d?(n.add(t.chunkId),u.push({chunkId:t.chunkId,chunkData:Uint8Array.from(t.chunkData)})):n.has(t.chunkId)||(n.add(t.chunkId),e.enqueue(Uint8Array.from(t.chunkData)))},m=()=>{if(d){f=!0;return}l=!0,s();try{e.close()}catch{}};s=()=>{r.off(`chunk:${i}`,p),r.off(`close:${i}`,m),c&&=(clearInterval(c),null)},r.on(`chunk:${i}`,p),r.on(`close:${i}`,m);let{files:h,extMap:g,dir:_}=await yi(o,i,t),v=h.length;if(typeof a==`number`&&a<0&&h.length>0){let e=h[h.length-1],t=g.get(e)??`.bin`;fi(await Ct(B.join(_,`${e}${t}`)))&&v--}let y=typeof a==`number`&&a<0?Math.max(0,v+a):a,b=!1;for(let t=y;t<h.length;t++){let r=h[t],i=r;if(n.has(i))continue;let a=g.get(r)??`.bin`,o=hi(await St(B.join(_,`${r}${a}`)));if(o?.eof===!0){b=!0;break}n.add(i),o.chunk.byteLength&&e.enqueue(Uint8Array.from(o.chunk))}d=!1,u.sort((e,t)=>e.chunkId.localeCompare(t.chunkId));for(let t of u)e.enqueue(Uint8Array.from(t.chunkData));if(b){l=!0,s();try{e.close()}catch{}return}if(f){l=!0,s();try{e.close()}catch{}return}for(let e=0;e<y&&e<h.length;e++)n.add(h[e]);if(l){s();return}let x=!1;c=setInterval(async()=>{if(!x){x=!0;try{let{files:r,extMap:a}=await yi(o,i,t);for(let t of r){let r=t;if(n.has(r))continue;n.add(r);let i=a.get(t)??`.bin`,o=hi(await St(B.join(_,`${t}${i}`)));if(o?.eof===!0){l=!0,s();try{e.close()}catch{}return}if(l)return;o.chunk.byteLength&&e.enqueue(Uint8Array.from(o.chunk))}}catch(e){e instanceof Error&&`code`in e||console.error(`[world-local] Unexpected polling error:`,e)}finally{x=!1}}},100)},cancel(){l=!0,s()}})}}}}function xi(e){let t=e?Object.fromEntries(Object.entries(e).filter(([,e])=>e!==void 0)):{},n={...it.value,...t};He(n.dataDir);let r=n.tag,i=wn(n),{clearCache:a,...o}=ci(n.dataDir,r),s=at(n);return{specVersion:oe(),capabilities:{hookRetention:{active:!0},hookResumeDedup:!0},...i,...o,...pn(`world.streams`,{...bi(n.dataDir,r),...n.streamFlushIntervalMs!==void 0&&{streamFlushIntervalMs:n.streamFlushIntervalMs}}),async start(){if(await Gt(n.dataDir),!s)return;let e=r?e=>pt(e,r):mt,t={...o.runs,list:(t=>o.runs.list({...t,fileIdFilter:e}))};await x(t,i.queue,`world-local`)},async close(){a(),await i.close()},async clear(){if(a(),r){let e=n.dataDir,t=B.join(e,`hooks`),i=await ht(t,r),{HookSchema:a}=await import(`../../_chunks/workflow/dist-veFIAdWV.js`).then(e=>e.t);await Promise.all(i.map(async n=>{let r=await X(B.join(t,n),a);r?.token&&(await Z(B.join(t,`tokens`,`${In(r.token)}.json`)),await Z(Qn(e,r.token,r.runId,r.hookId)))})),await Promise.all([`runs`,`steps`,`events`,`hooks`,`hooks/by-run`,`waits`,`streams/runs`].map(async t=>{let n=B.join(e,t),i=await ht(n,r);await Promise.all(i.map(e=>Z(B.join(n,e))))}));for(let t of[`token-index`,`id-index`]){let n=B.join(e,`hooks`,t),i;try{i=await L.readdir(n,{withFileTypes:!0})}catch{i=[]}await Promise.all(i.filter(e=>e.isDirectory()).map(async e=>{let t=B.join(n,e.name),i=await ht(t,r);await Promise.all(i.map(e=>Z(B.join(t,e))))}))}await L.rm(B.join(e,`.locks`),{recursive:!0,force:!0}).catch(()=>{});let o=B.join(e,`streams`,`chunks`),s;try{s=await L.readdir(o,{withFileTypes:!0})}catch{s=[]}await Promise.all(s.filter(e=>e.isDirectory()).map(async e=>{let t=B.join(o,e.name),n=await gt(t,r,`.bin`);await Promise.all(n.map(e=>L.unlink(B.join(t,e)).catch(()=>{})))})),dt()}else dt(),_r(),await Ae(n.dataDir,{recursive:!0,force:!0}),await Gt(n.dataDir)}}}export{Ft as DataDirAccessError,It as DataDirVersionError,Re as UnwritableDataDirError,xi as createWorld,Vt as ensureDataDir,Gt as initDataDir,Lt as parseVersion};
1
+ import{i as e,t}from"../../_chunks/workflow/rolldown-runtime-DPpTSio4.js";import{t as n}from"../../_chunks/workflow/debug-log-CVPstO1D.js";import{Ai as r,Bn as i,C as a,E as o,G as s,J as c,Kr as l,L as u,O as d,Q as f,R as p,Rr as m,U as h,W as g,X as _,Y as v,Z as y,Zr as b,_ as x,a as S,c as C,ct as w,d as ee,dt as te,f as ne,ft as re,ht as ie,k as T,l as ae,m as oe,mt as se,n as ce,nt as E,o as D,ot as le,q as ue,r as de,u as fe,ut as pe,v as me,x as O,y as k,z as he,zl as A,zn as j}from"../../_chunks/workflow/dist-DDeH-1ER.js";import{A as M,O as ge,d as _e,f as ve,o as ye,r as N,y as be}from"../../_chunks/workflow/dist-xTushGCp.js";import{i as P,n as F,r as xe,t as Se}from"../../_chunks/workflow/workflow-routes-CwqB063q.js";import{a as Ce,i as we,n as Te,r as Ee,t as De}from"../../_chunks/workflow/signal-exit-Dsy-TT0V.js";import{createHash as Oe}from"node:crypto";import{promisify as ke}from"node:util";import{fileURLToPath as I}from"node:url";import{promises as L}from"node:fs";import R,{access as Ae,constants as je,mkdir as Me,readFile as Ne,readdir as Pe,readlink as Fe,rm as Ie,unlink as Le,writeFile as Re}from"node:fs/promises";import z from"node:path";import{tmpdir as ze}from"node:os";import{execFile as Be}from"node:child_process";import{setTimeout as Ve}from"node:timers/promises";import He from"node:assert";import{EventEmitter as Ue}from"node:events";var We=class extends M{dataDir;constructor(e,t){super(`[workflow] The local (filesystem) world cannot create its data directory "${e}" (${t}). Workflow runs cannot be stored, so every run will fail before its first step. If this is a Vercel deployment, its filesystem is read-only and the local world cannot work there. The world is selected from the environment when the process starts: the Vercel world is used when VERCEL_DEPLOYMENT_ID is set, unless WORKFLOW_TARGET_WORLD says otherwise. Unset WORKFLOW_TARGET_WORLD in this deployment, or set WORKFLOW_TARGET_WORLD=vercel, to use the Vercel world. Otherwise point WORKFLOW_LOCAL_DATA_DIR at a writable directory.`,{code:t}),this.name=`UnwritableDataDirError`,this.dataDir=e}static is(e){return e instanceof Error&&e.name===`UnwritableDataDirError`}};const Ge=new Set([`EROFS`,`EACCES`,`EPERM`]);function Ke(e){return e!==void 0&&Ge.has(e)}const qe=A(`@workflow/world-local//buildTargetWarnings`,1,()=>({warnedAboutVercelDeployment:!1}));function Je(e){if(qe.warnedAboutVercelDeployment||!process.env.VERCEL_DEPLOYMENT_ID)return;let t=z.resolve(e),n=ze();t===n||t.startsWith(`${n}${z.sep}`)||(qe.warnedAboutVercelDeployment=!0,console.warn(`[workflow] Warning: the local (filesystem) world is running inside a Vercel deployment, writing to ${t}. That filesystem is read-only, so workflow runs will fail before their first step. The world is selected from the environment when the process starts: the Vercel world is used when VERCEL_DEPLOYMENT_ID is set, unless WORKFLOW_TARGET_WORLD says otherwise. Unset WORKFLOW_TARGET_WORLD in this deployment, or set WORKFLOW_TARGET_WORLD=vercel, to use the Vercel world.`))}function Ye(e,t=10){let n=parseInt(e,t);if(!Number.isNaN(n)&&n>=0&&n<=65535)return n}function Xe(e,t){let n=[],r=e.trim().split(`
2
+ `);for(let e of r){let r=e.trim().split(/\s+/);if(r.length<5||r[0]?.toUpperCase()!==`TCP`)continue;let[,i,,a,o]=r;if(a?.toUpperCase()!==`LISTENING`||o!==t.toString())continue;let s=i.lastIndexOf(`:`);if(s===-1)continue;let c=Ye(i.slice(s+1));c!==void 0&&n.push(c)}return n}const Ze=ke(Be);function Qe(e,t=10){let n=parseInt(e,t);if(!Number.isNaN(n)&&n>=0&&n<=65535)return n}const $e=((e,t)=>e.join(t))([``,`proc`],`/`);async function et(e){let t=[`${$e}/net/tcp`,`${$e}/net/tcp6`],n=[],r=new Set,i=`${$e}/${e}/fd`;try{let e=(await Pe(i)).sort((e,t)=>Number.parseInt(e,10)-Number.parseInt(t,10)),t=await Promise.allSettled(e.map(async e=>(await Fe(`${i}/${e}`)).match(/^socket:\[(\d+)\]$/)?.[1]??null));for(let e of t)e.status===`fulfilled`&&e.value&&(n.push(e.value),r.add(e.value))}catch{return[]}if(n.length===0)return[];let a=new Map;for(let e of t)try{let t=(await Ne(e,`utf8`)).split(`
3
+ `).slice(1);for(let e of t){if(!e.trim())continue;let t=e.trim().split(/\s+/);if(t.length<10)continue;let n=t[1],i=t[3],o=t[9];if(!n||i!==`0A`||!o||!r.has(o))continue;let s=n.indexOf(`:`);if(s===-1)continue;let c=n.slice(s+1);if(!c)continue;let l=Qe(c,16);l!==void 0&&a.set(o,l)}}catch{}let o=[];for(let e of n){let t=a.get(e);t!==void 0&&o.push(t)}return o}async function tt(e){try{let{stdout:t}=await Ze(`lsof`,[`-a`,`-i`,`-P`,`-n`,`-p`,e.toString()]),n=[],r=t.split(`
4
+ `);for(let e of r)if(e.includes(`LISTEN`)){let t=e.trim().split(/\s+/)[8];if(t){let e=t.lastIndexOf(`:`);if(e!==-1){let r=Qe(t.slice(e+1));r!==void 0&&n.push(r)}}}return n}catch{return[]}}async function nt(e){try{let{stdout:t}=await Ze(`cmd`,[`/c`,`netstat -ano -p tcp | findstr LISTENING`]);return Xe(t,e)}catch{return[]}}async function rt(){let{pid:e,platform:t}=process;try{switch(t){case`linux`:return await et(e);case`darwin`:return await tt(e);case`win32`:return await nt(e);default:return[]}}catch(e){return n(`[getAllPorts] Detection failed:`,e),[]}}const it=`${Se}/flow?__health`;async function at(e,t={}){let{endpoint:n=it,timeout:r=500}=t,i=new AbortController,a=setTimeout(()=>i.abort(),r);try{return(await fetch(`http://localhost:${e}${n}`,{method:`HEAD`,signal:i.signal})).status===200}catch{return!1}finally{clearTimeout(a)}}async function ot(e){let t=await rt();if(t.length===0)return;if(t.length===1)return t[0];let r=(await Promise.all(t.map(async t=>({port:t,isWorkflow:await at(t,e)})))).find(e=>e.isWorkflow);return r?r.port:(n(`[getWorkflowPort] Probing failed, falling back to first port:`,t[0]),t[0])}function st(e){let t={get value(){let n=e();return Object.defineProperty(t,"value",{value:n}),n}};return t}const ct=()=>process.env.WORKFLOW_LOCAL_DATA_DIR||`.workflow-data`,lt=()=>process.env.WORKFLOW_LOCAL_BASE_URL,ut=st(()=>({dataDir:ct(),baseUrl:lt()}));function dt(e){if(e.recoverActiveRuns!==void 0)return e.recoverActiveRuns;let t=process.env.WORKFLOW_LOCAL_RECOVER_ACTIVE_RUNS?.toLowerCase();return t!==`0`&&t!==`false`}function ft(e){return e.baseUrl??process.env.WORKFLOW_LOCAL_BASE_URL??F(`http://localhost`)}async function pt(e){if(e.baseUrl)return e.baseUrl;if(process.env.WORKFLOW_LOCAL_BASE_URL)return process.env.WORKFLOW_LOCAL_BASE_URL;if(typeof e.port==`number`)return F(`http://localhost:${e.port}`);if(process.env.PORT)return F(`http://localhost:${process.env.PORT}`);let t=await ot({endpoint:xe()});if(t)return F(`http://localhost:${t}`);throw Error(`Unable to resolve base URL for workflow queue.`)}const B=A(`@workflow/world-local//fs`,1,()=>({ulid:D(()=>Math.random()),createdFilesCache:new Set,createdDirectoriesCache:new Set}));function mt(e){let t=typeof e==`string`?e:String(e);return t.length>48?`${t.slice(0,48)}…`:t}var ht=class extends M{constructor(e,t){super(`Unsafe ${e} "${mt(t)}": must not be empty, contain ".", "/", "\\", or null bytes`),this.name=`UnsafeEntityIdError`}static is(e){return e instanceof Error&&e.name===`UnsafeEntityIdError`}};function V(e,t){if(t.length===0||t.startsWith(`.`)||t.includes(`/`)||t.includes(`\\`)||t.includes(`\0`)||t.includes(`.`))throw new ht(e,t)}function H(e,...t){let n=z.resolve(e),r=z.resolve(e,...t);if(r!==n&&!r.startsWith(n+z.sep))throw new ht(`path`,t.join(`/`));return r}const gt=process.platform===`win32`;async function U(e,t=5){if(!gt)return e();let n=[`EPERM`,`EBUSY`,`EACCES`];for(let r=0;r<=t;r++)try{return await e()}catch(e){if(!(r<t&&n.includes(e.code)))throw e;let i=10*2**r+Math.random()*10;await new Promise(e=>setTimeout(e,i))}throw Error(`Retry loop exited unexpectedly`)}function _t(){B.createdFilesCache.clear(),B.createdDirectoriesCache.clear()}const vt=/\.[a-zA-Z][a-zA-Z0-9-]*$/;function yt(e){return e.replace(vt,``)}function bt(e,t){return e.endsWith(`.${t}`)}function xt(e){return!vt.test(e)}function W(e,t,n,r){return V(`fileId`,n),r!==void 0&&V(`tag`,r),H(e,t,r?`${n}.${r}.json`:`${n}.json`)}async function G(e,t,n,r,i){if(V(`fileId`,n),i!==void 0&&V(`tag`,i),i){let a=await Y(H(e,t,`${n}.${i}.json`),r);if(a!==null)return a}return Y(H(e,t,`${n}.json`),r)}async function St(e,t){let n=`.${t}.json`;try{return(await L.readdir(e)).filter(e=>e.endsWith(n))}catch(e){if(e.code===`ENOENT`)return[];throw e}}async function Ct(e,t,n){let r=`.${t}${n}`;try{return(await L.readdir(e)).filter(e=>e.endsWith(r))}catch(e){if(e.code===`ENOENT`)return[];throw e}}async function wt(e){let t=z.resolve(e);if(!B.createdDirectoriesCache.has(t))try{await L.mkdir(t,{recursive:!0}),B.createdDirectoriesCache.add(t)}catch(e){let n=e.code;if(Ke(n)&&!await Tt(t))throw new We(t,n)}}async function Tt(e){try{return(await L.stat(e)).isDirectory()}catch{return!1}}async function Et(e,t){await wt(e);try{return await t()}catch(n){if(n.code!==`ENOENT`)throw n;return B.createdDirectoriesCache.delete(z.resolve(e)),await wt(e),t()}}function K(e,t){return t instanceof Uint8Array?{__type:`Uint8Array`,data:Buffer.from(t).toString(`base64`)}:t}function Dt(e,t){return typeof t==`object`&&t&&t.__type===`Uint8Array`&&typeof t.data==`string`?new Uint8Array(Buffer.from(t.data,`base64`)):t}async function q(e,t,n){return J(e,JSON.stringify(t,K,2),n)}async function J(e,t,n){if(!n?.overwrite){if(B.createdFilesCache.has(e))throw new N(`File ${e} already exists and 'overwrite' is false`);try{throw await L.access(e),B.createdFilesCache.add(e),new N(`File ${e} already exists and 'overwrite' is false`)}catch(e){if(e.code!==`ENOENT`)throw e}}let r=`${e}.tmp.${B.ulid()}`,i=!1;try{await Et(z.dirname(e),async()=>{await L.writeFile(r,t),i=!0,await U(()=>L.rename(r,e))}),B.createdFilesCache.add(e)}catch(e){throw i&&await U(()=>L.unlink(r),3).catch(()=>{}),e}}async function Y(e,t){try{let n=await U(()=>L.readFile(e,`utf-8`));return t.parse(JSON.parse(n,Dt))}catch(e){if(e.code===`ENOENT`)return null;throw e}}async function Ot(e){return await L.readFile(e)}async function kt(e){let t=await L.open(e,`r`);try{let e=Buffer.allocUnsafe(1),{bytesRead:n}=await t.read(e,0,1,0);return n===0?void 0:e[0]}finally{await t.close()}}async function X(e){try{await U(()=>L.unlink(e))}catch(e){if(e.code!==`ENOENT`)throw e}}async function Z(e,t){let n=`${e}.tmp.${B.ulid()}`,r=!1;try{return await Et(z.dirname(e),async()=>{await L.writeFile(n,t,{flag:`wx`}),r=!0;try{return await U(()=>L.link(n,e)),!0}catch(e){if(e.code===`EEXIST`)return!1;throw e}})}finally{r&&await U(()=>L.unlink(n),3).catch(()=>{})}}async function At(e,t){try{return await Et(z.dirname(t),()=>U(()=>L.link(e,t))),`linked`}catch(e){if(e.code===`EEXIST`)return`exists`;if(e.code===`ENOENT`)return`missing`;throw e}}async function Q(e){return jt(e,`.json`)}async function jt(e,t){try{return(await L.readdir(e)).filter(e=>e.endsWith(t)).map(e=>e.slice(0,-t.length))}catch(e){if(e.code===`ENOENT`)return[];throw e}}const Mt=`key:`;function Nt(e){if(!e)return null;if(e.startsWith(`key:`))return{timestamp:new Date(0),id:null,sortKey:e.slice(4)};let t=e.split(`|`);return{timestamp:new Date(t[0]),id:t[1]||null,sortKey:null}}function Pt(e,t,n){return n?`${Mt}${n}`:t?`${e.toISOString()}|${t}`:e.toISOString()}async function Ft(e){let{directory:t,schema:n,cachedItems:i,filePrefix:a,fileIdFilter:o,filter:s,sortOrder:c=`desc`,limit:l=20,cursor:u,getCreatedAt:d,getId:f,getSortKey:p,getSortKeyFromFileId:m}=e;a!==void 0&&V(`filePrefix`,a);let h=z.resolve(t),g=await Q(h),_=a?g.filter(e=>e.startsWith(a)):g,v=o?_.filter(o):_,y=Nt(u),b=v;if(y?.sortKey&&m){let e=y.sortKey;b=v.filter(t=>{let n=m(t);if(n===null)return!0;let r=n.localeCompare(e);return c===`desc`?r<0:r>0})}else y&&!y.sortKey&&(b=v.filter(e=>{let t=d(`${e}.json`);if(t){let e=y.timestamp.getTime(),n=t.getTime();return y.id?c===`desc`?n<=e:n>=e:c===`desc`?n<e:n>e}return!0}));let x=[];for(let e=0;e<b.length;e+=32){let t=b.slice(e,e+32),a=await Promise.all(t.map(async e=>{let t=z.join(h,`${e}.json`),a;try{let e=i?.get(t);a=e===void 0?await Y(t,n):structuredClone(e)}catch(t){if(t instanceof r)return console.warn(`Skipping item ${e} due to malformed JSON: ${t.message}`),null;throw t}return a&&s&&!await s(a)?null:a}));for(let e of a){if(!e)continue;let t=p?.(e)??null;if(y?.sortKey){if(t){let e=t.localeCompare(y.sortKey);if(c===`desc`?e>=0:e<=0)continue}x.push(e);continue}if(y){let t=e.createdAt.getTime(),n=y.timestamp.getTime();if(c===`desc`){if(t>n||t===n&&y.id&&f&&f(e)>=y.id)continue}else if(t<n||t===n&&y.id&&f&&f(e)<=y.id)continue}x.push(e)}}x.sort((e,t)=>{if(p){let n=p(e),r=p(t);if(n!==null&&r!==null)return c===`asc`?n.localeCompare(r):r.localeCompare(n)}let n=e.createdAt.getTime(),r=t.createdAt.getTime(),i=c===`asc`?n-r:r-n;if(i===0&&f){let n=f(e),r=f(t);return c===`asc`?n.localeCompare(r):r.localeCompare(n)}return i});let S=x.length>l,C=S?x.slice(0,l):x;return{data:C,cursor:C.length>0?Pt(C[C.length-1].createdAt,f?.(C[C.length-1]),p?.(C[C.length-1])):null,hasMore:S}}const It=A(`@workflow/world-local//packageInfo`,1,()=>({cached:null}));function Lt(){return typeof import.meta.url==`string`&&import.meta.url?z.dirname(I(import.meta.url)):null}async function Rt(){if(It.cached)return It.cached;let e=Lt();if(e)try{let t=await Ne(z.join(e,`../package.json`),`utf-8`);return It.cached=JSON.parse(t),It.cached}catch{}return It.cached={name:`@workflow/world-local`,version:`5.0.0-beta.43`},It.cached}const zt=`version.txt`;var Bt=class extends Error{dataDir;code;constructor(e,t,n){super(e),this.name=`DataDirAccessError`,this.dataDir=t,this.code=n}},Vt=class extends Error{oldVersion;newVersion;suggestedVersion;constructor(e,t,n,r){super(e),this.name=`DataDirVersionError`,this.oldVersion=t,this.newVersion=n,this.suggestedVersion=r}};function Ht(e){let t=e.match(/^(\d+)\.(\d+)\.(\d+)(?:-(.+))?$/);if(!t)throw Error(`Invalid version string: "${e}"`);return{major:parseInt(t[1],10),minor:parseInt(t[2],10),patch:parseInt(t[3],10),prerelease:t[4],raw:e}}function $(e){let t=`${e.major}.${e.minor}.${e.patch}`;return e.prerelease?`${t}-${e.prerelease}`:t}function Ut(e){let t=e.trim(),n=t.lastIndexOf(`@`);if(n<=0)throw Error(`Invalid version file content: "${e}"`);return{packageName:t.substring(0,n),version:Ht(t.substring(n+1))}}function Wt(e,t){return`${e}@${$(t)}`}function Gt(e,t){console.log(`[world-local] Upgrading from version ${$(e)} to ${$(t)}`)}async function Kt(e){let t=z.resolve(e);try{await Me(t,{recursive:!0})}catch(e){let n=e;if(n.code!==`EEXIST`)throw new Bt(`Failed to create data directory "${t}": ${n.message}`,t,n.code)}try{await Ae(t,je.R_OK)}catch(e){let n=e;throw new Bt(`Data directory "${t}" is not readable: ${n.message}`,t,n.code)}let n=z.join(t,`.workflow-write-test-${Date.now()}`);try{await Re(n,``),await Le(n).catch(e=>{if(e.code!==`ENOENT`)throw e})}catch(e){let n=e;throw new Bt(`Data directory "${t}" is not writable: ${n.message}`,t,n.code)}}async function qt(e){let t=z.join(z.resolve(e),zt);try{return Ut(await Ne(t,`utf-8`))}catch(e){if(e.code===`ENOENT`)return null;throw e}}async function Jt(e,t){let n=z.join(z.resolve(e),zt),r=Wt((await Rt()).name,t);await Re(n,r)}function Yt(e,t){return t||$(e)}async function Xt(e){await Kt(e);let t=await Rt(),n=Ht(t.version),r=await qt(e);if(r===null){await Jt(e,n);return}let{version:i}=r;if($(i)!==$(n))try{Gt(i,n),await Jt(e,n)}catch(e){let r=Yt(i,e instanceof Vt?e.suggestedVersion:void 0);throw console.error(`[world-local] Failed to upgrade data directory from version ${$(i)} to ${$(n)}:`,e instanceof Error?e.message:e),console.error(`[world-local] Data is not compatible with the current version. Please downgrade to ${t.name}@${r}`),e}}const Zt=A(`@workflow/world-local//telemetry`,1,()=>({apiPromise:null,tracerPromise:null}));async function Qt(){return Zt.apiPromise||=import(`../../@opentelemetry/api/index.js`).catch(()=>null),Zt.apiPromise}async function $t(){return Zt.tracerPromise||=Qt().then(e=>e?e.trace.getTracer(`workflow`):null),Zt.tracerPromise}async function en(e,...t){let[n,r]=await Promise.all([$t(),Qt()]),{fn:i,opts:a}=typeof t[0]==`function`?{fn:t[0],opts:{}}:{fn:t[1],opts:t[0]};if(!i)throw Error(`Function to trace must be provided`);return!n||!r?await i():n.startActiveSpan(e,a,async e=>{try{let t=await i(e);return e.setStatus({code:r.SpanStatusCode.OK}),t}catch(t){throw e.setStatus({code:r.SpanStatusCode.ERROR,message:t.message}),t}finally{e.end()}})}async function tn(e){let t=await Qt();if(t)return t.SpanKind[e]}function nn(...e){return t=>Object.fromEntries(e.map(e=>[e,t]))}const rn=nn(`peer.service`),an=nn(`rpc.system`),on=nn(`rpc.service`),sn=nn(`rpc.method`),cn=nn(`workflow.run.id`),ln=nn(`step.id`),un={peerService:`world-local`,rpcSystem:`local`,rpcService:`world-local`},dn={"world.runs.get":0,"world.runs.experimentalSetAttributes":0,"world.steps.get":0,"world.events.create":0,"world.events.get":0},fn=new Set([`world.steps.list`,`world.events.list`,`world.hooks.list`]);function pn(e){if(e.length>=2&&typeof e[1]==`object`&&e[1]!==null){let t=e[1];if(typeof t.eventType==`string`)return t.eventType}}function mn(e,t){return typeof e[t]==`string`?e[t]:void 0}function hn(e){if(typeof e!=`object`||!e)return;let t=e.runId;return typeof t==`string`?t:void 0}function gn(e){if(typeof e!=`object`||!e)return;let t=e;if(typeof t.runId==`string`)return t.runId;for(let e of[`run`,`step`,`hook`,`wait`]){let n=t[e];if(typeof n==`object`&&n){let e=n.runId;if(typeof e==`string`)return e}}}function _n(e,t,n){let r=`${e}.${t}`,i={},a=dn[r],o=a===void 0?fn.has(r)?hn(n[0]):void 0:mn(n,a);if(o&&Object.assign(i,cn(o)),r===`world.steps.get`){let e=mn(n,1);e&&Object.assign(i,ln(e))}return i}function vn(e,t){let n={};for(let r of Object.keys(t))if(typeof t[r]!=`function`)n[r]=t[r];else{let i=t[r],a=String(r);n[r]=async(...t)=>{let n=`${e}.${a}`;if(e===`world.events`&&a===`create`){let r=pn(t);r&&(n=`${e}.${a} ${r}`)}return en(n,{kind:await tn(`INTERNAL`)},async r=>{r?.setAttributes({...rn(un.peerService),...an(un.rpcSystem),...on(un.rpcService),...sn(n),..._n(e,a,t)});let o=await i(...t),s=gn(o);return s&&r?.setAttributes(cn(s)),o})}}return n}var yn=t((t=>{var n=t&&t.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.RateLimit=t.Sema=void 0;let r=n(e(`events`));function i(e,t,n,r,i){for(let a=0;a<i;++a)n[a+r]=e[a+t],e[a+t]=void 0}function a(e){return e>>>=0,--e,e|=e>>1,e|=e>>2,e|=e>>4,e|=e>>8,e|=e>>16,e+1}function o(e){return a(Math.min(Math.max(16,e),1073741824))}var s=class{constructor(e){this._capacity=o(e),this._length=0,this._front=0,this.arr=[]}push(e){let t=this._length;this.checkCapacity(t+1);let n=this._front+t&this._capacity-1;return this.arr[n]=e,this._length=t+1,t+1}pop(){let e=this._length;if(e===0)return;let t=this._front+e-1&this._capacity-1,n=this.arr[t];return this.arr[t]=void 0,this._length=e-1,n}shift(){let e=this._length;if(e===0)return;let t=this._front,n=this.arr[t];return this.arr[t]=void 0,this._front=t+1&this._capacity-1,this._length=e-1,n}get length(){return this._length}checkCapacity(e){this._capacity<e&&this.resizeTo(o(this._capacity*1.5+16))}resizeTo(e){let t=this._capacity;this._capacity=e;let n=this._front,r=this._length;if(n+r>t){let e=n+r&t-1;i(this.arr,0,this.arr,t,e)}}},c=class extends r.default{};function l(e){return typeof e==`function`}function u(){return`1`}var d=class{constructor(e,{initFn:t=u,pauseFn:n,resumeFn:r,capacity:i=10}={}){if(l(n)!==l(r))throw Error(`pauseFn and resumeFn must be both set for pausing`);this.nrTokens=e,this.free=new s(e),this.waiting=new s(i),this.releaseEmitter=new c,this.noTokens=t===u,this.pauseFn=n,this.resumeFn=r,this.paused=!1,this.releaseEmitter.on(`release`,e=>{let t=this.waiting.shift();t?t.resolve(e):(this.resumeFn&&this.paused&&(this.paused=!1,this.resumeFn()),this.free.push(e))});for(let n=0;n<e;n++)this.free.push(t())}tryAcquire(){return this.free.pop()}async acquire(){let e=this.tryAcquire();return e===void 0?new Promise((e,t)=>{this.pauseFn&&!this.paused&&(this.paused=!0,this.pauseFn()),this.waiting.push({resolve:e,reject:t})}):e}release(e){this.releaseEmitter.emit(`release`,this.noTokens?`1`:e)}drain(){let e=Array(this.nrTokens);for(let t=0;t<this.nrTokens;t++)e[t]=this.acquire();return Promise.all(e)}nrWaiting(){return this.waiting.length}};t.Sema=d;function f(e,{timeUnit:t=1e3,uniformDistribution:n=!1}={}){let r=new d(n?1:e),i=n?t/e:t;return async function(){await r.acquire(),setTimeout(()=>r.release(),i)}}t.RateLimit=f}))(),bn=Te(),xn=class{contentType=`application/json`;serialize(e){return Buffer.from(JSON.stringify(e,K))}async deserialize(e){let t=[],n=e.getReader();for(;;){let{done:e,value:r}=await n.read();if(e)break;r&&t.push(r)}let r=Buffer.concat(t).toString();return JSON.parse(r,Dt)}};const Sn=parseInt(process.env.WORKFLOW_LOCAL_QUEUE_MAX_VISIBILITY??`0`,10)||1/0,Cn=2147483647,wn=parseInt(process.env.WORKFLOW_LOCAL_QUEUE_CONCURRENCY??`0`,10)||1e3;function Tn(e,t){let n=process.env[e];if(n===void 0||n===``)return t;let r=Number.parseInt(n,10);return Number.isFinite(r)&&r>=0?r:t}function En(){return{bodyTimeout:Tn(`WORKFLOW_LOCAL_BODY_TIMEOUT_MS`,3e4),connections:1e3,headersTimeout:Tn(`WORKFLOW_LOCAL_HEADERS_TIMEOUT_MS`,3e4),keepAliveTimeout:3e4}}const Dn=`Cannot perform ArrayBuffer.prototype.slice on a detached ArrayBuffer`;function On(e){let t=e,n=new Set;for(;t&&typeof t==`object`&&!n.has(t);){if(n.add(t),`message`in t&&typeof t.message==`string`&&t.message.includes(Dn))return!0;t=`cause`in t?t.cause:void 0}return!1}function kn(e){let t=En(),r=me()?Ee({maxSockets:t.connections,keepAliveMs:t.keepAliveTimeout}):void 0,i=r?void 0:new bn.Agent(t),s=new xn,c=D(),l=new yn.Sema(wn),u=new AbortController,d=u.signal,f=new Map,p=new Map,h=async(a,u,m)=>{let h=[];if(m?.idempotencyKey){let e=f.get(m.idempotencyKey);if(e)return{messageId:e}}let g=s.serialize(u),{prefix:_}=o(a),v=O.parse(`msg_${c()}`),y=u,b=y.runId??void 0,x=y.stepId??void 0;if(m?.idempotencyKey){let e=m.idempotencyKey;f.set(e,v),h.push(()=>{f.delete(e)})}return(async()=>{if(m?.delaySeconds&&m.delaySeconds>0){let e=Math.min(m.delaySeconds*1e3,Cn);await Ve(e,void 0,{signal:d})}l.tryAcquire()||(n(`[world-local]: concurrency limit (${wn}) reached, waiting for queue to free up`),await l.acquire());let o=0;try{for(let n=0;n<256;n++){let s={...m?.headers,"content-type":`application/json`,"x-vqs-queue-name":a,"x-vqs-message-id":v,"x-vqs-message-attempt":String(o+1)},c=p.get(_),l,u;try{if(c)l=await c(new Request(P(ft(e),{type:`flow`}),{method:`POST`,headers:s,body:g}));else{let n=await pt(e),a=P(n,{type:`flow`});l=r?await Ce(a,{method:`POST`,headers:new Headers(s),body:g,agents:r,signal:d,headersTimeoutMs:t.headersTimeout,bodyTimeoutMs:t.bodyTimeout}):await fetch(a,{method:`POST`,duplex:`half`,dispatcher:i,headers:s,body:g,signal:d})}o++,u=await l.text()}catch(e){let t=e?.name;if(d.aborted||t===`AbortError`||t===`ResponseAborted`)return;if(On(e))throw e;console.error(`[world-local] Queue delivery failed at the transport (loop ${n+1}), retrying`,{queueName:a,messageId:v,...b&&{runId:b},...x&&{stepId:x},error:String(e)}),await Ve(5e3,void 0,{signal:d});continue}if(l.ok){try{let e=Number(JSON.parse(u).timeoutSeconds);if(Number.isFinite(e)&&e>=0){if(e>0){let t=Math.min(e*1e3,Cn);await Ve(t,void 0,{signal:d})}continue}}catch{}return}console.error(`[world-local] Queue message failed (attempt ${o}, HTTP ${l.status})`,{queueName:a,messageId:v,...b&&{runId:b},...x&&{stepId:x},handlerError:u}),await Ve(5e3,void 0,{signal:d})}console.error(`[world-local] Queue message exhausted safety limit (256 attempts)`,{queueName:a,messageId:v,...b&&{runId:b},...x&&{stepId:x}})}finally{l.release()}})().catch(e=>{e?.name!==`AbortError`&&e?.name!==`ResponseAborted`&&(On(e)?console.error(`[local world] Queue operation failed: detected "${Dn}". This usually means a Next.js proxy/middleware consumed Workflow's internal request before the executor could read it. Exclude \`/.well-known/workflow/*\` from your matcher. See https://workflow-sdk.dev/docs/getting-started/next#configure-proxy-handler`,{queueName:a,messageId:v,...b&&{runId:b},...x&&{stepId:x},originalError:e}):console.error(`[local world] Queue operation failed:`,e))}).finally(()=>{for(let e of h)e()}),{messageId:v}},g=m({"x-vqs-queue-name":a,"x-vqs-message-id":O,"x-vqs-message-attempt":ie()});return{queue:h,createQueueHandler:(e,t)=>async n=>{let r=g.safeParse(Object.fromEntries(n.headers));if(!r.success||!n.body)return Response.json({error:n.body?`Missing required headers`:`Missing request body`},{status:400});let i=r.data[`x-vqs-queue-name`],a=r.data[`x-vqs-message-id`],o=r.data[`x-vqs-message-attempt`];if(!i.startsWith(e))return Response.json({error:`Unhandled queue`},{status:400});let s=await new xn().deserialize(n.body);try{let e=await t(s,{attempt:o,queueName:i,messageId:a}),n=null;return typeof e?.timeoutSeconds==`number`&&(n=Math.min(e.timeoutSeconds,Sn)),n==null?Response.json({ok:!0}):Response.json({timeoutSeconds:n})}catch(e){return Response.json(String(e),{status:500})}},getDeploymentId:async()=>`dpl_local@${(await Rt()).version}`,registerHandler(e,t){p.set(e,t)},async close(){d.aborted||(u.abort(),r&&we(r),await i?.close())}}}var An=t(((t,n)=>{var r=e(`constants`),i=process.cwd,a=null,o=process.env.GRACEFUL_FS_PLATFORM||process.platform;process.cwd=function(){return a||=i.call(process),a};try{process.cwd()}catch{}if(typeof process.chdir==`function`){var s=process.chdir;process.chdir=function(e){a=null,s.call(process,e)},Object.setPrototypeOf&&Object.setPrototypeOf(process.chdir,s)}n.exports=c;function c(e){r.hasOwnProperty(`O_SYMLINK`)&&process.version.match(/^v0\.6\.[0-2]|^v0\.5\./)&&t(e),e.lutimes||n(e),e.chown=s(e.chown),e.fchown=s(e.fchown),e.lchown=s(e.lchown),e.chmod=i(e.chmod),e.fchmod=i(e.fchmod),e.lchmod=i(e.lchmod),e.chownSync=c(e.chownSync),e.fchownSync=c(e.fchownSync),e.lchownSync=c(e.lchownSync),e.chmodSync=a(e.chmodSync),e.fchmodSync=a(e.fchmodSync),e.lchmodSync=a(e.lchmodSync),e.stat=l(e.stat),e.fstat=l(e.fstat),e.lstat=l(e.lstat),e.statSync=u(e.statSync),e.fstatSync=u(e.fstatSync),e.lstatSync=u(e.lstatSync),e.chmod&&!e.lchmod&&(e.lchmod=function(e,t,n){n&&process.nextTick(n)},e.lchmodSync=function(){}),e.chown&&!e.lchown&&(e.lchown=function(e,t,n,r){r&&process.nextTick(r)},e.lchownSync=function(){}),o===`win32`&&(e.rename=typeof e.rename==`function`?(function(t){function n(n,r,i){var a=Date.now(),o=0;t(n,r,function s(c){if(c&&(c.code===`EACCES`||c.code===`EPERM`||c.code===`EBUSY`)&&Date.now()-a<6e4){setTimeout(function(){e.stat(r,function(e,a){e&&e.code===`ENOENT`?t(n,r,s):i(c)})},o),o<100&&(o+=10);return}i&&i(c)})}return Object.setPrototypeOf&&Object.setPrototypeOf(n,t),n})(e.rename):e.rename),e.read=typeof e.read==`function`?(function(t){function n(n,r,i,a,o,s){var c;if(s&&typeof s==`function`){var l=0;c=function(u,d,f){if(u&&u.code===`EAGAIN`&&l<10)return l++,t.call(e,n,r,i,a,o,c);s.apply(this,arguments)}}return t.call(e,n,r,i,a,o,c)}return Object.setPrototypeOf&&Object.setPrototypeOf(n,t),n})(e.read):e.read,e.readSync=typeof e.readSync==`function`?(function(t){return function(n,r,i,a,o){for(var s=0;;)try{return t.call(e,n,r,i,a,o)}catch(e){if(e.code===`EAGAIN`&&s<10){s++;continue}throw e}}})(e.readSync):e.readSync;function t(e){e.lchmod=function(t,n,i){e.open(t,r.O_WRONLY|r.O_SYMLINK,n,function(t,r){if(t){i&&i(t);return}e.fchmod(r,n,function(t){e.close(r,function(e){i&&i(t||e)})})})},e.lchmodSync=function(t,n){var i=e.openSync(t,r.O_WRONLY|r.O_SYMLINK,n),a=!0,o;try{o=e.fchmodSync(i,n),a=!1}finally{if(a)try{e.closeSync(i)}catch{}else e.closeSync(i)}return o}}function n(e){r.hasOwnProperty(`O_SYMLINK`)&&e.futimes?(e.lutimes=function(t,n,i,a){e.open(t,r.O_SYMLINK,function(t,r){if(t){a&&a(t);return}e.futimes(r,n,i,function(t){e.close(r,function(e){a&&a(t||e)})})})},e.lutimesSync=function(t,n,i){var a=e.openSync(t,r.O_SYMLINK),o,s=!0;try{o=e.futimesSync(a,n,i),s=!1}finally{if(s)try{e.closeSync(a)}catch{}else e.closeSync(a)}return o}):e.futimes&&(e.lutimes=function(e,t,n,r){r&&process.nextTick(r)},e.lutimesSync=function(){})}function i(t){return t&&function(n,r,i){return t.call(e,n,r,function(e){d(e)&&(e=null),i&&i.apply(this,arguments)})}}function a(t){return t&&function(n,r){try{return t.call(e,n,r)}catch(e){if(!d(e))throw e}}}function s(t){return t&&function(n,r,i,a){return t.call(e,n,r,i,function(e){d(e)&&(e=null),a&&a.apply(this,arguments)})}}function c(t){return t&&function(n,r,i){try{return t.call(e,n,r,i)}catch(e){if(!d(e))throw e}}}function l(t){return t&&function(n,r,i){typeof r==`function`&&(i=r,r=null);function a(e,t){t&&(t.uid<0&&(t.uid+=4294967296),t.gid<0&&(t.gid+=4294967296)),i&&i.apply(this,arguments)}return r?t.call(e,n,r,a):t.call(e,n,a)}}function u(t){return t&&function(n,r){var i=r?t.call(e,n,r):t.call(e,n);return i&&(i.uid<0&&(i.uid+=4294967296),i.gid<0&&(i.gid+=4294967296)),i}}function d(e){return!(e&&e.code!==`ENOSYS`&&(process.getuid&&process.getuid()===0||e.code!==`EINVAL`&&e.code!==`EPERM`))}}})),jn=t(((t,n)=>{var r=e(`stream`).Stream;n.exports=i;function i(e){return{ReadStream:t,WriteStream:n};function t(n,i){if(!(this instanceof t))return new t(n,i);r.call(this);var a=this;this.path=n,this.fd=null,this.readable=!0,this.paused=!1,this.flags=`r`,this.mode=438,this.bufferSize=65536,i||={};for(var o=Object.keys(i),s=0,c=o.length;s<c;s++){var l=o[s];this[l]=i[l]}if(this.encoding&&this.setEncoding(this.encoding),this.start!==void 0){if(typeof this.start!=`number`)throw TypeError(`start must be a Number`);if(this.end===void 0)this.end=1/0;else if(typeof this.end!=`number`)throw TypeError(`end must be a Number`);if(this.start>this.end)throw Error(`start must be <= end`);this.pos=this.start}if(this.fd!==null){process.nextTick(function(){a._read()});return}e.open(this.path,this.flags,this.mode,function(e,t){if(e){a.emit(`error`,e),a.readable=!1;return}a.fd=t,a.emit(`open`,t),a._read()})}function n(t,i){if(!(this instanceof n))return new n(t,i);r.call(this),this.path=t,this.fd=null,this.writable=!0,this.flags=`w`,this.encoding=`binary`,this.mode=438,this.bytesWritten=0,i||={};for(var a=Object.keys(i),o=0,s=a.length;o<s;o++){var c=a[o];this[c]=i[c]}if(this.start!==void 0){if(typeof this.start!=`number`)throw TypeError(`start must be a Number`);if(this.start<0)throw Error(`start must be >= zero`);this.pos=this.start}this.busy=!1,this._queue=[],this.fd===null&&(this._open=e.open,this._queue.push([this._open,this.path,this.flags,this.mode,void 0]),this.flush())}}})),Mn=t(((e,t)=>{t.exports=r;var n=Object.getPrototypeOf||function(e){return e.__proto__};function r(e){if(typeof e!=`object`||!e)return e;if(e instanceof Object)var t={__proto__:n(e)};else var t=Object.create(null);return Object.getOwnPropertyNames(e).forEach(function(n){Object.defineProperty(t,n,Object.getOwnPropertyDescriptor(e,n))}),t}})),Nn=t(((t,n)=>{var r=e(`fs`),i=An(),a=jn(),o=Mn(),s=e(`util`),c,l;typeof Symbol==`function`&&typeof Symbol.for==`function`?(c=Symbol.for(`graceful-fs.queue`),l=Symbol.for(`graceful-fs.previous`)):(c=`___graceful-fs.queue`,l=`___graceful-fs.previous`);function u(){}function d(e,t){Object.defineProperty(e,c,{get:function(){return t}})}var f=u;s.debuglog?f=s.debuglog(`gfs4`):/\bgfs4\b/i.test(process.env.NODE_DEBUG||``)&&(f=function(){var e=s.format.apply(s,arguments);e=`GFS4: `+e.split(/\n/).join(`
5
+ GFS4: `),console.error(e)}),r[c]||(d(r,global[c]||[]),r.close=(function(e){function t(t,n){return e.call(r,t,function(e){e||g(),typeof n==`function`&&n.apply(this,arguments)})}return Object.defineProperty(t,l,{value:e}),t})(r.close),r.closeSync=(function(e){function t(t){e.apply(r,arguments),g()}return Object.defineProperty(t,l,{value:e}),t})(r.closeSync),/\bgfs4\b/i.test(process.env.NODE_DEBUG||``)&&process.on(`exit`,function(){f(r[c]),e(`assert`).equal(r[c].length,0)})),global[c]||d(global,r[c]),n.exports=p(o(r)),process.env.TEST_GRACEFUL_FS_GLOBAL_PATCH&&!r.__patched&&(n.exports=p(r),r.__patched=!0);function p(e){i(e),e.gracefulify=p,e.createReadStream=ee,e.createWriteStream=te;var t=e.readFile;e.readFile=n;function n(e,n,r){return typeof n==`function`&&(r=n,n=null),i(e,n,r);function i(e,n,r,a){return t(e,n,function(t){t&&(t.code===`EMFILE`||t.code===`ENFILE`)?m([i,[e,n,r],t,a||Date.now(),Date.now()]):typeof r==`function`&&r.apply(this,arguments)})}}var r=e.writeFile;e.writeFile=o;function o(e,t,n,i){return typeof n==`function`&&(i=n,n=null),a(e,t,n,i);function a(e,t,n,i,o){return r(e,t,n,function(r){r&&(r.code===`EMFILE`||r.code===`ENFILE`)?m([a,[e,t,n,i],r,o||Date.now(),Date.now()]):typeof i==`function`&&i.apply(this,arguments)})}}var s=e.appendFile;s&&(e.appendFile=c);function c(e,t,n,r){return typeof n==`function`&&(r=n,n=null),i(e,t,n,r);function i(e,t,n,r,a){return s(e,t,n,function(o){o&&(o.code===`EMFILE`||o.code===`ENFILE`)?m([i,[e,t,n,r],o,a||Date.now(),Date.now()]):typeof r==`function`&&r.apply(this,arguments)})}}var l=e.copyFile;l&&(e.copyFile=u);function u(e,t,n,r){return typeof n==`function`&&(r=n,n=0),i(e,t,n,r);function i(e,t,n,r,a){return l(e,t,n,function(o){o&&(o.code===`EMFILE`||o.code===`ENFILE`)?m([i,[e,t,n,r],o,a||Date.now(),Date.now()]):typeof r==`function`&&r.apply(this,arguments)})}}var d=e.readdir;e.readdir=h;var f=/^v[0-5]\./;function h(e,t,n){typeof t==`function`&&(n=t,t=null);var r=f.test(process.version)?function(e,t,n,r){return d(e,i(e,t,n,r))}:function(e,t,n,r){return d(e,t,i(e,t,n,r))};return r(e,t,n);function i(e,t,n,i){return function(a,o){a&&(a.code===`EMFILE`||a.code===`ENFILE`)?m([r,[e,t,n],a,i||Date.now(),Date.now()]):(o&&o.sort&&o.sort(),typeof n==`function`&&n.call(this,a,o))}}}if(process.version.substr(0,4)===`v0.8`){var g=a(e);x=g.ReadStream,C=g.WriteStream}var _=e.ReadStream;_&&(x.prototype=Object.create(_.prototype),x.prototype.open=S);var v=e.WriteStream;v&&(C.prototype=Object.create(v.prototype),C.prototype.open=w),Object.defineProperty(e,"ReadStream",{get:function(){return x},set:function(e){x=e},enumerable:!0,configurable:!0}),Object.defineProperty(e,"WriteStream",{get:function(){return C},set:function(e){C=e},enumerable:!0,configurable:!0});var y=x;Object.defineProperty(e,"FileReadStream",{get:function(){return y},set:function(e){y=e},enumerable:!0,configurable:!0});var b=C;Object.defineProperty(e,"FileWriteStream",{get:function(){return b},set:function(e){b=e},enumerable:!0,configurable:!0});function x(e,t){return this instanceof x?(_.apply(this,arguments),this):x.apply(Object.create(x.prototype),arguments)}function S(){var e=this;re(e.path,e.flags,e.mode,function(t,n){t?(e.autoClose&&e.destroy(),e.emit(`error`,t)):(e.fd=n,e.emit(`open`,n),e.read())})}function C(e,t){return this instanceof C?(v.apply(this,arguments),this):C.apply(Object.create(C.prototype),arguments)}function w(){var e=this;re(e.path,e.flags,e.mode,function(t,n){t?(e.destroy(),e.emit(`error`,t)):(e.fd=n,e.emit(`open`,n))})}function ee(t,n){return new e.ReadStream(t,n)}function te(t,n){return new e.WriteStream(t,n)}var ne=e.open;e.open=re;function re(e,t,n,r){return typeof n==`function`&&(r=n,n=null),i(e,t,n,r);function i(e,t,n,r,a){return ne(e,t,n,function(o,s){o&&(o.code===`EMFILE`||o.code===`ENFILE`)?m([i,[e,t,n,r],o,a||Date.now(),Date.now()]):typeof r==`function`&&r.apply(this,arguments)})}}return e}function m(e){f(`ENQUEUE`,e[0].name,e[1]),r[c].push(e),_()}var h;function g(){for(var e=Date.now(),t=0;t<r[c].length;++t)r[c][t].length>2&&(r[c][t][3]=e,r[c][t][4]=e);_()}function _(){if(clearTimeout(h),h=void 0,r[c].length!==0){var e=r[c].shift(),t=e[0],n=e[1],i=e[2],a=e[3],o=e[4];if(a===void 0)f(`RETRY`,t.name,n),t.apply(null,n);else if(Date.now()-a>=6e4){f(`TIMEOUT`,t.name,n);var s=n.pop();typeof s==`function`&&s.call(null,i)}else{var l=Date.now()-o,u=Math.max(o-a,1);l>=Math.min(u*1.2,100)?(f(`RETRY`,t.name,n),t.apply(null,n.concat([a]))):r[c].push(e)}h===void 0&&(h=setTimeout(_,0))}}})),Pn=t(((e,t)=>{function n(e,t){typeof t==`boolean`&&(t={forever:t}),this._originalTimeouts=JSON.parse(JSON.stringify(e)),this._timeouts=e,this._options=t||{},this._maxRetryTime=t&&t.maxRetryTime||1/0,this._fn=null,this._errors=[],this._attempts=1,this._operationTimeout=null,this._operationTimeoutCb=null,this._timeout=null,this._operationStart=null,this._options.forever&&(this._cachedTimeouts=this._timeouts.slice(0))}t.exports=n,n.prototype.reset=function(){this._attempts=1,this._timeouts=this._originalTimeouts},n.prototype.stop=function(){this._timeout&&clearTimeout(this._timeout),this._timeouts=[],this._cachedTimeouts=null},n.prototype.retry=function(e){if(this._timeout&&clearTimeout(this._timeout),!e)return!1;var t=new Date().getTime();if(e&&t-this._operationStart>=this._maxRetryTime)return this._errors.unshift(Error(`RetryOperation timeout occurred`)),!1;this._errors.push(e);var n=this._timeouts.shift();if(n===void 0){if(this._cachedTimeouts)this._errors.splice(this._errors.length-1,this._errors.length),this._timeouts=this._cachedTimeouts.slice(0),n=this._timeouts.shift();else return!1}var r=this,i=setTimeout(function(){r._attempts++,r._operationTimeoutCb&&(r._timeout=setTimeout(function(){r._operationTimeoutCb(r._attempts)},r._operationTimeout),r._options.unref&&r._timeout.unref()),r._fn(r._attempts)},n);return this._options.unref&&i.unref(),!0},n.prototype.attempt=function(e,t){this._fn=e,t&&(t.timeout&&(this._operationTimeout=t.timeout),t.cb&&(this._operationTimeoutCb=t.cb));var n=this;this._operationTimeoutCb&&(this._timeout=setTimeout(function(){n._operationTimeoutCb()},n._operationTimeout)),this._operationStart=new Date().getTime(),this._fn(this._attempts)},n.prototype.try=function(e){console.log(`Using RetryOperation.try() is deprecated`),this.attempt(e)},n.prototype.start=function(e){console.log(`Using RetryOperation.start() is deprecated`),this.attempt(e)},n.prototype.start=n.prototype.try,n.prototype.errors=function(){return this._errors},n.prototype.attempts=function(){return this._attempts},n.prototype.mainError=function(){if(this._errors.length===0)return null;for(var e={},t=null,n=0,r=0;r<this._errors.length;r++){var i=this._errors[r],a=i.message,o=(e[a]||0)+1;e[a]=o,o>=n&&(t=i,n=o)}return t}})),Fn=t((e=>{var t=Pn();e.operation=function(n){return new t(e.timeouts(n),{forever:n&&n.forever,unref:n&&n.unref,maxRetryTime:n&&n.maxRetryTime})},e.timeouts=function(e){if(e instanceof Array)return[].concat(e);var t={retries:10,factor:2,minTimeout:1e3,maxTimeout:1/0,randomize:!1};for(var n in e)t[n]=e[n];if(t.minTimeout>t.maxTimeout)throw Error(`minTimeout is greater than maxTimeout`);for(var r=[],i=0;i<t.retries;i++)r.push(this.createTimeout(i,t));return e&&e.forever&&!r.length&&r.push(this.createTimeout(i,t)),r.sort(function(e,t){return e-t}),r},e.createTimeout=function(e,t){var n=t.randomize?Math.random()+1:1,r=Math.round(n*t.minTimeout*t.factor**+e);return r=Math.min(r,t.maxTimeout),r},e.wrap=function(t,n,r){if(n instanceof Array&&(r=n,n=null),!r)for(var i in r=[],t)typeof t[i]==`function`&&r.push(i);for(var a=0;a<r.length;a++){var o=r[a],s=t[o];t[o]=function(r){var i=e.operation(n),a=Array.prototype.slice.call(arguments,1),o=a.pop();a.push(function(e){i.retry(e)||(e&&(arguments[0]=i.mainError()),o.apply(this,arguments))}),i.attempt(function(){r.apply(t,a)})}.bind(t,s),t[o].options=n}}})),In=t(((e,t)=>{t.exports=Fn()})),Ln=t(((e,t)=>{let n=Symbol();function r(e,t,r){let i=t[n];if(i)return t.stat(e,(e,t)=>{if(e)return r(e);r(null,t.mtime,i)});let a=new Date(Math.ceil(Date.now()/1e3)*1e3+5);t.utimes(e,a,a,i=>{if(i)return r(i);t.stat(e,(e,i)=>{if(e)return r(e);let a=i.mtime.getTime()%1e3==0?`s`:`ms`;Object.defineProperty(t,n,{value:a}),r(null,i.mtime,a)})})}function i(e){let t=Date.now();return e===`s`&&(t=Math.ceil(t/1e3)*1e3),new Date(t)}t.exports.probe=r,t.exports.getMtime=i})),Rn=t(((t,n)=>{let r=e(`path`),i=Nn(),a=In(),o=De(),s=Ln(),c={};function l(e,t){return t.lockfilePath||`${e}.lock`}function u(e,t,n){if(!t.realpath)return n(null,r.resolve(e));t.fs.realpath(e,n)}function d(e,t,n){let r=l(e,t);t.fs.mkdir(r,i=>{if(!i)return s.probe(r,t.fs,(e,i,a)=>{if(e)return t.fs.rmdir(r,()=>{}),n(e);n(null,i,a)});if(i.code!==`EEXIST`)return n(i);if(t.stale<=0)return n(Object.assign(Error(`Lock file is already being held`),{code:`ELOCKED`,file:e}));t.fs.stat(r,(r,i)=>{if(r)return r.code===`ENOENT`?d(e,{...t,stale:0},n):n(r);if(!f(i,t))return n(Object.assign(Error(`Lock file is already being held`),{code:`ELOCKED`,file:e}));p(e,t,r=>{if(r)return n(r);d(e,{...t,stale:0},n)})})})}function f(e,t){return e.mtime.getTime()<Date.now()-t.stale}function p(e,t,n){t.fs.rmdir(l(e,t),e=>{if(e&&e.code!==`ENOENT`)return n(e);n()})}function m(e,t){let n=c[e];n.updateTimeout||(n.updateDelay=n.updateDelay||t.update,n.updateTimeout=setTimeout(()=>{n.updateTimeout=null,t.fs.stat(n.lockfilePath,(r,i)=>{let a=n.lastUpdate+t.stale<Date.now();if(r)return r.code===`ENOENT`||a?h(e,n,Object.assign(r,{code:`ECOMPROMISED`})):(n.updateDelay=1e3,m(e,t));if(n.mtime.getTime()!==i.mtime.getTime())return h(e,n,Object.assign(Error(`Unable to update lock within the stale threshold`),{code:`ECOMPROMISED`}));let o=s.getMtime(n.mtimePrecision);t.fs.utimes(n.lockfilePath,o,o,r=>{let i=n.lastUpdate+t.stale<Date.now();if(!n.released){if(r)return r.code===`ENOENT`||i?h(e,n,Object.assign(r,{code:`ECOMPROMISED`})):(n.updateDelay=1e3,m(e,t));n.mtime=o,n.lastUpdate=Date.now(),n.updateDelay=null,m(e,t)}})})},n.updateDelay),n.updateTimeout.unref&&n.updateTimeout.unref())}function h(e,t,n){t.released=!0,t.updateTimeout&&clearTimeout(t.updateTimeout),c[e]===t&&delete c[e],t.options.onCompromised(n)}function g(e,t,n){t={stale:1e4,update:null,realpath:!0,retries:0,fs:i,onCompromised:e=>{throw e},...t},t.retries=t.retries||0,t.retries=typeof t.retries==`number`?{retries:t.retries}:t.retries,t.stale=Math.max(t.stale||0,2e3),t.update=t.update==null?t.stale/2:t.update||0,t.update=Math.max(Math.min(t.update,t.stale/2),1e3),u(e,t,(e,r)=>{if(e)return n(e);let i=a.operation(t.retries);i.attempt(()=>{d(r,t,(e,a,o)=>{if(i.retry(e))return;if(e)return n(i.mainError());let s=c[r]={lockfilePath:l(r,t),mtime:a,mtimePrecision:o,options:t,lastUpdate:Date.now()};m(r,t),n(null,e=>{if(s.released)return e&&e(Object.assign(Error(`Lock is already released`),{code:`ERELEASED`}));_(r,{...t,realpath:!1},e)})})})})}function _(e,t,n){t={fs:i,realpath:!0,...t},u(e,t,(e,r)=>{if(e)return n(e);let i=c[r];if(!i)return n(Object.assign(Error(`Lock is not acquired/owned by you`),{code:`ENOTACQUIRED`}));i.updateTimeout&&clearTimeout(i.updateTimeout),i.released=!0,delete c[r],p(r,t,n)})}function v(e,t,n){t={stale:1e4,realpath:!0,fs:i,...t},t.stale=Math.max(t.stale||0,2e3),u(e,t,(e,r)=>{if(e)return n(e);t.fs.stat(l(r,t),(e,r)=>e?e.code===`ENOENT`?n(null,!1):n(e):n(null,!f(r,t)))})}function y(){return c}o(()=>{for(let e in c){let t=c[e].options;try{t.fs.rmdirSync(l(e,t))}catch{}}}),n.exports.lock=g,n.exports.unlock=_,n.exports.check=v,n.exports.getLocks=y})),zn=t(((e,t)=>{let n=Nn();function r(e){let t=[`mkdir`,`realpath`,`stat`,`rmdir`,`utimes`],n={...e};return t.forEach(t=>{n[t]=(...n)=>{let r=n.pop(),i;try{i=e[`${t}Sync`](...n)}catch(e){return r(e)}r(null,i)}}),n}function i(e){return(...t)=>new Promise((n,r)=>{t.push((e,t)=>{e?r(e):n(t)}),e(...t)})}function a(e){return(...t)=>{let n,r;if(t.push((e,t)=>{n=e,r=t}),e(...t),n)throw n;return r}}function o(e){if(e={...e},e.fs=r(e.fs||n),typeof e.retries==`number`&&e.retries>0||e.retries&&typeof e.retries.retries==`number`&&e.retries.retries>0)throw Object.assign(Error(`Cannot use retries with the sync api`),{code:`ESYNC`});return e}t.exports={toPromise:i,toSync:a,toSyncOptions:o}})),Bn=t(((e,t)=>{let n=Rn(),{toPromise:r,toSync:i,toSyncOptions:a}=zn();async function o(e,t){let i=await r(n.lock)(e,t);return r(i)}function s(e,t){let r=i(n.lock)(e,a(t));return i(r)}function c(e,t){return r(n.unlock)(e,t)}function l(e,t){return i(n.unlock)(e,a(t))}function u(e,t){return r(n.check)(e,t)}function d(e,t){return i(n.check)(e,a(t))}t.exports=o,t.exports.lock=o,t.exports.unlock=c,t.exports.lockSync=s,t.exports.unlockSync=l,t.exports.check=u,t.exports.checkSync=d}))();function Vn(e){return Oe(`sha256`).update(e).digest(`hex`)}function Hn(e,t,n){return H(e,`.locks`,`hooks`,n?`${t}.disposed.${n}`:`${t}.disposed`)}async function Un(e,t,n){let r=[Hn(e,t)];n&&r.push(Hn(e,t,n));for(let e of r)try{return await R.access(e),!0}catch{}return!1}function Wn(e,t,n){return H(e,`.locks`,`runs`,n?`${t}.terminal.${n}`:`${t}.terminal`)}async function Gn(e,t,n){let r=[Wn(e,t)];n&&r.push(Wn(e,t,n));for(let e of r)try{return await R.access(e),!0}catch(e){if(e.code!==`ENOENT`)throw e}return!1}function Kn(e,t,n){return H(e,`.locks`,`runs`,n?`${t}.pending.${n}`:`${t}.pending`)}function qn(e,t,n,r){return z.join(Kn(e,t,r),`${n}.json`)}async function Jn(e,t,n){let r=[Kn(e,t)];n&&r.push(Kn(e,t,n));for(let e of r){let t;try{t=await R.readdir(e)}catch(e){if(e.code===`ENOENT`)continue;throw e}for(let n of t)try{await U(()=>R.unlink(z.join(e,n)))}catch(e){if(e.code!==`ENOENT`)throw e}await R.rmdir(e).catch(()=>{})}}async function Yn(e,t,n){let r=await Xn(e,t,n),i=Date.now();if(r.maxId)try{let e=S(r.maxId.replace(/^evnt_/,``));i<=e&&(i=e+1)}catch{}return{eventId:`evnt_${ar(i)}`,createdAt:new Date(i)}}async function Xn(e,t,n){let r=[];try{r=await R.readdir(z.join(e,`events`))}catch(e){if(e.code!==`ENOENT`)throw e}let i=`${t}-`,a=[],o=null,s=0,c=!1,l=0;for(let e of r){if(!e.startsWith(i)||!e.endsWith(`.json`))continue;let t=e.slice(0,-5);if(!xt(t)&&!(n&&bt(t,n)))continue;let r=yt(t).slice(i.length);l+=1,a.push(r),(!o||r>o)&&(o=r);let u=ee(r);u!==null&&(c=!0,u>s&&(s=u))}return{maxId:o,usesSlots:c,maxSlot:s,count:l,ids:a}}function Zn(e,t){return z.join(e,`hooks`,`tokens`,`${Vn(t)}.json`)}const Qn=m({hookId:b().optional(),runId:b(),eventId:b().optional(),tokenRetentionUntil:se().optional()});async function $n(e){try{return await Y(e,Qn)}catch(e){if(e instanceof SyntaxError||e instanceof r)return null;throw e}}async function er(e,t,n){let r=Zn(e,t);await R.mkdir(z.dirname(r),{recursive:!0});let i=new AbortController,a;try{a=await(0,Bn.lock)(r,{realpath:!1,stale:3e4,update:1e3,retries:{retries:350,factor:1,minTimeout:100,maxTimeout:100},onCompromised(e){i.abort(new M(`Hook token claim lock was compromised`,{cause:e}))}})}catch(e){throw new M(`Could not acquire Hook token claim lock`,{cause:e})}let o;try{o=await n(i.signal),i.signal.throwIfAborted()}catch(e){throw i.signal.aborted||await a().catch(()=>{}),e}try{await a()}catch(e){throw new M(`Could not release Hook token claim lock`,{cause:e})}return o}function tr(e,t,n){let r=Oe(`sha256`).update(`${t}\x00${n}`).digest(`hex`);return z.join(e,`hooks`,`resumes`,`${r}.json`)}async function nr(e,t,n,r){await er(e,t,async i=>{let a=Zn(e,t),o=await $n(a);o&&o.runId===n&&o.hookId===r&&(i.throwIfAborted(),await X(a))})}function rr(e,t,n,r){let i=Oe(`sha256`).update(`${t}\x00${n}\x00${r}`).digest(`hex`);return z.join(e,`hooks`,`tokens`,`${i}.recovery.json`)}const ir=A(`@workflow/world-local//storageMonotonicUlid`,1,()=>({next:D(()=>Math.random())})),ar=e=>ir.next(e),or=e=>{let t=RegExp(`^${e}_`,`g`);return n=>{let r=yt(n.replace(/\.json$/,``))+`.json`,i=r.indexOf(`-`);if(i===-1){let e=r.replace(/\.json$/,``).replace(t,``);return ce(e)}if(e===`step`)return null;let a=r.substring(i+1).replace(/\.json$/,``).replace(t,``);return ce(a)}},sr=m({runId:b()}),cr=m({hookId:b(),tag:b().optional()});function lr(e,t){return H(e,`hooks`,`token-index`,Vn(t))}function ur(e,t){return V(`hookId`,t),H(e,`hooks`,`id-index`,t)}function dr(e){return H(e,`hooks`,`by-run`)}function fr(e){let t=yt(e);return t===e?void 0:e.slice(t.length+1)}function pr(e,t){return t?xt(e)||bt(e,t):xt(e)}async function mr(e){try{return await Y(e,s)}catch(e){if(e instanceof SyntaxError||e instanceof r)return null;throw e}}async function hr(e,t,n,r,i,a){V(`runId`,n),V(`eventId`,i),a!==void 0&&V(`tag`,a);let o=a?`${i}.${a}.json`:`${i}.json`,s=JSON.stringify({runId:n});await Promise.all([Z(z.join(lr(e,t),o),s),Z(z.join(ur(e,r),o),s)])}function gr(e,t,n,r){return W(e,`hooks/by-run`,`${t}-${n}`,r)}async function _r(e,t,n,r){await Z(gr(e,t,n,r),JSON.stringify(r?{hookId:n,tag:r}:{hookId:n}))}async function vr(e,t,n,r){await X(gr(e,t,n,r)),r&&await X(gr(e,t,n))}async function yr(e,t){V(`runId`,t);let n=dr(e),i=`${t}-`,a=[];for(let e of await Q(n)){if(!e.startsWith(i))continue;let t=null;try{t=await Y(z.join(n,`${e}.json`),cr)}catch(e){if(!(e instanceof SyntaxError||e instanceof r))throw e}a.push({fileId:e,hookId:t?.hookId??null,tag:t?.tag})}return a}async function br(e,t){await X(z.join(dr(e),`${t}.json`))}const xr=A(`@workflow/world-local//hookIndexEnsureCache`,1,()=>({ensuredBasedirs:new Map}));function Sr(){xr.ensuredBasedirs.clear()}async function Cr(e){let t=z.resolve(e),n=xr.ensuredBasedirs.get(t);return n||(n=Tr(t).catch(e=>{throw xr.ensuredBasedirs.delete(t),e}),xr.ensuredBasedirs.set(t,n)),n}async function wr(e,t,n){for(let r=0;r<e.length;r+=t)await Promise.all(e.slice(r,r+t).map(n))}async function Tr(e){let t=z.join(e,`hooks`,`.hook-index-complete`);try{await R.access(t);return}catch{}let n=z.join(e,`events`);await wr(await Q(n),32,async t=>{let r=await mr(z.join(n,`${t}.json`));if(!r||r.eventType!==`hook_created`||typeof r.correlationId!=`string`)return;let i=r.eventData?.token;if(typeof i==`string`)try{await hr(e,i,r.runId,r.correlationId,r.eventId,fr(t))}catch{}});let i=z.join(e,`hooks`);await wr(await Q(i),32,async t=>{let n=null;try{n=await Y(z.join(i,`${t}.json`),k)}catch(e){if(!(e instanceof SyntaxError||e instanceof r))throw e}if(n)try{await _r(e,n.runId,n.hookId,fr(t))}catch{}}),await Z(t,``)}async function Er(e,t,n,i){await Cr(e);let a;try{a=t.kind===`token`?lr(e,t.token):ur(e,t.hookId)}catch{return null}let o=(await Q(a)).filter(e=>pr(e,i)).sort((e,t)=>yt(t).localeCompare(yt(e)));for(let t of o){let i=null;try{i=await Y(z.join(a,`${t}.json`),sr)}catch(e){if(!(e instanceof SyntaxError||e instanceof r))throw e}if(!i)continue;let o=yt(t),s;try{s=W(e,`events`,`${i.runId}-${o}`,fr(t))}catch{continue}let c=await mr(s);if(c&&c.eventType===`hook_created`&&typeof c.correlationId==`string`&&n(c))return c}return null}function Dr(e,t){return t===`none`?{...e,input:void 0,output:void 0}:e}function Or(e,t){return t===`none`?{...e,input:void 0,output:void 0}:e}function kr(e,t){if(t===`none`){let{metadata:t,...n}=e;return n}return e}function Ar(e){if(e.eventType!==`hook_created`)return;let t=e.eventData.token;return typeof t==`string`?t:void 0}function jr(e){let{token:t,metadata:n,isWebhook:r,isSystem:i,tokenRetentionUntil:a}=e.eventData;return{runId:e.runId,hookId:e.correlationId,token:t,metadata:n,ownerId:`local-owner`,projectId:`local-project`,environment:`local`,createdAt:e.createdAt,specVersion:e.specVersion,isWebhook:r??!0,isSystem:i??!1,tokenRetentionUntil:a}}function Mr(e,t){return e.eventType===`hook_created`&&typeof e.correlationId==`string`&&t(e)}async function Nr(e,t,n){let r=await G(e,`runs`,t,h,n);return r?g(r.status):!1}async function Pr(e,t,n,r){let i=await Er(e,t,e=>Mr(e,n),r);if(!i||!Mr(i,n))return null;if(await Nr(e,i.runId,r)){let e=i.eventData.tokenRetentionUntil;if(!e||e.getTime()<=Date.now())return null}return await Un(e,i.correlationId,r)?null:i}async function Fr(e,t,n){let r=jr(t);return await Z(Zn(e,r.token),JSON.stringify({token:r.token,hookId:r.hookId,runId:r.runId,eventId:t.eventId,tokenRetentionUntil:t.eventData.tokenRetentionUntil})),await _r(e,r.runId,r.hookId,n),await Z(W(e,`hooks`,r.hookId,n),JSON.stringify(r,K,2)),r}async function Ir(e,t,n){let r=await Pr(e,{kind:`token`,token:t},e=>Ar(e)===t,n);return r?Fr(e,r,n):null}async function Lr(e,t,n){let r=await Pr(e,{kind:`id`,hookId:t},e=>e.correlationId===t,n);return r?Fr(e,r,n):null}function Rr(e,t){async function n(n){return await Un(e,n.hookId,t)?!1:n.tokenRetentionUntil&&n.tokenRetentionUntil.getTime()>Date.now()?!0:!await Nr(e,n.runId,t)}async function r(r){let i=await $n(Zn(e,r));if(i?.hookId){try{let a=await G(e,`hooks`,i.hookId,k,t);if(a?.token===r){if(!await n(a))throw new ye(r);return{...a,isWebhook:a.isWebhook??!0}}}catch(e){if(!ht.is(e))throw e}return null}let a=z.join(e,`hooks`),o=await Q(a);for(let e of o){let t=await Y(z.join(a,`${e}.json`),k);if(t?.token===r){if(!await n(t))throw new ye(r);return{...t,isWebhook:t.isWebhook??!0}}}return null}async function i(r,i){V(`hookId`,r);let a=await G(e,`hooks`,r,k,t);if(a&&!await n(a))throw new ye(r);let o=a??await Lr(e,r,t);if(!o)throw new ye(r);let s=i?.resolveData||`all`;return kr({...o,isWebhook:o.isWebhook??!0},s)}async function a(n){let i=await r(n)??await Ir(e,n,t);if(!i)throw new ye(n);return i}async function o(t){let r=z.join(e,`hooks`),i=t.resolveData||`all`,a=await Ft({directory:r,schema:k,sortOrder:t.pagination?.sortOrder??`asc`,limit:t.pagination?.limit,cursor:t.pagination?.cursor,filePrefix:void 0,filter:async e=>t.runId&&e.runId!==t.runId?!1:n(e),getCreatedAt:()=>null,getId:e=>e.hookId});return{...a,data:a.data.map(e=>kr(e,i))}}return{get:i,getByToken:a,list:o}}async function zr(e,t){await Cr(e);for(let n of await yr(e,t)){if(n.hookId){let i=null,a=null;try{a=W(e,`hooks`,n.hookId,n.tag),i=await Y(a,k)}catch(e){if(!ht.is(e)&&!(e instanceof SyntaxError||e instanceof r))throw e}if(i&&a&&i.runId===t){if(i.tokenRetentionUntil&&i.tokenRetentionUntil.getTime()>Date.now())continue;await nr(e,i.token,i.runId,i.hookId),await X(rr(e,i.token,i.runId,i.hookId)),await X(a)}}await br(e,n.fileId)}}const Br=A(`@workflow/world-local//streamerMonotonicUlid`,1,()=>({next:D(()=>Math.random())})),Vr=e=>Br.next(e),Hr=m({streams:i(b())});function Ur(e){return e===1}function Wr(e){let t=Buffer.from([+!!e.eof]);return Buffer.concat([t,e.chunk])}function Gr(e){return Ur(e[0])}function Kr(e){return{eof:Gr(e),chunk:Buffer.from(e.subarray(1))}}async function qr(e){try{return await R.readdir(e)}catch(e){if(e.code===`ENOENT`)return[];throw e}}function Jr(e,t,n,r=n,i=()=>!0){for(let a of t){if(!a.endsWith(n))continue;let t=a.slice(0,-n.length);i(t)&&e.set(t,r)}}function Yr(e,t){return V(`streamName`,t),z.join(e,t)}async function Xr(e,t,n){let r=Yr(e,t),i=await qr(r),a=new Map;return Jr(a,i,`.json`),Jr(a,i,`.bin`,`.bin`,n?e=>!e.endsWith(`.${n}`):void 0),n&&Jr(a,i,`.${n}.bin`),{files:[...a.keys()].sort(),extMap:a,dir:r}}const Zr=`chnk_${`0`.repeat(26)}`;async function Qr(e,t,n){let r=z.join(e,`streams`,`chunks`),i=n?`.${n}`:``,a;try{V(`runId`,t),a=(await G(e,`streams/runs`,t,Hr,n))?.streams??[]}catch(e){$r(`streams of ${t}`,e);return}for(let e of a)try{let t=Yr(r,e);await J(z.join(t,`${Zr}${i}.bin`),Wr({chunk:Buffer.from([]),eof:!0}),{overwrite:!0});for(let e of await qr(t))e.startsWith(Zr)||(e.endsWith(`.bin`)||e.endsWith(`.json`))&&await U(()=>R.unlink(z.join(t,e))).catch(t=>{t.code!==`ENOENT`&&$r(e,t)})}catch(t){$r(e,t)}}function $r(e,t){console.warn(`[world-local] Failed to purge stream data for ${e}:`,t instanceof Error?t.message:t)}function ei(e,t){let n=t?`.${t}`:``,r=new Ue,i=new Set;async function a(n,r){V(`runId`,n),V(`streamName`,r);let a=`${n}:${r}`;if(i.has(a))return;let o=W(e,`streams/runs`,n,t),s=(await G(e,`streams/runs`,n,Hr,t))?.streams??[];s.includes(r)||(s.push(r),await q(o,{streams:s},{overwrite:!0})),i.add(a)}function o(e){return typeof e==`string`?Buffer.from(new TextEncoder().encode(e)):e instanceof Buffer?e:Buffer.from(e)}return{streams:{async write(t,i,s){let c=`chnk_${Vr()}`;await a(await t,i);let l=o(s),u=Wr({chunk:l,eof:!1});await J(z.join(Yr(z.join(e,`streams`,`chunks`),i),`${c}${n}.bin`),u);let d=Uint8Array.from(l);r.emit(`chunk:${i}`,{streamName:i,chunkData:d,chunkId:c})},async writeMulti(t,i,s){if(s.length===0)return;let c=s.map(()=>`chnk_${Vr()}`);await a(await t,i);let l=s.map(e=>o(e)).map(async(t,r)=>{let a=c[r],o=Wr({chunk:t,eof:!1});return await J(z.join(Yr(z.join(e,`streams`,`chunks`),i),`${a}${n}.bin`),o),{chunkId:a,chunkData:Uint8Array.from(t)}});for(let e of l){let{chunkId:t,chunkData:n}=await e;r.emit(`chunk:${i}`,{streamName:i,chunkData:n,chunkId:t})}},async close(t,i){let o=`chnk_${Vr()}`;await a(await t,i),await J(z.join(Yr(z.join(e,`streams`,`chunks`),i),`${o}${n}.bin`),Wr({chunk:Buffer.from([]),eof:!0})),r.emit(`close:${i}`,{streamName:i})},async list(n){return V(`runId`,n),(await G(e,`streams/runs`,n,Hr,t))?.streams??[]},async getChunks(n,r,i){let a=i?.limit??100,{files:o,extMap:s,dir:c}=await Xr(z.join(e,`streams`,`chunks`),r,t),l=0;if(i?.cursor)try{l=JSON.parse(Buffer.from(i.cursor,`base64`).toString(`utf-8`)).i}catch{l=0}let u=!1,d=[],f=0;for(let e of o){let t=s.get(e)??`.bin`,n=z.join(c,`${e}${t}`);if(f<l){if(Ur(await kt(n))){u=!0;break}f++;continue}if(d.length>=a){Ur(await kt(n))?u=!0:f++;break}let r=Kr(await Ot(n));if(r.eof){u=!0;break}d.push({index:f,data:Uint8Array.from(r.chunk)}),f++}let p=!u&&f>l+d.length,m=l+d.length;return{data:d,cursor:p?Buffer.from(JSON.stringify({i:m})).toString(`base64`):null,hasMore:p,done:u}},async getInfo(n,r){let{files:i,extMap:a,dir:o}=await Xr(z.join(e,`streams`,`chunks`),r,t),s=!1,c=0;for(let e of i){let t=a.get(e)??`.bin`;if(Ur(await kt(z.join(o,`${e}${t}`)))){s=!0;break}c++}return{tailIndex:c-1,done:s}},async get(n,i,a=0){let o=z.join(e,`streams`,`chunks`),s=()=>{},c=null,l=!1;return new ReadableStream({async start(e){let n=new Set,u=[],d=!0,f=!1,p=t=>{if(t.chunkData.byteLength===0){n.add(t.chunkId);return}d?(n.add(t.chunkId),u.push({chunkId:t.chunkId,chunkData:Uint8Array.from(t.chunkData)})):n.has(t.chunkId)||(n.add(t.chunkId),e.enqueue(Uint8Array.from(t.chunkData)))},m=()=>{if(d){f=!0;return}l=!0,s();try{e.close()}catch{}};s=()=>{r.off(`chunk:${i}`,p),r.off(`close:${i}`,m),c&&=(clearInterval(c),null)},r.on(`chunk:${i}`,p),r.on(`close:${i}`,m);let{files:h,extMap:g,dir:_}=await Xr(o,i,t),v=h.length;if(typeof a==`number`&&a<0&&h.length>0){let e=h[h.length-1],t=g.get(e)??`.bin`;Ur(await kt(z.join(_,`${e}${t}`)))&&v--}let y=typeof a==`number`&&a<0?Math.max(0,v+a):a,b=!1;for(let t=y;t<h.length;t++){let r=h[t],i=r;if(n.has(i))continue;let a=g.get(r)??`.bin`,o=Kr(await Ot(z.join(_,`${r}${a}`)));if(o?.eof===!0){b=!0;break}n.add(i),o.chunk.byteLength&&e.enqueue(Uint8Array.from(o.chunk))}d=!1,u.sort((e,t)=>e.chunkId.localeCompare(t.chunkId));for(let t of u)e.enqueue(Uint8Array.from(t.chunkData));if(b){l=!0,s();try{e.close()}catch{}return}if(f){l=!0,s();try{e.close()}catch{}return}for(let e=0;e<y&&e<h.length;e++)n.add(h[e]);if(l){s();return}let x=!1;c=setInterval(async()=>{if(!x){x=!0;try{let{files:r,extMap:a}=await Xr(o,i,t);for(let t of r){let r=t;if(n.has(r))continue;n.add(r);let i=a.get(t)??`.bin`,o=Kr(await Ot(z.join(_,`${t}${i}`)));if(o?.eof===!0){l=!0,s();try{e.close()}catch{}return}if(l)return;o.chunk.byteLength&&e.enqueue(Uint8Array.from(o.chunk))}}catch(e){e instanceof Error&&`code`in e||console.error(`[world-local] Unexpected polling error:`,e)}finally{x=!1}}},100)},cancel(){l=!0,s()}})}}}}function ti(e){let t=te(e);return t.unsupported&&console.warn(`[world-local] Ignoring unrecognized ${w} value ${JSON.stringify(t.raw)}; keeping the run's data.`),t.mode===`none`}function ni(e,t){return{...e,input:void 0,output:void 0,error:void 0,expiredAt:t}}async function ri(e,t,n){await Promise.all([ai(z.join(e,`steps`),t,e=>{e.input=void 0,e.output=void 0,e.error=void 0}),ai(z.join(e,`events`),t,e=>{let t=e.eventData;if(t&&typeof t==`object`)for(let n of E(String(e.eventType)))delete t[n]}),oi(e,t),Qr(e,t,n)])}const ii=l(b(),j());async function ai(e,t,n){let r;try{r=await Q(e)}catch(t){si(e,t);return}for(let i of r){if(!i.startsWith(`${t}-`))continue;let r=z.join(e,`${i}.json`);try{let e=await Y(r,ii);if(!e)continue;n(e),await q(r,e,{overwrite:!0})}catch(e){si(r,e)}}}async function oi(e,t){let n;try{await Cr(e),n=await yr(e,t)}catch(e){si(`hooks of ${t}`,e);return}for(let r of n)if(r.hookId)try{let n=W(e,`hooks`,r.hookId,r.tag),i=await Y(n,ii);if(!i||i.runId!==t)continue;i.metadata=void 0,await q(n,i,{overwrite:!0})}catch(e){si(r.hookId,e)}}function si(e,t){console.warn(`[world-local] Failed to purge user data for ${e}:`,t instanceof Error?t.message:t)}const ci=new Ue;ci.setMaxListeners(0);function li(){return d(`WORKFLOW_LOCAL_RUN_STATUS_POLL_INTERVAL_MS`,100,{integer:!0,min:1})}function ui(e){ci.emit(`run:${e}`)}function di(e,t,n){return t<=0||n?.aborted?Promise.resolve():new Promise(r=>{let i=`run:${e}`,a=!1,o=()=>{a||(a=!0,clearTimeout(s),ci.off(i,o),n?.removeEventListener(`abort`,o),r())},s=setTimeout(o,t);ci.once(i,o),n?.addEventListener(`abort`,o,{once:!0})})}async function fi(e,t,n,r,i,a){if(g(a.status)||await Gn(e,t))throw new _e(`Workflow run "${t}" is already in a terminal state`);let o=qn(e,t,n);await Z(o,r);try{if(await Gn(e,t)||await At(o,i)!==`linked`)throw new _e(`Workflow run "${t}" is already in a terminal state`)}finally{await R.unlink(o).catch(()=>{})}}async function pi(e,t,n,r,i){V(`runId`,t);let a=i?.resolveData??`all`;switch(n.eventType){case`run_cancelled`:{await Z(Wn(e,t),``),await Jn(e,t);let n=new Date,i={runId:r.runId,deploymentId:r.deploymentId,workflowName:r.workflowName,specVersion:r.specVersion,executionContext:r.executionContext,input:r.input,createdAt:r.createdAt,expiredAt:r.expiredAt,startedAt:r.startedAt,status:`cancelled`,output:void 0,error:void 0,completedAt:n,updatedAt:n,attributes:r.attributes},o=ti(i.attributes),s=o?ni(i,n):i;return await q(H(e,`runs`,`${t}.json`),s,{overwrite:!0}),ui(t),await zr(e,t),o&&await ri(e,t,void 0),{event:void 0,run:Dr(s,a)}}case`wait_completed`:case`hook_received`:{let i=`evnt_${ar()}`,o=new Date,s={...n,runId:t,eventId:i,createdAt:o,specVersion:7},c=H(e,`events`,`${`${t}-${i}`}.json`);return n.eventType===`hook_received`?await fi(e,t,i,JSON.stringify(s,K,2),c,r):await q(c,s),{event:f(s,a)}}default:throw Error(`Event type '${n.eventType}' not supported for legacy runs (specVersion: ${r.specVersion||`undefined`}). Please upgrade 'workflow' package.`)}}const mi=A(`@workflow/world-local//runFileLocks`,1,()=>({byKey:new Map}));function hi(e,t){let n=mi.byKey.get(e),r={},i=(async()=>{n&&await n.catch(()=>void 0);try{return await t()}finally{mi.byKey.get(e)===r.task&&mi.byKey.delete(e)}})();return r.task=i,mi.byKey.set(e,i),i}function gi(e,t){let n=(async(n,r)=>{V(`runId`,n);let i=await G(e,`runs`,n,h,t);if(!i)throw new ge(n);return Dr(i,r?.resolveData??`all`)});return{get:n,waitForTerminalStatus:(async(e,t)=>{let r=Date.now()+(t?.timeoutMs??0);for(;;){let i=await n(e,t);if(g(i.status))return i;let a=r-Date.now();if(a<=0||t?.signal?.aborted)return i;await di(e,Math.min(a,li()),t?.signal)}}),getMany:(async(e,t)=>{let r=[...new Set(e)],i=await Promise.all(r.map(async e=>{try{return await n(e,t)}catch(e){if(e instanceof ge)return null;throw e}})),a=new Map(r.map((e,t)=>[e,i[t]]));return e.map(e=>a.get(e)??null)}),list:(async t=>{let n=t?.resolveData??`all`,r=await Ft({directory:z.join(e,`runs`),schema:h,fileIdFilter:t?.fileIdFilter,filter:e=>!(t?.workflowName&&e.workflowName!==t.workflowName||t?.status&&e.status!==t.status),sortOrder:t?.pagination?.sortOrder??`desc`,limit:t?.pagination?.limit??200,cursor:t?.pagination?.cursor,getCreatedAt:or(`wrun`),getId:e=>e.runId});return n===`none`?{...r,data:r.data.map(e=>({...e,input:void 0,output:void 0}))}:r}),experimentalSetAttributes:async(n,r,i)=>(V(`runId`,n),hi(n,async()=>{let a=await G(e,`runs`,n,h,t);if(!a)throw new ge(n);try{re(r,{existingKeys:Object.keys(a.attributes??{}),allowReservedAttributes:i?.allowReservedAttributes})}catch(e){throw e instanceof le,e}let o=pe(a.attributes,r),s={...a,attributes:o,updatedAt:new Date};return await q(W(e,`runs`,n,t),s,{overwrite:!0}),{attributes:o}}))}}const _i=864e5;function vi(){let e=Number(process.env.WORKFLOW_LOCAL_HOOK_RETENTION_LIMIT_DAYS??30);if(!Number.isFinite(e)||e<=0)throw new M(`WORKFLOW_LOCAL_HOOK_RETENTION_LIMIT_DAYS must be a positive number`,{status:400});return e*_i}const yi=m({eventId:b()}),bi=m({runId:b(),resumeId:b(),hookId:b(),eventId:b(),payloadDigest:b().optional()});function xi(e,t){return e.eventType===`hook_received`&&e.correlationId===t.hookId&&(e.resumeId===void 0||e.resumeId===t.resumeId)}async function Si(e,t,n,r){let i=await Xn(e,t,r);for(let a of i.ids){let i=await G(e,`events`,`${t}-${a}`,s,r);if(i&&i.resumeId===n.resumeId&&xi(i,n))return i}return null}async function Ci(e,t,n){if(t.hookId&&await Un(e,t.hookId,n))return!0;let r=await G(e,`runs`,t.runId,h,n);return r?g(r.status)?!t.tokenRetentionUntil||t.tokenRetentionUntil.getTime()<=Date.now():!1:!0}async function wi(e){try{return await Y(e,yi)}catch(e){if(e instanceof SyntaxError||e instanceof r)return null;throw e}}function Ti(e){return ne(e.eventId)?e.eventId:null}function Ei(e,t){let n=yt(t).slice(e.length+1);return ne(n)?n:null}async function Di(e,t,n){return(await Ft({directory:z.join(e,`events`),schema:s,filePrefix:`${t}-`,filter:e=>e.eventType===`hook_created`&&e.correlationId===n,limit:1,getCreatedAt:or(`evnt`),getId:e=>e.eventId})).data[0]?.eventId??null}async function Oi(e,t,n,r,i){let a=await G(e,`events`,`${t}-${r}`,s,i);if(!a||a.eventType!==`hook_created`||a.correlationId!==n||await G(e,`hooks`,n,k,i))return;let o=jr(a);await hr(e,o.token,t,n,r,i),await _r(e,t,n,i),await Z(W(e,`hooks`,n,i),JSON.stringify(o,K,2))}async function ki(e,t,n,r,i){let a=rr(e,t,n,r);return await Z(a,JSON.stringify({eventId:i}))?i:(await wi(a))?.eventId??null}function Ai(e,t,n){let r=e.get(t),i={},a=(async()=>{r&&await r.catch(()=>void 0);try{return await n()}finally{e.get(t)===i.task&&e.delete(t)}})();return i.task=a,e.set(t,a),a}async function ji(e,t){let n=z.join(e,`waits`),r=await Q(n);for(let e of r)e.startsWith(`${t}-`)&&await X(z.join(n,`${e}.json`))}async function Mi(e,t,n,r){return hi(t,async()=>{let i=(await Y(W(e,`runs`,t,n),h))?.attributes??r.attributes,a={...r,attributes:i},o=g(a.status)&&ti(i);return o&&(a=ni(a,new Date)),await q(W(e,`runs`,t,n),a,{overwrite:!0}),g(a.status)&&ui(t),{run:a,purged:o}})}function Ni(e,t){let n=vi(),r=4194304,i=new Map,a=new Map,o=new Map,l=0;function d(e){let t=i.get(e);if(!t)return;i.delete(e),l-=a.get(e)??0,a.delete(e);let n=o.get(t.runId);n?.delete(e),n?.size===0&&o.delete(t.runId)}function m(e){for(let t of o.get(e)??[])d(t)}function b(){i.clear(),a.clear(),o.clear(),l=0,x.clear()}let x=new Map;function S(e){return t?`${e}.${t}`:e}async function w(n,r){let i=`${n}-${oe(r)}`;for(let n of t?[W(e,`events`,i,t),W(e,`events`,i)]:[W(e,`events`,i)])try{return await R.stat(n),!0}catch(e){if(e.code!==`ENOENT`)throw e}return!1}async function te(n,r){let i=S(n),a=x.get(i);if(a===void 0||r?.rescan){let r=await Xn(e,n,t);a===void 0?(a=r.count>0&&!r.usesSlots?null:{published:r.maxSlot},x.set(i,a)):a!==null&&(a.published=Math.max(a.published,r.maxSlot))}if(a===null)return null;let o=Math.max(a.published+1,1,r?.atLeast??1);for(;await w(n,o);)a.published=Math.max(a.published,o),o+=1;return o}function ie(e,t){let n=ee(t);if(n===null)return;let r=x.get(S(e));r&&(r.published=Math.max(r.published,n))}async function ae(e){let t=await te(e);return t===null?`evnt_${ar()}`:oe(t)}async function se(n){let r=await te(n,{rescan:!0});return r===null?Yn(e,n,t):{eventId:oe(r),createdAt:new Date}}function E(e,t,n){if(n>r)return;for(;i.size>0&&(i.size>=1e3||l+n>r);){let e=i.keys().next().value;d(e)}i.set(e,t),a.set(e,n),l+=n;let s=o.get(t.runId)??new Set;s.add(e),o.set(t.runId,s)}function D(e,t,n){if(y(e.eventType)){m(e.runId);return}let i=Buffer.byteLength(n);if(i>r)return;let a=s.safeParse(JSON.parse(n,Dt));a.success&&E(t,a.data,i)}async function le(n){let r=n;for(let n=0;;n++){let i=W(e,`events`,`${r.runId}-${r.eventId}`,t),a=JSON.stringify(r,K,2),o=ee(r.eventId);if(o===null)return await J(i,a),D(r,i,a),r;if(await Z(i,a))return ie(r.runId,r.eventId),D(r,i,a),r;let s=await te(r.runId,{rescan:n>0&&n%8==0,atLeast:o+1});He(s!==null),r={...r,eventId:oe(s)}}}let me=(t,n)=>Ft({directory:z.join(e,`events`),schema:s,cachedItems:i,filePrefix:`${t}-`,sortOrder:n.sortOrder??`asc`,limit:n.limit,cursor:n.cursor,getCreatedAt:or(`evnt`),getId:e=>e.eventId,getSortKey:Ti,getSortKeyFromFileId:e=>Ei(t,e)}),O=new Map,A=new Map,j={clearCache:b,async create(r,i,a){if(i.eventType===`hook_created`&&i.eventData.tokenRetentionUntil!==void 0&&i.eventData.tokenRetentionUntil.getTime()>Date.now()+n)throw new M(`Hook minimum retention cannot exceed ${n/_i} days in the Local World.`,{status:400});if(r!=null&&r!==``&&V(`runId`,r),`correlationId`in i&&typeof i.correlationId==`string`&&V(`correlationId`,i.correlationId),_(i.eventType)&&r&&i.correlationId){let e=t?`${r}-${i.correlationId}.${t}`:`${r}-${i.correlationId}`;return Ai(O,e,o)}if(v(i.eventType)&&r&&i.correlationId){let e=t?`${r}-${i.correlationId}.hook.${t}`:`${r}-${i.correlationId}.hook`;return Ai(A,e,o)}return o();async function o(){let n=``,o=!1,l=null,d=new Date,v;if(i.eventType===`run_created`&&(!r||r===``))v=`wrun_${ar()}`;else if(r)v=r;else throw Error(`runId is required for non-run_created events`);if(i.eventType===`run_created`&&r&&r!==``){let e=de(v,`wrun_`);if(e)throw new M(e)}let b=i.specVersion??7,x=null;if(i.eventType!==`run_created`&&![`step_completed`,`step_retrying`].includes(i.eventType)&&(x=await G(e,`runs`,v,h,t),i.eventType===`run_started`&&!x&&`eventData`in i&&i.eventData)){let n=i.eventData;if(n.deploymentId&&n.workflowName&&n.input!==void 0){re(Object.entries(n.attributes??{}).map(([e,t])=>({key:e,value:t})),{allowReservedAttributes:n.allowReservedAttributes===!0});let r={runId:v,deploymentId:n.deploymentId,status:`pending`,workflowName:n.workflowName,specVersion:b,executionContext:n.executionContext,input:n.input,output:void 0,error:void 0,startedAt:void 0,completedAt:void 0,attributes:n.attributes??{},encryptionPublicKey:n.encryptionPublicKey,createdAt:d,updatedAt:d};if(await Z(W(e,`runs`,v,t),JSON.stringify(r,K))){let e=await ae(v);await le({eventType:`run_created`,runId:v,eventId:e,createdAt:d,specVersion:b,eventData:{deploymentId:n.deploymentId,workflowName:n.workflowName,input:n.input,executionContext:n.executionContext,attributes:n.attributes,allowReservedAttributes:n.allowReservedAttributes,encryptionPublicKey:n.encryptionPublicKey}}),x=r}else x=await G(e,`runs`,v,h,t)}}if(n=await ae(v),!x&&(i.eventType===`run_failed`||i.eventType===`attr_set`||i.eventType===`run_started`))throw new ge(v);if(x){if(fe(x.specVersion))throw new ve(x.specVersion,7);if(C(x.specVersion))return pi(e,v,i,x,a)}let S=ue(i),w=S&&i.eventType===`step_started`;if(x&&g(x.status)){if(i.eventType===`run_cancelled`&&x.status===`cancelled`){let e=await le({...i,runId:v,eventId:n,createdAt:d,specVersion:b}),t=a?.resolveData??`all`;return{event:f(e,t),run:x,...x?{maxEvents:T()}:{}}}if(i.eventType===`run_started`)throw new _e(`Workflow run "${v}" is already in terminal state "${x.status}"`);if(y(i.eventType))throw new N(`Cannot transition run from terminal state "${x.status}"`);if(S)throw new N(`Cannot create new entities on run in terminal state "${x.status}"`);if(i.eventType===`attr_set`)throw new N(`Cannot set attributes on run in terminal state "${x.status}"`)}let E=null;if(_(i.eventType)&&i.eventType!==`step_created`&&i.correlationId){if(E=await G(e,`steps`,`${v}-${i.correlationId}`,p,t),!E&&!w)throw new M(`Step "${i.correlationId}" not found`);if(w&&E)throw new N(`Step "${i.correlationId}" already created`);if(E){if(he(E.status))throw new N(`Cannot modify step in terminal state "${E.status}"`);if(x&&g(x.status)&&E.status!==`running`)throw new _e(`Cannot modify non-running step on run in terminal state "${x.status}"`)}}if(c(i.eventType)&&i.correlationId){if(i.eventType===`hook_received`&&a?.resumeId){let n=await Y(tr(e,v,a.resumeId),bi);if(n&&n.hookId===i.correlationId&&(!a.resumePayloadDigest||!n.payloadDigest||n.payloadDigest===a.resumePayloadDigest)){let r=await G(e,`events`,`${v}-${n.eventId}`,s,t),i=r&&xi(r,n)?r:await Si(e,v,n,t);if(i)return{event:i}}}if(i.eventType===`hook_received`&&await Un(e,i.correlationId,t)||!await G(e,`hooks`,i.correlationId,k,t))throw new ye(i.correlationId);if(i.eventType===`hook_received`&&a?.resumeId){let r=tr(e,v,a.resumeId),c=async r=>{if(r.hookId!==i.correlationId)throw new N(`hook_received resumeId "${a.resumeId}" already recorded for a different hook`);if(a.resumePayloadDigest&&r.payloadDigest&&r.payloadDigest!==a.resumePayloadDigest)throw new N(`hook_received resumeId "${a.resumeId}" already recorded with a different payload`);let c=await G(e,`events`,`${v}-${r.eventId}`,s,t);if(c&&xi(c,r))return{event:c};let u=await Si(e,v,r,t);return u?{event:u}:(l=r.eventId,c||(n=r.eventId,o=!0),null)},u=await Y(r,bi);if(u){let e=await c(u);if(e)return e}else if(o=!ne(n),l=n,!await Z(r,JSON.stringify({runId:v,resumeId:a.resumeId,hookId:i.correlationId,eventId:n,...a.resumePayloadDigest?{payloadDigest:a.resumePayloadDigest}:{}}))){l=null;let e=await Y(r,bi);if(e){let t=await c(e);if(t)return t}}}}let O={...i,runId:v,eventId:n,createdAt:d,specVersion:b,...i.eventType===`hook_received`&&a?.resumeId?{resumeId:a.resumeId}:{}};if(i.eventType===`run_started`&&`eventData`in O&&delete O.eventData,w&&O.eventType===`step_started`&&O.eventData){let{input:e,...t}=O.eventData;O={...O,eventData:t}}let A,j=!1,P,F,xe,Se=!1,Ce;if(y(i.eventType)&&x){await Z(Wn(e,v,t),``),await Jn(e,v,t);let r=await se(v);n=r.eventId,O={...O,eventId:n,createdAt:r.createdAt}}if(i.eventType===`run_created`&&`eventData`in i){let n=i.eventData;if(re(Object.entries(n.attributes??{}).map(([e,t])=>({key:e,value:t})),{allowReservedAttributes:n.allowReservedAttributes===!0}),A={runId:v,deploymentId:n.deploymentId,status:`pending`,workflowName:n.workflowName,specVersion:b,executionContext:n.executionContext,input:n.input,output:void 0,error:void 0,startedAt:void 0,completedAt:void 0,attributes:n.attributes??{},encryptionPublicKey:n.encryptionPublicKey,createdAt:d,updatedAt:d},!await Z(W(e,`runs`,v,t),JSON.stringify(A,K,2)))throw new N(`Workflow run "${v}" already exists`)}else if(i.eventType===`run_started`){if(x){if(x.status===`running`){if(a?.skipPreload)return{run:x,maxEvents:T()};let e=await me(v,{limit:T()});return{run:x,events:e.data,cursor:e.cursor,hasMore:e.hasMore,maxEvents:T()}}let n=await Mi(e,v,t,{runId:x.runId,deploymentId:x.deploymentId,workflowName:x.workflowName,specVersion:x.specVersion,executionContext:x.executionContext,input:x.input,createdAt:x.createdAt,expiredAt:x.expiredAt,status:`running`,output:void 0,error:void 0,completedAt:void 0,startedAt:x.startedAt??d,updatedAt:d,attributes:x.attributes,encryptionPublicKey:x.encryptionPublicKey});A=n.run,j=n.purged}}else if(i.eventType===`run_completed`&&`eventData`in i){let n=i.eventData;if(x){let r=await Mi(e,v,t,{runId:x.runId,deploymentId:x.deploymentId,workflowName:x.workflowName,specVersion:x.specVersion,executionContext:x.executionContext,input:x.input,createdAt:x.createdAt,expiredAt:x.expiredAt,startedAt:x.startedAt,status:`completed`,output:n.output,error:void 0,completedAt:d,updatedAt:d,attributes:x.attributes,encryptionPublicKey:x.encryptionPublicKey});A=r.run,j=r.purged,await Promise.all([zr(e,v),ji(e,v)])}}else if(i.eventType===`run_failed`&&`eventData`in i){let n=i.eventData;if(x){let r=await Mi(e,v,t,{runId:x.runId,deploymentId:x.deploymentId,workflowName:x.workflowName,specVersion:x.specVersion,executionContext:x.executionContext,input:x.input,createdAt:x.createdAt,expiredAt:x.expiredAt,startedAt:x.startedAt,status:`failed`,output:void 0,error:n.error,errorCode:n.errorCode,completedAt:d,updatedAt:d,attributes:x.attributes,encryptionPublicKey:x.encryptionPublicKey});A=r.run,j=r.purged,await Promise.all([zr(e,v),ji(e,v)])}}else if(i.eventType===`run_cancelled`){if(x){let n=await Mi(e,v,t,{runId:x.runId,deploymentId:x.deploymentId,workflowName:x.workflowName,specVersion:x.specVersion,executionContext:x.executionContext,input:x.input,createdAt:x.createdAt,expiredAt:x.expiredAt,startedAt:x.startedAt,status:`cancelled`,output:void 0,error:void 0,completedAt:d,updatedAt:d,attributes:x.attributes,encryptionPublicKey:x.encryptionPublicKey});A=n.run,j=n.purged,await Promise.all([zr(e,v),ji(e,v)])}}else if(i.eventType===`attr_set`&&x)A=await hi(v,async()=>{let n=await Y(W(e,`runs`,v,t),h);if(!n)throw new ge(v);if(re(i.eventData.changes,{existingKeys:Object.keys(n.attributes),allowReservedAttributes:i.eventData.allowReservedAttributes===!0}),i.correlationId&&i.eventData.writer.type===`workflow`&&!await Z(H(e,`.locks`,`attributes`,t?`${v}-${i.correlationId}.created.${t}`:`${v}-${i.correlationId}.created`),``))throw new N(`Attribute event "${i.correlationId}" already exists`);let r={...n,attributes:pe(n.attributes,i.eventData.changes),updatedAt:d};return await q(W(e,`runs`,v,t),r,{overwrite:!0}),r});else if(i.eventType===`step_created`&&`eventData`in i){if(!await Z(H(e,`.locks`,`steps`,t?`${v}-${i.correlationId}.created.${t}`:`${v}-${i.correlationId}.created`),``))throw new N(`Step "${i.correlationId}" already created`);let n=i.eventData;P={runId:v,stepId:i.correlationId,stepName:n.stepName,status:`pending`,input:n.input,output:void 0,error:void 0,attempt:0,startedAt:void 0,completedAt:void 0,createdAt:d,updatedAt:d,specVersion:b},await q(W(e,`steps`,`${v}-${i.correlationId}`,t),P)}else if(i.eventType===`step_started`){if(!E&&w){let n=i.eventData;if(await Z(H(e,`.locks`,`steps`,t?`${v}-${i.correlationId}.created.${t}`:`${v}-${i.correlationId}.created`),``)){let r={runId:v,stepId:i.correlationId,stepName:n.stepName,status:`pending`,input:n.input,output:void 0,error:void 0,attempt:0,startedAt:void 0,completedAt:void 0,createdAt:d,updatedAt:d,specVersion:b};await q(W(e,`steps`,`${v}-${i.correlationId}`,t),r);let a=await ae(v);await le({eventType:`step_created`,runId:v,eventId:a,createdAt:d,specVersion:b,correlationId:i.correlationId,eventData:{stepName:n.stepName,input:n.input}}),E=r,Se=!0}else throw new N(`Step "${i.correlationId}" already created`)}if(E){if(E.retryAfter&&E.retryAfter.getTime()>Date.now())throw new be(`Cannot start step "${i.correlationId}": retryAfter timestamp has not been reached yet`,{retryAfter:Math.ceil((E.retryAfter.getTime()-Date.now())/1e3)});let n=`${v}-${i.correlationId}`,r=await G(e,`steps`,n,p,t);if(r&&he(r.status))throw new N(`Cannot modify step in terminal state "${r.status}"`);P={...E,status:`running`,startedAt:E.startedAt??d,attempt:E.attempt+1,retryAfter:void 0,updatedAt:d},await q(W(e,`steps`,n,t),P,{overwrite:!0})}}else if(i.eventType===`step_completed`&&`eventData`in i){let n=i.eventData;if(E){let r=`${v}-${i.correlationId}`;if(!await Z(H(e,`.locks`,`steps`,t?`${r}.terminal.${t}`:`${r}.terminal`),``))throw new N(`Cannot modify step in terminal state`);P={...E,status:`completed`,output:n.result,completedAt:d,updatedAt:d},await q(W(e,`steps`,r,t),P,{overwrite:!0})}}else if(i.eventType===`step_failed`&&`eventData`in i){let n=i.eventData;if(E){let r=`${v}-${i.correlationId}`;if(!await Z(H(e,`.locks`,`steps`,t?`${r}.terminal.${t}`:`${r}.terminal`),``))throw new N(`Cannot modify step in terminal state`);P={...E,status:`failed`,error:n.error,completedAt:d,updatedAt:d},await q(W(e,`steps`,r,t),P,{overwrite:!0})}}else if(i.eventType===`step_retrying`&&`eventData`in i){let n=i.eventData;if(E){let r=`${v}-${i.correlationId}`;P={...E,status:`pending`,error:n.error,retryAfter:n.retryAfter,updatedAt:d},await q(W(e,`steps`,r,t),P,{overwrite:!0})}}else if(i.eventType===`hook_created`&&`eventData`in i){let r=i.eventData,s=Zn(e,r.token),c=JSON.stringify({token:r.token,hookId:i.correlationId,runId:v,eventId:n,tokenRetentionUntil:r.tokenRetentionUntil}),l=await er(e,r.token,async n=>{let a=await $n(s);return a||=(n.throwIfAborted(),await X(s),await Ir(e,r.token,t),await $n(s)),a?a.runId===v&&a.hookId===i.correlationId?{status:`owned`,claim:a}:await Ci(e,a,t)?(n.throwIfAborted(),await X(s),a.hookId&&(await X(W(e,`hooks`,a.hookId,t)),await X(rr(e,r.token,a.runId,a.hookId)),await vr(e,a.runId,a.hookId,t)),n.throwIfAborted(),He(await Z(s,c)),{status:`claimed`}):{status:`conflict`,claim:a}:(n.throwIfAborted(),He(await Z(s,c)),{status:`claimed`})});if(l.status===`owned`){let a=l.claim,s;if(a.eventId)s=a.eventId;else{let a=await Di(e,v,i.correlationId);if(a!==null)throw await Oi(e,v,i.correlationId,a,t),new N(`Hook "${i.correlationId}" already created`);let o=await ki(e,r.token,v,i.correlationId,n);if(o===null)throw new N(`Hook "${i.correlationId}" already created`);s=o}n=s,o=!0;let c=ce(n.replace(/^evnt_/,``))??d;O={...i,eventData:{...i.eventData,tokenRetentionUntil:a.tokenRetentionUntil},runId:v,eventId:n,createdAt:c,specVersion:b}}if(l.status===`conflict`){let e=l.claim,t=await le({eventType:`hook_conflict`,correlationId:i.correlationId,eventData:{token:r.token,conflictingRunId:e.runId},runId:v,eventId:n,createdAt:d,specVersion:b}),o=a?.resolveData??`all`,s=typeof a?.sinceCursor==`string`?await me(v,{sortOrder:`asc`,cursor:a.sinceCursor}):void 0,c={event:f(t,o),run:A,step:P,hook:void 0};return s?{...c,events:o===`none`?s.data.map(e=>f(e,o)):s.data,cursor:s.cursor,hasMore:s.hasMore}:c}let u=O.eventData;F={runId:v,hookId:i.correlationId,token:u.token,metadata:u.metadata,ownerId:`local-owner`,projectId:`local-project`,environment:`local`,createdAt:O.createdAt,specVersion:b,isWebhook:u.isWebhook??!1,isSystem:u.isSystem??!1,tokenRetentionUntil:u.tokenRetentionUntil},Ce=l.status===`owned`?{overwrite:!0}:void 0,await hr(e,r.token,v,i.correlationId,n,t)}else if(i.eventType===`hook_disposed`){if(!await Z(Hn(e,i.correlationId,t),``))throw new N(`Hook "${i.correlationId}" already disposed`);let n=W(e,`hooks`,i.correlationId,t),r=await G(e,`hooks`,i.correlationId,k,t);r&&(await nr(e,r.token,r.runId,r.hookId),await X(rr(e,r.token,r.runId,r.hookId))),await X(n),await vr(e,v,i.correlationId,t)}else if(i.eventType===`wait_created`&&`eventData`in i){let n=`${v}-${i.correlationId}`;if(!await Z(H(e,`.locks`,`waits`,t?`${n}.created.${t}`:`${n}.created`),``))throw new N(`Wait "${i.correlationId}" already exists`);let r=i.eventData;xe={waitId:n,runId:v,status:`waiting`,resumeAt:r.resumeAt,completedAt:void 0,createdAt:d,updatedAt:d,specVersion:b},await q(W(e,`waits`,n,t),xe)}else if(i.eventType===`wait_completed`){let n=`${v}-${i.correlationId}`,r=H(e,`.locks`,`waits`,t?`${n}.completed.${t}`:`${n}.completed`);if(!await Z(r,``))throw new N(`Wait "${i.correlationId}" already completed`);let a=await G(e,`waits`,n,u,t);if(!a)throw await R.unlink(r).catch(()=>{}),new M(`Wait "${i.correlationId}" not found`);xe={...a,status:`completed`,completedAt:d,updatedAt:d},await q(W(e,`waits`,n,t),xe,{overwrite:!0})}if(i.eventType===`hook_received`&&i.correlationId&&await Un(e,i.correlationId,t))throw new ye(i.correlationId);let we=W(e,`events`,`${v}-${n}`,t),Te=JSON.stringify(O,K,2),Ee=async r=>{let i=ee(n);if(o||i===null)return!1;let a=await te(v,{rescan:r>0&&r%8==0,atLeast:i+1});return a!==null&&(n=oe(a),O={...O,eventId:n},we=W(e,`events`,`${v}-${n}`,t),Te=JSON.stringify(O,K,2),!0)},De=!1;for(let r=0;;r++){if(i.eventType===`hook_received`){let r=await Gn(e,v,t),i=r?null:await G(e,`runs`,v,h,t);if(r||i&&g(i.status))throw new _e(`Workflow run "${v}" is already in a terminal state`);let a=qn(e,v,`${n}.${ar()}`,t);if(!await Z(a,Te))throw new M(`Failed to stage event "${n}" for run "${v}": staging path already exists`);try{if(await Gn(e,v,t))throw new _e(`Workflow run "${v}" is already in a terminal state`);let n=await At(a,we);if(n===`missing`)throw new _e(`Workflow run "${v}" is already in a terminal state`);De=n===`linked`}finally{await X(a).catch(()=>{})}}else De=await Z(we,Te);if(De){ie(v,n);break}if(i.eventType===`hook_received`&&a?.resumeId){let r=await G(e,`events`,`${v}-${n}`,s,t);if(r&&xi(r,{runId:v,resumeId:a.resumeId,hookId:i.correlationId,eventId:n}))return{event:r}}if(!await Ee(r))break}if(!De)throw i.eventType===`hook_created`&&i.correlationId&&await Oi(e,v,i.correlationId,n,t),new N(`Event "${n}" already exists for run "${v}"`);D(O,we,Te),i.eventType===`hook_received`&&a?.resumeId&&l!==null&&l!==n&&await J(tr(e,v,a.resumeId),JSON.stringify({runId:v,resumeId:a.resumeId,hookId:i.correlationId,eventId:n,...a.resumePayloadDigest?{payloadDigest:a.resumePayloadDigest}:{}}),{overwrite:!0}),F&&i.eventType===`hook_created`&&(await _r(e,F.runId,F.hookId,t),await q(W(e,`hooks`,F.hookId,t),F,Ce)),j&&(await ri(e,v,t),m(v));let Oe=a?.resolveData??`all`,ke=f(O,Oe),I;if(i.eventType===`run_started`&&A&&!a?.skipPreload&&(I=await me(v,{limit:T()})),typeof a?.sinceCursor==`string`){let e=await me(v,{sortOrder:`asc`,cursor:a.sinceCursor});I=Oe===`none`?{...e,data:e.data.map(e=>f(e,Oe))}:e}let L={event:ke,run:A,step:P,hook:F,wait:xe,...Se?{stepCreated:!0}:{},...A?{maxEvents:T()}:{}};return I?{...L,events:I.data,cursor:I.cursor,hasMore:I.hasMore}:L}},async get(n,r,i){V(`runId`,n),V(`eventId`,r);let a=await G(e,`events`,`${n}-${r}`,s,t);if(!a)throw Error(`Event ${r} in run ${n} not found`);let o=i?.resolveData??`all`;return f(a,o)},async list(e){let{runId:t}=e;V(`runId`,t);let n=e.resolveData??`all`,r=await me(t,{...e.pagination,limit:e.pagination?.limit??T()});return n===`none`?{...r,data:r.data.map(e=>f(e,n))}:r},async listByCorrelationId(t){let n=t.correlationId;V(`correlationId`,n),V(`runId`,t.runId);let r=t.resolveData??`all`,a=await Ft({directory:z.join(e,`events`),schema:s,cachedItems:i,filePrefix:`${t.runId}-`,filter:e=>e.correlationId===n,sortOrder:t.pagination?.sortOrder??`asc`,limit:t.pagination?.limit,cursor:t.pagination?.cursor,getCreatedAt:or(`evnt`),getId:e=>e.eventId,getSortKey:Ti,getSortKeyFromFileId:e=>Ei(t.runId,e)});return r===`none`?{...a,data:a.data.map(e=>f(e,r))}:a}};async function P(e,t,n){if(!e.event)return e;let r=ee(e.event.eventId);if(r===null||t<1||r<=t+1)return e;let i=r-t-1,a=await j.list({runId:e.event.runId,pagination:{cursor:`${Mt}${oe(t)}`,limit:i,sortOrder:`asc`},resolveData:n}),o=e.event.eventId,s=a.data.filter(e=>e.eventId<o);return{...e,events:s,cursor:null,hasMore:s.length<r-t-1}}let F=(async(e,t,n)=>{if(n?.eventCount===void 0)return j.create(e,t,n);let r=n.resolveData??`all`,i=await j.create(e,t,n);return typeof n.sinceCursor==`string`?i:P(i,n.eventCount,r)});return{...j,create:F}}function Pi(e,t){return{get:(async(n,r,i)=>{V(`runId`,n),V(`stepId`,r);let a=await G(e,`steps`,`${n}-${r}`,p,t);if(!a)throw Error(`Step ${r} in run ${n} not found`);return Or(a,i?.resolveData??`all`)}),list:(async t=>{V(`runId`,t.runId);let n=t.resolveData??`all`,r=await Ft({directory:z.join(e,`steps`),schema:p,filePrefix:`${t.runId}-`,sortOrder:t.pagination?.sortOrder??`desc`,limit:t.pagination?.limit,cursor:t.pagination?.cursor,getCreatedAt:or(`step`),getId:e=>e.stepId});return n===`none`?{...r,data:r.data.map(e=>({...e,input:void 0,output:void 0}))}:r})}}function Fi(e,t){let n=gi(e,t),r=Pi(e,t),i=Ni(e,t),a=Rr(e,t);return{runs:vn(`world.runs`,n),steps:vn(`world.steps`,r),events:vn(`world.events`,i),hooks:vn(`world.hooks`,a),clearCache:()=>i.clearCache()}}function Ii(e){let t=e?Object.fromEntries(Object.entries(e).filter(([,e])=>e!==void 0)):{},n={...ut.value,...t};Je(n.dataDir);let r=n.tag,i=kn(n),{clearCache:a,...o}=Fi(n.dataDir,r),s=dt(n);return{specVersion:ae(),capabilities:{hookRetention:{active:!0},hookResumeDedup:!0},...i,...o,...vn(`world.streams`,{...ei(n.dataDir,r),...n.streamFlushIntervalMs!==void 0&&{streamFlushIntervalMs:n.streamFlushIntervalMs}}),async start(){if(await Xt(n.dataDir),!s)return;let e=r?e=>bt(e,r):xt,t={...o.runs,list:(t=>o.runs.list({...t,fileIdFilter:e}))};await x(t,i.queue,`world-local`)},async close(){a(),await i.close()},async clear(){if(a(),r){let e=n.dataDir,t=z.join(e,`hooks`),i=await St(t,r),{HookSchema:a}=await import(`../../_chunks/workflow/dist-DDeH-1ER.js`).then(e=>e.t);await Promise.all(i.map(async n=>{let r=await Y(z.join(t,n),a);r?.token&&(await X(z.join(t,`tokens`,`${Vn(r.token)}.json`)),await X(rr(e,r.token,r.runId,r.hookId)))})),await Promise.all([`runs`,`steps`,`events`,`hooks`,`hooks/by-run`,`waits`,`streams/runs`].map(async t=>{let n=z.join(e,t),i=await St(n,r);await Promise.all(i.map(e=>X(z.join(n,e))))}));for(let t of[`token-index`,`id-index`]){let n=z.join(e,`hooks`,t),i;try{i=await L.readdir(n,{withFileTypes:!0})}catch{i=[]}await Promise.all(i.filter(e=>e.isDirectory()).map(async e=>{let t=z.join(n,e.name),i=await St(t,r);await Promise.all(i.map(e=>X(z.join(t,e))))}))}await L.rm(z.join(e,`.locks`),{recursive:!0,force:!0}).catch(()=>{});let o=z.join(e,`streams`,`chunks`),s;try{s=await L.readdir(o,{withFileTypes:!0})}catch{s=[]}await Promise.all(s.filter(e=>e.isDirectory()).map(async e=>{let t=z.join(o,e.name),n=await Ct(t,r,`.bin`);await Promise.all(n.map(e=>L.unlink(z.join(t,e)).catch(()=>{})))})),_t()}else _t(),Sr(),await Ie(n.dataDir,{recursive:!0,force:!0}),await Xt(n.dataDir)}}}export{Bt as DataDirAccessError,Vt as DataDirVersionError,We as UnwritableDataDirError,Ii as createWorld,Kt as ensureDataDir,Xt as initDataDir,Ht as parseVersion};