openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
1 lines • 10.3 kB
JavaScript
import{Mt as e,S as t,x as n}from"./sqlite-readonly-subsystem-C-VJT-xk.mjs";import{t as r}from"./sqlite-readonly-deferred-B75K7ut7.mjs";import{o as i}from"./sqlite-readonly-runtime-process-manifest-CLhsN5hb.mjs";import{n as a}from"./sqlite-readonly-error-graph-internal-BvCeLnSw.mjs";import o from"node:path";import s from"node:fs";import{fileURLToPath as c}from"node:url";import{AsyncLocalStorage as l}from"node:async_hooks";async function settlesWithin(e,t){return await i(e.then(()=>!0),t,()=>!1,{ref:!1})}const u=e(Symbol.for(`openclaw.asyncWorkScope`),()=>new l),d=e(Symbol.for(`openclaw.asyncWorkScopeAncestry`),()=>new l),f=e(Symbol.for(`openclaw.asyncWorkScopeClosedError`),()=>class extends Error{constructor(){super(`Async work scope is closed`),this.name=`AsyncWorkScopeClosedError`}});var p=class AsyncWorkScope{constructor(e){this.failures=e,this.pending=/* @__PURE__ */ new Set,this.controller=new AbortController,this.phase=`open`}get signal(){return this.controller.signal}get hasPendingWork(){return this.pending.size>0}get isClosing(){return this.phase!==`open`}enter(e){let n=u.getStore();if(n===this)return e();let r=d.getStore(),i=n?r?.scope===n?r:{scope:n}:void 0;return t(u,this,()=>(d.enterWith({scope:this,parent:i}),e()))}run(e){if(this.phase===`closed`)throw new f;if(this.pending.size>0)return this.enter(e);let t=r();this.pending.add(t.promise);try{return this.enter(e)}finally{t.resolve(),this.pending.delete(t.promise)}}track(e){if(this.phase===`closed`)return Promise.reject(new f);let t=r();this.pending.add(t.promise),t.promise.then(()=>this.pending.delete(t.promise),e=>{this.pending.delete(t.promise),this.failures&&(a(e),this.failures.add(e))});try{t.resolve(this.enter(e))}catch(e){t.reject(e)}return t.promise}beginClose(e){this.phase===`open`&&(this.phase=`closing`,this.controller.abort(e),a(this.controller.signal.reason))}runWhenIdle(e){return AsyncWorkScope.runWhenAllIdle(()=>[this],()=>this.track(e))}static async runWhenAllIdle(e,t){let n=e();for(;n.some(e=>e.pending.size>0);)await Promise.allSettled(n.flatMap(e=>Array.from(e.pending))),n=e();return t()}async drain(){for(this.beginClose();this.pending.size>0;)await Promise.allSettled(this.pending);this.phase=`closed`}};e(Symbol.for(`openclaw.gatewayRetainedWorkTimeoutError`),()=>class extends Error{constructor(){super(`Retained Gateway work did not settle after abort; resources remain retained`)}});function runOutsideAsyncWorkScope(e){return u.getStore()===void 0?d.getStore()===void 0?e():d.exit(e):t(u,void 0,()=>(d.enterWith(void 0),e()))}function getAsyncWorkSignal(){return u.getStore()?.signal}function appendPluginInstanceCleanupFailures(e,t,n){for(let r of n.errors)e.some(e=>e.pluginId===t&&e.error===r)||e.push({pluginId:t,hookId:`instance`,error:r})}function createPluginCacheSdk(){return{hosts:/* @__PURE__ */ new Map,contexts:/* @__PURE__ */ new Map,roots:/* @__PURE__ */ new Set,packageNames:/* @__PURE__ */ new Map,packageSearches:/* @__PURE__ */ new Map,argvDirectories:/* @__PURE__ */ new Map,devSourceRoots:/* @__PURE__ */ new Map,runtimeModules:/* @__PURE__ */ new Map,normalizedJitiAliases:/* @__PURE__ */ new Map,aliasFacts:/* @__PURE__ */ new WeakMap,native:{sdkProviders:/* @__PURE__ */ new Map,nextSdkProviderOrder:0,parents:/* @__PURE__ */ new Map,aliases:/* @__PURE__ */ new Map,registeredHosts:/* @__PURE__ */ new Set,hostRoots:/* @__PURE__ */ new Map,nearestPackageRoots:/* @__PURE__ */ new Map,loaderPackageRoots:/* @__PURE__ */ new Map,allowedParentRoots:/* @__PURE__ */ new Map}}}e(Symbol.for(`openclaw.pluginInventoryRetiredError`),()=>class extends Error{constructor(){super(`Plugin inventory has retired; begin a new plugin operation.`),this.name=`PluginInventoryRetiredError`}}),e(Symbol.for(`openclaw.pluginSourceRecoveryUnavailableError`),()=>class extends Error{constructor(e){super(`Captured plugin source is missing; its previous code cannot be recovered.`,{cause:e}),this.name=`PluginSourceRecoveryUnavailableError`}});const m=e(Symbol.for(`openclaw.pluginInstanceDrainTimeoutError`),()=>class extends Error{constructor(e,t,n,r){super(e,n),this.settled=t,this.forcedRetirement=r,this.name=`PluginInstanceDrainTimeoutError`}}),h=e(Symbol.for(`openclaw.pluginCache`),()=>({snapshotOwners:/* @__PURE__ */ new WeakMap,retirements:[]})),g=e(Symbol.for(`openclaw.pluginCacheRetainers`),()=>/* @__PURE__ */ new WeakMap),_=e(Symbol.for(`openclaw.pluginInstanceCacheOwners`),()=>/* @__PURE__ */ new WeakMap);function releasePluginCacheInstance(e,t){let n=_.get(e);if(t)t.instances.delete(e),n?.delete(t);else{for(let t of n??[])t.instances.delete(e);n?.clear()}n?.size===0&&_.delete(e)}function getPluginCacheRetainers(e){let t=g.get(e);return t||(t={references:/* @__PURE__ */ new Set,controller:new AbortController,settled:r()},g.set(e,t)),t}function createPluginMetadataCache(){return{current:{snapshot:void 0,owner:`operation`,configFingerprint:void 0,agentWorkspaceFingerprint:void 0,envFingerprint:void 0,defaultDiscoveryCompatible:!1,compatibleConfigFingerprints:void 0,configIdentities:/* @__PURE__ */ new WeakSet},snapshots:/* @__PURE__ */ new Map,derivedIndexes:/* @__PURE__ */ new WeakMap,preparedManifests:/* @__PURE__ */ new WeakMap,snapshotManifestFacts:/* @__PURE__ */ new WeakMap,discovery:/* @__PURE__ */ new Map,sharedDiscovery:/* @__PURE__ */ new Map,projections:/* @__PURE__ */ new WeakMap,projectionSources:/* @__PURE__ */ new WeakMap,completions:/* @__PURE__ */ new WeakMap,indexFacts:/* @__PURE__ */ new WeakMap,providerPolicyOwners:/* @__PURE__ */ new WeakMap,channelAdapters:/* @__PURE__ */ new WeakMap,bundledChannelCatalogs:/* @__PURE__ */ new Map,bundledProviderPolicySurfaces:/* @__PURE__ */ new WeakMap,staticCatalogStates:/* @__PURE__ */ new WeakMap,modelSuppressionResolvers:/* @__PURE__ */ new WeakMap,mcpAuthDeclarations:/* @__PURE__ */ new WeakMap}}function createPluginCache(e={}){return{async[Symbol.asyncDispose](){await retirePluginCache(this)},kind:e.kind??`operation`,roots:/* @__PURE__ */ new Map,rootAliases:/* @__PURE__ */ new Map,sdk:createPluginCacheSdk(),setupModules:/* @__PURE__ */ new Map,instances:/* @__PURE__ */ new Set,metadata:createPluginMetadataCache(),installRecords:/* @__PURE__ */ new Map,persistedInstalledIndex:/* @__PURE__ */ new Map,preparedBundledDiscoveryModes:/* @__PURE__ */ new Map,dependencyStatus:/* @__PURE__ */ new WeakMap,moduleLoaders:/* @__PURE__ */ new Map,sources:/* @__PURE__ */ new Map,sourceAliases:/* @__PURE__ */ new Map,runtimeRecordRoots:/* @__PURE__ */ new WeakMap}}function getProcessPluginCache(){return h.current??=createPluginCache({kind:`process`})}function getScopedPluginCache(){return n()?.cacheScope?.cache}function getPluginCache(){return getScopedPluginCache()??getProcessPluginCache()}function retirePluginCache(e,t,n){let i=getPluginCacheRetainers(e);if(i.retirement)return i.retirement;let o=r();return i.retirement=o.promise,i.controller.abort(),a(i.controller.signal.reason),runOutsideAsyncWorkScope(async()=>{i.references.size&&await i.settled.promise;let r=new p;try{return await r.track(()=>beginPluginCacheRetirement(e,t,n))}finally{await r.drain()}}).then(o.resolve,o.reject),o.promise}function beginPluginCacheRetirement(e,t,n){if(e.retirement)return e.retirement;let i=r();return e.retirement=i.promise,(async()=>{t?.();let r=e.retireRegistryLoads?.(),i=/* @__PURE__ */ new Set([...e.setupModules.values(),...e.instances]);for(let e of i)e.quiesce();let[a]=await Promise.allSettled([r]),o=await Promise.allSettled([...i].map(async e=>({resource:e,result:await e.dispose(void 0,n)}))),s=e.sourceAdmissions;if(s){let e=o.flatMap(e=>e.status===`fulfilled`?e.value.result.errors.flatMap(e=>e instanceof m?[e.settled]:[]):[]);e.length>0?Promise.allSettled(e).then(()=>s.dispose()).catch(e=>process.emitWarning(`Plugin native capture cleanup failed: ${String(e)}`)):await s.dispose()}e.setupModules.clear();for(let t of e.instances)releasePluginCacheInstance(t,e);let c=[...a.status===`rejected`?[a.reason]:[],...o.flatMap(e=>e.status===`rejected`?[e.reason]:[])];if(c.length)throw AggregateError(c,`Plugin cache resources failed to retire`);let l=a.status===`fulfilled`?a.value:void 0,u=[...l?.failures??[]];for(let e of o){if(e.status!==`fulfilled`)continue;let{resource:t,result:n}=e.value;appendPluginInstanceCleanupFailures(u,t.pluginId,n)}return{cleanupCount:l?.cleanupCount??0,failures:u}})().then(i.resolve,i.reject),i.promise}function parsePackageName(e){let t=JSON.parse(e);return typeof t.name==`string`?t.name:null}function readPackageNameSync(e){let t=getPluginCache().sdk.packageNames,n=o.join(o.resolve(e),`package.json`);if(t.has(n))return t.get(n)??null;try{let e=parsePackageName(s.readFileSync(n,`utf-8`));return t.set(n,e),e}catch{return t.set(n,null),null}}function findPackageRootSync(e){for(let t of iterAncestorDirs(e))if(readPackageNameSync(t)===`openclaw`)return t;return null}function*iterAncestorDirs(e){let t=o.resolve(e);for(let e=0;e<12&&(yield t,o.basename(t)!==`node_modules`);e+=1){let e=o.dirname(t);if(e===t)break;t=e}}function candidateDirsFromArgv1(e){let t=getPluginCache().sdk.argvDirectories,n=o.resolve(e),r=t.get(n);if(r)return[...r];let i=n,a=[];try{let e=s.realpathSync(i);e!==i&&a.push(o.dirname(e))}catch{}a.push(o.dirname(i));let c=i.split(o.sep),l=c.lastIndexOf(`.bin`);if(l>0&&c[l-1]===`node_modules`){let e=o.basename(i),t=c.slice(0,l).join(o.sep);a.push(o.join(t,e))}let u=dedupeCandidates(a);return t.set(n,u),[...u]}function preparePackageRootSearch(e,t){let n=buildCandidates(e),r=n.join(`\0`),i=getPluginCache().sdk.packageSearches,a=i.get(r);return{candidates:n,first:a?.all?a.all[0]??null:a?.first,complete(e){return i.set(r,t?{...i.get(r),first:e}:{first:e}),e}}}function resolveOpenClawPackageRootSync(e){let t=preparePackageRootSearch(e,!1);if(t.first!==void 0)return t.first;for(let e of t.candidates){let n=findPackageRootSync(e);if(n)return t.complete(n)}return t.complete(null)}function buildCandidates(e){let t=[];if(e.moduleUrl)try{t.push(o.dirname(c(e.moduleUrl)))}catch{}return e.argv1&&t.push(...candidateDirsFromArgv1(e.argv1)),e.cwd&&t.push(e.cwd),dedupeCandidates(t)}function dedupeCandidates(e){return[...new Set(e.map(e=>o.resolve(e)))]}export{settlesWithin as a,runOutsideAsyncWorkScope as i,p as n,getAsyncWorkSignal as r,resolveOpenClawPackageRootSync as t};