openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
999 lines (998 loc) • 33.8 kB
JavaScript
import { c as normalizeOptionalLowercaseString, l as normalizeOptionalString, o as normalizeLowercaseStringOrEmpty } from "./string-coerce-CCIiB4H7.mjs";
import { c as resolveUserPath } from "./home-dir-EKmgmdPG.mjs";
import { l as isRecord } from "./record-coerce-CVPuDqcc.mjs";
import { y as sortUniqueStrings } from "./string-normalization-DLmfYZXI.mjs";
import "./utils-C8YECn2Q.mjs";
import { C as resolveIsNixMode } from "./paths-DAcAg5aV.mjs";
import { n as groupPluginRecords } from "./record-groups-DII71OvH.mjs";
import { a as getPluginCache } from "./plugin-cache-B_eRuqTM.mjs";
import { a as resolveCompatibilityHostVersion } from "./version-GlxUMdxI.mjs";
import { t as decodeMountInfoPath } from "./mountinfo-path-CJN-JB-q.mjs";
import { n as isPathInside, t as formatPosixMode } from "./path-safety-CTChYC4Z.mjs";
import { a as pluginCacheRealpathSync, c as readPluginCacheFile, n as parsePluginCacheJson, o as pluginCacheStatSync, r as pluginCacheExistsSync, s as readPluginCacheDirectory, u as refreshPluginCacheStat } from "./plugin-cache-files-e1aGp2KM.mjs";
import { t as PUBLIC_SURFACE_SOURCE_EXTENSIONS } from "./package-entrypoints-Do32y0v-.mjs";
import { r as loadPluginManifest } from "./manifest-Y5vPZPOf.mjs";
import { n as getPackageManifestMetadata, r as resolvePackageExtensionEntries, t as DEFAULT_PLUGIN_ENTRY_CANDIDATES } from "./package-manifest-CC8p56hY.mjs";
import { c as resolveSourceCheckoutDependencyDiagnostic, i as isPluginInPackageBundledRoots, n as hasUsableBundledPluginTree, s as resolveBundledPluginsDir } from "./bundled-dir-BKvdAqkP.mjs";
import { t as normalizePluginPolicyId } from "./plugin-policy-id-CkilMowp.mjs";
import { n as hashStableJson } from "./installed-plugin-index-hash-BfBbMPjv.mjs";
import { i as loadBundleManifest, r as detectBundleManifestFormat } from "./bundle-manifest-js7o0H7U.mjs";
import { c as shouldSkipIncompatiblePackagePluginApi, i as inspectPluginLoadPath, s as pluginPathFailureDiagnostic } from "./discovery-availability-DtlJ7XvT.mjs";
import { t as shouldRejectHardlinkedPluginFiles } from "./hardlink-policy-Kq1Lxk7_.mjs";
import { n as resolvePackageRuntimeExtensions, r as resolvePackageSetupSource } from "./package-entry-resolution-CDVAv_m5.mjs";
import { n as resolvePluginSourceRoots } from "./roots-DLOdGM8J.mjs";
import { r as normalizePluginDependencySpecs } from "./status-dependencies-core-BbL--1ba.mjs";
import fs from "node:fs";
import path from "node:path";
//#region 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);
/** Editable installs have no reusable identity; npm replacement records invalidate installed code. */
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 ?? ""
]);
}
//#endregion
//#region src/plugins/bundled-load-path-aliases.ts
const PACKAGED_BUNDLED_ROOTS = [path.join("dist", "extensions"), path.join("dist-runtime", "extensions")];
/** Normalizes bundled lookup paths without preserving trailing separators. */
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;
}
/** Parses a path under a packaged bundled plugin root. */
function parsePackagedBundledPluginPath(e) {
const t = findBundledRoot(e);
return t?.bundledLeaf ? t : null;
}
/** Builds the legacy extensions-root alias for a packaged bundled plugin path. */
function buildLegacyBundledPath(e) {
const t = parsePackagedBundledPluginPath(e);
if (!t) return null;
return path.join(t.packageRoot, "extensions", t.bundledLeaf);
}
/** Builds the legacy extensions root for a packaged bundled plugin root. */
function buildLegacyBundledRootPath(e) {
const t = findBundledRoot(e);
return t ? path.join(t.packageRoot, "extensions") : null;
}
/** Parses a path under the legacy bundled extensions root. */
function parseLegacyBundledPluginPath(e) {
const t = findBundledRoot(e, ["extensions"]);
if (!t?.bundledLeaf) return null;
return {
packageRoot: t.packageRoot,
legacyRoot: t.bundledRoot,
bundledLeaf: t.bundledLeaf
};
}
/** Builds current and legacy aliases for a packaged bundled plugin path. */
function buildBundledPluginLoadPathAliases(e) {
const t = buildLegacyBundledPath(e);
if (!t) return [];
return [{
kind: "current",
path: e
}, {
kind: "legacy",
path: t
}];
}
//#endregion
//#region src/plugins/bundled-source-overlays.ts
/** Parses Linux mountinfo content into absolute mount points. */
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";
}
/** True when a path appears to be a mounted bundled source overlay. */
function isBundledSourceOverlayPath(e) {
const t = path.resolve(e.sourcePath);
return (e.mountPoints ?? readLinuxMountPoints()).has(t) || isFilesystemMountPoint(t);
}
/** Lists source overlay directories that shadow packaged bundled plugin dirs. */
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));
}
//#endregion
//#region 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`
});
}
}
//#endregion
//#region src/plugins/plugin-lifecycle-trace.ts
/** Checks the opt-in plugin lifecycle tracing environment flag. */
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}`);
}
/** Traces a synchronous plugin lifecycle phase when tracing is enabled. */
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
});
}
}
/** Traces an async plugin lifecycle phase when tracing is enabled. */
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
});
}
}
//#endregion
//#region src/plugins/discovery.ts
/** Discovers plugin candidates from bundled, workspace, global, package, and bundle roots. */
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(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(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) {
const t = {
candidates: [],
diagnostics: []
};
const { candidates: n, diagnostics: r } = t;
const i = /* @__PURE__ */ new Map();
function addCandidate(e) {
const t = path.resolve(e.source);
if (i.has(t)) {
const n = i.get(t);
if (n) mergeCandidateInstallOwner(n, e.installOwner, e.installOwnerAmbiguous === true);
return;
}
const a = pluginCacheRealpathSync(e.rootDir) ?? path.resolve(e.rootDir);
const o = checkSourceEscapesRoot({
source: t,
rootDir: a
}) ?? checkPathStatAndPermissions({
source: t,
rootDir: a,
origin: e.origin,
uid: currentUid()
});
if (o) {
r.push({
level: "warn",
...e.idHint ? { pluginId: e.idHint } : {},
...o
});
i.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: a,
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);
n.push(u);
i.set(t, u);
}
function discoverPluginDirectory(t) {
const { dir: n, rootRealPath: i } = t;
const a = t.requireBuiltRuntimeEntry ?? isManagedPluginDir({
dir: n,
realpath: i,
managedPluginDirs: t.managedPluginDirs
});
const o = shouldRejectHardlinkedPluginFiles({
origin: t.origin,
rootDir: n,
env: e
});
const s = readPackageManifest(n, o, i);
const c = getPackageManifestMetadata(s ?? void 0);
const l = loadPluginManifest(n, o, i);
const u = l.ok ? l : void 0;
const d = u?.manifest.id;
const f = normalizeOptionalString(d) ?? normalizeOptionalString(c?.plugin?.id) ?? normalizeOptionalString(c?.channel?.id) ?? derivePackagePluginIdHint(s?.name) ?? path.basename(n);
if (shouldSkipIncompatiblePackagePluginApi({
origin: t.origin,
packageManifest: c,
pluginId: f,
packageDir: n,
env: e,
diagnostics: r
})) return true;
const p = resolvePackageExtensionEntries(s ?? void 0);
if (p.status === "invalid" || p.status === "empty") {
r.push({
level: "error",
source: n,
message: p.status === "invalid" ? p.error : "package.json openclaw.extensions is empty",
...f ? { pluginId: f } : {}
});
return true;
}
const m = p.status === "ok" ? p.entries : [];
const h = {
packageDir: n,
...i !== void 0 ? { packageRootRealPath: i } : {},
manifest: s,
pluginIdHint: f,
origin: t.origin,
requireBuiltRuntimeEntry: a,
sourceLabel: n,
diagnostics: r,
rejectHardlinks: o
};
const g = resolvePackageSetupSource(h);
const addPackageCandidate = (e, r, i) => {
addCandidate({
idHint: r,
...i ? { effectivePluginId: i } : {},
diagnosticIdHint: f,
source: e,
...g ? { setupSource: g } : {},
rootDir: n,
origin: t.origin,
workspaceDir: t.workspaceDir,
...t.installOwner ? { installOwner: t.installOwner } : {},
...t.installOwnerAmbiguous ? { installOwnerAmbiguous: true } : {},
manifest: s,
packageDir: n,
requiredPluginIds: u?.manifest.requiresPlugins,
requiredPluginSource: u?.manifestPath
});
};
if (m.length > 0) {
const e = resolvePluginPackageEntries({
...h,
extensions: m,
manifestId: d ?? normalizeOptionalString(c?.plugin?.id)
});
for (const t of e) addPackageCandidate(t.source, t.idHint, m.length > 1 ? t.idHint : void 0);
return true;
}
const _ = detectBundleManifestFormat(n);
if (_) {
const e = loadBundleManifest({
rootDir: n,
...i !== void 0 ? { rootRealPath: i } : {},
bundleFormat: _,
rejectHardlinks: o
});
if (!e.ok) r.push({
level: "error",
message: e.error,
source: e.manifestPath
});
else {
addCandidate({
idHint: e.manifest.id,
source: n,
rootDir: n,
origin: t.origin,
format: "bundle",
bundleFormat: _,
workspaceDir: t.workspaceDir,
...t.installOwner ? { installOwner: t.installOwner } : {},
...t.installOwnerAmbiguous ? { installOwnerAmbiguous: true } : {},
manifest: s,
packageDir: n,
bundledManifestId: e.manifest.id,
bundledManifestPath: e.manifestPath
});
return true;
}
}
const v = [...DEFAULT_PLUGIN_ENTRY_CANDIDATES].map((e) => path.join(n, e)).find((e) => pluginCacheExistsSync(e));
if (v && isExtensionFile(v)) {
addPackageCandidate(v, d ?? path.basename(n));
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) {
r.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 i = n.isSymbolicLink() ? pluginCacheStatSync(t) : n;
const a = i?.isFile() ? "file" : i?.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(pluginCacheRealpathSync(e.dir) ?? path.resolve(e.dir), s)) {
r.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 i = inspectPluginLoadPath(n, t.origin, r);
if (!i) return;
const a = (t.origin === "config" || t.origin === "global") && isHostBundledPluginRoot(i.isFile() ? path.dirname(n) : n, e) ? "bundled" : t.origin;
if (i.isFile()) {
if (!isExtensionFile(n)) {
r.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 (i.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 r = n.length;
for (const n of e) if (typeof n === "string" && n.trim()) discoverFromPath({
rawPath: n.trim(),
origin: "config",
workspaceDir: t
});
for (const e of n.slice(r)) e.configSelected = true;
}
function finish() {
const e = /* @__PURE__ */ new Map();
const i = /* @__PURE__ */ new Set();
const a = [];
for (const t of n) {
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 r) {
const t = [
e.level,
e.pluginId ?? "",
e.source ?? "",
e.message
].join("\0");
if (i.has(t)) continue;
i.add(t);
a.push(e);
}
t.candidates = [...e.values()];
t.diagnostics = a;
return t;
}
return {
result: t,
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()
};
}
/** Discovers only explicit plugins.load.paths candidates without scanning shared roots. */
function discoverConfiguredPluginLoadPaths(e) {
const t = e.env ?? process.env;
const n = getPluginCache().metadata.discovery;
const r = hashStableJson({
phase: e.deduplicate ? "configured-published" : "configured-raw",
loadPaths: e.loadPaths,
workspaceDir: e.workspaceDir,
policy: discoveryPolicy(t)
});
const i = n.get(r);
if (i) return i;
const a = createPluginScanner(t);
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;
}
//#endregion
export { recordPluginCandidateInstallOwner as _, isPluginLifecycleTraceEnabled as a, isBundledSourceOverlayPath as c, buildLegacyBundledRootPath as d, normalizeBundledLookupPath as f, isPluginCandidateInstallOwnerAmbiguous as g, createPluginInstallOwnerMetadata as h, resolvePluginPackageEntries as i, listBundledSourceOverlayDirs as l, parsePackagedBundledPluginPath as m, discoverOpenClawPlugins as n, tracePluginLifecyclePhase as o, parseLegacyBundledPluginPath as p, resolveBundledSourceCheckoutExtensionsDir as r, tracePluginLifecyclePhaseAsync as s, discoverConfiguredPluginLoadPaths as t, buildBundledPluginLoadPathAliases as u, resolveImmutableInstallIdentity as v, resolvePluginCandidateInstallOwner as y };