openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
286 lines (285 loc) • 13.1 kB
JavaScript
import { l as isRecord } from "./record-coerce-CVPuDqcc.mjs";
import { t as isBlockedObjectKey } from "./prototype-keys-CLGi5xDj.mjs";
import { a as normalizeWindowsPathForComparison$1, n as isNotFoundPathError$1 } from "./path-guards-TIjxtj6H.mjs";
import { n as groupPluginRecords } from "./record-groups-DII71OvH.mjs";
import { a as getPluginCache, d as getProcessPluginCache } from "./plugin-cache-B_eRuqTM.mjs";
import { n as compareValidSemver } from "./semver-DUtldgR6.mjs";
import { r as cloneEnvWithPlatformSemantics } from "./config-env-vars-ByeGN-9N.mjs";
import { m as validatePluginId, p as resolvePluginNpmProjectsDir, r as isPluginNpmProjectDir, s as resolveDefaultPluginNpmDir } from "./install-paths-Bwm0P5EG.mjs";
import { u as tryReadJsonObjectSync } from "./json-files-Cb1h8pYs.mjs";
import { a as createPluginInstallRecordMap, i as copyPluginInstallRecordMap, o as getPluginInstallRecordMapEntry, u as setPluginInstallRecordMapEntry } from "./installed-plugin-index-row-CdwQuK63.mjs";
import { a as isPrereleaseResolutionAllowed, s as parseRegistryNpmSpec } from "./npm-registry-spec-HKkAvl6N.mjs";
import { r as resolveInstalledPluginIndexStorePath } from "./installed-plugin-index-store-path-VYnur1Rc.mjs";
import { i as preparePersistedInstalledPluginIndexCacheEntry, n as inspectPersistedInstalledPluginIndexInstallRecords, r as inspectPersistedInstalledPluginIndexInstallRecordsSync } from "./installed-plugin-index-record-state-euCqi7PU.mjs";
import { i as hasRetainedManagedNpmInstallMarker, l as listManagedPluginNpmProjectsSync, s as resolveRetainedManagedNpmInstallPackageInfo } from "./managed-npm-retention-1zEp6KL9.mjs";
import fs from "node:fs";
import path from "node:path";
import { safeStatSync } from "@openclaw/fs-safe/path";
//#region src/plugins/installed-plugin-index-record-cache.ts
/** Explicit ledger writes/reloads leave the Gateway's embedded boot snapshot unchanged. */
function clearLoadInstalledPluginIndexInstallRecordsCache() {
for (const e of /* @__PURE__ */ new Set([getPluginCache(), getProcessPluginCache()])) {
e.installRecords.clear();
e.persistedInstalledIndex.clear();
}
}
//#endregion
//#region src/plugins/installed-plugin-index-record-reader.ts
/** Reads installed-index records back into manifest registry records. */
function readStringRecord(e) {
if (!isRecord(e)) return {};
const t = {};
for (const [n, r] of Object.entries(e).toSorted(([e], [t]) => e.localeCompare(t))) {
if (isBlockedObjectKey(n)) continue;
if (typeof r === "string" && r.trim()) t[n] = r.trim();
}
return t;
}
function hasPackagePluginMetadata(e) {
const t = e.openclaw;
if (!isRecord(t)) return false;
const n = t.extensions;
return Array.isArray(n) && n.some((e) => typeof e === "string");
}
function readManifestPluginId(e) {
const t = tryReadJsonObjectSync(path.join(e, "openclaw.plugin.json"));
return (typeof t?.id === "string" ? t.id.trim() : "") || void 0;
}
function resolveRecoveredManagedNpmRoot(e = {}) {
return path.resolve(e.stateDir ? path.join(e.stateDir, "npm") : resolveDefaultPluginNpmDir(e.env));
}
function resolveRecoveredManagedNpmPluginId(e) {
const { packageManifest: t } = e;
if (!t || !hasPackagePluginMetadata(t)) return;
const n = typeof t.name === "string" && t.name.trim() ? t.name.trim() : e.packageName;
const r = readManifestPluginId(e.packageDir) ?? n;
return validatePluginId(r) ? void 0 : r;
}
function readManagedNpmInstallTimestampMs(e) {
const t = e.sharedLegacyRoot ? [e.packageDir] : [path.join(e.projectRoot, "package.json"), e.projectRoot];
for (const e of t) try {
return fs.statSync(e).mtimeMs;
} catch {}
return 0;
}
function buildRecoveredManagedNpmInstallCandidatesForRoot(e) {
const t = readStringRecord(e.rootManifest?.dependencies);
const n = [];
for (const [r, i] of Object.entries(t)) {
const t = path.join(e.projectRoot, "node_modules", ...r.split("/"));
if (!safeStatSync(t)?.isDirectory()) continue;
if (hasRetainedManagedNpmInstallMarker(t)) continue;
const a = tryReadJsonObjectSync(path.join(t, "package.json"));
const o = resolveRecoveredManagedNpmPluginId({
packageName: r,
packageDir: t,
packageManifest: a
});
if (!o) continue;
const s = typeof a?.version === "string" && a.version.trim() ? a.version.trim() : void 0;
n.push({
pluginId: o,
installTimestampMs: readManagedNpmInstallTimestampMs({
packageDir: t,
projectRoot: e.projectRoot,
sharedLegacyRoot: e.sharedLegacyRoot
}),
installRecord: {
source: "npm",
spec: `${r}@${i}`,
installPath: t,
...s ? {
version: s,
resolvedName: r,
resolvedVersion: s
} : {},
...s ? { resolvedSpec: `${r}@${s}` } : {}
}
});
}
return n;
}
/** Lists recoverable managed npm installs without assigning active precedence. */
function listRecoveredManagedNpmInstallCandidates(e = {}) {
const t = resolveRecoveredManagedNpmRoot(e);
return [...buildRecoveredManagedNpmInstallCandidatesForRoot({
projectRoot: t,
rootManifest: tryReadJsonObjectSync(path.join(t, "package.json")),
sharedLegacyRoot: true
}), ...listManagedPluginNpmProjectsSync(t).flatMap(({ projectRoot: e, manifest: t }) => buildRecoveredManagedNpmInstallCandidatesForRoot({
projectRoot: e,
rootManifest: t,
sharedLegacyRoot: false
}))];
}
function recordsShareInstallPath(e, t) {
if (!e?.installPath || !t.installPath) return false;
return normalizeInstallPathForComparison(e.installPath) === normalizeInstallPathForComparison(t.installPath);
}
function normalizeInstallPathForComparison(e) {
const t = path.resolve(e);
return process.platform === "win32" ? normalizeWindowsPathForComparison$1(t) : t;
}
function pickMostRecentRecoveredManagedNpmCandidate(e) {
return e.toSorted((e, t) => {
const n = t.installTimestampMs - e.installTimestampMs;
if (n !== 0) return n;
return (t.installRecord.installPath ?? "").localeCompare(e.installRecord.installPath ?? "");
})[0];
}
function emitManagedNpmRecoveryFallbackWarning(e) {
process.emitWarning(`Managed npm recovery found ${e.candidates.length} installs for plugin "${e.pluginId}" without an authoritative active path; selected the most recently installed candidate. Run \`openclaw doctor --fix\` to persist and retire stale generations.`, {
code: "OPENCLAW_PLUGIN_INSTALL_RECOVERY_FALLBACK",
type: "OpenClawPluginRecoveryWarning",
detail: JSON.stringify({
pluginId: e.pluginId,
selectedInstallPath: e.selected.installRecord.installPath,
candidates: e.candidates.map((e) => ({
installPath: e.installRecord.installPath,
installTimestampMs: e.installTimestampMs
}))
})
});
}
function buildRecoveredManagedNpmInstallRecords(e, t = {}) {
const n = resolveRecoveredManagedNpmRoot(t);
const r = createPluginInstallRecordMap();
const i = groupPluginRecords(listRecoveredManagedNpmInstallCandidates(t), (e) => e.pluginId);
for (const [t, a] of i) {
const i = getPluginInstallRecordMapEntry(e ?? void 0, t);
const o = a.find((e) => recordsShareInstallPath(i, e.installRecord));
const s = o ?? pickMostRecentRecoveredManagedNpmCandidate(a);
setPluginInstallRecordMapEntry(r, t, s.installRecord);
const c = isUnavailableManagedNpmInstallRecord({
npmRoot: n,
persisted: i,
recovered: s.installRecord
});
if (!o && a.length > 1 && (!i || c)) emitManagedNpmRecoveryFallbackWarning({
pluginId: t,
selected: s,
candidates: a
});
}
return r;
}
function readInstallRecordVersion(e) {
return e?.resolvedVersion ?? e?.version;
}
function isUnavailableManagedNpmInstallRecord(e) {
const t = e.persisted?.installPath;
if (e.persisted?.source !== "npm" || !t) return false;
try {
if (fs.statSync(t).isDirectory()) return false;
} catch (e) {
if (!isNotFoundPathError$1(e)) return false;
}
const n = resolveRetainedManagedNpmInstallPackageInfo(t);
if (!n || n.packageName !== e.recovered.resolvedName) return false;
const r = normalizeInstallPathForComparison(e.npmRoot);
return normalizeInstallPathForComparison(n.projectRoot) === r || normalizeInstallPathForComparison(path.dirname(n.projectRoot)) === normalizeInstallPathForComparison(resolvePluginNpmProjectsDir(e.npmRoot));
}
function mergeRecoveredManagedNpmMetadata(e, t, n = {}) {
const r = {
...e,
...t
};
if (n.preservePersistedSpec) {
const n = e.spec ? parseRegistryNpmSpec(e.spec) : null;
const i = n !== null && isPrereleaseResolutionAllowed({
spec: n,
resolvedVersion: t.resolvedVersion
}) && (n.selectorKind !== "exact-version" || n.selector !== void 0 && t.resolvedVersion !== void 0 && compareValidSemver(n.selector, t.resolvedVersion) === 0);
if (n?.name === t.resolvedName && i) r.spec = e.spec;
}
delete r.integrity;
delete r.shasum;
delete r.resolvedAt;
delete r.installedAt;
return r;
}
function isForeignManagedNpmInstallRecord(e) {
if (e.record?.source !== "npm") return false;
const t = e.record.installPath;
if (!t) return false;
const n = resolveRetainedManagedNpmInstallPackageInfo(t);
if (!n) return false;
const r = path.dirname(n.projectRoot);
if (path.basename(r) !== "projects") return false;
const i = path.dirname(r);
if (normalizeInstallPathForComparison(i) === normalizeInstallPathForComparison(e.npmRoot)) return false;
return isPluginNpmProjectDir({
packageName: n.packageName,
projectDir: n.projectRoot,
npmDir: i
});
}
/** Lists existing npm projects that could be copied managed state or external installs. */
function findForeignManagedNpmInstallRecordPluginIds(e, t) {
const n = resolveRecoveredManagedNpmRoot(t);
return Object.entries(e ?? {}).flatMap(([e, t]) => isForeignManagedNpmInstallRecord({
npmRoot: n,
record: t
}) ? [e] : []);
}
function mergeRecoveredManagedNpmRecord(e) {
if (e.persisted && isUnavailableManagedNpmInstallRecord(e)) return mergeRecoveredManagedNpmMetadata(e.persisted, e.recovered, { preservePersistedSpec: true });
const t = readInstallRecordVersion(e.persisted);
const n = readInstallRecordVersion(e.recovered);
if (e.persisted?.source === "npm" && recordsShareInstallPath(e.persisted, e.recovered) && n && t !== n) return mergeRecoveredManagedNpmMetadata(e.persisted, e.recovered);
return e.persisted ?? e.recovered;
}
/** Merges persisted records with managed npm installs recovered from the current root. */
function mergeRecoveredManagedNpmInstallRecords(e, t) {
const n = resolveRecoveredManagedNpmRoot(t);
const r = buildRecoveredManagedNpmInstallRecords(e, t);
const i = copyPluginInstallRecordMap(e ?? void 0);
for (const [e, t] of Object.entries(r)) setPluginInstallRecordMapEntry(i, e, mergeRecoveredManagedNpmRecord({
npmRoot: n,
persisted: getPluginInstallRecordMapEntry(i, e),
recovered: t
}));
return i;
}
/** Read the committed install ledger through its worker-backed metadata owner. */
async function readPersistedInstalledPluginIndexInstallRecordsAsync(e = {}) {
const t = await preparePersistedInstalledPluginIndexCacheEntry(e);
const n = inspectPersistedInstalledPluginIndexInstallRecords(t.entry);
return n.status === "valid" ? copyPluginInstallRecordMap(n.records) : null;
}
function requireLoadablePluginInstallRecordState(e) {
if (e.status === "invalid") throw new Error("Persisted plugin install records are invalid. Run openclaw doctor to inspect and repair plugin installation state.");
return e.status === "valid" ? e.records : null;
}
function resolveInstallRecordsCacheKey(e) {
return [path.resolve(resolveInstalledPluginIndexStorePath(e)), resolveRecoveredManagedNpmRoot(e)].join("\0");
}
/** Loads installed plugin records, recovering managed npm installs and caching the result. */
async function loadInstalledPluginIndexInstallRecords(e = {}) {
const t = {
...e,
env: cloneEnvWithPlatformSemantics(e.env ?? process.env)
};
const n = resolveInstallRecordsCacheKey(t);
const r = getPluginCache().installRecords;
const i = r.get(n);
if (i) return copyPluginInstallRecordMap(i);
const a = await preparePersistedInstalledPluginIndexCacheEntry(t);
a.assertCurrent();
const o = mergeRecoveredManagedNpmInstallRecords(requireLoadablePluginInstallRecordState(inspectPersistedInstalledPluginIndexInstallRecords(a.entry)), t);
a.assertCurrent();
r.set(n, o);
return copyPluginInstallRecordMap(o);
}
/** Synchronously loads installed plugin records, recovering managed npm installs and caching them. */
function loadInstalledPluginIndexInstallRecordsSync(e = {}) {
const t = resolveInstallRecordsCacheKey(e);
const n = getPluginCache().installRecords;
const r = n.get(t);
if (r) return copyPluginInstallRecordMap(r);
const i = mergeRecoveredManagedNpmInstallRecords(requireLoadablePluginInstallRecordState(inspectPersistedInstalledPluginIndexInstallRecordsSync(e)), e);
n.set(t, i);
return copyPluginInstallRecordMap(i);
}
//#endregion
export { readPersistedInstalledPluginIndexInstallRecordsAsync as a, loadInstalledPluginIndexInstallRecordsSync as i, listRecoveredManagedNpmInstallCandidates as n, clearLoadInstalledPluginIndexInstallRecordsCache as o, loadInstalledPluginIndexInstallRecords as r, findForeignManagedNpmInstallRecordPluginIds as t };