eve
Version:
Filesystem-first framework for durable backend AI agents that run anywhere.
5 lines • 88.8 kB
JavaScript
import{i as e,t}from"../../_chunks/workflow/rolldown-runtime-DPpTSio4.js";import{C as n,M as r,S as i,T as a,b as o,c as s,s as c}from"../../_chunks/workflow/schemas-4CmFgxN_.js";import{B as l,C as u,G as d,H as f,K as p,M as m,N as h,P as g,R as _,U as v,W as y,Z as b,a as x,at as ee,b as S,c as te,d as ne,ft as re,g as C,h as w,ht as T,l as ie,lt as ae,m as oe,mt as E,n as se,o as ce,ot as le,pt as ue,q as D,r as de,rt as fe,s as pe,st as me,tt as O,ut as k,v as A,z as j}from"../../_chunks/workflow/dist-DjECvUyK.js";import{n as M,t as N}from"../../_chunks/workflow/coerce-D0oqvQ_w.js";import{t as P}from"../../_chunks/workflow/debug-log-CVPstO1D.js";import{A as F,O as he,d as ge,f as _e,o as ve,r as I,y as ye}from"../../_chunks/workflow/dist-xTushGCp.js";import{i as be,n as xe,r as Se,t as Ce}from"../../_chunks/workflow/workflow-routes-CwqB063q.js";import{a as we,i as Te,n as Ee,r as De,t as Oe}from"../../_chunks/workflow/signal-exit-B9U6kH7R.js";import{createHash as ke}from"node:crypto";import{promisify as Ae}from"node:util";import{fileURLToPath as je}from"node:url";import{promises as L}from"node:fs";import R,{access as Me,constants as Ne,mkdir as Pe,readFile as Fe,readdir as Ie,readlink as Le,rm as Re,unlink as ze,writeFile as Be}from"node:fs/promises";import z from"node:path";import{tmpdir as Ve}from"node:os";import{execFile as He}from"node:child_process";import{setTimeout as Ue}from"node:timers/promises";import We from"node:assert";import{EventEmitter as Ge}from"node:events";var Ke=class extends F{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 qe=new Set([`EROFS`,`EACCES`,`EPERM`]);function Je(e){return e!==void 0&&qe.has(e)}const Ye=E(`@workflow/world-local//buildTargetWarnings`,1,()=>({warnedAboutVercelDeployment:!1}));function Xe(e){if(Ye.warnedAboutVercelDeployment||!process.env.VERCEL_DEPLOYMENT_ID)return;let t=z.resolve(e),n=Ve();t===n||t.startsWith(`${n}${z.sep}`)||(Ye.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 Ze(e,t=10){let n=parseInt(e,t);if(!Number.isNaN(n)&&n>=0&&n<=65535)return n}function Qe(e,t){let n=[],r=e.trim().split(`
`);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=Ze(i.slice(s+1));c!==void 0&&n.push(c)}return n}const $e=Ae(He);function et(e,t=10){let n=parseInt(e,t);if(!Number.isNaN(n)&&n>=0&&n<=65535)return n}const tt=((e,t)=>e.join(t))([``,`proc`],`/`);async function nt(e){let t=[`${tt}/net/tcp`,`${tt}/net/tcp6`],n=[],r=new Set,i=`${tt}/${e}/fd`;try{let e=(await Ie(i)).sort((e,t)=>Number.parseInt(e,10)-Number.parseInt(t,10)),t=await Promise.allSettled(e.map(async e=>(await Le(`${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 Fe(e,`utf8`)).split(`
`).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=et(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 rt(e){try{let{stdout:t}=await $e(`lsof`,[`-a`,`-i`,`-P`,`-n`,`-p`,e.toString()]),n=[],r=t.split(`
`);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=et(t.slice(e+1));r!==void 0&&n.push(r)}}}return n}catch{return[]}}async function it(e){try{let{stdout:t}=await $e(`cmd`,[`/c`,`netstat -ano -p tcp | findstr LISTENING`]);return Qe(t,e)}catch{return[]}}async function at(){let{pid:e,platform:t}=process;try{switch(t){case`linux`:return await nt(e);case`darwin`:return await rt(e);case`win32`:return await it(e);default:return[]}}catch(e){return P(`[getAllPorts] Detection failed:`,e),[]}}const ot=`${Ce}/flow?__health`;async function st(e,t={}){let{endpoint:n=ot,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 ct(e){let t=await at();if(t.length===0)return;if(t.length===1)return t[0];let n=(await Promise.all(t.map(async t=>({port:t,isWorkflow:await st(t,e)})))).find(e=>e.isWorkflow);return n?n.port:(P(`[getWorkflowPort] Probing failed, falling back to first port:`,t[0]),t[0])}function lt(e){let t={get value(){let n=e();return Object.defineProperty(t,"value",{value:n}),n}};return t}const ut=()=>process.env.WORKFLOW_LOCAL_DATA_DIR||`.workflow-data`,dt=()=>process.env.WORKFLOW_LOCAL_BASE_URL,ft=lt(()=>({dataDir:ut(),baseUrl:dt()}));function pt(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 mt(e){return e.baseUrl??process.env.WORKFLOW_LOCAL_BASE_URL??xe(`http://localhost`)}async function ht(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 xe(`http://localhost:${e.port}`);if(process.env.PORT)return xe(`http://localhost:${process.env.PORT}`);let t=await ct({endpoint:Se()});if(t)return xe(`http://localhost:${t}`);throw Error(`Unable to resolve base URL for workflow queue.`)}const B=E(`@workflow/world-local//fs`,1,()=>({ulid:k(()=>Math.random()),createdFilesCache:new Set,createdDirectoriesCache:new Set}));function gt(e){let t=typeof e==`string`?e:String(e);return t.length>48?`${t.slice(0,48)}…`:t}var _t=class extends F{constructor(e,t){super(`Unsafe ${e} "${gt(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 _t(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 _t(`path`,t.join(`/`));return r}const vt=process.platform===`win32`;async function U(e,t=5){if(!vt)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 yt(){B.createdFilesCache.clear(),B.createdDirectoriesCache.clear()}const bt=/\.[a-zA-Z][a-zA-Z0-9-]*$/;function xt(e){return e.replace(bt,``)}function St(e,t){return e.endsWith(`.${t}`)}function Ct(e){return!bt.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 J(H(e,t,`${n}.${i}.json`),r);if(a!==null)return a}return J(H(e,t,`${n}.json`),r)}async function wt(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 Tt(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 Et(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(Je(n)&&!await Dt(t))throw new Ke(t,n)}}async function Dt(e){try{return(await L.stat(e)).isDirectory()}catch{return!1}}async function Ot(e,t){await Et(e);try{return await t()}catch(n){if(n.code!==`ENOENT`)throw n;return B.createdDirectoriesCache.delete(z.resolve(e)),await Et(e),t()}}function K(e,t){return t instanceof Uint8Array?{__type:`Uint8Array`,data:Buffer.from(t).toString(`base64`)}:t}function kt(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 At(e,JSON.stringify(t,K,2),n)}async function At(e,t,n){if(!n?.overwrite){if(B.createdFilesCache.has(e))throw new I(`File ${e} already exists and 'overwrite' is false`);try{throw await L.access(e),B.createdFilesCache.add(e),new I(`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 Ot(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 J(e,t){try{let n=await U(()=>L.readFile(e,`utf-8`));return t.parse(JSON.parse(n,kt))}catch(e){if(e.code===`ENOENT`)return null;throw e}}async function jt(e){return await L.readFile(e)}async function Mt(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 Y(e){try{await U(()=>L.unlink(e))}catch(e){if(e.code!==`ENOENT`)throw e}}async function X(e,t){let n=`${e}.tmp.${B.ulid()}`,r=!1;try{return await Ot(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 Nt(e,t){try{return await Ot(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 Z(e){return Pt(e,`.json`)}async function Pt(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 Ft=`key:`;function It(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 Lt(e,t,n){return n?`${Ft}${n}`:t?`${e.toISOString()}|${t}`:e.toISOString()}async function Rt(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 Z(h),_=a?g.filter(e=>e.startsWith(a)):g,v=o?_.filter(o):_,y=It(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 J(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 ee=x.length>l,S=ee?x.slice(0,l):x;return{data:S,cursor:S.length>0?Lt(S[S.length-1].createdAt,f?.(S[S.length-1]),p?.(S[S.length-1])):null,hasMore:ee}}const zt=E(`@workflow/world-local//packageInfo`,1,()=>({cached:null}));function Bt(){return typeof import.meta.url==`string`&&import.meta.url?z.dirname(je(import.meta.url)):null}async function Vt(){if(zt.cached)return zt.cached;let e=Bt();if(e)try{let t=await Fe(z.join(e,`../package.json`),`utf-8`);return zt.cached=JSON.parse(t),zt.cached}catch{}return zt.cached={name:`@workflow/world-local`,version:`5.0.0-beta.46`},zt.cached}const Ht=`version.txt`;var Ut=class extends Error{dataDir;code;constructor(e,t,n){super(e),this.name=`DataDirAccessError`,this.dataDir=t,this.code=n}},Wt=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 Gt(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 Q(e){let t=`${e.major}.${e.minor}.${e.patch}`;return e.prerelease?`${t}-${e.prerelease}`:t}function Kt(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:Gt(t.substring(n+1))}}function qt(e,t){return`${e}@${Q(t)}`}function Jt(e,t){console.log(`[world-local] Upgrading from version ${Q(e)} to ${Q(t)}`)}async function Yt(e){let t=z.resolve(e);try{await Pe(t,{recursive:!0})}catch(e){let n=e;if(n.code!==`EEXIST`)throw new Ut(`Failed to create data directory "${t}": ${n.message}`,t,n.code)}try{await Me(t,Ne.R_OK)}catch(e){let n=e;throw new Ut(`Data directory "${t}" is not readable: ${n.message}`,t,n.code)}let n=z.join(t,`.workflow-write-test-${Date.now()}`);try{await Be(n,``),await ze(n).catch(e=>{if(e.code!==`ENOENT`)throw e})}catch(e){let n=e;throw new Ut(`Data directory "${t}" is not writable: ${n.message}`,t,n.code)}}async function Xt(e){let t=z.join(z.resolve(e),Ht);try{return Kt(await Fe(t,`utf-8`))}catch(e){if(e.code===`ENOENT`)return null;throw e}}async function Zt(e,t){let n=z.join(z.resolve(e),Ht),r=qt((await Vt()).name,t);await Be(n,r)}function Qt(e,t){return t||Q(e)}async function $t(e){await Yt(e);let t=await Vt(),n=Gt(t.version),r=await Xt(e);if(r===null){await Zt(e,n);return}let{version:i}=r;if(Q(i)!==Q(n))try{Jt(i,n),await Zt(e,n)}catch(e){let r=Qt(i,e instanceof Wt?e.suggestedVersion:void 0);throw console.error(`[world-local] Failed to upgrade data directory from version ${Q(i)} to ${Q(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 en=E(`@workflow/world-local//telemetry`,1,()=>({apiPromise:null,tracerPromise:null}));async function tn(){return en.apiPromise||=import(`../../@opentelemetry/api/index.js`).catch(()=>null),en.apiPromise}async function nn(){return en.tracerPromise||=tn().then(e=>e?e.trace.getTracer(`workflow`):null),en.tracerPromise}async function rn(e,...t){let[n,r]=await Promise.all([nn(),tn()]),{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 an(e){let t=await tn();if(t)return t.SpanKind[e]}function on(...e){return t=>Object.fromEntries(e.map(e=>[e,t]))}const sn=on(`peer.service`),cn=on(`rpc.system`),ln=on(`rpc.service`),un=on(`rpc.method`),dn=on(`workflow.run.id`),fn=on(`step.id`),pn={peerService:`world-local`,rpcSystem:`local`,rpcService:`world-local`},mn={"world.runs.get":0,"world.runs.experimentalSetAttributes":0,"world.steps.get":0,"world.events.create":0,"world.events.get":0},hn=new Set([`world.steps.list`,`world.events.list`,`world.hooks.list`]);function gn(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 _n(e,t){return typeof e[t]==`string`?e[t]:void 0}function vn(e){if(typeof e!=`object`||!e)return;let t=e.runId;return typeof t==`string`?t:void 0}function yn(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 bn(e,t,n){let r=`${e}.${t}`,i={},a=mn[r],o=a===void 0?hn.has(r)?vn(n[0]):void 0:_n(n,a);if(o&&Object.assign(i,dn(o)),r===`world.steps.get`){let e=_n(n,1);e&&Object.assign(i,fn(e))}return i}function xn(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=gn(t);r&&(n=`${e}.${a} ${r}`)}return rn(n,{kind:await an(`INTERNAL`)},async r=>{r?.setAttributes({...sn(pn.peerService),...cn(pn.rpcSystem),...ln(pn.rpcService),...un(n),...bn(e,a,t)});let o=await i(...t),s=yn(o);return s&&r?.setAttributes(dn(s)),o})}}return n}var Sn=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}))(),Cn=Ee(),wn=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,kt)}};const Tn=parseInt(process.env.WORKFLOW_LOCAL_QUEUE_MAX_VISIBILITY??`0`,10)||1/0,En=2147483647,Dn=parseInt(process.env.WORKFLOW_LOCAL_QUEUE_CONCURRENCY??`0`,10)||1e3;function On(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 kn(){return{bodyTimeout:On(`WORKFLOW_LOCAL_BODY_TIMEOUT_MS`,3e4),connections:1e3,headersTimeout:On(`WORKFLOW_LOCAL_HEADERS_TIMEOUT_MS`,3e4),keepAliveTimeout:3e4}}const An=`Cannot perform ArrayBuffer.prototype.slice on a detached ArrayBuffer`;function jn(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(An))return!0;t=`cause`in t?t.cause:void 0}return!1}function Mn(e){let t=kn(),n=w()?De({maxSockets:t.connections,keepAliveMs:t.keepAliveTimeout}):void 0,r=n?void 0:new Cn.Agent(t),i=new wn,a=k(),s=new Sn.Sema(Dn),c=new AbortController,l=c.signal,d=new Map,f=new Map,p=async(o,c,p)=>{let m=[];if(p?.idempotencyKey){let e=d.get(p.idempotencyKey);if(e)return{messageId:e}}let h=i.serialize(c),{prefix:g}=u(o),_=A.parse(`msg_${a()}`),v=c,y=v.runId??void 0,b=v.stepId??void 0;if(p?.idempotencyKey){let e=p.idempotencyKey;d.set(e,_),m.push(()=>{d.delete(e)})}return(async()=>{if(p?.delaySeconds&&p.delaySeconds>0){let e=Math.min(p.delaySeconds*1e3,En);await Ue(e,void 0,{signal:l})}s.tryAcquire()||(P(`[world-local]: concurrency limit (${Dn}) reached, waiting for queue to free up`),await s.acquire());let i=0;try{for(let a=0;a<256;a++){let s={...p?.headers,"content-type":`application/json`,"x-vqs-queue-name":o,"x-vqs-message-id":_,"x-vqs-message-attempt":String(i+1)},c=f.get(g),u,d;try{if(c)u=await c(new Request(be(mt(e),{type:`flow`}),{method:`POST`,headers:s,body:h}));else{let i=await ht(e),a=be(i,{type:`flow`});u=n?await we(a,{method:`POST`,headers:new Headers(s),body:h,agents:n,signal:l,headersTimeoutMs:t.headersTimeout,bodyTimeoutMs:t.bodyTimeout}):await fetch(a,{method:`POST`,duplex:`half`,dispatcher:r,headers:s,body:h,signal:l})}i++,d=await u.text()}catch(e){let t=e?.name;if(l.aborted||t===`AbortError`||t===`ResponseAborted`)return;if(jn(e))throw e;console.error(`[world-local] Queue delivery failed at the transport (loop ${a+1}), retrying`,{queueName:o,messageId:_,...y&&{runId:y},...b&&{stepId:b},error:String(e)}),await Ue(5e3,void 0,{signal:l});continue}if(u.ok){try{let e=Number(JSON.parse(d).timeoutSeconds);if(Number.isFinite(e)&&e>=0){if(e>0){let t=Math.min(e*1e3,En);await Ue(t,void 0,{signal:l})}continue}}catch{}return}console.error(`[world-local] Queue message failed (attempt ${i}, HTTP ${u.status})`,{queueName:o,messageId:_,...y&&{runId:y},...b&&{stepId:b},handlerError:d}),await Ue(5e3,void 0,{signal:l})}console.error(`[world-local] Queue message exhausted safety limit (256 attempts)`,{queueName:o,messageId:_,...y&&{runId:y},...b&&{stepId:b}})}finally{s.release()}})().catch(e=>{e?.name!==`AbortError`&&e?.name!==`ResponseAborted`&&(jn(e)?console.error(`[local world] Queue operation failed: detected "${An}". 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:o,messageId:_,...y&&{runId:y},...b&&{stepId:b},originalError:e}):console.error(`[local world] Queue operation failed:`,e))}).finally(()=>{for(let e of m)e()}),{messageId:_}},m=T(o({"x-vqs-queue-name":S,"x-vqs-message-id":A,"x-vqs-message-attempt":M()}));return{queue:p,createQueueHandler:(e,t)=>async n=>{let r=m.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 wn().deserialize(n.body);try{let e=await t(s,{attempt:o,queueName:i,messageId:a});if(typeof s==`object`&&s&&`invoke`in s&&s.invoke===!0)return Response.json({result:e});let n=null;return typeof e==`object`&&e&&`timeoutSeconds`in e&&typeof e.timeoutSeconds==`number`&&(n=Math.min(e.timeoutSeconds,Tn)),n==null?Response.json({ok:!0}):Response.json({timeoutSeconds:n})}catch(e){return Response.json(String(e),{status:500})}},getDeploymentId:async()=>`dpl_local@${(await Vt()).version}`,registerHandler(e,t){f.set(e,t)},async close(){l.aborted||(c.abort(),n&&Te(n),await r?.close())}}}var Nn=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`))}}})),Pn=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())}}})),Fn=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}})),In=t(((t,n)=>{var r=e(`fs`),i=Nn(),a=Pn(),o=Fn(),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(`
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=ne,e.createWriteStream=re;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,S=g.WriteStream}var _=e.ReadStream;_&&(x.prototype=Object.create(_.prototype),x.prototype.open=ee);var v=e.WriteStream;v&&(S.prototype=Object.create(v.prototype),S.prototype.open=te),Object.defineProperty(e,"ReadStream",{get:function(){return x},set:function(e){x=e},enumerable:!0,configurable:!0}),Object.defineProperty(e,"WriteStream",{get:function(){return S},set:function(e){S=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=S;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 ee(){var e=this;w(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 S(e,t){return this instanceof S?(v.apply(this,arguments),this):S.apply(Object.create(S.prototype),arguments)}function te(){var e=this;w(e.path,e.flags,e.mode,function(t,n){t?(e.destroy(),e.emit(`error`,t)):(e.fd=n,e.emit(`open`,n))})}function ne(t,n){return new e.ReadStream(t,n)}function re(t,n){return new e.WriteStream(t,n)}var C=e.open;e.open=w;function w(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 C(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))}}})),Ln=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}})),Rn=t((e=>{var t=Ln();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}}})),zn=t(((e,t)=>{t.exports=Rn()})),Bn=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})),Vn=t(((t,n)=>{let r=e(`path`),i=In(),a=zn(),o=Oe(),s=Bn(),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})),Hn=t(((e,t)=>{let n=In();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}})),Un=t(((e,t)=>{let n=Vn(),{toPromise:r,toSync:i,toSyncOptions:a}=Hn();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 Wn(e){return ke(`sha256`).update(e).digest(`hex`)}function Gn(e,t,n){return H(e,`.locks`,`hooks`,n?`${t}.disposed.${n}`:`${t}.disposed`)}async function Kn(e,t,n){let r=[Gn(e,t)];n&&r.push(Gn(e,t,n));for(let e of r)try{return await R.access(e),!0}catch{}return!1}function qn(e,t,n){return H(e,`.locks`,`runs`,n?`${t}.terminal.${n}`:`${t}.terminal`)}async function Jn(e,t,n){let r=[qn(e,t)];n&&r.push(qn(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 Yn(e,t,n){return H(e,`.locks`,`runs`,n?`${t}.pending.${n}`:`${t}.pending`)}function Xn(e,t,n,r){return z.join(Yn(e,t,r),`${n}.json`)}async function Zn(e,t,n){let r=[Yn(e,t)];n&&r.push(Yn(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 Qn(e,t,n){let r=await $n(e,t,n),i=Date.now();if(r.maxId)try{let e=ae(r.maxId.replace(/^evnt_/,``));i<=e&&(i=e+1)}catch{}return{eventId:`evnt_${cr(i)}`,createdAt:new Date(i)}}async function $n(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(!Ct(t)&&!(n&&St(t,n)))continue;let r=xt(t).slice(i.length);l+=1,a.push(r),(!o||r>o)&&(o=r);let u=te(r);u!==null&&(c=!0,u>s&&(s=u))}return{maxId:o,usesSlots:c,maxSlot:s,count:l,ids:a}}function er(e,t){return z.join(e,`hooks`,`tokens`,`${Wn(t)}.json`)}const tr=T(o({hookId:a().optional(),runId:a(),eventId:a().optional(),tokenRetentionUntil:N().optional()}));async function nr(e){try{return await J(e,tr)}catch(e){if(e instanceof SyntaxError||e instanceof r)return null;throw e}}async function rr(e,t,n){let r=er(e,t);await R.mkdir(z.dirname(r),{recursive:!0});let i=new AbortController,a;try{a=await(0,Un.lock)(r,{realpath:!1,stale:3e4,update:1e3,retries:{retries:350,factor:1,minTimeout:100,maxTimeout:100},onCompromised(e){i.abort(new F(`Hook token claim lock was compromised`,{cause:e}))}})}catch(e){throw new F(`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 F(`Could not release Hook token claim lock`,{cause:e})}return o}function ir(e,t,n){let r=ke(`sha256`).update(`${t}\x00${n}`).digest(`hex`);return z.join(e,`hooks`,`resumes`,`${r}.json`)}async function ar(e,t,n,r){await rr(e,t,async i=>{let a=er(e,t),o=await nr(a);o&&o.runId===n&&o.hookId===r&&(i.throwIfAborted(),await Y(a))})}function or(e,t,n,r){let i=ke(`sha256`).update(`${t}\x00${n}\x00${r}`).digest(`hex`);return z.join(e,`hooks`,`tokens`,`${i}.recovery.json`)}const sr=E(`@workflow/world-local//storageMonotonicUlid`,1,()=>({next:k(()=>Math.random())})),cr=e=>sr.next(e),lr=e=>{let t=RegExp(`^${e}_`,`g`);return n=>{let r=xt(n.replace(/\.json$/,``))+`.json`,i=r.indexOf(`-`);if(i===-1){let e=r.replace(/\.json$/,``).replace(t,``);return se(e)}if(e===`step`)return null;let a=r.substring(i+1).replace(/\.json$/,``).replace(t,``);return se(a)}},ur=T(o({runId:a()})),dr=T(o({hookId:a(),tag:a().optional()}));function fr(e,t){return H(e,`hooks`,`token-index`,Wn(t))}function pr(e,t){return V(`hookId`,t),H(e,`hooks`,`id-index`,t)}function mr(e){return H(e,`hooks`,`by-run`)}function hr(e){let t=xt(e);return t===e?void 0:e.slice(t.length+1)}function gr(e,t){return t?Ct(e)||St(e,t):Ct(e)}async function _r(e){try{return await J(e,l)}catch(e){if(e instanceof SyntaxError||e instanceof r)return null;throw e}}async function vr(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([X(z.join(fr(e,t),o),s),X(z.join(pr(e,r),o),s)])}function yr(e,t,n,r){return W(e,`hooks/by-run`,`${t}-${n}`,r)}async function br(e,t,n,r){await X(yr(e,t,n,r),JSON.stringify(r?{hookId:n,tag:r}:{hookId:n}))}async function xr(e,t,n,r){await Y(yr(e,t,n,r)),r&&await Y(yr(e,t,n))}async function Sr(e,t){V(`runId`,t);let n=mr(e),i=`${t}-`,a=[];for(let e of await Z(n)){if(!e.startsWith(i))continue;let t=null;try{t=await J(z.join(n,`${e}.json`),dr)}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 Cr(e,t){await Y(z.join(mr(e),`${t}.json`))}const wr=E(`@workflow/world-local//hookIndexEnsureCache`,1,()=>({ensuredBasedirs:new Map}));function Tr(){wr.ensuredBasedirs.clear()}async function Er(e){let t=z.resolve(e),n=wr.ensuredBasedirs.get(t);return n||(n=Or(t).catch(e=>{throw wr.ensuredBasedirs.delete(t),e}),wr.ensuredBasedirs.set(t,n)),n}async function Dr(e,t,n){for(let r=0;r<e.length;r+=t)await Promise.all(e.slice(r,r+t).map(n))}async function Or(e){let t=z.join(e,`hooks`,`.hook-index-complete`);try{await R.access(t);return}catch{}let n=z.join(e,`events`);await Dr(await Z(n),32,async t=>{let r=await _r(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 vr(e,i,r.runId,r.correlationId,r.eventId,hr(t))}catch{}});let i=z.join(e,`hooks`);await Dr(await Z(i),32,async t=>{let n=null;try{n=await J(z.join(i,`${t}.json`),C)}catch(e){if(!(e instanceof SyntaxError||e instanceof r))throw e}if(n)try{await br(e,n.runId,n.hookId,hr(t))}catch{}}),await X(t,``)}async function kr(e,t,n,i){await Er(e);let a;try{a=t.kind===`token`?fr(e,t.token):pr(e,t.hookId)}catch{return null}let o=(await Z(a)).filter(e=>gr(e,i)).sort((e,t)=>xt(t).localeCompare(xt(e)));for(let t of o){let i=null;try{i=await J(z.join(a,`${t}.json`),ur)}catch(e){if(!(e instanceof SyntaxError||e instanceof r))throw e}if(!i)continue;let o=xt(t),s;try{s=W(e,`events`,`${i.runId}-${o}`,hr(t))}catch{continue}let c=await _r(s);if(c&&c.eventType===`hook_created`&&typeof c.correlationId==`string`&&n(c))return c}return null}function Ar(e,t){return t===`none`?{...e,input:void 0,output:void 0}:e}function jr(e,t){return t===`none`?{...e,input:void 0,output:void 0}:e}function Mr(e,t){if(t===`none`){let{metadata:t,...n}=e;return n}return e}function Nr(e){if(e.eventType!==`hook_created`)return;let t=e.eventData.token;return typeof t==`string`?t:void 0}function Pr(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 Fr(e,t){return e.eventType===`hook_created`&&typeof e.correlationId==`string`&&t(e)}async function Ir(e,t,n){let r=await G(e,`runs`,t,_,n);return r?j(r.status):!1}async function Lr(e,t,n,r){let i=await kr(e,t,e=>Fr(e,n),r);if(!i||!Fr(i,n))return null;if(await Ir(e,i.runId,r)){let e=i.eventData.tokenRetentionUntil;if(!e||e.getTime()<=Date.now())return null}return await Kn(e,i.correlationId,r)?null:i}async function Rr(e,t,n){let r=Pr(t);return await X(er(e,r.token),JSON.stringify({token:r.token,hookId:r.hookId,runId:r.runId,eventId:t.eventId,tokenRetentionUntil:t.eventData.tokenRetentionUntil})),await br(e,r.runId,r.hookId,n),await X(W(e,`hooks`,r.hookId,n),JSON.stringify(r,K,2)),r}async function zr(e,t,n){let r=await Lr(e,{kind:`token`,token:t},e=>Nr(e)===t,n);return r?Rr(e,r,n):null}async function Br(e,t,n){let r=await Lr(e,{kind:`id`,hookId:t},e=>e.correlationId===t,n);return r?Rr(e,r,n):null}function Vr(e,t){async function n(n){return await Kn(e,n.hookId,t)?!1:n.tokenRetentionUntil&&n.tokenRetentionUntil.getTime()>Date.now()?!0:!await Ir(e,n.runId,t)}async function r(r){let i=await nr(er(e,r));if(i?.hookId){try{let a=await G(e,`hooks`,i.hookId,C,t);if(a?.token===r){if(!await n(a))throw new ve(r);return{...a,isWebhook:a.isWebhook??!0}}}catch(e){if(!_t.is(e))throw e}return null}let a=z.join(e,`hooks`),o=await Z(a);for(let e of o){let t=await J(z.join(a,`${e}.json`),C);if(t?.token===r){if(!await n(t))throw new ve(r);return{...t,isWebhook:t.isWebhook??!0}}}return null}async function i(r,i){V(`hookId`,r);let a=await G(e,`hooks`,r,C,t);if(a&&!await n(a))throw new ve(r);let o=a??await Br(e,r,t);if(!o)throw new ve(r);let s=i?.resolveData||`all`;return Mr({...o,isWebhook:o.isWebhook??!0},s)}async function a(n){let i=await r(n)??await zr(e,n,t);if(!i)throw new ve(n);return i}async function o(t){let r=z.join(e,`hooks`),i=t.resolveData||`all`,a=await Rt({directory:r,schema:C,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=>Mr(e,i))}}return{get:i,getByToken:a,list:o}}async function Hr(e,t){await Er(e);for(let n of await Sr(e,t)){if(n.hookId){let i=null,a=null;try{a=W(e,`hooks`,n.hookId,n.tag),i=await J(a,C)}catch(e){if(!_t.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 ar(e,i.token,i.runId,i.hookId),await Y(or(e,i.token,i.runId,i.hookId)),await Y(a)}}await Cr(e,n.fileId)}}const Ur=E(`@workflow/world-local//streamerMonotonicUlid`,1,()=>({next:k(()=>Math.random())})),Wr=e=>Ur.next(e),Gr=T(o({streams:s(a())}));function Kr(e){return e===1}function qr(e){let t=Buffer.from([+!!e.eof]);return Buffer.concat([t,e.chunk])}function Jr(e){return Kr(e[0])}function Yr(e){return{eof:Jr(e),chunk:Buffer.from(e.subarray(1))}}async function Xr(e){try{return await R.readdir(e)}catch(e){if(e.code===`ENOENT`)return[];throw e}}function Zr(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 Qr(e,t){return V(`streamName`,t),z.join(e,t)}async function $r(e,t,n){let r=Qr(e,t),i=await Xr(r),a=new Map;return Zr(a,i,`.json`),Zr(a,i,`.bin`,`.bin`,n?e=>!e.endsWith(`.${n}`):void 0),n&&Zr(a,i,`.${n}.bin`),{files:[...a.keys()].sort(),extMap:a,dir:r}}const ei=`chnk_${`0`.repeat(26)}`;async function ti(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,Gr,n))?.streams??[]}catch(e){ni(`streams of ${t}`,e);return}for(let e of a)try{let t=Qr(r,e);await At(z.join(t,`${ei}${i}.bin`),qr({chunk:Buffer.from([]),eof:!0}),{overwrite:!0});for(let e of await Xr(t))e.startsWith(ei)||(e.endsWith(`.bin`)||e.endsWith(`.json`))&&await U(()=>R.unlink(z.join(t,e))).catch(t=>{t.code!==`ENOENT`&&ni(e,t)})}catch(t){ni(e,t)}}function ni(e,t){console.warn(`[world-local] Failed to purge stream data for ${e}:`,t instanceof Error?t.message:t)}function ri(e,t){let n=t?`.${t}`:``,r=new Ge,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,Gr,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_${Wr()}`;await a(await t,i);let l=o(s),u=qr({chunk:l,eof:!1});await At(z.join(Qr(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_${Wr()}`);await a(await t,i);let l=s.map(e=>o(e)).map(async(t,r)=>{let a=c[r],o=qr({chunk:t,eof:!1});return await At(z.join(Qr(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_${Wr()}`;await a(await t,i),await At(z.join(Qr(z.join(e,`streams`,`chunks`),i),`${o}${n}.bin`),qr({chunk:Buffer.from([]),eof:!0})),r.emit(`close:${i}`,{streamName:i})},async list(n){return V(`runId`,n),(await G(e,`streams/runs`,n,Gr,t))?.streams??[]},async getChunks(n,r,i){let a=i?.limit??100,{files:o,extMap:s,dir:c}=await $r(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(Kr(await Mt(n))){u=!0;break}f++;continue}if(d.length>=a){Kr(await Mt(n))?u=!0:f++;break}let r=Yr(await jt(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 $r(z.join(e,`streams`,`chunks`),r,t),s=!1,c=0;for(let e of i){let t=a.get(e)??`.bin`;if(Kr(await Mt(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 $r(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`;Kr(await Mt(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=Yr(await jt(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 $r(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=Yr(await jt(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 ii(e){let t=le(e);return t.unsupported&&console.warn(`[world-local] Ignoring unrecognized ${fe} value ${JSON.stringify(t.raw)}; keeping the run's data.`),t.mode===`none`}function ai(e,t){return{...e,input:void 0,output:void 0,error:void 0,expiredAt:t}}async function oi(e,t,n){await Promise.all([ci(z.join(e,`steps`),t,e=>{e.input=void 0,e.output=void 0,e.error=void 0}),ci(z.join(e,`events`),t,e=>{let t=e.eventData;if(t&&typeof t==`object`)for(let n of b(String(e.eventType)))delete t[n]}),li(e,t),ti(e,t,n)])}const si=n(a(),c()),$=i(e=>{if(e&&typeof e==`object`&&`eventType`in e&&`eventData`in e){let t=e.eventData;if(t&&typeof t==`object`)for(let n of b(String(e.eventType)))n in t||(t[n]=void 0)}return e},l);async function ci(e,t,n){let r;try{r=await Z(e)}catch(t){ui(e,t);return}for(let i of r){if(!i.startsWith(`${t}-`))continue;let r=z.join(e,`${i}.json`);try{let e=await J(r,si);if(!e)continue;n(e),await q(r,e,{overwrite:!0})}catch(e){ui(r,e)}}}async function li(e,t){let n;try{await Er(e),n=await Sr(e,t)}catch(e){ui(`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 J(n,si);if(!i||i.runId!==t)continue;i.metadata=void 0,await q(n,i,{overwrite:!0})}catch(e){ui(r.hookId,e)}}function ui(e,t){console.warn(`[world-local] Failed to purge user data for ${e}:`,t instanceof Error?t.message:t)}const di=new Ge;di.setMaxListeners(0);function fi(){return re(`WORKFLOW_LOCAL_RUN_STATUS_POLL_INTERVAL_MS`,100,{integer:!0,min:1})}function pi(e){di.emit(`run:${e}`)}function mi(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),di.off(i,o),n?.removeEventListener(`abort`,o),r())},s=setTimeout(o,t);di.once(i,o),n?.addEventListener(`abort`,o,{once:!0})})}async function hi(e,t,n,r,i,a){if(j(a.status)||await Jn(e,t))throw new ge(`Workflow run "${t}" is already in a terminal state`);let o=Xn(e,t,n);await X(o,r);try{if(await Jn(e,t)||await Nt(o,i)!==`linked`)throw new ge(`Workflow run "${t}" is already in a terminal state`)}finally{await R.unlink(o).catch(()=>{})}}async function gi(e,t,n,r,i){V(`runId`,t);let a=i?.resolveData??`all`;switch(n.eventType){case`run_cancelled`:{await X(qn(e,t),``),await Zn(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=ii(i.attributes),s=o?ai(i,n):i;return await q(H(e,`runs`,`${t}.json`),s,{overwrite:!0}),pi(t),await Hr(e,t),o&&await oi(e,t,void 0),{event:void 0,run:Ar(s,a)}}case`wait_completed`:case`hook_received`:{let i=`evnt_${cr()}`,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 hi(e,t,i,JSON.stringify(s,K,2),c,r):await q(c,s),{event:D(s,a)}}default:throw Error(`Event type '${n.eventType}' not supported for legacy runs (specVersion: ${r.specVersion||`undefined`}). Please upgrade 'workflow' package.`)}}const _i=E(`@workflow/world-local//runFileLocks`,1,()=>({byKey:new Map}));function vi(e,t){let n=_i.byKey.get(e),r={},i=(async()=>{n&&await n.catch(()=>void 0);try{return await t()}finally{_i.byKey.get(e)===r.task&&_i.byKey.delete(e)}})();return r.task=i,_i.byKey.set(e,i),i}function yi(e,t){let n=(async(n,r)=>{V(`runId`,n);let i=await G(e,`runs`,n,_,t);if(!i)throw new he(n);return Ar(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(j(i.status))return i;let a=r-Date.now();if(a<=0||t?.signal?.aborted)return i;await mi(e,Math.min(a,fi()),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 he)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 Rt({directory:z.join(e,`runs`),schema:_,fileIdFilter:t?.fileIdFilter,filter:e=>!(t?.workflowName&&e.workflowName!==t.workflowName||t?.status!==void 0&&!(Array.isArray(t.status)?t.status:[t.status]).includes(e.status)),sortOrder:t?.pagination?.sortOrder??`desc`,limit:t?.pagination?.limit??200,cursor:t?.pagination?.cursor,getCreatedAt:lr(`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),vi(n,async()=>{let a=await G(e,`runs`,n,_,t);if(!a)throw new he(n);try{me(r,{existingKeys:Object.keys(a.attributes??{}),allowReservedAttributes:i?.allowReservedAttributes})}catch(e){throw e instanceof O,e}let o=ee(a.attributes,r),s={...a,attributes:o,updatedAt:new Date};return await q(W(e,`runs`,n,t),s,{overwrite:!0}),{attributes:o}}))}}const bi=864e5;function xi(){let e=Number(process.env.WORKFLOW_LOCAL_HOOK_RETENTION_LIMIT_DAYS??30);if(!Number.isFinite(e)||e<=0)throw new F(`WORKFLOW_LOCAL_HOOK_RETENTION_LIMIT_DAYS must be a positive number`,{status:400});return e*bi}const Si=T(o({eventId:a()})),Ci=T(o({runId:a(),resumeId:a(),hookId:a(),eventId:a(),payloadDigest:a().optional()}));function wi(e,t){return e.eventType===`hook_received`&&e.correlationId===t.hookId&&(e.resumeId===void 0||e.resumeId===t.resumeId)}async function Ti(e,t,n,r){let i=await $n(e,t,r);for(let a of i.ids){let i=await G(e,`events`,`${t}-${a}`,$,r);if(i&&i.resumeId===n.resumeId&&wi(i,n))return i}return null}async function Ei(e,t,n){if(t.hookId&&await Kn(e,t.hookId,n))return!0;let r=await G(e,`runs`,t.runId,_,n);return r?j(r.status)?!t.tokenRetentionUntil||t.tokenRetentionUntil.getTime()<=Date.now():!1:!0}async function Di(e){try{return await J(e,Si)}catch(e){if(e instanceof SyntaxError||e instanceof r)return null;throw e}}function Oi(e){return ie(e.eventId)?e.eventId:null}function ki(e,t){let n=xt(t).slice(e.length+1);return ie(n)?n:null}async function Ai(e,t,n){return(await Rt({directory:z.join(e,`events`),schema:$,filePrefix:`${t}-`,filter:e=>e.eventType===`hook_created`&&e.correlationId===n,limit:1,getCreatedAt:lr(`evnt`),getId:e=>e.eventId})).data[0]?.eventId??null}async function ji(e,t,n,r,i){let a=await G(e,`events`,`${t}-${r}`,$,i);if(!a||a.eventType!==`hook_created`||a.correlationId!==n||await G(e,`hooks`,n,C,i))return;let o=Pr(a);await vr(e,o.token,t,n,r,i),await br(e,t,n,i),await X(W(e,`hooks`,n,i),JSON.stringify(o,K,2))}async function Mi(e,t,n,r,i){let a=or(e,t,n,r);return await X(a,JSON.stringify({eventId:i}))?i:(await Di(a))?.eventId??null}function Ni(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 Pi(e,t){let n=z.join(e,`waits`),r=await Z(n);for(let e of r)e.startsWith(`${t}-`)&&await Y(z.join(n,`${e}.json`))}async function Fi(e,t,n,r){return vi(t,async()=>{let i=(await J(W(e,`runs`,t,n),_))?.attributes??r.attributes,a={...r,attributes:i},o=j(a.status)&&ii(i);return o&&(a=ai(a,new Date)),await q(W(e,`runs`,t,n),a,{overwrite:!0}),j(a.status)&&pi(t),{run:a,purged:o}})}function Ii(e,t){let n=xi(),r=4194304,i=new Map,a=new Map,o=new Map,s=0;function c(e){let t=i.get(e);if(!t)return;i.delete(e),s-=a.get(e)??0,a.delete(e);let n=o.get(t.runId);n?.delete(e),n?.size===0&&o.delete(t.runId)}function l(e){for(let t of o.get(e)??[])c(t)}function u(){i.clear(),a.clear(),o.clear(),s=0,b.clear()}let b=new Map;function S(e){return t?`${e}.${t}`:e}async function re(n,r){let i=`${n}-${ne(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 w(n,r){let i=S(n),a=b.get(i);if(a===void 0||r?.rescan){let r=await $n(e,n,t);a===void 0?(a=r.count>0&&!r.usesSlots?null:{published:r.maxSlot},b.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 re(n,o);)a.published=Math.max(a.published,o),o+=1;return o}function T(e,t){let n=te(t);if(n===null)return;let r=b.get(S(e));r&&(r.published=Math.max(r.published,n))}async function ae(e){let t=await w(e);return t===null?`evnt_${cr()}`:ne(t)}async function oe(n){let r=await w(n,{rescan:!0});return r===null?Qn(e,n,t):{eventId:ne(r),createdAt:new Date}}function E(e,t,n){if(n>r)return;for(;i.size>0&&(i.size>=1e3||s+n>r);){let e=i.keys().next().value;c(e)}i.set(e,t),a.set(e,n),s+=n;let l=o.get(t.runId)??new Set;l.add(e),o.set(t.runId,l)}function ce(e,t,n){if(p(e.eventType)){l(e.runId);return}let i=Buffer.byteLength(n);if(i>r)return;let a=$.safeParse(JSON.parse(n,kt));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=te(r.eventId);if(o===null)return await At(i,a),ce(r,i,a),r;if(await X(i,a))return T(r.runId,r.eventId),ce(r,i,a),r;let s=await w(r.runId,{rescan:n>0&&n%8==0,atLeast:o+1});We(s!==null),r={...r,eventId:ne(s)}}}let fe=(t,n)=>Rt({directory:z.join(e,`events`),schema:$,cachedItems:i,filePrefix:`${t}-`,sortOrder:n.sortOrder??`asc`,limit:n.limit,cursor:n.cursor,getCreatedAt:lr(`evnt`),getId:e=>e.eventId,getSortKey:Oi,getSortKeyFromFileId:e=>ki(t,e)}),O=new Map,k=new Map,A={clearCache:u,async create(r,i,a){if(i.eventType===`hook_created`&&i.eventData.tokenRetentionUntil!==void 0&&i.eventData.tokenRetentionUntil.getTime()>Date.now()+n)throw new F(`Hook minimum retention cannot exceed ${n/bi} 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),d(i.eventType)&&r&&i.correlationId){let e=t?`${r}-${i.correlationId}.${t}`:`${r}-${i.correlationId}`;return Ni(O,e,o)}if(y(i.eventType)&&r&&i.correlationId){let e=t?`${r}-${i.correlationId}.hook.${t}`:`${r}-${i.correlationId}.hook`;return Ni(k,e,o)}return o();async function o(){let n=``,o=!1,s=null,c=new Date,u;if(i.eventType===`run_created`&&(!r||r===``))u=`wrun_${cr()}`;else if(r)u=r;else throw Error(`runId is required for non-run_created events`);if(i.eventType===`run_created`&&r&&r!==``){let e=de(u,`wrun_`);if(e)throw new F(e)}let y=i.specVersion??7,b=null;if(i.eventType!==`run_created`&&![`step_completed`,`step_retrying`].includes(i.eventType)&&(b=await G(e,`runs`,u,_,t),i.eventType===`run_started`&&!b&&`eventData`in i&&i.eventData)){let n=i.eventData;if(n.deploymentId&&n.workflowName&&n.input!==void 0){me(Object.entries(n.attributes??{}).map(([e,t])=>({key:e,value:t})),{allowReservedAttributes:n.allowReservedAttributes===!0});let r={runId:u,deploymentId:n.deploymentId,status:`pending`,workflowName:n.workflowName,specVersion:y,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:c,updatedAt:c};if(await X(W(e,`runs`,u,t),JSON.stringify(r,K))){let e=await ae(u);await le({eventType:`run_created`,runId:u,eventId:e,createdAt:c,specVersion:y,eventData:{deploymentId:n.deploymentId,workflowName:n.workflowName,input:n.input,executionContext:n.executionContext,attributes:n.attributes,allowReservedAttributes:n.allowReservedAttributes,encryptionPublicKey:n.encryptionPublicKey}}),b=r}else b=await G(e,`runs`,u,_,t)}}if(n=await ae(u),!b&&(i.eventType===`run_failed`||i.eventType===`attr_set`||i.eventType===`run_started`))throw new he(u);if(b){if(pe(b.specVersion))throw new _e(b.specVersion,7);if(x(b.specVersion))return gi(e,u,i,b,a)}let S=f(i),re=S&&i.eventType===`step_started`;if(b&&j(b.status)){if(i.eventType===`run_cancelled`&&b.status===`cancelled`){let e=await le({...i,runId:u,eventId:n,createdAt:c,specVersion:y}),t=a?.resolveData??`all`;return{event:D(e,t),run:b,...b?{maxEvents:ue()}:{}}}if(i.eventType===`run_started`)throw new ge(`Workflow run "${u}" is already in terminal state "${b.status}"`);if(p(i.eventType))throw new I(`Cannot transition run from terminal state "${b.status}"`);if(S)throw new I(`Cannot create new entities on run in terminal state "${b.status}"`);if(i.eventType===`attr_set`)throw new I(`Cannot set attributes on run in terminal state "${b.status}"`)}let E=null;if(d(i.eventType)&&i.eventType!==`step_created`&&i.correlationId){if(E=await G(e,`steps`,`${u}-${i.correlationId}`,h,t),!E&&!re)throw new F(`Step "${i.correlationId}" not found`);if(re&&E)throw new I(`Step "${i.correlationId}" already created`);if(E){if(g(E.status))throw new I(`Cannot modify step in terminal state "${E.status}"`);if(b&&j(b.status)&&(E.status!==`running`||i.eventType===`step_started`))throw new ge(`Cannot ${i.eventType===`step_started`?`start`:`modify non-running`} step on run in terminal state "${b.status}"`)}}if(v(i.eventType)&&i.correlationId){if(i.eventType===`hook_received`&&a?.resumeId){let n=await J(ir(e,u,a.resumeId),Ci);if(n&&n.hookId===i.correlationId&&(!a.resumePayloadDigest||!n.payloadDigest||n.payloadDigest===a.resumePayloadDigest)){let r=await G(e,`events`,`${u}-${n.eventId}`,$,t),i=r&&wi(r,n)?r:await Ti(e,u,n,t);if(i)return{event:i}}}if(i.eventType===`hook_received`&&await Kn(e,i.correlationId,t)||!await G(e,`hooks`,i.correlationId,C,t))throw new ve(i.correlationId);if(i.eventType===`hook_received`&&a?.resumeId){let r=ir(e,u,a.resumeId),c=async r=>{if(r.hookId!==i.correlationId)throw new I(`hook_received resumeId "${a.resumeId}" already recorded for a different hook`);if(a.resumePayloadDigest&&r.payloadDigest&&r.payloadDigest!==a.resumePayloadDigest)throw new I(`hook_received resumeId "${a.resumeId}" already recorded with a different payload`);let c=await G(e,`events`,`${u}-${r.eventId}`,$,t);if(c&&wi(c,r))return{event:c};let l=await Ti(e,u,r,t);return l?{event:l}:(s=r.eventId,c||(n=r.eventId,o=!0),null)},l=await J(r,Ci);if(l){let e=await c(l);if(e)return e}else if(o=!ie(n),s=n,!await X(r,JSON.stringify({runId:u,resumeId:a.resumeId,hookId:i.correlationId,eventId:n,...a.resumePayloadDigest?{payloadDigest:a.resumePayloadDigest}:{}}))){s=null;let e=await J(r,Ci);if(e){let t=await c(e);if(t)return t}}}}let O={...i,runId:u,eventId:n,createdAt:c,specVersion:y,...i.eventType===`hook_received`&&a?.resumeId?{resumeId:a.resumeId}:{}};if(i.eventType===`run_started`&&`eventData`in O&&delete O.eventData,re&&O.eventType===`step_started`&&O.eventData){let{input:e,...t}=O.eventData;O={...O,eventData:t}}let k,A=!1,M,N,P,be=!1,xe;if(p(i.eventType)&&b){await X(qn(e,u,t),``),await Zn(e,u,t);let r=await oe(u);n=r.eventId,O={...O,eventId:n,createdAt:r.createdAt}}if(i.eventType===`run_created`&&`eventData`in i){let n=i.eventData;if(me(Object.entries(n.attributes??{}).map(([e,t])=>({key:e,value:t})),{allowReservedAttributes:n.allowReservedAttributes===!0}),k={runId:u,deploymentId:n.deploymentId,status:`pending`,workflowName:n.workflowName,specVersion:y,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:c,updatedAt:c},!await X(W(e,`runs`,u,t),JSON.stringify(k,K,2)))throw new I(`Workflow run "${u}" already exists`)}else if(i.eventType===`run_started`){if(b){if(b.status===`running`){if(a?.skipPreload)return{run:b,maxEvents:ue()};let e=await fe(u,{limit:ue()});return{run:b,events:e.data,cursor:e.cursor,hasMore:e.hasMore,maxEvents:ue()}}let n=await Fi(e,u,t,{runId:b.runId,deploymentId:b.deploymentId,workflowName:b.workflowName,specVersion:b.specVersion,executionContext:b.executionContext,input:b.input,createdAt:b.createdAt,expiredAt:b.expiredAt,status:`running`,output:void 0,error:void 0,completedAt:void 0,startedAt:b.startedAt??c,updatedAt:c,attributes:b.attributes,encryptionPublicKey:b.encryptionPublicKey});k=n.run,A=n.purged}}else if(i.eventType===`run_completed`&&`eventData`in i){let n=i.eventData;if(b){let r=await Fi(e,u,t,{runId:b.runId,deploymentId:b.deploymentId,workflowName:b.workflowName,specVersion:b.specVersion,executionContext:b.executionContext,input:b.input,createdAt:b.createdAt,expiredAt:b.expiredAt,startedAt:b.startedAt,status:`completed`,output:n.output,error:void 0,completedAt:c,updatedAt:c,attributes:b.attributes,encryptionPublicKey:b.encryptionPublicKey});k=r.run,A=r.purged,await Promise.all([Hr(e,u),Pi(e,u)])}}else if(i.eventType===`run_failed`&&`eventData`in i){let n=i.eventData;if(b){let r=await Fi(e,u,t,{runId:b.runId,deploymentId:b.deploymentId,workflowName:b.workflowName,specVersion:b.specVersion,executionContext:b.executionContext,input:b.input,createdAt:b.createdAt,expiredAt:b.expiredAt,startedAt:b.startedAt,status:`failed`,output:void 0,error:n.error,errorCode:n.errorCode,completedAt:c,updatedAt:c,attributes:b.attributes,encryptionPublicKey:b.encryptionPublicKey});k=r.run,A=r.purged,await Promise.all([Hr(e,u),Pi(e,u)])}}else if(i.eventType===`run_cancelled`){if(b){let n=await Fi(e,u,t,{runId:b.runId,deploymentId:b.deploymentId,workflowName:b.workflowName,specVersion:b.specVersion,executionContext:b.executionContext,input:b.input,createdAt:b.createdAt,expiredAt:b.expiredAt,startedAt:b.startedAt,status:`cancelled`,output:void 0,error:void 0,completedAt:c,updatedAt:c,attributes:b.attributes,encryptionPublicKey:b.encryptionPublicKey});k=n.run,A=n.purged,await Promise.all([Hr(e,u),Pi(e,u)])}}else if(i.eventType===`attr_set`&&b)k=await vi(u,async()=>{let n=await J(W(e,`runs`,u,t),_);if(!n)throw new he(u);if(me(i.eventData.changes,{existingKeys:Object.keys(n.attributes),allowReservedAttributes:i.eventData.allowReservedAttributes===!0}),i.correlationId&&i.eventData.writer.type===`workflow`&&!await X(H(e,`.locks`,`attributes`,t?`${u}-${i.correlationId}.created.${t}`:`${u}-${i.correlationId}.created`),``))throw new I(`Attribute event "${i.correlationId}" already exists`);let r={...n,attributes:ee(n.attributes,i.eventData.changes),updatedAt:c};return await q(W(e,`runs`,u,t),r,{overwrite:!0}),r});else if(i.eventType===`step_created`&&`eventData`in i){if(!await X(H(e,`.locks`,`steps`,t?`${u}-${i.correlationId}.created.${t}`:`${u}-${i.correlationId}.created`),``))throw new I(`Step "${i.correlationId}" already created`);let n=i.eventData;M={runId:u,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:c,updatedAt:c,specVersion:y},await q(W(e,`steps`,`${u}-${i.correlationId}`,t),M)}else if(i.eventType===`step_started`){if(!E&&re){let n=i.eventData;if(await X(H(e,`.locks`,`steps`,t?`${u}-${i.correlationId}.created.${t}`:`${u}-${i.correlationId}.created`),``)){let r={runId:u,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:c,updatedAt:c,specVersion:y};await q(W(e,`steps`,`${u}-${i.correlationId}`,t),r);let a=await ae(u);await le({eventType:`step_created`,runId:u,eventId:a,createdAt:c,specVersion:y,correlationId:i.correlationId,eventData:{stepName:n.stepName,input:n.input}}),E=r,be=!0}else throw new I(`Step "${i.correlationId}" already created`)}if(E){if(E.retryAfter&&E.retryAfter.getTime()>Date.now())throw new ye(`Cannot start step "${i.correlationId}": retryAfter timestamp has not been reached yet`,{retryAfter:Math.ceil((E.retryAfter.getTime()-Date.now())/1e3)});let n=`${u}-${i.correlationId}`,r=await G(e,`steps`,n,h,t);if(r&&g(r.status))throw new I(`Cannot modify step in terminal state "${r.status}"`);M={...E,status:`running`,startedAt:E.startedAt??c,attempt:E.attempt+1,retryAfter:void 0,updatedAt:c},await q(W(e,`steps`,n,t),M,{overwrite:!0})}}else if(i.eventType===`step_completed`&&`eventData`in i){let n=i.eventData;if(E){let r=`${u}-${i.correlationId}`;if(!await X(H(e,`.locks`,`steps`,t?`${r}.terminal.${t}`:`${r}.terminal`),``))throw new I(`Cannot modify step in terminal state`);M={...E,status:`completed`,output:n.result,completedAt:c,updatedAt:c},await q(W(e,`steps`,r,t),M,{overwrite:!0})}}else if(i.eventType===`step_failed`&&`eventData`in i){let n=i.eventData;if(E){let r=`${u}-${i.correlationId}`;if(!await X(H(e,`.locks`,`steps`,t?`${r}.terminal.${t}`:`${r}.terminal`),``))throw new I(`Cannot modify step in terminal state`);M={...E,status:`failed`,error:n.error,completedAt:c,updatedAt:c},await q(W(e,`steps`,r,t),M,{overwrite:!0})}}else if(i.eventType===`step_retrying`&&`eventData`in i){let n=i.eventData;if(E){let r=`${u}-${i.correlationId}`;M={...E,status:`pending`,error:n.error,retryAfter:n.retryAfter,updatedAt:c},await q(W(e,`steps`,r,t),M,{overwrite:!0})}}else if(i.eventType===`hook_created`&&`eventData`in i){let r=i.eventData,s=er(e,r.token),l=JSON.stringify({token:r.token,hookId:i.correlationId,runId:u,eventId:n,tokenRetentionUntil:r.tokenRetentionUntil}),d=await rr(e,r.token,async n=>{let a=await nr(s);return a||=(n.throwIfAborted(),await Y(s),await zr(e,r.token,t),await nr(s)),a?a.runId===u&&a.hookId===i.correlationId?{status:`owned`,claim:a}:await Ei(e,a,t)?(n.throwIfAborted(),await Y(s),a.hookId&&(await Y(W(e,`hooks`,a.hookId,t)),await Y(or(e,r.token,a.runId,a.hookId)),await xr(e,a.runId,a.hookId,t)),n.throwIfAborted(),We(await X(s,l)),{status:`claimed`}):{status:`conflict`,claim:a}:(n.throwIfAborted(),We(await X(s,l)),{status:`claimed`})});if(d.status===`owned`){let a=d.claim,s;if(a.eventId)s=a.eventId;else{let a=await Ai(e,u,i.correlationId);if(a!==null)throw await ji(e,u,i.correlationId,a,t),new I(`Hook "${i.correlationId}" already created`);let o=await Mi(e,r.token,u,i.correlationId,n);if(o===null)throw new I(`Hook "${i.correlationId}" already created`);s=o}n=s,o=!0;let l=se(n.replace(/^evnt_/,``))??c;O={...i,eventData:{...i.eventData,tokenRetentionUntil:a.tokenRetentionUntil},runId:u,eventId:n,createdAt:l,specVersion:y}}if(d.status===`conflict`){let e=d.claim,t=await le({eventType:`hook_conflict`,correlationId:i.correlationId,eventData:{token:r.token,conflictingRunId:e.runId},runId:u,eventId:n,createdAt:c,specVersion:y}),o=a?.resolveData??`all`,s=typeof a?.sinceCursor==`string`?await fe(u,{sortOrder:`asc`,cursor:a.sinceCursor}):void 0,l={event:D(t,o),run:k,step:M,hook:void 0};return s?{...l,events:o===`none`?s.data.map(e=>D(e,o)):s.data,cursor:s.cursor,hasMore:s.hasMore}:l}let f=O.eventData;N={runId:u,hookId:i.correlationId,token:f.token,metadata:f.metadata,ownerId:`local-owner`,projectId:`local-project`,environment:`local`,createdAt:O.createdAt,specVersion:y,isWebhook:f.isWebhook??!1,isSystem:f.isSystem??!1,tokenRetentionUntil:f.tokenRetentionUntil},xe=d.status===`owned`?{overwrite:!0}:void 0,await vr(e,r.token,u,i.correlationId,n,t)}else if(i.eventType===`hook_disposed`){if(!await X(Gn(e,i.correlationId,t),``))throw new I(`Hook "${i.correlationId}" already disposed`);let n=W(e,`hooks`,i.correlationId,t),r=await G(e,`hooks`,i.correlationId,C,t);r&&(await ar(e,r.token,r.runId,r.hookId),await Y(or(e,r.token,r.runId,r.hookId))),await Y(n),await xr(e,u,i.correlationId,t)}else if(i.eventType===`wait_created`&&`eventData`in i){let n=`${u}-${i.correlationId}`;if(!await X(H(e,`.locks`,`waits`,t?`${n}.created.${t}`:`${n}.created`),``))throw new I(`Wait "${i.correlationId}" already exists`);let r=i.eventData;P={waitId:n,runId:u,status:`waiting`,resumeAt:r.resumeAt,completedAt:void 0,createdAt:c,updatedAt:c,specVersion:y},await q(W(e,`waits`,n,t),P)}else if(i.eventType===`wait_completed`){let n=`${u}-${i.correlationId}`,r=H(e,`.locks`,`waits`,t?`${n}.completed.${t}`:`${n}.completed`);if(!await X(r,``))throw new I(`Wait "${i.correlationId}" already completed`);let a=await G(e,`waits`,n,m,t);if(!a)throw await R.unlink(r).catch(()=>{}),new F(`Wait "${i.correlationId}" not found`);P={...a,status:`completed`,completedAt:c,updatedAt:c},await q(W(e,`waits`,n,t),P,{overwrite:!0})}if(i.eventType===`hook_received`&&i.correlationId&&await Kn(e,i.correlationId,t))throw new ve(i.correlationId);let Se=W(e,`events`,`${u}-${n}`,t),Ce=JSON.stringify(O,K,2),we=async r=>{let i=te(n);if(o||i===null)return!1;let a=await w(u,{rescan:r>0&&r%8==0,atLeast:i+1});return a!==null&&(n=ne(a),O={...O,eventId:n},Se=W(e,`events`,`${u}-${n}`,t),Ce=JSON.stringify(O,K,2),!0)},Te=!1;for(let r=0;;r++){if(i.eventType===`hook_received`){let r=await Jn(e,u,t),i=r?null:await G(e,`runs`,u,_,t);if(r||i&&j(i.status))throw new ge(`Workflow run "${u}" is already in a terminal state`);let a=Xn(e,u,`${n}.${cr()}`,t);if(!await X(a,Ce))throw new F(`Failed to stage event "${n}" for run "${u}": staging path already exists`);try{if(await Jn(e,u,t))throw new ge(`Workflow run "${u}" is already in a terminal state`);let n=await Nt(a,Se);if(n===`missing`)throw new ge(`Workflow run "${u}" is already in a terminal state`);Te=n===`linked`}finally{await Y(a).catch(()=>{})}}else Te=await X(Se,Ce);if(Te){T(u,n);break}if(i.eventType===`hook_received`&&a?.resumeId){let r=await G(e,`events`,`${u}-${n}`,$,t);if(r&&wi(r,{runId:u,resumeId:a.resumeId,hookId:i.correlationId,eventId:n}))return{event:r}}if(!await we(r))break}if(!Te)throw i.eventType===`hook_created`&&i.correlationId&&await ji(e,u,i.correlationId,n,t),new I(`Event "${n}" already exists for run "${u}"`);ce(O,Se,Ce),i.eventType===`hook_received`&&a?.resumeId&&s!==null&&s!==n&&await At(ir(e,u,a.resumeId),JSON.stringify({runId:u,resumeId:a.resumeId,hookId:i.correlationId,eventId:n,...a.resumePayloadDigest?{payloadDigest:a.resumePayloadDigest}:{}}),{overwrite:!0}),N&&i.eventType===`hook_created`&&(await br(e,N.runId,N.hookId,t),await q(W(e,`hooks`,N.hookId,t),N,xe)),A&&(await oi(e,u,t),l(u));let Ee=a?.resolveData??`all`,De=D(O,Ee),Oe;if(i.eventType===`run_started`&&k&&!a?.skipPreload&&(Oe=await fe(u,{limit:ue()})),typeof a?.sinceCursor==`string`){let e=await fe(u,{sortOrder:`asc`,cursor:a.sinceCursor});Oe=Ee===`none`?{...e,data:e.data.map(e=>D(e,Ee))}:e}let ke={event:De,run:k,step:M,hook:N,wait:P,...be?{stepCreated:!0}:{},...k?{maxEvents:ue()}:{}};return Oe?{...ke,events:Oe.data,cursor:Oe.cursor,hasMore:Oe.hasMore}:ke}},async get(n,r,i){V(`runId`,n),V(`eventId`,r);let a=await G(e,`events`,`${n}-${r}`,$,t);if(!a)throw Error(`Event ${r} in run ${n} not found`);let o=i?.resolveData??`all`;return D(a,o)},async list(e){let{runId:t}=e;V(`runId`,t);let n=e.resolveData??`all`,r=await fe(t,{...e.pagination,limit:e.pagination?.limit??ue()});return n===`none`?{...r,data:r.data.map(e=>D(e,n))}:r},async listByCorrelationId(t){let n=t.correlationId;V(`correlationId`,n),V(`runId`,t.runId);let r=t.resolveData??`all`,a=await Rt({directory:z.join(e,`events`),schema:$,cachedItems:i,filePrefix:`${t.runId}-`,filter:e=>e.correlationId===n,sortOrder:t.pagination?.sortOrder??`asc`,limit:t.pagination?.limit,cursor:t.pagination?.cursor,getCreatedAt:lr(`evnt`),getId:e=>e.eventId,getSortKey:Oi,getSortKeyFromFileId:e=>ki(t.runId,e)});return r===`none`?{...a,data:a.data.map(e=>D(e,r))}:a}};async function M(e,t,n){if(!e.event)return e;let r=te(e.event.eventId);if(r===null||t<1||r<=t+1)return e;let i=r-t-1,a=await A.list({runId:e.event.runId,pagination:{cursor:`${Ft}${ne(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 N=(async(e,t,n)=>{if(n?.eventCount===void 0)return A.create(e,t,n);let r=n.resolveData??`all`,i=await A.create(e,t,n);return typeof n.sinceCursor==`string`?i:M(i,n.eventCount,r)});return{...A,create:N}}function Li(e,t){return{get:(async(n,r,i)=>{V(`runId`,n),V(`stepId`,r);let a=await G(e,`steps`,`${n}-${r}`,h,t);if(!a)throw Error(`Step ${r} in run ${n} not found`);return jr(a,i?.resolveData??`all`)}),list:(async t=>{V(`runId`,t.runId);let n=t.resolveData??`all`,r=await Rt({directory:z.join(e,`steps`),schema:h,filePrefix:`${t.runId}-`,sortOrder:t.pagination?.sortOrder??`desc`,limit:t.pagination?.limit,cursor:t.pagination?.cursor,getCreatedAt:lr(`step`),getId:e=>e.stepId});return n===`none`?{...r,data:r.data.map(e=>({...e,input:void 0,output:void 0}))}:r})}}function Ri(e,t){let n=yi(e,t),r=Li(e,t),i=Ii(e,t),a=Vr(e,t);return{runs:xn(`world.runs`,n),steps:xn(`world.steps`,r),events:xn(`world.events`,i),hooks:xn(`world.hooks`,a),clearCache:()=>i.clearCache()}}function zi(e){let t=e?Object.fromEntries(Object.entries(e).filter(([,e])=>e!==void 0)):{},n={...ft.value,...t};Xe(n.dataDir);let r=n.tag,i=Mn(n),{clearCache:a,...o}=Ri(n.dataDir,r),s=pt(n);return{specVersion:ce(),capabilities:{hookRetention:{active:!0},hookResumeDedup:!0},...i,...o,...xn(`world.streams`,{...ri(n.dataDir,r),...n.streamFlushIntervalMs!==void 0&&{streamFlushIntervalMs:n.streamFlushIntervalMs}}),async start(){if(await $t(n.dataDir),!s)return;let e=r?e=>St(e,r):Ct,t={...o.runs,list:(t=>o.runs.list({...t,fileIdFilter:e}))};await oe(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 wt(t,r),{HookSchema:a}=await import(`../../_chunks/workflow/dist-DjECvUyK.js`).then(e=>e.t);await Promise.all(i.map(async n=>{let r=await J(z.join(t,n),a);r?.token&&(await Y(z.join(t,`tokens`,`${Wn(r.token)}.json`)),await Y(or(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 wt(n,r);await Promise.all(i.map(e=>Y(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 wt(t,r);await Promise.all(i.map(e=>Y(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 Tt(t,r,`.bin`);await Promise.all(n.map(e=>L.unlink(z.join(t,e)).catch(()=>{})))})),yt()}else yt(),Tr(),await Re(n.dataDir,{recursive:!0,force:!0}),await $t(n.dataDir)}}}export{Ut as DataDirAccessError,Wt as DataDirVersionError,Ke as UnwritableDataDirError,zi as createWorld,Yt as ensureDataDir,$t as initDataDir,Gt as parseVersion};