UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

17 lines • 34.5 kB
import{c as normalizeOptionalLowercaseString,l as normalizeOptionalString,o as normalizeLowercaseStringOrEmpty}from"./string-coerce-CpTFcSwY.mjs";import{c as resolveUserPath}from"./home-dir-DEN5DisQ.mjs";import{a as extractErrorCode}from"./error-coercion-DlKnt6w-.mjs";import{l as isRecord}from"./record-coerce-BTbqdJ3-.mjs";import{y as sortUniqueStrings}from"./string-normalization-D_oBUpO3.mjs";import{a as getPluginCache}from"./plugin-cache-B6QVpzXr.mjs";import{r as isPathInside}from"./path-guards-DGttsOJI.mjs";import"./utils-Dlk0IYAa.mjs";import{n as resolveRealpathOrAbsolute}from"./boundary-path-BeuXNL_4.mjs";import{a as pluginCacheRealpathSync,c as readPluginCacheFile,d as formatPosixMode,f as isPathInside$1,n as parsePluginCacheJson,o as pluginCacheStatSync,r as pluginCacheExistsSync,s as readPluginCacheDirectory,u as refreshPluginCacheStat}from"./plugin-cache-files-BGuripl0.mjs";import{t as PUBLIC_SURFACE_SOURCE_EXTENSIONS}from"./package-entrypoints-QGX6Paeq.mjs";import{r as loadPluginManifest}from"./manifest-D8YdMedM.mjs";import{n as getPackageManifestMetadata,r as resolvePackageExtensionEntries,t as DEFAULT_PLUGIN_ENTRY_CANDIDATES}from"./package-manifest-CMy2j7Hf.mjs";import{c as resolveSourceCheckoutDependencyDiagnostic,i as isPluginInPackageBundledRoots,n as hasUsableBundledPluginTree,s as resolveBundledPluginsDir}from"./bundled-dir-CMJ7m2eP.mjs";import{t as normalizePluginPolicyId}from"./plugin-policy-id-Nz6ZTOOH.mjs";import{c as normalizePluginId}from"./config-state-C1eV6UWf.mjs";import{i as isMissingPathError}from"./errno-DUBt6SQQ.mjs";import{C as resolveIsNixMode}from"./paths-D_FOvGon.mjs";import{n as groupPluginRecords}from"./record-groups-BlmybP6F.mjs";import{n as formatErrorMessageWithCode}from"./errors-D37BJTfI.mjs";import{a as resolveCompatibilityHostVersion}from"./version-DrZ9Nfde.mjs";import{t as decodeMountInfoPath}from"./mountinfo-path-TifqQAkt.mjs";import{n as hashStableJson}from"./installed-plugin-index-hash-BPd0uDLE.mjs";import{i as loadBundleManifest,r as detectBundleManifestFormat}from"./bundle-manifest-CeCINH5W.mjs";import{n as resolvePackagePluginApiRange,r as satisfiesPluginApiRange}from"./package-compat-rJypqhZh.mjs";import{t as shouldRejectHardlinkedPluginFiles}from"./hardlink-policy-S8MtjHnf.mjs";import{n as resolvePackageRuntimeExtensions,r as resolvePackageSetupSource}from"./package-entry-resolution-CtQS-t-Q.mjs";import{n as resolvePluginSourceRoots}from"./roots-0Hx1ReJX.mjs";import{r as normalizePluginDependencySpecs}from"./status-dependencies-core-CiFaEmWP.mjs";import fs from"node:fs";import path from"node:path"; //!src/plugins/candidate-install-owner.ts function createPluginInstallOwnerMetadata(e,t){const n=Symbol.for(e);function read(e){return e[n]}return{record:(e,r,i=false)=>{if(r||i)Object.defineProperty(e,n,{configurable:t,enumerable:true,value:i?{ambiguous:true}:{installOwner:r}});return e},resolve:e=>read(e)?.installOwner,isAmbiguous:e=>read(e)?.ambiguous===true}}const{record:recordPluginCandidateInstallOwner,resolve:resolvePluginCandidateInstallOwner,isAmbiguous:isPluginCandidateInstallOwnerAmbiguous}=createPluginInstallOwnerMetadata(`openclaw.pluginCandidateInstallOwner`,true);function resolveImmutableInstallIdentity(e,t,n){const r=t?n[t]:void 0;if(e!==`global`||r?.source!==`npm`||!r.integrity)return;return JSON.stringify([t,r.installPath??``,r.resolvedSpec??r.spec??``,r.integrity,r.installedAt??``])} //!src/plugins/bundled-load-path-aliases.ts const PACKAGED_BUNDLED_ROOTS=[path.join(`dist`,`extensions`),path.join(`dist-runtime`,`extensions`)];function normalizeBundledLookupPath(e){const t=path.normalize(e);const n=path.parse(t).root;let r=t;while(r.length>n.length&&(r.endsWith(path.sep)||r.endsWith(`/`)))r=r.slice(0,-1);return r}function findBundledRoot(e,t=PACKAGED_BUNDLED_ROOTS){const n=normalizeBundledLookupPath(e);for(const e of t){const t=`${path.sep}${e}`;const r=n.lastIndexOf(t);if(r===-1)continue;const i=r+t.length;if(n.length!==i&&n[i]!==path.sep)continue;return{packageRoot:n.slice(0,r),bundledRoot:n.slice(0,i),bundledLeaf:n.slice(i+path.sep.length)}}return null}function parsePackagedBundledPluginPath(e){const t=findBundledRoot(e);return t?.bundledLeaf?t:null}function buildLegacyBundledPath(e){const t=parsePackagedBundledPluginPath(e);if(!t)return null;return path.join(t.packageRoot,`extensions`,t.bundledLeaf)}function buildLegacyBundledRootPath(e){const t=findBundledRoot(e);return t?path.join(t.packageRoot,`extensions`):null}function parseLegacyBundledPluginPath(e){const t=findBundledRoot(e,[`extensions`]);if(!t?.bundledLeaf)return null;return{packageRoot:t.packageRoot,legacyRoot:t.bundledRoot,bundledLeaf:t.bundledLeaf}}function buildBundledPluginLoadPathAliases(e){const t=buildLegacyBundledPath(e);if(!t)return[];return[{kind:`current`,path:e},{kind:`legacy`,path:t}]} //!src/plugins/bundled-source-overlays.ts function parseLinuxMountInfoMountPoints(e){const t=/* @__PURE__ */ new Set;for(const n of e.split(/\r?\n/u)){const e=n.trim();if(!e)continue;const r=e.split(` `)[4];if(!r)continue;t.add(path.resolve(decodeMountInfoPath(r)))}return t}function readLinuxMountPoints(){const e=getPluginCache().metadata;if(!e.discoveryMountPoints)try{e.discoveryMountPoints=parseLinuxMountInfoMountPoints(fs.readFileSync(`/proc/self/mountinfo`,`utf8`))}catch{e.discoveryMountPoints=/* @__PURE__ */ new Set}return e.discoveryMountPoints}function isFilesystemMountPoint(e){const t=pluginCacheStatSync(e);const n=pluginCacheStatSync(path.dirname(e));return Boolean(t&&n&&(t.dev!==n.dev||t.ino===n.ino))}function sourceOverlaysDisabled(e){const t=normalizeOptionalLowercaseString(e.OPENCLAW_DISABLE_BUNDLED_SOURCE_OVERLAYS);return t===`1`||t===`true`}function isBundledSourceOverlayPath(e){const t=path.resolve(e.sourcePath);return(e.mountPoints??readLinuxMountPoints()).has(t)||isFilesystemMountPoint(t)}function listBundledSourceOverlayDirs(e){if(sourceOverlaysDisabled(e.env??process.env)||!e.bundledRoot)return[];const t=buildLegacyBundledRootPath(e.bundledRoot);if(!t||!pluginCacheExistsSync(t))return[];let n;try{n=readPluginCacheDirectory(t)}catch{return[]}const r=readLinuxMountPoints();const i=isBundledSourceOverlayPath({sourcePath:t,mountPoints:r});const a=[];for(const o of n){if(!o.isDirectory())continue;const n=path.join(t,o.name);const s=path.join(e.bundledRoot,o.name);if(!pluginCacheExistsSync(s))continue;if(!i&&!isBundledSourceOverlayPath({sourcePath:n,mountPoints:r}))continue;a.push(n)}return a.toSorted((e,t)=>e.localeCompare(t))} //!src/plugins/runtime-degraded-state.ts const PLUGIN_AVAILABILITY_POLICY={state:`configured-unavailable`,severity:`warning`,repairCommand:`openclaw doctor --fix`};function describePluginAvailabilityFailure(e,t){return{source:e,severity:PLUGIN_AVAILABILITY_POLICY.severity,message:`Plugin "${e}" is unavailable: ${t} Run \`${PLUGIN_AVAILABILITY_POLICY.repairCommand}\`.`}}let activeDegradedPlugins=[];function buildDegradedPluginsFromVerificationFailures(e){const t=/* @__PURE__ */ new Map;for(const n of e){if(t.has(n.pluginId))continue;t.set(n.pluginId,{pluginId:n.pluginId,state:PLUGIN_AVAILABILITY_POLICY.state,diagnostic:{kind:`plugin-verification`,reason:n.reason,detail:n.detail,...n.installPath?{installPath:n.installPath}:{}}})}return[...t.values()]}function setActiveDegradedPlugins(e){activeDegradedPlugins=[...e]}function listActiveDegradedPlugins(){return activeDegradedPlugins}function findActiveDegradedPlugin(e){return activeDegradedPlugins.find(t=>t.pluginId===e)}function clearActiveDegradedPlugin(e){activeDegradedPlugins=activeDegradedPlugins.filter(t=>t.pluginId!==e)}function pluginInstallPathMatchesRoot(e,t){if(!e)return false;return resolveRealpathOrAbsolute(e)===resolveRealpathOrAbsolute(t)}function degradedPluginMatchesRoot(e,t){return pluginInstallPathMatchesRoot(e.diagnostic.installPath,t)}function toPublicPluginVerificationDiagnostic(e){const t=e.reason===`missing-openclaw-peer-link`?`Plugin declares peerDependency "openclaw", but its host peer link is missing or invalid.`:e.installPath?e.detail.replaceAll(e.installPath,`<plugin-install>`):e.detail;return{kind:e.kind,reason:e.reason,detail:t}}function formatPluginVerificationDiagnostic(e){const t=toPublicPluginVerificationDiagnostic(e);return`configured plugin payload verification failed (${t.reason}): ${t.detail}`} //!src/plugins/discovery-availability.ts const CONFIGURED_PLUGIN_PATH_UNAVAILABLE=`configured-plugin-path-unavailable`;const CONFIGURED_PLUGIN_PATH_INSPECTION_FAILED=`configured-plugin-path-inspection-failed`;function shouldSkipIncompatiblePackagePluginApi(e){if(e.origin===`bundled`)return false;const t=resolvePackagePluginApiRange(e.packageManifest);if(!t.ok){e.diagnostics.push({level:`warn`,configDisposition:`preserve`,source:path.join(e.packageDir,`package.json`),message:`invalid package plugin API metadata: ${t.error}; skipping discovery (check package.json openclaw.compat.pluginApi)`,pluginId:e.pluginId});return true}const n=t.range;if(!n||e.inspectingPreviousArtifact)return false;const r=resolveCompatibilityHostVersion(e.env);if(satisfiesPluginApiRange(r,n))return false;e.diagnostics.push({level:`warn`,configDisposition:`preserve`,source:path.join(e.packageDir,`package.json`),message:`plugin requires plugin API ${n}, but this host is ${r}; skipping discovery (check "openclaw --version", OPENCLAW_COMPATIBILITY_HOST_VERSION, or run "openclaw doctor")`,pluginId:e.pluginId});return true}function isConfiguredPluginPathDiagnosticCode(e){return e===CONFIGURED_PLUGIN_PATH_UNAVAILABLE||e===CONFIGURED_PLUGIN_PATH_INSPECTION_FAILED}function pluginPathFailureDiagnostic(e,t,n){if(t===`config`&&!isMissingPathError(n)){const t=extractErrorCode(n)??`UNKNOWN`;const r=`${t===`EACCES`||t===`EPERM`?`Fix permissions on ${e}`:t===`ELOOP`?`Fix the symbolic link loop at ${e}`:`Resolve the filesystem inspection error on ${e}`}, then run \`${PLUGIN_AVAILABILITY_POLICY.repairCommand}\`.`;return{level:`warn`,code:CONFIGURED_PLUGIN_PATH_INSPECTION_FAILED,configDisposition:`preserve`,errorCode:t,source:e,fixHint:r,message:`Configured plugin load path inspection failed: ${e} (${formatErrorMessageWithCode(n)}). Uninspected plugin configuration is preserved. ${r}`}}return t===`config`?{level:`warn`,code:CONFIGURED_PLUGIN_PATH_UNAVAILABLE,configDisposition:`preserve`,source:e,message:`Configured plugin load path is unavailable: ${e}. Uninspected plugin configuration is preserved. Restore access to the path, then run \`${PLUGIN_AVAILABILITY_POLICY.repairCommand}\`.`}:{level:`error`,source:e,message:`plugin path not found: ${e}`}}function inspectPluginLoadPath(e,t,n){try{const r=pluginCacheStatSync(e,t===`config`);if(!r&&!pluginCacheExistsSync(e))n.push(pluginPathFailureDiagnostic(e,t,void 0));if(t===`config`&&r){if(r.isDirectory())readPluginCacheDirectory(e);else if(!r.isFile())throw Object.assign(/* @__PURE__ */ new Error(`Plugin load path is not a regular file or directory`),{code:`ERR_INVALID_FILE_TYPE`})}return r}catch(r){n.push(pluginPathFailureDiagnostic(e,t,r));return null}}function findUninspectedPluginDiagnostic(e){return e.find(e=>e.configDisposition===`preserve`)}function pluginDiagnosticToConfigWarning(e,t){return{path:t,message:e.message,code:e.code,source:e.source,...e.errorCode?{errorCode:e.errorCode}:{},...e.fixHint?{fixHint:e.fixHint}:{}}}function hasIncompletePluginDiscovery(e){return e.some(e=>e.level===`error`||e.configDisposition===`preserve`)}function createBlockedPluginDiagnosticLookup(e){const t=`blocked plugin candidate:`;const n=/* @__PURE__ */ new Map;const r=[];const normalizeBlockedDiagnosticPath=t=>{const n=t?.trim();if(!n)return``;try{return path.resolve(resolveUserPath(n,e.env??process.env))}catch{return path.resolve(n)}};for(const i of e.diagnostics){if(!i.message.startsWith(t))continue;if(!i.pluginId&&i.source)r.push({message:i.message,source:i.source});if(i.pluginId){const e=normalizePluginId(i.pluginId);for(const t of[i.pluginId,e])if(t&&!n.has(t))n.set(t,{message:i.message,...i.source?{source:i.source}:{}})}}const blockedDiagnosticSourceMatchesPluginId=(t,n)=>{const r=normalizePluginId(n);if(!r)return false;const i=normalizeBlockedDiagnosticPath(t.source);if(!i)return false;if(normalizePluginId(path.basename(i))===r||normalizePluginId(path.basename(path.dirname(i)))===r)return true;for(const t of e.config?.plugins?.load?.paths??[]){const e=normalizeBlockedDiagnosticPath(t);if(e&&normalizePluginId(path.basename(e))===r&&(isPathInside(e,i)||isPathInside(i,e)))return true}return false};return e=>n.get(e)??n.get(normalizePluginId(e))??r.find(t=>blockedDiagnosticSourceMatchesPluginId(t,e))} //!src/plugins/discovery-required-plugins.ts function addMissingRequiredPluginDiagnostics(e,t){const n=new Set(e.candidates.map(e=>normalizePluginPolicyId(e.idHint)));const r=/* @__PURE__ */ new Set;let i;for(const a of e.candidates)for(const o of a.requiredPluginIds??[]){const s=normalizePluginPolicyId(o);if(n.has(s))continue;if(!i){i=/* @__PURE__ */ new Set;for(const n of e.candidates){if(n.origin!==`config`||n.packageDir)continue;const e=shouldRejectHardlinkedPluginFiles({origin:n.origin,rootDir:n.rootDir,env:t.env});const r=loadPluginManifest(n.rootDir,e);if(r.ok)i.add(normalizePluginPolicyId(r.manifest.id))}}if(i.has(s))continue;const c=`${normalizePluginPolicyId(a.idHint)}\0${s}`;if(r.has(c))continue;r.add(c);e.diagnostics.push({level:`warn`,pluginId:a.idHint,source:a.requiredPluginSource??a.source,message:`plugin "${a.idHint}" requires plugin "${o}"; install "${o}" to use it`})}} //!src/plugins/plugin-lifecycle-trace.ts function isPluginLifecycleTraceEnabled(){const e=process.env.OPENCLAW_PLUGIN_LIFECYCLE_TRACE?.trim().toLowerCase();return e===`1`||e===`true`||e===`yes`}function emitPluginLifecycleTrace(e){const t=Number(process.hrtime.bigint()-e.start)/1e6;const n=Object.entries(e.details??{}).filter(e=>e[1]!==void 0).map(([e,t])=>`${e}=${typeof t===`string`?JSON.stringify(t):t}`).join(` `);const r=n?` ${n}`:``;console.error(`[plugins:lifecycle] phase=${JSON.stringify(e.phase)} ms=${t.toFixed(2)} status=${e.status}${r}`)}function tracePluginLifecyclePhase(e,t,n){if(!isPluginLifecycleTraceEnabled())return t();const r=process.hrtime.bigint();let i=`error`;try{const e=t();i=`ok`;return e}finally{emitPluginLifecycleTrace({phase:e,start:r,status:i,details:n})}}async function tracePluginLifecyclePhaseAsync(e,t,n){if(!isPluginLifecycleTraceEnabled())return t();const r=process.hrtime.bigint();let i=`error`;try{const e=await t();i=`ok`;return e}finally{emitPluginLifecycleTrace({phase:e,start:r,status:i,details:n})}} //!src/plugins/discovery.ts const SCANNED_DIRECTORY_IGNORE_NAMES=/* @__PURE__ */ new Set([`.git`,`.hg`,`.svn`,`.turbo`,`.yarn`,`.yarn-cache`,`build`,`coverage`,`dist`,`node_modules`]);function currentUid(){if(process.platform===`win32`||typeof process.getuid!==`function`)return null;return process.getuid()}function checkSourceEscapesRoot(e){const t=pluginCacheRealpathSync(e.source);const n=pluginCacheRealpathSync(e.rootDir);if(!t||!n)return null;if(isPathInside$1(n,t))return null;return{source:e.source,message:`blocked plugin candidate: source escapes plugin root (${e.source} -> ${t}; root=${n})`}}function checkPathStatAndPermissions(e){if(process.platform===`win32`)return null;const t=[e.rootDir,e.source];const n=/* @__PURE__ */ new Set;for(const r of t){const t=path.resolve(r);if(n.has(t))continue;n.add(t);let i=pluginCacheStatSync(r);if(!i)return{source:r,message:`blocked plugin candidate: cannot stat path (${r})`};let a=i.mode&511;if((a&2)!==0&&e.origin===`bundled`)try{fs.chmodSync(r,a&-19);const e=refreshPluginCacheStat(r);if(!e)return{source:r,message:`blocked plugin candidate: cannot stat path (${r})`};i=e;a=e.mode&511}catch{}if((a&2)!==0)return{source:r,message:`blocked plugin candidate: world-writable path (${r}, mode=${formatPosixMode(a)})`};if(e.origin!==`bundled`&&e.uid!==null&&typeof i.uid===`number`&&i.uid!==e.uid&&i.uid!==0)return{source:r,message:`blocked plugin candidate: suspicious ownership (${r}, uid=${i.uid}, expected uid=${e.uid} or root)`}}return null}function isExtensionFile(e){const t=path.extname(e);if(!PUBLIC_SURFACE_SOURCE_EXTENSIONS.some(e=>e===t))return false;if(/\.d\.[cm]?ts$/.test(e))return false;return!normalizeLowercaseStringOrEmpty(path.basename(e)).includes(`.test.`)}function shouldIgnoreScannedDirectory(e){const t=normalizeLowercaseStringOrEmpty(e);return!t||SCANNED_DIRECTORY_IGNORE_NAMES.has(t)||t.endsWith(`.bak`)||t.includes(`.backup-`)||t.includes(`.disabled`)}function resolvesToSameDirectory(e,t){if(!e||!t)return false;const n=pluginCacheRealpathSync(e);const r=pluginCacheRealpathSync(t);if(n&&r)return n===r;return path.resolve(e)===path.resolve(t)}function mergeCandidateInstallOwner(e,t,n){const r=resolvePluginCandidateInstallOwner(e);const i=r&&t&&r!==t;if(isPluginCandidateInstallOwnerAmbiguous(e)||n||i)recordPluginCandidateInstallOwner(e,void 0,true);else if(t)recordPluginCandidateInstallOwner(e,t)}function prepareInstalledPluginPaths(e,t,n){const r=/* @__PURE__ */ new Map;const i=/* @__PURE__ */ new Set;const a=/* @__PURE__ */ new Set;const resolveRecordPath=e=>typeof e===`string`&&e.trim()?resolveUserPath(e,t):void 0;for(const[t,o]of Object.entries(e??{})){const e=resolveRecordPath(o.installPath);const s=resolveRecordPath(o.sourcePath);for(const t of[e,s])if(t&&pluginCacheExistsSync(t)){const e=resolveManagedPluginDirKey(t);if(e)a.add(e)}const c=e??s;if(!c||!pluginCacheExistsSync(c))continue;const l=pluginCacheRealpathSync(c)??path.resolve(c);const u=!(o.source===`path`&&e&&s&&resolvesToSameDirectory(e,s));const d=r.get(l);if(d){d.requireBuiltRuntimeEntry||=u;if(d.installOwner!==t){delete d.installOwner;d.installOwnerAmbiguous=true;n.push({level:`error`,source:c,message:`multiple plugin install records claim the same package path; refresh or reinstall the package before using managed lifecycle actions`})}}else{r.set(l,{path:c,requireBuiltRuntimeEntry:u,installOwner:t});const e=resolveManagedPluginDirKey(c);if(e)i.add(e)}}return{installedPaths:[...r.values()],installedPluginDirKeys:i,managedPluginDirs:a}}function resolveManagedPluginDirKey(e){const t=pluginCacheStatSync(e);if(!t)return null;const n=t.isFile()?path.dirname(e):e;return pluginCacheRealpathSync(n)??path.resolve(n)}function isManagedPluginDir(e){if(!e.managedPluginDirs||e.managedPluginDirs.size===0)return false;const t=e.realpath??pluginCacheRealpathSync(e.dir)??path.resolve(e.dir);return e.managedPluginDirs.has(t)}function readPackageManifest(e,t=true,n){const r=readPluginCacheFile({rootDir:e,...n!==void 0?{rootRealPath:n}:{},relativePath:`package.json`,rejectHardlinks:t});if(!r.ok)return null;const i=parsePluginCacheJson(r);return i.ok&&isRecord(i.value)?i.value:null}function derivePackagePluginIdHint(e){const t=normalizeOptionalString(e);if(!t)return;const n=t.slice(t.lastIndexOf(`/`)+1);for(const e of[`-provider`,`-plugin`])if(n.endsWith(e)&&n.length>e.length)return n.slice(0,-e.length);return normalizeOptionalString(n)}function resolvePluginPackageEntries(e){const t=groupPluginRecords(resolvePackageRuntimeExtensions(e),t=>{const n=t.source;const r=e.manifestId;const i=e.manifest?.name;const a=path.basename(e.packageDir);const o=e.extensions.length>1;const s=path.basename(n,path.extname(n));const c=normalizeOptionalString(r)??derivePackagePluginIdHint(i)??a;return o?`${c}/${s}`:c});const n=[];for(const[r,i]of t){if(e.extensions.length>1&&i.length>1){e.diagnostics.push({level:`error`,pluginId:r,source:e.sourceLabel,message:`plugin package entries collide on derived id "${r}" (${i.map(t=>path.relative(e.packageDir,t.source)).join(`, `)}); rename the entry files to unique basenames`});continue}for(const e of i)n.push({...e,idHint:r})}return n}function isSourceCheckoutExtensionsDir(e){const t=path.dirname(e);return pluginCacheExistsSync(path.join(t,`.git`))&&pluginCacheExistsSync(path.join(t,`pnpm-workspace.yaml`))&&pluginCacheExistsSync(path.join(t,`src`))&&hasUsableBundledPluginTree(e)}function resolveBundledSourceCheckoutExtensionsDir(e){if(!e)return;const t=buildLegacyBundledRootPath(e);if(!t||!isPluginInPackageBundledRoots({rootDir:t,packageRoot:path.dirname(t)})||!isSourceCheckoutExtensionsDir(t))return;return t}function isHostBundledPluginRoot(e,t){const n=resolveBundledPluginsDir(t);const r=pluginCacheRealpathSync(e)??path.resolve(e);return[n,resolveBundledSourceCheckoutExtensionsDir(n)].some(e=>e&&isPathInside$1(pluginCacheRealpathSync(e)??path.resolve(e),r))}function readChildDirectoryNames(e){if(!e||!pluginCacheExistsSync(e))return/* @__PURE__ */ new Set;try{return new Set(sortUniqueStrings(readPluginCacheDirectory(e).filter(e=>e.isDirectory()).map(e=>e.name)))}catch{return/* @__PURE__ */ new Set}}function readBundledDistOptOutDirectoryNames(e){const t=/* @__PURE__ */ new Set;if(!e)return t;for(const n of readChildDirectoryNames(e))if(getPackageManifestMetadata(readPackageManifest(path.join(e,n),false)??void 0)?.build?.bundledDist===false)t.add(n);return t}function createPluginScanner(e,t=false){const n={candidates:[],diagnostics:[]};const{candidates:r,diagnostics:i}=n;const a=/* @__PURE__ */ new Map;function addCandidate(e){const t=path.resolve(e.source);if(a.has(t)){const n=a.get(t);if(n)mergeCandidateInstallOwner(n,e.installOwner,e.installOwnerAmbiguous===true);return}const n=pluginCacheRealpathSync(e.rootDir)??path.resolve(e.rootDir);const o=checkSourceEscapesRoot({source:t,rootDir:n})??checkPathStatAndPermissions({source:t,rootDir:n,origin:e.origin,uid:currentUid()});if(o){i.push({level:`warn`,...e.idHint?{pluginId:e.idHint}:{},...o});a.set(t,void 0);return}const s=e.manifest??null;const c=getPackageManifestMetadata(s??void 0);const l=normalizePluginDependencySpecs({dependencies:s?.dependencies,optionalDependencies:s?.optionalDependencies});const u={idHint:e.idHint,...e.effectivePluginId?{effectivePluginId:e.effectivePluginId}:{},...e.diagnosticIdHint&&e.diagnosticIdHint!==e.idHint?{diagnosticIdHint:e.diagnosticIdHint}:{},source:t,setupSource:e.setupSource,rootDir:n,origin:e.origin,format:e.format??`openclaw`,bundleFormat:e.bundleFormat,workspaceDir:e.workspaceDir,packageName:normalizeOptionalString(s?.name),packageVersion:normalizeOptionalString(s?.version),packageDescription:normalizeOptionalString(s?.description),packageDir:e.packageDir,packageManifest:c,packageDependencies:l.dependencies,packageOptionalDependencies:l.optionalDependencies,rawPackageManifest:s??void 0,bundledManifestId:e.bundledManifestId,bundledManifestPath:e.bundledManifestPath,...e.requiredPluginIds&&e.requiredPluginIds.length>0?{requiredPluginIds:e.requiredPluginIds}:{},...e.requiredPluginSource?{requiredPluginSource:e.requiredPluginSource}:{}};recordPluginCandidateInstallOwner(u,e.installOwner,e.installOwnerAmbiguous===true);r.push(u);a.set(t,u)}function discoverPluginDirectory(n){const{dir:r,rootRealPath:a}=n;const o=n.requireBuiltRuntimeEntry??isManagedPluginDir({dir:r,realpath:a,managedPluginDirs:n.managedPluginDirs});const s=shouldRejectHardlinkedPluginFiles({origin:n.origin,rootDir:r,env:e});const c=readPackageManifest(r,s,a);const l=getPackageManifestMetadata(c??void 0);const u=loadPluginManifest(r,s,a);const d=u.ok?u:void 0;const f=d?.manifest.id;const p=normalizeOptionalString(f)??normalizeOptionalString(l?.plugin?.id)??normalizeOptionalString(l?.channel?.id)??derivePackagePluginIdHint(c?.name)??path.basename(r);if(shouldSkipIncompatiblePackagePluginApi({inspectingPreviousArtifact:t,origin:n.origin,packageManifest:l,pluginId:p,packageDir:r,env:e,diagnostics:i}))return true;const m=resolvePackageExtensionEntries(c??void 0);if(m.status===`invalid`||m.status===`empty`){i.push({level:`error`,source:r,message:m.status===`invalid`?m.error:`package.json openclaw.extensions is empty`,...p?{pluginId:p}:{}});return true}const h=m.status===`ok`?m.entries:[];const g={packageDir:r,...a!==void 0?{packageRootRealPath:a}:{},manifest:c,pluginIdHint:p,origin:n.origin,requireBuiltRuntimeEntry:o,sourceLabel:r,diagnostics:i,rejectHardlinks:s};const _=resolvePackageSetupSource(g);const addPackageCandidate=(e,t,i)=>{addCandidate({idHint:t,...i?{effectivePluginId:i}:{},diagnosticIdHint:p,source:e,..._?{setupSource:_}:{},rootDir:r,origin:n.origin,workspaceDir:n.workspaceDir,...n.installOwner?{installOwner:n.installOwner}:{},...n.installOwnerAmbiguous?{installOwnerAmbiguous:true}:{},manifest:c,packageDir:r,requiredPluginIds:d?.manifest.requiresPlugins,requiredPluginSource:d?.manifestPath})};if(h.length>0){const e=resolvePluginPackageEntries({...g,extensions:h,manifestId:f??normalizeOptionalString(l?.plugin?.id)});for(const t of e)addPackageCandidate(t.source,t.idHint,h.length>1?t.idHint:void 0);return true}const v=detectBundleManifestFormat(r);if(v){const e=loadBundleManifest({rootDir:r,...a!==void 0?{rootRealPath:a}:{},bundleFormat:v,rejectHardlinks:s});if(!e.ok)i.push({level:`error`,message:e.error,source:e.manifestPath});else{addCandidate({idHint:e.manifest.id,source:r,rootDir:r,origin:n.origin,format:`bundle`,bundleFormat:v,workspaceDir:n.workspaceDir,...n.installOwner?{installOwner:n.installOwner}:{},...n.installOwnerAmbiguous?{installOwnerAmbiguous:true}:{},manifest:c,packageDir:r,bundledManifestId:e.manifest.id,bundledManifestPath:e.manifestPath});return true}}const y=[...DEFAULT_PLUGIN_ENTRY_CANDIDATES].map(e=>path.join(r,e)).find(e=>pluginCacheExistsSync(e));if(y&&isExtensionFile(y)){addPackageCandidate(y,f??path.basename(r));return true}return false}function discoverInDirectory(e){if(!pluginCacheExistsSync(e.dir))return;let t;try{t=readPluginCacheDirectory(e.dir).toSorted((e,t)=>e.name<t.name?-1:e.name>t.name?1:0)}catch(t){i.push(e.origin===`config`?pluginPathFailureDiagnostic(e.dir,e.origin,t):{level:`warn`,message:`failed to read extensions dir: ${e.dir} (${String(t)})`,source:e.dir});return}for(const n of t){const t=path.join(e.dir,n.name);const r=n.isSymbolicLink()?pluginCacheStatSync(t):n;const a=r?.isFile()?`file`:r?.isDirectory()?`directory`:null;if(a===`file`){if(!(e.scanFiles??e.origin===`bundled`)||!isExtensionFile(t))continue;addCandidate({idHint:path.basename(n.name,path.extname(n.name)),source:t,rootDir:path.dirname(t),origin:e.origin,workspaceDir:e.workspaceDir,...e.installOwner?{installOwner:e.installOwner}:{},...e.installOwnerAmbiguous?{installOwnerAmbiguous:true}:{}});continue}if(a!==`directory`)continue;if(e.skipDirectories?.has(n.name))continue;if(shouldIgnoreScannedDirectory(n.name))continue;const o=pluginCacheRealpathSync(t)??void 0;const s=o??path.resolve(t);if(e.origin===`bundled`&&!isPathInside$1(pluginCacheRealpathSync(e.dir)??path.resolve(e.dir),s)){i.push({level:`error`,source:t,message:`blocked plugin candidate: package directory escapes bundled root (${t})`});continue}if(e.skipRootDirKeys?.has(s))continue;discoverPluginDirectory({...e,dir:t,rootRealPath:o})}}function discoverFromPath(t){const n=resolveUserPath(t.rawPath,e);const r=inspectPluginLoadPath(n,t.origin,i);if(!r)return;const a=(t.origin===`config`||t.origin===`global`)&&isHostBundledPluginRoot(r.isFile()?path.dirname(n):n,e)?`bundled`:t.origin;if(r.isFile()){if(!isExtensionFile(n)){i.push({level:`error`,message:`plugin path is not a supported file: ${n}`,source:n});return}addCandidate({idHint:path.basename(n,path.extname(n)),source:n,rootDir:path.dirname(n),origin:a,workspaceDir:t.workspaceDir,...t.installOwner?{installOwner:t.installOwner}:{},...t.installOwnerAmbiguous?{installOwnerAmbiguous:true}:{}});return}if(r.isDirectory()){if(discoverPluginDirectory({...t,origin:a,dir:n,rootRealPath:pluginCacheRealpathSync(n)??void 0}))return;discoverInDirectory({dir:n,origin:a,workspaceDir:t.workspaceDir,...t.scanFiles!==void 0||t.origin===`config`?{scanFiles:t.scanFiles??true}:{},...t.requireBuiltRuntimeEntry!==void 0?{requireBuiltRuntimeEntry:t.requireBuiltRuntimeEntry}:{},...t.managedPluginDirs?{managedPluginDirs:t.managedPluginDirs}:{},...t.skipRootDirKeys?{skipRootDirKeys:t.skipRootDirKeys}:{}})}}function discoverConfiguredPaths(e,t){const n=r.length;for(const n of e)if(typeof n===`string`&&n.trim())discoverFromPath({rawPath:n.trim(),origin:`config`,workspaceDir:t});for(const e of r.slice(n))e.configSelected=true}function finish(){const e=/* @__PURE__ */ new Map;const t=/* @__PURE__ */ new Set;const a=[];for(const t of r){const n=pluginCacheRealpathSync(t.source)??path.resolve(t.source);const r=e.get(n);if(r){const i=t.origin===`bundled`?t:r;const a=i===t?r:t;if(a.origin===`config`||a.configSelected)i.configSelected=true;if(a.sourcePreferred)i.sourcePreferred=true;mergeCandidateInstallOwner(i,resolvePluginCandidateInstallOwner(a),isPluginCandidateInstallOwnerAmbiguous(a));e.set(n,i);continue}e.set(n,t)}for(const e of i){const n=[e.level,e.pluginId??``,e.source??``,e.message].join(`\0`);if(t.has(n))continue;t.add(n);a.push(e)}n.candidates=[...e.values()];n.diagnostics=a;return n}return{result:n,discoverConfiguredPaths,discoverFromPath,discoverInDirectory,finish}}function discoveryPolicy(e,t){return{ownershipUid:currentUid(),compatibilityHostVersion:resolveCompatibilityHostVersion(e),bundledRoot:t??resolveBundledPluginsDir(e)??``,nix:resolveIsNixMode(e),sourceOverlaysDisabled:e.OPENCLAW_DISABLE_BUNDLED_SOURCE_OVERLAYS??``,home:e.OPENCLAW_HOME??``,userHome:e.HOME??``,userProfile:e.USERPROFILE??``,cwd:process.cwd()}}function discoverConfiguredPluginLoadPaths(e){const t=e.env??process.env;const n=getPluginCache().metadata.discovery;const r=hashStableJson({phase:e.deduplicate?`configured-published`:`configured-raw`,inspectingPreviousArtifact:e.inspectingPreviousArtifact===true,loadPaths:e.loadPaths,workspaceDir:e.workspaceDir,policy:discoveryPolicy(t)});const i=n.get(r);if(i)return i;const a=createPluginScanner(t,e.inspectingPreviousArtifact);a.discoverConfiguredPaths(e.loadPaths,normalizeOptionalString(e.workspaceDir));const o=e.deduplicate?a.finish():a.result;n.set(r,o);return o}function discoverSharedPluginRoots(e){const{roots:t,env:n}=e;const r=getPluginCache().metadata.sharedDiscovery;const i=hashStableJson({roots:t,installRecords:Object.entries(e.installRecords??{}),rootScope:e.rootScope??`all`,policy:discoveryPolicy(n,t.stock)});const a=r.get(i);if(a)return a;const o=createPluginScanner(n);const{result:s,discoverInDirectory:c}=o;const l=/* @__PURE__ */ new Set;const discoverWorkspacePath=e=>{const t=s.candidates.length;o.discoverFromPath(e);for(const e of s.candidates.slice(t))l.add(e)};tracePluginLifecyclePhase(`discovery scan`,()=>{for(const e of listBundledSourceOverlayDirs({bundledRoot:t.stock,env:n})){const t=s.candidates.length;discoverWorkspacePath({rawPath:e,origin:`bundled`});for(const e of s.candidates.slice(t))e.sourcePreferred=true;s.diagnostics.push({level:`warn`,source:e,message:`using bind-mounted bundled plugin source overlay; this source overrides the packaged dist bundle for the same plugin id`})}const r=resolveSourceCheckoutDependencyDiagnostic(n);if(r)s.diagnostics.push({level:`warn`,source:r.source,message:r.message});const i=resolveBundledSourceCheckoutExtensionsDir(t.stock);const a=readBundledDistOptOutDirectoryNames(i);if(i)for(const e of a)discoverWorkspacePath({rawPath:path.join(i,e),origin:`bundled`});if(t.stock)c({dir:t.stock,origin:`bundled`,skipDirectories:a});const o=resolvesToSameDirectory(i,t.stock);if(i&&!o)c({dir:i,origin:`bundled`,skipDirectories:readChildDirectoryNames(t.stock)});if(e.rootScope!==`bundled`){const{installedPaths:r,installedPluginDirKeys:i,managedPluginDirs:a}=prepareInstalledPluginPaths(e.installRecords,n,s.diagnostics);for(const e of r)discoverWorkspacePath({rawPath:e.path,origin:`global`,...e.installOwner?{installOwner:e.installOwner}:{},...e.installOwnerAmbiguous?{installOwnerAmbiguous:true}:{},requireBuiltRuntimeEntry:e.requireBuiltRuntimeEntry,managedPluginDirs:a,scanFiles:true});c({dir:t.global,origin:`global`,managedPluginDirs:a,skipRootDirKeys:i})}},{scope:`shared`});const u={candidates:s.candidates.map(e=>({candidate:e,usesWorkspace:l.has(e)})),diagnostics:s.diagnostics};r.set(i,u);return u}function discoverOpenClawPlugins(e){const t=e.env??process.env;const n=normalizeOptionalString(e.workspaceDir);const r=n?resolveUserPath(n,t):void 0;const i=resolvePluginSourceRoots({workspaceDir:r,env:t});const a=e.bundledRoot?{...i,stock:path.resolve(e.bundledRoot)}:i;const o=getPluginCache().metadata.discovery;const s=hashStableJson({phase:`all`,roots:a,workspaceDir:n,loadPaths:e.extraPaths??[],installRecords:Object.entries(e.installRecords??{}),rootScope:e.rootScope??`all`,policy:discoveryPolicy(t,a.stock)});const c=o.get(s);if(c)return c;const l=createPluginScanner(t);const{result:u,discoverInDirectory:d}=l;if(e.rootScope!==`bundled`)tracePluginLifecyclePhase(`discovery scan`,()=>{l.discoverConfiguredPaths(e.extraPaths??[],n);const t=resolvesToSameDirectory(r,a.stock)||resolvesToSameDirectory(a.workspace,a.global);if(a.workspace&&r&&!t)d({dir:a.workspace,origin:`workspace`,workspaceDir:r})},{scope:`scoped`,extraPathCount:e.extraPaths?.length??0});const f=discoverSharedPluginRoots({roots:{stock:a.stock,global:a.global},installRecords:e.installRecords,env:t,rootScope:e.rootScope});for(const{candidate:e,usesWorkspace:t}of f.candidates)u.candidates.push({...e,...t?{workspaceDir:n}:{}});u.diagnostics.push(...f.diagnostics);l.finish();addMissingRequiredPluginDiagnostics(u,{env:t});o.set(s,u);return u}export{parsePackagedBundledPluginPath as A,toPublicPluginVerificationDiagnostic as C,buildLegacyBundledRootPath as D,buildBundledPluginLoadPathAliases as E,resolvePluginCandidateInstallOwner as F,isPluginCandidateInstallOwnerAmbiguous as M,recordPluginCandidateInstallOwner as N,normalizeBundledLookupPath as O,resolveImmutableInstallIdentity as P,setActiveDegradedPlugins as S,listBundledSourceOverlayDirs as T,describePluginAvailabilityFailure as _,isPluginLifecycleTraceEnabled as a,listActiveDegradedPlugins as b,createBlockedPluginDiagnosticLookup as c,isConfiguredPluginPathDiagnosticCode as d,pluginDiagnosticToConfigWarning as f,degradedPluginMatchesRoot as g,clearActiveDegradedPlugin as h,resolvePluginPackageEntries as i,createPluginInstallOwnerMetadata as j,parseLegacyBundledPluginPath as k,findUninspectedPluginDiagnostic as l,buildDegradedPluginsFromVerificationFailures as m,discoverOpenClawPlugins as n,tracePluginLifecyclePhase as o,PLUGIN_AVAILABILITY_POLICY as p,resolveBundledSourceCheckoutExtensionsDir as r,tracePluginLifecyclePhaseAsync as s,discoverConfiguredPluginLoadPaths as t,hasIncompletePluginDiscovery as u,findActiveDegradedPlugin as v,isBundledSourceOverlayPath as w,pluginInstallPathMatchesRoot as x,formatPluginVerificationDiagnostic as y};