eve
Version:
Filesystem-first framework for durable backend AI agents that run anywhere.
5 lines • 88.2 kB
JavaScript
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(`
`);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(`
`).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(`
`);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(`
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};