UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

508 lines (507 loc) • 23.2 kB
import { l as normalizeOptionalString } from "./string-coerce-CCIiB4H7.mjs"; import { c as resolveUserPath } from "./home-dir-EKmgmdPG.mjs"; import { l as isRecord } from "./record-coerce-CVPuDqcc.mjs"; import { a as normalizeWindowsPathForComparison } from "./path-guards-TIjxtj6H.mjs"; import { p as shortenHomePath } from "./utils-C8YECn2Q.mjs"; import { n as groupPluginRecords } from "./record-groups-DII71OvH.mjs"; import { t as formatCliCommand } from "./command-format-CqdwUgPk.mjs"; import { f as normalizeBundledLookupPath } from "./discovery-DvJYrQFY.mjs"; import { b as retirePluginCache, i as createPluginCache, w as withPluginCache } from "./plugin-cache-B_eRuqTM.mjs"; import { a as loadInstalledPluginIndex } from "./installed-plugin-index-DYqse_gE.mjs"; import { u as tryReadJsonObjectSync } from "./json-files-Cb1h8pYs.mjs"; import { i as copyPluginInstallRecordMap, u as setPluginInstallRecordMapEntry } from "./installed-plugin-index-row-CdwQuK63.mjs"; import { a as isExternallyDistributedPlugin } from "./official-external-plugin-catalog-DtkWz1Xo.mjs"; import { n as resolveInstalledPluginIndexStateDatabaseOptions, r as resolveInstalledPluginIndexStorePath } from "./installed-plugin-index-store-path-VYnur1Rc.mjs"; import { r as inspectPersistedInstalledPluginIndexInstallRecordsSync } from "./installed-plugin-index-record-state-euCqi7PU.mjs"; import { a as markRetainedManagedNpmInstall, i as hasRetainedManagedNpmInstallMarker } from "./managed-npm-retention-1zEp6KL9.mjs"; import { i as loadInstalledPluginIndexInstallRecordsSync, n as listRecoveredManagedNpmInstallCandidates, o as clearLoadInstalledPluginIndexInstallRecordsCache, r as loadInstalledPluginIndexInstallRecords } from "./installed-plugin-index-record-reader-B-7uGQZ9.mjs"; import { a as resolveTrustedOfficialClawHubPackageName, i as isTrustedOfficialPluginInstallRecord, o as resolveTrustedSourceLinkedOfficialClawHubInstall } from "./official-external-install-records-DHqBi8wk.mjs"; import { a as resolveInstalledManifestRegistryIndexFingerprint } from "./plugin-control-plane-context-BmY6xICT.mjs"; import { t as preservePluginSourceAdmissions } from "./installed-plugin-index-source-admissions-Dc9OUryQ.mjs"; import { r as readPersistedInstalledPluginIndexSync } from "./installed-plugin-index-store-fgfm3NWB.mjs"; import { s as resolveControlPlaneRegistryParams } from "./plugin-registry-snapshot-CcrTrj6P.mjs"; import { n as writeJsonTarget } from "./json-file-Dp3xU7Al.mjs"; import { o as withPluginLifecycleLease } from "./plugin-lifecycle-lease-CXjHGDEI.mjs"; import { s as writePersistedInstalledPluginIndex } from "./installed-plugin-index-store-write-D9fWnpon.mjs"; import { i as withoutPluginInstallRecords, n as removePluginInstallRecordFromRecords } from "./installed-plugin-index-records-MNCNSlg8.mjs"; import { a as resolveBundledPluginSources } from "./bundled-sources-CIS6N5EC.mjs"; import { t as note } from "./note-CnLgHvug.mjs"; import { n as maybeRepairPluginOpenClawHostLinks, r as resolveDoctorPluginNpmRoots, t as listPluginOpenClawHostLinkIssues } from "./doctor-plugin-host-links-DL8L-gHX.mjs"; import { t as refreshPluginRegistry } from "./plugin-registry-refresh-CTdSIjgO.mjs"; import { t as normalizeOptionalTrimmedStringRecord } from "./collection-input-CE0ascdi.mjs"; import fs from "node:fs"; import path from "node:path"; import { isDeepStrictEqual } from "node:util"; //#region src/plugins/stale-local-bundled-plugin-install-records.ts function normalizePathForCompare(e, t) { return path.resolve(normalizeBundledLookupPath(resolveUserPath(e, t))); } function primaryInstallRecordPath(e) { if (typeof e.installPath === "string" && e.installPath.trim()) return e.installPath; if (typeof e.sourcePath === "string" && e.sourcePath.trim()) return e.sourcePath; return null; } function looksLikeCompiledBundledPluginPath(e, t) { const n = normalizeBundledLookupPath(e).split(/[\\/]+/u); return n.some((e, r) => { return (e === "dist" || e === "dist-runtime") && n[r + 1] === "extensions" && n[r + 2] === t; }); } function hasStaleBundledVersion(e, t) { const n = e.version?.trim(); const r = t.version?.trim(); return Boolean(n && r && n !== r); } /** Lists path install records that still point at stale compiled bundled plugin output. */ function listStaleLocalBundledPluginInstallRecords(e) { const t = e.bundled ?? resolveBundledPluginSources({ workspaceDir: e.workspaceDir, env: e.env }); const n = []; for (const [r, i] of Object.entries(e.installRecords).toSorted(([e], [t]) => e.localeCompare(t))) { if (i.source !== "path") continue; const a = t.get(r); if (!a?.localPath) continue; if (!hasStaleBundledVersion(i, a)) continue; const o = primaryInstallRecordPath(i); if (!o) continue; const s = normalizePathForCompare(o, e.env); const c = normalizePathForCompare(a.localPath, e.env); if (s === c) continue; if (!looksLikeCompiledBundledPluginPath(s, r)) continue; n.push({ pluginId: r, record: i, stalePath: s, bundledPath: c }); } return n; } /** Removes stale compiled bundled plugin path records from an install record map. */ function pruneStaleLocalBundledPluginInstallRecords(e) { const t = listStaleLocalBundledPluginInstallRecords(e); if (t.length === 0) return { records: e.installRecords, stale: t }; const n = new Set(t.map((e) => e.pluginId)); return { records: Object.fromEntries(Object.entries(e.installRecords).filter(([e]) => !n.has(e))), stale: t }; } //#endregion //#region src/commands/doctor/shared/plugin-registry-migration.ts /** Backfill shipped ClawHub authority only from a catalog-bound legacy install record. */ function migrateOfficialPluginInstallProvenance(e) { const t = copyPluginInstallRecordMap(e); for (const [n, r] of Object.entries(e)) { if (r.source !== "clawhub" || r.clawhubUrl !== void 0 || r.clawhubChannel !== void 0 || r.sourcePath !== void 0 || !resolveTrustedSourceLinkedOfficialClawHubInstall({ pluginId: n, record: r })) continue; const e = { ...r, clawhubUrl: "https://clawhub.ai", clawhubChannel: "official" }; const i = resolveTrustedOfficialClawHubPackageName(e); if (isTrustedOfficialPluginInstallRecord({ pluginId: n, packageName: i, record: e })) setPluginInstallRecordMapEntry(t, n, e); } return t; } var InvalidPluginInstallRecordStateError = class extends Error {}; function preflightPluginRegistryDoctorMigration(e = {}) { const t = resolveInstalledPluginIndexStorePath(e); const n = inspectPersistedInstalledPluginIndexInstallRecordsSync(e); if (n.status === "invalid") throw new InvalidPluginInstallRecordStateError(`Persisted plugin install records are invalid at ${t}. Stop the Gateway, back up this database, delete only the config_machine_state row with state_key='plugins.installedIndex' using SQLite tooling, then rerun \`openclaw doctor --fix\` to rebuild it.`); if (fs.existsSync(t)) { const r = readPersistedInstalledPluginIndexSync(e); if (r) return { /** Migration action selected before reading or writing registry state. */ action: "skip-existing", /** Persisted plugin index path that migration will inspect or write. */ filePath: t, /** Authoritative pre-repair generation used to detect a real inventory change. */ current: r }; if (n.status !== "missing") return { action: "migrate", filePath: t }; } return { action: "initialize", filePath: t }; } //#endregion //#region src/commands/doctor-plugin-registry.ts const PLUGIN_REGISTRY_CHECK_ID = "core/doctor/plugin-registry"; function normalizeManagedInstallPath(e) { const t = path.resolve(e); return process.platform === "win32" ? normalizeWindowsPathForComparison(t) : t; } async function listStaleManagedNpmInstallGenerations(e) { const t = await loadInstalledPluginIndexInstallRecords(e); const n = listRecoveredManagedNpmInstallCandidates(e); const r = groupPluginRecords(n, (e) => e.pluginId); const i = []; for (const [e, n] of r) { const r = t[e]; if (r?.source !== "npm" || !r.installPath) continue; const a = normalizeManagedInstallPath(r.installPath); if (!n.find((e) => e.installRecord.installPath && normalizeManagedInstallPath(e.installRecord.installPath) === a)) continue; for (const t of n) { const n = t.installRecord.installPath; if (!n || normalizeManagedInstallPath(n) === a) continue; i.push({ kind: "stale-managed-npm-install-generation", pluginId: e, packageDir: n, ...t.installRecord.resolvedVersion ? { version: t.installRecord.resolvedVersion } : {} }); } } return i.toSorted((e, t) => e.packageDir.localeCompare(t.packageDir)); } /** Marks non-authoritative managed npm trees for safe cleanup after gateway shutdown. */ async function maybeRepairStaleManagedNpmInstallGenerations(e) { const t = await listStaleManagedNpmInstallGenerations(e); if (t.length === 0) return; const formatGeneration = (e) => `- ${e.pluginId}: ${shortenHomePath(e.packageDir)}${e.version ? ` (${e.version})` : ""}`; if (!e.prompter.shouldRepair) { note([ "Managed npm plugin installs have stale non-authoritative generations:", ...t.map(formatGeneration), `Repair with ${formatCliCommand("openclaw doctor --fix")} to retire stale generations after the gateway restarts.` ].join("\n"), "Plugin registry"); return; } const n = []; for (const e of t) if (await markRetainedManagedNpmInstall({ packageDir: e.packageDir, pluginId: e.pluginId, reason: "doctor-repaired-stale-managed-npm-generation" })) n.push(e); if (n.length === 0) return; clearLoadInstalledPluginIndexInstallRecordsCache(); note(["Retired stale managed npm plugin generation(s); they will be pruned after the gateway restarts:", ...n.map(formatGeneration)].join("\n"), "Plugin registry"); } function readStringMap(e) { return (isRecord(e) ? normalizeOptionalTrimmedStringRecord(e) : void 0) ?? {}; } function deleteObjectKey(e, t) { if (!Object.hasOwn(e, t)) return false; delete e[t]; return true; } function listStaleManagedNpmBundledPlugins(e) { const t = loadInstalledPluginIndex({ ...e, installRecords: {} }).plugins.filter((e) => e.origin === "bundled" && !isExternallyDistributedPlugin(e)); const n = new Map(t.map((e) => [e.packageName, e])); const r = []; for (const t of resolveDoctorPluginNpmRoots(e)) { const e = path.join(t, "package.json"); const i = readStringMap(tryReadJsonObjectSync(e)?.dependencies); for (const e of Object.keys(i).toSorted((e, t) => e.localeCompare(t))) { if (!e.startsWith("@openclaw/")) continue; const i = n.get(e); if (!i) continue; const a = path.join(t, "node_modules", ...e.split("/")); if (hasRetainedManagedNpmInstallMarker(a)) continue; const o = normalizeOptionalString(tryReadJsonObjectSync(path.join(a, "openclaw.plugin.json"))?.id); if (!o || o !== i.pluginId) continue; const s = normalizeOptionalString(tryReadJsonObjectSync(path.join(a, "package.json"))?.version); r.push({ pluginId: o, packageName: e, packageDir: a, npmRoot: t, ...s ? { version: s } : {} }); } } return r; } function loadCurrentBundledPluginSources(e) { const t = loadInstalledPluginIndex({ ...e, installRecords: {} }).plugins.filter((e) => e.origin === "bundled"); return new Map(t.map((e) => [e.pluginId, { pluginId: e.pluginId, localPath: e.rootDir, ...e.packageName ? { npmSpec: e.packageName } : {}, ...e.packageVersion ? { version: e.packageVersion } : {} }])); } async function listStaleLocalBundledPluginInstallRecordShadows(e) { return listStaleLocalBundledPluginInstallRecords({ installRecords: await loadInstalledPluginIndexInstallRecords(e), workspaceDir: e.workspaceDir, env: e.env, bundled: loadCurrentBundledPluginSources(e) }); } function removeManagedNpmDependency(e) { const t = path.join(e.npmRoot, "package.json"); const n = tryReadJsonObjectSync(t) ?? {}; const r = readStringMap(n.dependencies); delete r[e.packageName]; if (Object.keys(r).length === 0) delete n.dependencies; else n.dependencies = r; writeJsonTarget(t, n); removeManagedNpmPackageLockDependency(e); fs.rmSync(e.packageDir, { recursive: true, force: true }); const i = path.dirname(e.packageDir); if (path.basename(path.dirname(i)) === "node_modules") try { fs.rmdirSync(i); } catch {} } function removeManagedNpmPackageLockDependency(e) { const t = path.join(e.npmRoot, "package-lock.json"); const n = tryReadJsonObjectSync(t); if (!n) return; let r = false; const i = n.packages; if (isRecord(i)) { const t = i[""]; if (isRecord(t)) { const n = readStringMap(t.dependencies); if (deleteObjectKey(n, e.packageName)) { r = true; if (Object.keys(n).length === 0) delete t.dependencies; else t.dependencies = n; } } r = deleteObjectKey(i, `node_modules/${e.packageName}`) || r; } const a = n.dependencies; if (isRecord(a)) r = deleteObjectKey(a, e.packageName) || r; if (r) writeJsonTarget(t, n); } /** Removes managed npm packages that shadow current bundled plugins when repair is enabled. */ function maybeRepairStaleManagedNpmBundledPlugins(e) { const t = listStaleManagedNpmBundledPlugins(e); if (t.length === 0) return null; const n = t.map((e) => `- ${e.pluginId}: ${e.packageName}${e.version ? `@${e.version}` : ""}`); if (!e.prompter.shouldRepair) { note([ "Managed npm plugin packages shadow bundled plugins:", ...n, `Repair with ${formatCliCommand("openclaw doctor --fix")} to remove stale managed npm packages and rebuild the plugin registry.` ].join("\n"), "Plugin registry"); return null; } let r = e.installRecords ?? loadInstalledPluginIndexInstallRecordsSync(e); const i = [...new Set(t.map((e) => e.pluginId))].toSorted((e, t) => e.localeCompare(t)); for (const e of i) r = removePluginInstallRecordFromRecords(r, e); for (const e of t) removeManagedNpmDependency(e); note(["Removed stale managed npm plugin package(s) shadowing bundled plugins:", ...n].join("\n"), "Plugin registry"); return { installRecords: r, removedPluginIds: i }; } /** Removes local install records that shadow current bundled plugin sources. */ async function maybeRepairStaleLocalBundledPluginInstallRecords(e) { const t = await listStaleLocalBundledPluginInstallRecordShadows(e); if (t.length === 0) return []; const n = e.prompter.shouldRepair; note([ n ? "Removed stale local bundled plugin install record(s) shadowing bundled plugins:" : "Local bundled plugin install records shadow bundled plugins:", ...t.map((e) => `- ${e.pluginId}: ${shortenHomePath(e.stalePath)}`), ...!n ? [`Repair with ${formatCliCommand("openclaw doctor --fix")} to remove stale local install records and rebuild the plugin registry.`] : [] ].join("\n"), "Plugin registry"); return n ? t.map((e) => e.pluginId) : []; } async function loadRepairedPluginInstallRecords(e, t, n) { let r = n ?? await loadInstalledPluginIndexInstallRecords(e); for (const e of t) r = removePluginInstallRecordFromRecords(r, e); return migrateOfficialPluginInstallProvenance(r); } async function detectPluginRegistryHealthIssues(e) { const t = preflightPluginRegistryDoctorMigration(e); const n = []; if (t.action === "migrate") n.push({ kind: "registry-missing-or-stale", path: t.filePath }); for (const t of listStaleManagedNpmBundledPlugins(e)) n.push({ kind: "stale-managed-npm-bundled-plugin", ...t }); for (const t of await listStaleLocalBundledPluginInstallRecordShadows(e)) n.push({ kind: "stale-local-bundled-plugin-install-record", pluginId: t.pluginId, stalePath: t.stalePath }); n.push(...await listStaleManagedNpmInstallGenerations(e)); const r = await listPluginOpenClawHostLinkIssues(e); for (const e of r.peerLinkIssues) n.push({ kind: "managed-npm-openclaw-peer-link", ...e }); for (const e of r.packageReadFailures) n.push({ kind: "managed-npm-package-unreadable", ...e }); for (const e of r.registeredPeerLinkIssues) n.push({ kind: "registered-npm-openclaw-host-link", ...e }); for (const e of r.registeredPackageReadFailures) n.push({ kind: "registered-npm-package-unreadable", ...e }); return n; } function pluginRegistryIssueToHealthFinding(e) { const finding = (e, t, n, r) => ({ checkId: PLUGIN_REGISTRY_CHECK_ID, severity: "warning", message: e, path: t, ...r === void 0 ? {} : { target: r }, fixHint: n }); switch (e.kind) { case "registry-missing-or-stale": return finding("Persisted plugin registry is missing or stale.", e.path, "Run `openclaw doctor --fix` to rebuild the plugin registry from enabled plugins."); case "stale-managed-npm-bundled-plugin": return finding(`Managed npm package ${e.packageName}${e.version ? `@${e.version}` : ""} shadows bundled plugin ${e.pluginId}.`, e.packageDir, "Run `openclaw doctor --fix` to remove stale managed npm packages and rebuild the plugin registry.", e.pluginId); case "stale-local-bundled-plugin-install-record": return finding(`Local install record for bundled plugin ${e.pluginId} points at a stale path.`, e.stalePath, "Run `openclaw doctor --fix` to remove stale local install records and rebuild the plugin registry.", e.pluginId); case "managed-npm-openclaw-peer-link": return finding(`Managed npm package ${e.packageName} has a broken OpenClaw peer link: ${e.reason}.`, e.packageDir, "Run `openclaw doctor --fix` to relink managed npm plugin packages.", e.packageName); case "registered-npm-openclaw-host-link": return finding(`Registered plugin ${e.packageName} has a broken OpenClaw host link: ${e.reason}.`, e.packageDir, "Run `openclaw doctor --fix` to relink the installed plugin package.", e.packageName); case "managed-npm-package-unreadable": case "registered-npm-package-unreadable": return finding(`${e.kind === "managed-npm-package-unreadable" ? "Managed npm" : "Registered plugin"} package could not be inspected: ${e.reason}.`, e.packageDir, "Restore access to the package files, then run `openclaw doctor` again."); default: return { checkId: PLUGIN_REGISTRY_CHECK_ID, severity: "warning", category: "recommended", docsUrl: "https://docs.openclaw.ai/cli/doctor/checks", message: `Managed npm plugin ${e.pluginId}${e.version ? `@${e.version}` : ""} is a stale non-authoritative generation.`, path: e.packageDir, target: e.pluginId, fixHint: "Run `openclaw doctor --fix` to retire the stale generation for pruning after the gateway restarts." }; } } function pluginRegistryIssueToRepairEffect(e) { const effect = (e, t, n) => ({ kind: e, action: t, target: n, dryRunSafe: false }); switch (e.kind) { case "registry-missing-or-stale": return effect("state", "would-rebuild-plugin-registry", e.path); case "stale-managed-npm-bundled-plugin": return effect("package", "would-remove-stale-managed-npm-bundled-plugin", e.packageDir); case "stale-local-bundled-plugin-install-record": return effect("state", "would-remove-stale-local-bundled-plugin-install-record", e.pluginId); case "managed-npm-openclaw-peer-link": return effect("package", "would-relink-managed-npm-openclaw-peer", e.packageDir); case "registered-npm-openclaw-host-link": return effect("package", "would-relink-registered-npm-openclaw-host", e.packageDir); case "managed-npm-package-unreadable": return effect("package", "requires-managed-npm-package-readability-repair", e.packageDir); case "registered-npm-package-unreadable": return effect("package", "requires-registered-npm-package-readability-repair", e.packageDir); default: return { kind: "package", action: "would-retire-stale-managed-npm-install-generation", target: e.packageDir, dryRunSafe: false }; } } /** * Runs plugin registry doctor repairs and refreshes the persisted plugin index when needed. * * Stale bundled shadows are removed before registry migration so the rebuilt index resolves the * current bundled source instead of an obsolete managed/local install record. */ async function maybeRepairPluginRegistryState(e) { const t = resolveControlPlaneRegistryParams(e); const readPreflight = () => { try { return preflightPluginRegistryDoctorMigration(t); } catch (e) { if (!(e instanceof InvalidPluginInstallRecordStateError)) throw e; note(e.message, "Plugin registry"); return; } }; const n = readPreflight(); if (!n) return { config: t.config }; if (!t.prompter.shouldRepair) return await inspectOrRepairPluginRegistryState(t, n); const r = createPluginCache(); try { if (await withPluginCache(r, async () => { const e = readPreflight(); if (e?.action !== "skip-existing") return false; const n = loadInstalledPluginIndex({ ...t, config: withoutPluginInstallRecords(t.config), installRecords: await loadRepairedPluginInstallRecords(t, []) }); preservePluginSourceAdmissions(e.current, n); return isDeepStrictEqual(e.current, { ...n, generatedAtMs: e.current.generatedAtMs, refreshReason: e.current.refreshReason }) && (await detectPluginRegistryHealthIssues(t)).length === 0; })) return { config: t.config }; } finally { await retirePluginCache(r); } return await withPluginLifecycleLease(resolveInstalledPluginIndexStateDatabaseOptions(t), async () => { const e = readPreflight(); return e ? inspectOrRepairPluginRegistryState(t, e) : { config: t.config }; }); } async function inspectOrRepairPluginRegistryState(e, t) { clearLoadInstalledPluginIndexInstallRecordsCache(); const n = maybeRepairStaleManagedNpmBundledPlugins(e); const r = await maybeRepairStaleLocalBundledPluginInstallRecords(e); await maybeRepairStaleManagedNpmInstallGenerations(e); const i = await maybeRepairPluginOpenClawHostLinks(e); const a = [.../* @__PURE__ */ new Set([...n?.removedPluginIds ?? [], ...r])]; if (!e.prompter.shouldRepair) { if (t.action === "migrate") note(["Persisted plugin registry is missing or stale.", `Repair with ${formatCliCommand("openclaw doctor --fix")} to rebuild ${shortenHomePath(t.filePath)} from enabled plugins.`].join("\n"), "Plugin registry"); return { config: e.config }; } const o = await loadRepairedPluginInstallRecords(e, a, n?.installRecords); let s; const c = t.action !== "skip-existing"; if (c) { s = { ...loadInstalledPluginIndex({ ...e, config: withoutPluginInstallRecords(e.config), installRecords: o }), refreshReason: "migration" }; await writePersistedInstalledPluginIndex(s, e); } else s = await refreshPluginRegistry({ ...e, reason: "migration", installRecords: o }); const l = s.plugins.length; const u = s.plugins.filter((e) => e.enabled).length; note(`Plugin registry ${c ? "rebuilt" : "refreshed"}: ${u}/${l} enabled plugins indexed.`, "Plugin registry"); const d = t.action !== "skip-existing" || resolveInstalledManifestRegistryIndexFingerprint(t.current) !== resolveInstalledManifestRegistryIndexFingerprint(s) || i; return { config: e.config, ...d ? { pluginInventoryChanged: true } : {} }; } //#endregion export { pluginRegistryIssueToRepairEffect as a, pluginRegistryIssueToHealthFinding as i, maybeRepairPluginRegistryState as n, pruneStaleLocalBundledPluginInstallRecords as o, maybeRepairStaleManagedNpmBundledPlugins as r, detectPluginRegistryHealthIssues as t };