openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
9 lines • 10.5 kB
JavaScript
import{l as resolveGlobalSingleton}from"./string-coerce-BBqv4GXj.mjs";import{n as materializeErrorStack}from"./error-graph-internal-CZk3K2nJ.mjs";import{n as getPluginExecutionFrame,r as PluginInstanceDrainTimeoutError}from"./plugin-instance-invocation-D2U32-yV.mjs";import{t as createDeferredCore}from"./deferred-QsZCoVH-.mjs";import{r as runOutsideAsyncWorkScope,t as AsyncWorkScope}from"./async-work-scope-DYLSvs89.mjs";import"./runtime-process-manifest-B40zGDrA.mjs";import openClawRootFsSync from"node:fs";import path from"node:path";import{fileURLToPath}from"node:url";
//!src/plugins/host-hook-cleanup-result.ts
function appendPluginInstanceCleanupFailures(e,t,n){for(const r of n.errors){if(e.some(e=>e.pluginId===t&&e.error===r))continue;e.push({pluginId:t,hookId:`instance`,error:r})}}
//!src/plugins/plugin-cache-sdk.ts
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}}}
//!src/plugins/plugin-cache.ts
const state=resolveGlobalSingleton(Symbol.for(`openclaw.pluginCache`),()=>({snapshotOwners:/* @__PURE__ */ new WeakMap,retirements:[]}));const cacheRetainers=resolveGlobalSingleton(Symbol.for(`openclaw.pluginCacheRetainers`),()=>/* @__PURE__ */ new WeakMap);const instanceCacheOwners=resolveGlobalSingleton(Symbol.for(`openclaw.pluginInstanceCacheOwners`),()=>/* @__PURE__ */ new WeakMap);function releasePluginCacheInstance(e,t){const n=instanceCacheOwners.get(e);if(t){t.instances.delete(e);n?.delete(t)}else{for(const t of n??[])t.instances.delete(e);n?.clear()}if(n?.size===0)instanceCacheOwners.delete(e)}function getPluginCacheRetainers(e){let t=cacheRetainers.get(e);if(!t){t={references:/* @__PURE__ */ new Set,controller:new AbortController,settled:createDeferredCore()};cacheRetainers.set(e,t)}return t}function getPluginCacheRetirementSignal(e){return getPluginCacheRetainers(e).controller.signal}function createPluginMetadataCache(){return{current:{snapshot:void 0,owner:`operation`,configFingerprint:void 0,agentWorkspaceFingerprint:void 0,envFingerprint:void 0,defaultDiscoveryCompatible:false,compatibleConfigFingerprints:void 0,configIdentities:/* @__PURE__ */ new WeakSet},autoEnable:/* @__PURE__ */ new WeakMap,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 invalidatePluginCacheMetadata(e){e.inspectionNativeEsmPolicy=void 0;e.sourceAdmissions?.invalidate();e.metadata=createPluginMetadataCache();e.sdk.native.parents.clear();for(const t of e.roots.values()){t.files.clear();t.checkedEntries.clear();t.paths.clear();t.directory=void 0;t.artifacts.clear();t.runtimeArtifacts.clear();t.entryBoundaries.clear();t.entryPaths.clear()}e.rootAliases.clear();e.installRecords.clear();e.persistedInstalledIndex.clear();e.preparedBundledDiscoveryModes.clear();e.dependencyStatus=/* @__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 state.current??=createPluginCache({kind:`process`})}function getScopedPluginCache(){return getPluginExecutionFrame()?.cacheScope?.cache}function getScopedPluginCaches(){const e=[];for(let t=getPluginExecutionFrame()?.cacheScope;t;t=t.parent)e.push(t.cache);return e}function getPluginCache(){return getScopedPluginCache()??getProcessPluginCache()}function retirePluginCache(e,t,n){const r=getPluginCacheRetainers(e);if(r.retirement)return r.retirement;const i=createDeferredCore();r.retirement=i.promise;const retire=async()=>{if(r.references.size)await r.settled.promise;const i=new AsyncWorkScope;try{return await i.track(()=>beginPluginCacheRetirement(e,t,n))}finally{await i.drain()}};r.controller.abort();materializeErrorStack(r.controller.signal.reason);runOutsideAsyncWorkScope(retire).then(i.resolve,i.reject);return i.promise}function beginPluginCacheRetirement(e,t,n){if(e.retirement)return e.retirement;const r=createDeferredCore();e.retirement=r.promise;const cleanup=async()=>{t?.();const r=e.retireRegistryLoads?.();const i=/* @__PURE__ */ new Set([...e.setupModules.values(),...e.instances]);for(const e of i)e.quiesce();const[a]=await Promise.allSettled([r]);const o=await Promise.allSettled([...i].map(async e=>({resource:e,result:await e.dispose(void 0,n)})));const s=e.sourceAdmissions;if(s){const e=o.flatMap(e=>e.status===`fulfilled`?e.value.result.errors.flatMap(e=>e instanceof PluginInstanceDrainTimeoutError?[e.settled]:[]):[]);if(e.length>0)Promise.allSettled(e).then(()=>s.dispose()).catch(e=>process.emitWarning(`Plugin native capture cleanup failed: ${String(e)}`));else await s.dispose()}e.setupModules.clear();for(const t of e.instances)releasePluginCacheInstance(t,e);const c=[...a.status===`rejected`?[a.reason]:[],...o.flatMap(e=>e.status===`rejected`?[e.reason]:[])];if(c.length)throw new AggregateError(c,`Plugin cache resources failed to retire`);const l=a.status===`fulfilled`?a.value:void 0;const u=[...l?.failures??[]];for(const e of o){if(e.status!==`fulfilled`)continue;const{resource:t,result:n}=e.value;appendPluginInstanceCleanupFailures(u,t.pluginId,n)}return{cleanupCount:l?.cleanupCount??0,failures:u}};cleanup().then(r.resolve,r.reject);return r.promise}function getPluginCacheRoot(e){const t=getPluginCache();const n=t.roots.get(t.rootAliases.get(e)??e);if(n)return n;const r=path.resolve(e);const i=t.rootAliases.get(r)??r;let a=t.roots.get(i);if(!a){a={rootDir:i,files:/* @__PURE__ */ new Map,checkedEntries:/* @__PURE__ */ new Map,paths:/* @__PURE__ */ new Map,artifacts:/* @__PURE__ */ new Map,runtimeArtifacts:/* @__PURE__ */ new Map,entryBoundaries:/* @__PURE__ */ new Map,entryPaths:/* @__PURE__ */ new Map};t.roots.set(i,a)}return a}function mergeRootFacts(e,t){for(const[n,r]of t)if(!e.has(n))e.set(n,r)}function bindPluginCacheRoot(e,t){const n=getPluginCacheRoot(e);if(n.rootDir===t)return n;const r=getPluginCache();const i=path.resolve(e);const a=path.resolve(t);n.rootDir=a;const o=r.roots.get(a);if(o&&o!==n){mergeRootFacts(n.files,o.files);mergeRootFacts(n.checkedEntries,o.checkedEntries);mergeRootFacts(n.paths,o.paths);mergeRootFacts(n.artifacts,o.artifacts);mergeRootFacts(n.runtimeArtifacts,o.runtimeArtifacts);mergeRootFacts(n.entryBoundaries,o.entryBoundaries);mergeRootFacts(n.entryPaths,o.entryPaths);n.directory??=o.directory;n.publicSurfaceBoundary??=o.publicSurfaceBoundary;Object.assign(o,n)}r.roots.set(a,n);r.rootAliases.set(i,a);return n}
//!src/infra/openclaw-root.ts
function parsePackageName(e){const t=JSON.parse(e);return typeof t.name===`string`?t.name:null}function readPackageNameSync(e){const t=getPluginCache().sdk.packageNames;const n=path.join(path.resolve(e),`package.json`);if(t.has(n))return t.get(n)??null;try{const e=parsePackageName(openClawRootFsSync.readFileSync(n,`utf-8`));t.set(n,e);return e}catch{t.set(n,null);return null}}function findPackageRootSync(e){for(const t of iterAncestorDirs(e))if(readPackageNameSync(t)===`openclaw`)return t;return null}function*iterAncestorDirs(e){let t=path.resolve(e);for(let e=0;e<12;e+=1){yield t;if(path.basename(t)===`node_modules`)break;const e=path.dirname(t);if(e===t)break;t=e}}function candidateDirsFromArgv1(e){const t=getPluginCache().sdk.argvDirectories;const n=path.resolve(e);const r=t.get(n);if(r)return[...r];const i=n;const a=[];try{const e=openClawRootFsSync.realpathSync(i);if(e!==i)a.push(path.dirname(e))}catch{}a.push(path.dirname(i));const o=i.split(path.sep);const s=o.lastIndexOf(`.bin`);if(s>0&&o[s-1]===`node_modules`){const e=path.basename(i);const t=o.slice(0,s).join(path.sep);a.push(path.join(t,e))}const c=dedupeCandidates(a);t.set(n,c);return[...c]}function preparePackageRootSearch(e,t){const n=buildCandidates(e);const r=n.join(`\0`);const i=getPluginCache().sdk.packageSearches;const a=i.get(r);return{candidates:n,first:a?.all?a.all[0]??null:a?.first,complete(e){i.set(r,t?{...i.get(r),first:e}:{first:e});return e}}}function resolveOpenClawPackageRootSync(e){const t=preparePackageRootSearch(e,false);if(t.first!==void 0)return t.first;for(const e of t.candidates){const n=findPackageRootSync(e);if(n)return t.complete(n)}return t.complete(null)}function buildCandidates(e){const t=[];if(e.moduleUrl)try{t.push(path.dirname(fileURLToPath(e.moduleUrl)))}catch{}if(e.argv1)t.push(...candidateDirsFromArgv1(e.argv1));if(e.cwd)t.push(e.cwd);return dedupeCandidates(t)}function dedupeCandidates(e){return[...new Set(e.map(e=>path.resolve(e)))]}export{getPluginCacheRoot as a,getScopedPluginCaches as c,getPluginCacheRetirementSignal as i,invalidatePluginCacheMetadata as l,bindPluginCacheRoot as n,getProcessPluginCache as o,getPluginCache as r,getScopedPluginCache as s,resolveOpenClawPackageRootSync as t};