openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
35 lines • 36.7 kB
JavaScript
import{a as isRecord}from"./record-coerce-DwDZngEy.mjs";import{a as normalizeOptionalString,i as normalizeOptionalLowercaseString}from"./string-coerce-BBqv4GXj.mjs";import{l as asSafeIntegerInRange}from"./number-coercion-DIhBGkET.mjs";import{P as parseJsonWithJson5Fallback}from"./redact-LQdRaLFO.mjs";import{n as filterStringEntries,p as uniqueStrings,r as normalizeArrayBackedTrimmedStringList}from"./string-normalization-mfgVoo8i.mjs";import{a as readFileDescriptorBoundedSync$1,r as openRootFileSync}from"./boundary-file-read-LFsZ_JrU.mjs";import{c as isPathInside$2,u as normalizeWindowsPathPreservingCase}from"./state-dir-C22DK7p0.mjs";import{a as resolveUserPath,o as tryProcessCwd}from"./home-dir-C2A7IM0a.mjs";import{r as FsSafeError}from"./utils-CfSlIBx_.mjs";import{n as materializeErrorStack}from"./error-graph-internal-CZk3K2nJ.mjs";import{a as getPluginCacheRoot,n as bindPluginCacheRoot,r as getPluginCache,t as resolveOpenClawPackageRootSync}from"./openclaw-root-BKCLHFAM.mjs";import{n as isTruthyEnvValue}from"./env-BVwgaeaj.mjs";import{n as isDeeplyFrozenPlainData,r as runtimeConfigPublication,t as freezeJsonSnapshot}from"./immutable-data-CTpsHTyy.mjs";import{n as resolveRootPathSync}from"./boundary-path-BX4AG0xQ.mjs";import{t as cloneConfigWithResolutionFacts}from"./resolution-facts-BKHp-Zw8.mjs";import{t as MANIFEST_KEY}from"./legacy-names-DkIbrLEh.mjs";import{t as BUNDLED_OFFICIAL_EXTERNAL_PLUGIN_CATALOG_ENTRIES}from"./official-external-plugin-bundled-catalogs-8wb6D0XI.mjs";import fsSync from"node:fs";import{isPathInside,safeRealpathSync as safeRealpathSync$1}from"@openclaw/fs-safe/path";import path from"node:path";import{fileURLToPath}from"node:url";import crypto from"node:crypto";import{formatPosixMode,readRegularFileSync}from"@openclaw/fs-safe/advanced";import os from"node:os";
//!src/infra/test-runtime-env.ts
function isVitestRuntimeEnv(e=process.env){const t=e.VITEST;return t===`true`||t===`1`||e.VITEST_POOL_ID!==void 0||e.VITEST_WORKER_ID!==void 0||e.NODE_ENV===`test`}
//!src/plugins/path-safety.ts
function canProbeWindowsPhysicalAlias(e,t){const n=/^(?:[\\/]{2}[?.][\\/])?[A-Za-z]:[\\/]/.exec(t)?.[0];if(n)return isPathInside(n,t);const r=normalizeWindowsPathPreservingCase(e);const i=isPathInside(e,r)&&isPathInside(r,e)?path.win32.parse(r).root||r:e;return isPathInside(i,t)}function resolvePhysicalPathInsideRootSync(e,t){if(process.platform!==`win32`)return;try{if(!canProbeWindowsPhysicalAlias(e,t)&&!canProbeWindowsPhysicalAlias(fsSync.realpathSync(e),t))return;const n=fsSync.statSync(e,{bigint:true});if(!n.isDirectory()||n.ino===0n)return;let r=path.resolve(t);while(true){const e=fsSync.statSync(r,{bigint:true});if(e.dev===n.dev&&e.ino===n.ino){const e=fsSync.realpathSync(r);return{rootPath:e,targetPath:path.resolve(e,path.relative(r,t)),rootIdentity:Object.freeze({dev:n.dev,ino:n.ino})}}const i=path.dirname(r);if(i===r)return;r=i}}catch{return}}function isPathInside$1(e,t){return isPathInside(e,t)||resolvePhysicalPathInsideRootSync(e,t)!==void 0}function createIdentityBoundRootFileFs(e,t){const lstatSync=((...n)=>{const r=Reflect.apply(fsSync.lstatSync,fsSync,n);if(n[0]===e){const n=typeof r.ino===`bigint`?r:fsSync.lstatSync(e,{bigint:true});if(!r.isDirectory()||n.dev!==t.dev||n.ino!==t.ino)throw new FsSafeError(`path-mismatch`,`plugin root identity changed during alias reconciliation`)}return r});return{closeSync:fsSync.closeSync,constants:fsSync.constants,fstatSync:fsSync.fstatSync,lstatSync,openSync:fsSync.openSync,readFileSync:fsSync.readFileSync,realpathSync:fsSync.realpathSync}}function openPluginRootFileSync(e){const t=e.rootRealPath??e.rootPath;const n=isPathInside(t,e.filePath)?void 0:resolvePhysicalPathInsideRootSync(t,e.filePath);return openRootFileSync({absolutePath:n?.targetPath??e.filePath,rootPath:n?.rootPath??e.rootPath,rootRealPath:n?.rootPath??e.rootRealPath,boundaryLabel:e.boundaryLabel??`plugin root`,rejectHardlinks:e.rejectHardlinks,maxBytes:e.maxBytes,skipLexicalRootCheck:n?true:void 0,ioFs:n?createIdentityBoundRootFileFs(n.rootPath,n.rootIdentity):void 0})}
//!src/plugins/plugin-cache-files.ts
const DEFAULT_PLUGIN_METADATA_MAX_BYTES=16777216;var CachedFileType=class{constructor(e){this.mode=e}isFile(){return(this.mode&fsSync.constants.S_IFMT)===fsSync.constants.S_IFREG}isDirectory(){return(this.mode&fsSync.constants.S_IFMT)===fsSync.constants.S_IFDIR}isSymbolicLink(){return(this.mode&fsSync.constants.S_IFMT)===fsSync.constants.S_IFLNK}};var CachedStat=class extends CachedFileType{constructor(e){super(e.mode);this.uid=e.uid;this.nlink=e.nlink;this.dev=e.dev;this.ino=e.ino;this.size=e.size;this.mtimeMs=e.mtimeMs}};var CachedDirectoryEntry=class extends CachedFileType{constructor(e){super(e.isFile()?fsSync.constants.S_IFREG:e.isDirectory()?fsSync.constants.S_IFDIR:e.isSymbolicLink()?fsSync.constants.S_IFLNK:0);this.name=e.name}};function capturedPluginFile(e,t,n,r){return{ok:true,path:e,rootRealPath:t,contents:n,hash:crypto.createHash(`sha256`).update(n).digest(`hex`),signature:{size:r.size,mtimeMs:r.mtimeMs,ctimeMs:r.ctimeMs}}}function entryKey(e,t){return JSON.stringify([path.normalize(e),t])}function enforceFileSize(e,t,n=`validation`,r){if(e.ok&&t!==void 0&&Math.max(e.signature.size,e.contents.length)>t)return{ok:false,failure:{ok:false,reason:n,error:new FsSafeError(`too-large`,`File exceeds ${t} bytes: ${r??e.path}`)}};return e}function pathFacts(e){const t=path.resolve(e);const n=getPluginCacheRoot(path.dirname(t));const r=path.basename(t);let i=n.paths.get(r);if(!i){i={};n.paths.set(r,i)}return i}function pluginCacheExistsSync(e){const t=pathFacts(e);return t.exists??=fsSync.existsSync(e)}function resolveRealpath(e){if(path.resolve(e)===e){if(pathFacts(e).nativeRealpath===e)return e;if(process.platform!==`win32`){const t=path.dirname(e);const n=pluginCacheLstatSync(e);if(t!==e&&n&&!n.isSymbolicLink()){const n=pluginCacheRealpathSync(t);if(n)return path.join(n,path.basename(e))}}else if(pluginCacheRealpathSync(e,true)===e)return e}return fsSync.realpathSync(e)}function pluginCacheRealpathSync(e,t=false){const n=pathFacts(e);const r=t?`nativeRealpath`:`realpath`;if(n[r]===void 0)try{n[r]=t?fsSync.realpathSync.native(e):resolveRealpath(e);pathFacts(n[r])[r]=n[r]}catch{n[r]=null}return n[r]}function refreshPluginCacheStat(e){pathFacts(e).stat=void 0;return pluginCacheStatSync(e)}function pluginCacheStatSync(e,t=false){const n=pathFacts(e);if(n.stat===void 0){n.statError=void 0;try{n.stat=new CachedStat(fsSync.statSync(e));n.exists=true}catch(e){materializeErrorStack(e);n.statError=e;n.stat=null}}if(n.stat===null&&t)throw n.statError;return n.stat}function pluginCacheLstatSync(e){const t=pathFacts(e);if(t.lstat===void 0)try{t.lstat=new CachedStat(fsSync.lstatSync(e))}catch{t.lstat=null}return t.lstat}function readPluginCacheDirectory(e){const t=getPluginCacheRoot(e);if(!t.directory)try{t.directory={ok:true,entries:fsSync.readdirSync(e,{withFileTypes:true}).map(e=>new CachedDirectoryEntry(e))}}catch(e){materializeErrorStack(e);t.directory={ok:false,error:e}}if(!t.directory.ok)throw t.directory.error;return t.directory.entries}function checkPluginCacheEntry(e){let t=getPluginCacheRoot(e.rootDir);const n=entryKey(e.relativePath,e.rejectHardlinks);const r=t.checkedEntries.get(n);if(r)return r;const i=path.resolve(e.rootDir,e.relativePath);let a;if(!pluginCacheExistsSync(i))try{const n=resolveRootPathSync({absolutePath:i,rootPath:e.rootDir,rootCanonicalPath:e.rootRealPath,boundaryLabel:`plugin package directory`});t=bindPluginCacheRoot(e.rootDir,n.rootCanonicalPath);a={ok:true,path:n.canonicalPath,rootRealPath:n.rootCanonicalPath,exists:false}}catch(e){a={ok:false,reason:`validation`,error:e}}else{const n=openPluginRootFileSync({filePath:i,rootPath:e.rootDir,rootRealPath:e.rootRealPath,boundaryLabel:`plugin package directory`,rejectHardlinks:e.rejectHardlinks});if(!n.ok)a=n;else{fsSync.closeSync(n.fd);t=bindPluginCacheRoot(e.rootDir,n.rootRealPath);Object.assign(pathFacts(n.path),{exists:true,stat:new CachedStat(n.stat)});if(process.platform!==`win32`)pathFacts(n.path).nativeRealpath=n.path;a={ok:true,path:n.path,rootRealPath:n.rootRealPath,exists:true}}}if(!a.ok)materializeErrorStack(a.error);t.checkedEntries.set(n,a);return a}function readPluginCacheFile(e){let t=getPluginCacheRoot(e.rootDir);const n=e.maxBytes===null?void 0:e.maxBytes??DEFAULT_PLUGIN_METADATA_MAX_BYTES;const r=entryKey(e.relativePath,e.rejectHardlinks);let i=t.files.get(r)??t.files.get(JSON.stringify([r,n]));if(!i&&!e.rejectHardlinks){const n=t.files.get(entryKey(e.relativePath,true));i=n?.ok?n:void 0}if(i)return enforceFileSize(i,n);const a=path.resolve(e.rootDir);const o=path.resolve(a,e.relativePath);const s=t.checkedEntries.get(r);if(pathFacts(o).exists===false||s&&(!s.ok||!s.exists)){const e={ok:false,failure:s&&!s.ok?s:{ok:false,reason:`path`}};t.files.set(r,e);return e}const c=e.rootRealPath??pluginCacheRealpathSync(a)??a;const l=getPluginCacheRoot(c).files.get(r);if(l?.ok){bindPluginCacheRoot(a,c);return enforceFileSize(l,n)}const u=path.resolve(c,e.relativePath);const d=openPluginRootFileSync({filePath:u,rootRealPath:c,rootPath:c,boundaryLabel:`plugin root`,rejectHardlinks:e.rejectHardlinks,maxBytes:n});let f;if(!d.ok){f={ok:false,failure:d};if(d.reason===`path`&&d.error&&typeof d.error===`object`&&`code`in d.error&&d.error.code===`ENOENT`){pathFacts(o).exists=false;pathFacts(u).exists=false}}else{t=bindPluginCacheRoot(a,d.rootRealPath);try{const e=n===void 0?fsSync.readFileSync(d.fd):readFileDescriptorBoundedSync$1(d.fd,n);f=capturedPluginFile(d.path,d.rootRealPath,e,d.stat);Object.assign(pathFacts(u),{exists:true,stat:new CachedStat(d.stat)});t.checkedEntries.set(r,{ok:true,path:d.path,rootRealPath:d.rootRealPath,exists:true})}catch(e){f={ok:false,failure:{ok:false,reason:`io`,error:e},failurePhase:`read`}}finally{fsSync.closeSync(d.fd)}}if(!f.ok)materializeErrorStack(f.failure.error);t.files.set(f.ok?r:JSON.stringify([r,n]),f);return f}function readPluginCacheRegularFile(e){const t=path.resolve(e.filePath);const n=path.dirname(t);const r=pluginCacheRealpathSync(n)??n;const i=bindPluginCacheRoot(n,r);const a=path.basename(t);const o=JSON.stringify([`regular`,a]);const s=JSON.stringify([`regular`,a,e.maxBytes]);let c=i.files.get(o)??i.files.get(s);if(!c&&pathFacts(t).exists===false){c={ok:false,failure:{ok:false,reason:`path`}};i.files.set(o,c)}if(!c)try{const{buffer:n,stat:s}=readRegularFileSync({filePath:t,maxBytes:e.maxBytes});c=capturedPluginFile(path.join(r,a),r,n,s);Object.assign(pathFacts(t),{exists:true,stat:new CachedStat(s)});i.files.set(o,c)}catch(e){materializeErrorStack(e);c={ok:false,failure:{ok:false,reason:`io`,error:e}};i.files.set(e instanceof FsSafeError&&e.code===`too-large`?s:o,c);if(e&&typeof e===`object`&&`code`in e&&e.code===`ENOENT`)pathFacts(t).exists=false}return enforceFileSize(c,e.maxBytes,`io`,t)}function readPluginCacheJsonFile(e,t={}){const n=readPluginCacheRegularFile({filePath:e,...t});return n.ok?parsePluginCacheJson(n):{ok:false,error:n.failure.error}}function parsePluginCacheJson(e,t={}){const n=t.json5?`json5`:`json`;if(!e[n])try{const r=e.contents.toString(`utf8`);e[n]={ok:true,value:t.json5?parseJsonWithJson5Fallback(r):JSON.parse(r)}}catch(t){materializeErrorStack(t);e[n]={ok:false,error:t}}return e[n]}
//!src/plugins/package-entrypoints.ts
const PUBLIC_SURFACE_SOURCE_EXTENSIONS=[`.ts`,`.mts`,`.js`,`.mjs`,`.cts`,`.cjs`];function isTypeScriptPackageEntry(e){return[`.ts`,`.tsx`,`.mts`,`.cts`].includes(path.extname(e).toLowerCase())}function listBuiltRuntimeEntryCandidates(e){if(!isTypeScriptPackageEntry(e))return[];const t=e.replace(/\\/g,`/`);const n=t.replace(/\.[^.]+$/u,``);const r=n.replace(/^\.\//u,``);const i=r.startsWith(`src/`)?`./dist/${r.slice(4)}`:`./dist/${r}`;const a=path.extname(t).toLowerCase();const o=a===`.mts`?[`.mjs`,`.js`,`.cjs`]:a===`.cts`?[`.cjs`,`.js`,`.mjs`]:[`.js`,`.mjs`,`.cjs`];return[i,...r.startsWith(`src/`)?[`./dist/${r}`]:[],n].flatMap(e=>o.map(t=>`${e}${t}`))}
//!src/plugins/package-manifest.ts
const DEFAULT_PLUGIN_ENTRY_CANDIDATES=[`index.ts`,`index.js`,`index.mjs`,`index.cjs`];function getPackageManifestMetadata(e){return e?.[MANIFEST_KEY]}function resolvePackageExtensionEntries(e){const t=e?.[MANIFEST_KEY];if(t===void 0||t===null)return{status:`missing`,entries:[]};if(!isRecord(t))return{status:`invalid`,entries:[],error:`package.json openclaw must be an object`};const n=t.extensions;if(n===void 0||n===null)return{status:`missing`,entries:[]};if(!Array.isArray(n))return{status:`invalid`,entries:[],error:`package.json openclaw.extensions must be an array`};const r=[];for(const[e,t]of n.entries()){const n=normalizeOptionalString(t);if(!n)return{status:`invalid`,entries:[],error:`package.json openclaw.extensions[${e}] must be a non-empty string`};r.push(n)}if(r.length===0)return{status:`empty`,entries:[]};return{status:`ok`,entries:r}}
//!src/plugins/plugin-runtime-artifact-selection.ts
function resolveCanonicalDistRuntimeSource(e){const t=`${path.sep}dist-runtime${path.sep}extensions${path.sep}`;const n=e.indexOf(t);if(n===-1)return e;const r=`${e.slice(0,n)}${path.sep}dist${path.sep}extensions${path.sep}${e.slice(n+t.length)}`;return pluginCacheExistsSync(r)?r:e}function resolvePluginRuntimeExecutionArtifact(e){const t=resolveCanonicalDistRuntimeSource(e.source);const n=resolveCanonicalDistRuntimeSource(e.rootDir);return{source:t,rootDir:n!==e.rootDir&&!isPathInside$2(pluginCacheRealpathSync(n)??n,pluginCacheRealpathSync(t)??t)?e.rootDir:n}}function resolvePluginRuntimeArtifactSelection(e){const{source:t,rootDir:n}=resolvePluginRuntimeExecutionArtifact({source:pluginCacheRealpathSync(e.source)??path.resolve(e.source),rootDir:pluginCacheRealpathSync(e.rootDir)??path.resolve(e.rootDir)});const r=getPluginCacheRoot(n).runtimeArtifacts;const i=JSON.stringify([e.source,e.entryKind,e.origin,e.preferBuiltPluginArtifacts,e.sourcePreferred,e.packageManifest?.build?.bundledDist]);let a=r.get(i);if(!a){a=resolvePluginRuntimeExecutionArtifact(resolvePreferredBuiltRuntimeArtifact({...e,source:t,rootDir:n}));r.set(i,a)}return a}function resolvePluginRuntimeArtifactPreference(e){if(e!==void 0)return e?`all`:`source`;return/\.[cm]?js$/.test(new URL(import.meta.url).pathname)?`bundled`:`source`}function resolveBundledArtifactRelativePath(e,t){const n=readPluginCacheFile({rootDir:e,relativePath:`package.json`,rejectHardlinks:false});const r=n.ok?parsePluginCacheJson(n):void 0;const i=r?.ok&&isRecord(r.value)?getPackageManifestMetadata(r.value):void 0;const a=[...i?.runtimeExtensions?.length?i.runtimeExtensions:i?.extensions??[],i?.runtimeSetupEntry??i?.setupEntry].filter(e=>typeof e===`string`);const o=t.replace(/\.[^.]+$/u,``);const s=a.find(e=>path.normalize(e).replace(/\.[^.]+$/u,``)===o);if(s)return/\.[cm]?js$/.test(s)?s:null;const c=new Set(a.map(e=>path.extname(e)));const l=c.size===1?[...c][0]:void 0;if(!l||![`.js`,`.mjs`,`.cjs`].includes(l)||a.some(e=>path.normalize(e).startsWith(`dist${path.sep}`)))return null;return t.replace(/\.[^.]+$/u,l)}function resolvePackageLocalDistRuntimeArtifact(e){const t=path.relative(e.rootDir,e.source);if(!isTypeScriptPackageEntry(t)||t===``||t.startsWith(`..`)||path.isAbsolute(t))return null;for(const n of listBuiltRuntimeEntryCandidates(t)){if(e.origin===`bundled`&&!n.startsWith(`./dist/`))continue;const t=path.resolve(e.rootDir,n);if(pluginCacheExistsSync(t))return pluginCacheRealpathSync(t)??path.resolve(t)}return null}function resolvePreferredBundledRootArtifactFromCanonicalPaths(e){const{rootDir:t,source:n}=e;const r=e.packageManifest?.build?.bundledDist===false;const i=path.dirname(t);if(path.basename(i)!==`extensions`)return{source:n,rootDir:t};const a=path.dirname(i);if(path.basename(a)===`dist`||path.basename(a)===`dist-runtime`)return{source:n,rootDir:t};const o=path.relative(t,n);if(o===``||o.startsWith(`..`)||path.isAbsolute(o))return{source:n,rootDir:t};for(const e of r?[`dist`]:[`dist-runtime`,`dist`]){const n=path.join(a,e,`extensions`,path.basename(t));const r=resolveBundledArtifactRelativePath(n,o);if(!r)continue;const i=path.join(n,r);if(pluginCacheExistsSync(i))return{source:pluginCacheRealpathSync(i)??path.resolve(i),rootDir:pluginCacheRealpathSync(n)??path.resolve(n)}}return{source:n,rootDir:t}}function resolvePreferredBuiltRuntimeArtifact(e){const{rootDir:t,source:n}=e;if(!e.preferBuiltPluginArtifacts||e.sourcePreferred)return{source:n,rootDir:t};if(e.origin!==`bundled`){const r=resolvePackageLocalDistRuntimeArtifact({...e,source:n,rootDir:t});return r?{source:r,rootDir:t}:{source:n,rootDir:t}}const r=e.packageManifest?.build?.bundledDist===false?null:resolvePackageLocalDistRuntimeArtifact({...e,source:n,rootDir:t});if(r)return{source:r,rootDir:t};return resolvePreferredBundledRootArtifactFromCanonicalPaths({source:n,rootDir:t,packageManifest:e.packageManifest})}
//!src/plugins/bundled-dir.ts
const DISABLED_BUNDLED_PLUGINS_DIR=path.join(os.tmpdir(),`openclaw-empty-bundled-plugins`);const TEST_TRUST_BUNDLED_PLUGINS_DIR_ENV=`OPENCLAW_TEST_TRUST_BUNDLED_PLUGINS_DIR`;function areBundledPluginsDisabled(e=process.env){const t=normalizeOptionalLowercaseString(e.OPENCLAW_DISABLE_BUNDLED_PLUGINS);return t===`1`||t===`true`}function resolveDisabledBundledPluginsDir(){if(!pluginCacheExistsSync(DISABLED_BUNDLED_PLUGINS_DIR)){fsSync.mkdirSync(DISABLED_BUNDLED_PLUGINS_DIR,{recursive:true});refreshPluginCacheStat(DISABLED_BUNDLED_PLUGINS_DIR)}return DISABLED_BUNDLED_PLUGINS_DIR}function isSourceCheckoutRoot(e){return pluginCacheExistsSync(path.join(e,`pnpm-workspace.yaml`))&&pluginCacheExistsSync(path.join(e,`src`))&&pluginCacheExistsSync(path.join(e,`extensions`))}function shouldTrustTestBundledPluginsDirOverride(e){const t=e!==process.env;if(!isTruthyEnvValue(e[TEST_TRUST_BUNDLED_PLUGINS_DIR_ENV])&&!(t&&isTruthyEnvValue(process.env[TEST_TRUST_BUNDLED_PLUGINS_DIR_ENV])))return false;return isVitestRuntimeEnv(e)||t&&isVitestRuntimeEnv(process.env)}function hasUsableBundledPluginTree(e){if(!pluginCacheExistsSync(e))return false;try{return readPluginCacheDirectory(e).some(t=>{if(!t.isDirectory())return false;const n=path.join(e,t.name);return pluginCacheExistsSync(path.join(n,`package.json`))||pluginCacheExistsSync(path.join(n,`openclaw.plugin.json`))})}catch{return false}}function safeRealpathSync(e){return pluginCacheRealpathSync(e,true)}function trustedBundledPluginRootsForPackageRoot(e){const t=[path.join(e,`dist`,`extensions`),path.join(e,`dist-runtime`,`extensions`)];if(isSourceCheckoutRoot(e))t.push(path.join(e,`extensions`));return t}function resolvePackageRootsForBundledPlugins(e){const t=resolveOpenClawPackageRootSync({argv1:process.argv[1]});const n=t&&e&&isPluginInPackageBundledRoots({rootDir:e,packageRoot:t})?null:t;const r=resolveOpenClawPackageRootSync({moduleUrl:import.meta.url});return uniqueStrings([n,r].filter(e=>Boolean(e)))}function resolveSourceCheckoutDependencyDiagnostic(e=process.env){if(areBundledPluginsDisabled(e))return null;for(const e of resolvePackageRootsForBundledPlugins()){if(!isSourceCheckoutRoot(e))continue;const t=path.join(e,`extensions`);if(!isPluginInPackageBundledRoots({rootDir:t,packageRoot:e})||!hasUsableBundledPluginTree(t))continue;if(pluginCacheExistsSync(path.join(e,`node_modules`,`.pnpm`)))continue;return{source:e,message:"OpenClaw source checkout detected without pnpm workspace dependencies; run `pnpm install` from the repo root so bundled plugins can load package-local dependencies."}}return null}function resolveTrustedExistingOverride(e){const t=safeRealpathSync(e);if(!t)return null;const n=resolveOpenClawPackageRootSync({moduleUrl:import.meta.url});if(!n||!isPluginInPackageBundledRoots({rootDir:t,packageRoot:n}))return null;if(!hasUsableBundledPluginTree(t))return null;return t}function isPluginInPackageBundledRoots(e){const t=safeRealpathSync(e.rootDir);const n=safeRealpathSync(e.packageRoot);if(!t||!n)return false;return trustedBundledPluginRootsForPackageRoot(e.packageRoot).map(e=>safeRealpathSync(e)).some(e=>e!==null&&isPathInside$2(n,e)&&isPathInside$2(e,t))}function isForeignBundledPluginRoot(e,t=process.env){const n=safeRealpathSync(e);if(!n)return false;const r=path.dirname(n);const i=path.dirname(r);if(path.basename(r)!==`extensions`||![`dist`,`dist-runtime`].includes(path.basename(i)))return false;const a=path.dirname(i);if(resolveOpenClawPackageRootSync({cwd:a})!==a||!isPluginInPackageBundledRoots({rootDir:n,packageRoot:a}))return false;const o=resolveBundledPluginsDir(t);const s=o?safeRealpathSync(o):null;if(s&&isPathInside$2(s,n))return false;const c=resolvePackageRootsForBundledPlugins();return c.length>0&&!c.some(e=>isPluginInPackageBundledRoots({rootDir:n,packageRoot:e}))}function resolveBundledDirFromPackageRoot(e,t=`bundled`){const n=path.join(e,`dist`,`extensions`);const r=path.join(e,`dist-runtime`,`extensions`);if(isSourceCheckoutRoot(e)){const i=path.join(e,`extensions`);return(t===`source`?[i]:[n,r,i]).find(t=>isPluginInPackageBundledRoots({rootDir:t,packageRoot:e})&&hasUsableBundledPluginTree(t))}return pluginCacheExistsSync(n)?[r,n].find(t=>isPluginInPackageBundledRoots({rootDir:t,packageRoot:e})):void 0}function resolveBundledPluginsDirUncached(e){if(areBundledPluginsDisabled(e))return resolveDisabledBundledPluginsDir();const t=e.OPENCLAW_BUNDLED_PLUGINS_DIR?.trim();let n=null;if(t){const r=resolveUserPath(t,e);if(pluginCacheExistsSync(r)){if(shouldTrustTestBundledPluginsDirOverride(e))return path.resolve(r);const t=resolveTrustedExistingOverride(r);if(t)return t;n=r}}for(const e of resolvePackageRootsForBundledPlugins(n)){const t=resolveBundledDirFromPackageRoot(e,resolvePluginRuntimeArtifactPreference());if(t)return t}const r=path.dirname(process.execPath);const i=path.join(r,`dist`,`extensions`);if(pluginCacheExistsSync(i))return i;const a=path.join(r,`extensions`);if(pluginCacheExistsSync(a))return a;try{let e=path.dirname(fileURLToPath(import.meta.url));for(let t=0;t<6;t+=1){const t=path.join(e,`extensions`);if(pluginCacheExistsSync(t))return t;const n=path.dirname(e);if(n===e)break;e=n}}catch{}}function resolveBundledPluginsDir(e=process.env){const t=areBundledPluginsDisabled(e);const n=t?void 0:e.OPENCLAW_BUNDLED_PLUGINS_DIR?.trim();const r=n?resolveUserPath(n,e):void 0;const i=shouldTrustTestBundledPluginsDirOverride(e);const a=process.argv[1];const o=process.execPath;const s=tryProcessCwd();const c=getPluginCache().metadata;const l=c.bundledPluginsDir;if(l&&l.moduleUrl===import.meta.url&&l.disabled===t&&l.resolvedOverride===r&&l.trustOverride===i&&l.argv1===a&&l.execPath===o&&l.cwd===s)return l.value;const u=resolveBundledPluginsDirUncached(e);c.bundledPluginsDir={moduleUrl:import.meta.url,disabled:t,resolvedOverride:r,trustOverride:i,argv1:a,execPath:o,cwd:s,value:u};return u}
//!src/channels/bundled-channel-catalog-read.ts
const OFFICIAL_CHANNEL_CATALOG_RELATIVE_PATH=path.join(`dist`,`channel-catalog.json`);function listPackageRoots(){return uniqueStrings([resolveOpenClawPackageRootSync({cwd:process.cwd()}),resolveOpenClawPackageRootSync({moduleUrl:import.meta.url})].filter(e=>Boolean(e)))}function readBundledExtensionCatalogEntriesSync(e){if(!e)return[];try{return readPluginCacheDirectory(e).filter(e=>e.isDirectory()).flatMap(t=>{const n=path.join(e,t.name,`package.json`);const r=readPluginCacheJsonFile(n);return r.ok&&isRecord(r.value)?[r.value]:[]})}catch{return[]}}function readOfficialCatalogFileSync(){const e=[...BUNDLED_OFFICIAL_EXTERNAL_PLUGIN_CATALOG_ENTRIES];for(const t of listPackageRoots()){const n=path.join(t,OFFICIAL_CHANNEL_CATALOG_RELATIVE_PATH);const r=readPluginCacheJsonFile(n);if(r.ok&&isRecord(r.value)){const t=Array.isArray(r.value.entries)?r.value.entries.filter(e=>isRecord(e)):[];return[...e,...t]}}return e}function toBundledChannelEntry(e){const t=e.openclaw?.channel;const n=normalizeOptionalLowercaseString(t?.id);if(!n||!t)return null;return{id:n,channel:t,aliases:Array.isArray(t.aliases)?t.aliases.map(e=>normalizeOptionalLowercaseString(e)).filter(e=>Boolean(e)):[],order:typeof t.order===`number`&&Number.isFinite(t.order)?t.order:Number.MAX_SAFE_INTEGER}}function listBundledChannelCatalogEntries(){const e=resolveBundledPluginsDir();const t=getPluginCache().metadata.bundledChannelCatalogs;const n=JSON.stringify([process.cwd(),e]);const r=t.get(n);if(r)return r;const i=/* @__PURE__ */ new Map;for(const t of readBundledExtensionCatalogEntriesSync(e)){const e=toBundledChannelEntry(t);if(e)i.set(e.id,e)}for(const e of readOfficialCatalogFileSync()){const t=toBundledChannelEntry(e);if(t)i.set(t.id,i.get(t.id)??t)}const a=Array.from(i.values()).toSorted((e,t)=>e.order-t.order||e.id.localeCompare(t.id));t.set(n,a);return a}
//!src/channels/bundled-channel-ids.generated.ts
const GENERATED_BUNDLED_CHANNEL_IDS=[{channelId:`a2a`,order:75,label:`A2A`},{channelId:`buzz`,order:56,label:`Buzz`},{channelId:`clickclack`,order:85,label:`ClickClack`},{channelId:`discord`,label:`Discord`},{channelId:`feishu`,aliases:[`lark`],order:35,label:`Feishu`},{channelId:`googlechat`,aliases:[`gchat`,`google-chat`],order:55,label:`Google Chat`},{channelId:`imessage`,aliases:[`imsg`],label:`iMessage`},{channelId:`irc`,aliases:[`internet-relay-chat`],label:`IRC`},{channelId:`line`,order:75,label:`LINE`},{channelId:`matrix`,order:70,label:`Matrix`},{channelId:`mattermost`,order:65,label:`Mattermost`},{channelId:`msteams`,aliases:[`teams`],order:60,label:`Microsoft Teams`},{channelId:`nextcloud-talk`,aliases:[`nc`,`nc-talk`],order:65,label:`Nextcloud Talk`},{channelId:`nostr`,order:55,label:`Nostr`},{channelId:`qa-channel`,order:999,configurable:false,label:`QA Channel`},{channelId:`raft`,order:72,label:`Raft`},{channelId:`reef`,label:`Reef`},{channelId:`signal`,label:`Signal`},{channelId:`slack`,label:`Slack`},{channelId:`sms`,order:88,label:`SMS`},{channelId:`synology-chat`,order:90,label:`Synology Chat`},{channelId:`telegram`,label:`Telegram`},{channelId:`tlon`,order:90,label:`Tlon`},{channelId:`twitch`,aliases:[`twitch-chat`],label:`Twitch`},{channelId:`whatsapp`,label:`WhatsApp`},{channelId:`x`,order:85,label:`X (Twitter)`},{channelId:`zalo`,aliases:[`zl`],order:80,label:`Zalo`},{channelId:`zalouser`,aliases:[`zlu`],order:85,label:`Zalo Personal`}];
//!src/channels/ids.ts
const BUNDLED_CHAT_CHANNEL_ENTRIES=GENERATED_BUNDLED_CHANNEL_IDS.filter(e=>e.configurable!==false).map(e=>({id:normalizeOptionalLowercaseString(e.channelId)??e.channelId,aliases:e.aliases??[],label:e.label?.trim()||void 0,order:e.order??Number.MAX_SAFE_INTEGER})).toSorted((e,t)=>e.order-t.order||e.id.localeCompare(t.id,`en`,{sensitivity:`base`}));const CHAT_CHANNEL_ID_SET=new Set(BUNDLED_CHAT_CHANNEL_ENTRIES.map(e=>e.id));const CHAT_CHANNEL_ORDER=Object.freeze(BUNDLED_CHAT_CHANNEL_ENTRIES.map(e=>e.id));const CHAT_CHANNEL_ALIASES=Object.fromEntries(BUNDLED_CHAT_CHANNEL_ENTRIES.flatMap(e=>e.aliases.map(t=>[t,e.id])));function normalizeRuntimeBundledChatChannelId(e){return listBundledChannelCatalogEntries().find(t=>t.id===e||t.aliases.includes(e))?.id??null}function normalizeChatChannelId(e){const t=normalizeOptionalLowercaseString(e);if(!t)return null;const n=CHAT_CHANNEL_ALIASES[t]??t;return CHAT_CHANNEL_ID_SET.has(n)?n:normalizeRuntimeBundledChatChannelId(t)}
//!src/plugins/default-enablement.ts
function isPluginEnabledByDefaultForPlatform(e,t=process.platform){if(e.enabledByDefault===true)return true;return e.enabledByDefaultOnPlatforms?.includes(t)===true}
//!src/plugins/plugin-policy-id.ts
function normalizePluginPolicyId(e){return normalizeOptionalLowercaseString(e)??``}
//!src/plugins/slots.ts
const DEFAULT_SLOT_BY_KEY={memory:`memory-core`,contextEngine:`legacy`};const PLUGIN_SLOT_KEYS=Object.keys(DEFAULT_SLOT_BY_KEY);function defaultSlotIdForKey(e){return DEFAULT_SLOT_BY_KEY[e]}function normalizeSlotValue(e){const t=normalizeOptionalString(e);if(!t)return;if(normalizeOptionalLowercaseString(t)===`none`)return null;return t}function resolveSlotSelection(e,t){const n=normalizeSlotValue(t);if(n===void 0)return{kind:`default`,pluginId:defaultSlotIdForKey(e)};return n===null?{kind:`off`}:{kind:`pinned`,pluginId:n}}
//!src/plugins/config-normalization-shared.ts
const identityNormalizePluginId=e=>e.trim();function normalizePluginConfigList(e,t){return filterStringEntries(e).map(e=>t(e)).filter(Boolean)}function normalizeHookTimeoutMs(e){return asSafeIntegerInRange(e,{min:1,max:6e5})}function normalizeHookTimeouts(e){if(!isRecord(e))return;const t={};for(const[n,r]of Object.entries(e)){const e=normalizeHookTimeoutMs(r);if(e!==void 0)t[n]=e}return Object.keys(t).length>0?t:void 0}function normalizePluginHooks(e){if(!isRecord(e))return;const t={};for(const n of[`allowPromptModification`,`allowConversationAccess`])if(typeof e[n]===`boolean`)t[n]=e[n];const n=normalizeHookTimeoutMs(e.timeoutMs);const r=normalizeHookTimeouts(e.timeouts);if(n!==void 0)t.timeoutMs=n;if(r!==void 0)t.timeouts=r;return Object.keys(t).length>0?t:void 0}function normalizePluginModelConfig(e,t){if(!isRecord(e))return;const n={};if(typeof e.allowModelOverride===`boolean`)n.allowModelOverride=e.allowModelOverride;for(const[r,i]of[[`allowedModels`,`hasAllowedModelsConfig`],[`allowedCompletionModels`,`hasAllowedCompletionModelsConfig`]]){if(r===`allowedCompletionModels`&&t!==`llm`)continue;const a=normalizeArrayBackedTrimmedStringList(e[r]);if(a){n[i]=true;if(a.length>0)n[r]=a}}if(t===`llm`){for(const t of[`allowAuthProfileOverride`,`allowAgentIdOverride`])if(typeof e[t]===`boolean`)n[t]=e[t]}return Object.keys(n).length>0?n:void 0}function normalizePluginEntries(e,t){if(!isRecord(e))return{};const n={};for(const[r,i]of Object.entries(e)){const e=t(r);if(!e)continue;if(!isRecord(i)){n[e]={};continue}const a=i;n[e]={...n[e],enabled:typeof a.enabled===`boolean`?a.enabled:n[e]?.enabled,hooks:normalizePluginHooks(a.hooks)??n[e]?.hooks,subagent:normalizePluginModelConfig(a.subagent,`subagent`)??n[e]?.subagent,llm:normalizePluginModelConfig(a.llm,`llm`)??n[e]?.llm,config:`config`in a?a.config:n[e]?.config}}return n}function normalizePluginsConfigWithResolverCore(e,t=identityNormalizePluginId){const n=resolveSlotSelection(`memory`,e?.slots?.memory);const resolvePolicyId=e=>normalizePluginPolicyId(t(e));return{enabled:e?.enabled??true,allow:normalizePluginConfigList(e?.allow,resolvePolicyId),deny:normalizePluginConfigList(e?.deny,resolvePolicyId),loadPaths:normalizePluginConfigList(e?.load?.paths,identityNormalizePluginId),slots:{memory:n.kind===`off`?null:n.pluginId,contextEngine:normalizeSlotValue(e?.slots?.contextEngine)},entries:normalizePluginEntries(e?.entries,resolvePolicyId)}}function resolveChannelConfigEnablement(e,t,n){const r=e?.channels;if(!r||n?.length===0)return;const i=(n?.length?n.map(e=>normalizeChatChannelId(e)??e):[normalizeChatChannelId(t)]).map(e=>{const t=e?r[e]:void 0;return isRecord(t)?t.enabled:void 0});if(i.includes(true))return true;return i.every(e=>e===false)?false:void 0}
//!src/plugins/config-activation-shared.ts
function resolvePluginActivationStateShared(e){const t=e.activationSource??{plugins:e.config,rootConfig:e.rootConfig};const n=normalizePluginPolicyId(e.id);let r;if(t.plugins.entries[n]?.enabled===true)r=`enabled in config`;else if(e.origin===`bundled`&&resolveChannelConfigEnablement(t.rootConfig,e.id,e.channelIds)===true)r=`channel enabled in config`;else if(t.plugins.slots.memory===e.id)r=`selected memory slot`;else if(t.plugins.contextEngineOwnerId!==void 0?t.plugins.contextEngineOwnerId===n:t.plugins.slots.contextEngine===e.id)r=`selected context engine slot`;else if(e.origin!==`bundled`&&t.plugins.allow.includes(n))r=`selected in allowlist`;const decision=(e,t={})=>({enabled:e!==`disabled`,activated:e!==`disabled`,explicitlyEnabled:r!==void 0,source:e,reason:void 0,...t});if(!e.config.enabled)return decision(`disabled`,{reason:`plugins disabled`});const i=normalizePluginPolicyId(e.id);if(e.config.deny.includes(i))return decision(`disabled`,{reason:`blocked by denylist`});const a=e.config.entries[i];if(a?.enabled===false)return decision(`disabled`,{reason:`disabled in config`});if(resolveChannelConfigEnablement(t.rootConfig??e.rootConfig,e.id,e.channelIds)===false)return decision(`disabled`,{reason:`channel disabled in config`});const o=e.config.allow.includes(i);if(e.origin===`workspace`&&!o&&a?.enabled!==true&&r!==`selected context engine slot`)return decision(`disabled`,{reason:`workspace plugin (disabled by default)`});if(e.config.slots.memory===e.id)return decision(`explicit`,{explicitlyEnabled:true,reason:`selected memory slot`});if(e.config.contextEngineOwnerId!==void 0?e.config.contextEngineOwnerId===i:e.config.slots.contextEngine===e.id)return decision(`explicit`,{explicitlyEnabled:true,reason:`selected context engine slot`});if(e.allowBundledChannelExplicitBypassesAllowlist===true&&r===`channel enabled in config`)return decision(`explicit`,{explicitlyEnabled:true,reason:r});if(e.config.allow.length>0&&!o)return decision(`disabled`,{reason:`not in allowlist`});if(r)return decision(`explicit`,{explicitlyEnabled:true,reason:r});const s=e.autoEnabledReason||(a?.enabled===true?`enabled by effective config`:void 0)||(e.origin===`bundled`&&resolveChannelConfigEnablement(e.rootConfig,e.id,e.channelIds)===true?`channel configured`:void 0);if(e.origin===`bundled`&&e.enabledByDefault===true&&(!s||t.plugins.allow.length===0||t.plugins.allow.includes(i)))return decision(`default`,{explicitlyEnabled:false,reason:`bundled default enablement`});if(s)return decision(`auto`,{explicitlyEnabled:false,reason:s});if(e.origin===`bundled`)return decision(`disabled`,{explicitlyEnabled:false,reason:`bundled (disabled by default)`});return decision(`default`)}
//!src/plugins/config-state.ts
const BUILT_IN_PLUGIN_ALIAS_LOOKUP=/* @__PURE__ */ new Map([[`google-gemini-cli`,`google`],[`minimax-portal`,`minimax`],[`minimax-portal-auth`,`minimax`]]);function normalizePluginId(e){const t=normalizePluginPolicyId(e);return BUILT_IN_PLUGIN_ALIAS_LOOKUP.get(t)??t}const createNormalizedPluginsConfig=e=>normalizePluginsConfigWithResolverCore(e,normalizePluginId);const normalizePluginsConfig=e=>{if(preparedRuntimePluginsConfig&&preparedRuntimePluginsConfig.source===e)return preparedRuntimePluginsConfig.value;const t=e??EMPTY_PLUGINS_CONFIG;if(!isDeeplyFrozenPlainData(t))return createNormalizedPluginsConfig(t);let n=frozenPluginsConfigs.get(t);if(!n){n=createSharedNormalizedPluginsConfig(t);frozenPluginsConfigs.set(t,n)}return n};let preparedRuntimePluginsConfig;const EMPTY_PLUGINS_CONFIG=Object.freeze({});const frozenPluginsConfigs=/* @__PURE__ */ new WeakMap;function createSharedNormalizedPluginsConfig(e){const t=createNormalizedPluginsConfig(e);for(const e of Object.values(t.entries)){Object.freeze(e.hooks?.timeouts);Object.freeze(e.hooks);Object.freeze(e.subagent?.allowedModels);Object.freeze(e.subagent);Object.freeze(e.llm?.allowedModels);Object.freeze(e.llm?.allowedCompletionModels);Object.freeze(e.llm);Object.freeze(e)}Object.freeze(t.entries);for(const e of[t.allow,t.deny,t.loadPaths,t.slots])Object.freeze(e);return Object.freeze(t)}function resolveEffectivePluginActivationState(e){return resolvePluginActivationStateShared({...e,config:e.config??normalizePluginsConfig(e.rootConfig?.plugins),allowBundledChannelExplicitBypassesAllowlist:true})}
//!src/config/runtime-config-capture-state.ts
const captures=/* @__PURE__ */ new WeakMap;function captureRuntimeConfigWithSource(e,t,n=runtimeConfigPublication.current?.config){const clone=e=>freezeJsonSnapshot(cloneConfigWithResolutionFacts(e));const r=clone(e);const i=t===e?r:clone(t);captures.set(r,{source:i,origin:e,runtimeOwned:e===n});if(i!==r)captures.set(i,{source:i,origin:t,runtimeOwned:t===n});return r}export{readPluginCacheJsonFile as A,parsePluginCacheJson as C,pluginCacheStatSync as D,pluginCacheRealpathSync as E,isVitestRuntimeEnv as F,formatPosixMode as M,isPathInside$1 as N,readPluginCacheDirectory as O,safeRealpathSync$1 as P,checkPluginCacheEntry as S,pluginCacheLstatSync as T,getPackageManifestMetadata as _,normalizePluginPolicyId as a,isTypeScriptPackageEntry as b,isForeignBundledPluginRoot as c,resolveBundledPluginsDir as d,resolveSourceCheckoutDependencyDiagnostic as f,DEFAULT_PLUGIN_ENTRY_CANDIDATES as g,resolvePluginRuntimeExecutionArtifact as h,normalizePluginsConfigWithResolverCore as i,refreshPluginCacheStat as j,readPluginCacheFile as k,isPluginInPackageBundledRoots as l,resolvePluginRuntimeArtifactSelection as m,normalizePluginsConfig as n,isPluginEnabledByDefaultForPlatform as o,shouldTrustTestBundledPluginsDirOverride as p,resolveEffectivePluginActivationState as r,hasUsableBundledPluginTree as s,captureRuntimeConfigWithSource as t,isSourceCheckoutRoot as u,resolvePackageExtensionEntries as v,pluginCacheExistsSync as w,listBuiltRuntimeEntryCandidates as x,PUBLIC_SURFACE_SOURCE_EXTENSIONS as y};