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