openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
11 lines • 18 kB
JavaScript
import{l as normalizeOptionalString}from"./string-coerce-CpTFcSwY.mjs";import{l as isRecord}from"./record-coerce-BTbqdJ3-.mjs";import{b as retirePluginCache,i as createPluginCache,w as withPluginCache}from"./plugin-cache-B6QVpzXr.mjs";import{a as normalizeWindowsPathForComparison}from"./path-guards-DGttsOJI.mjs";import{f as shortenHomePath}from"./utils-Dlk0IYAa.mjs";import{n as groupPluginRecords}from"./record-groups-BlmybP6F.mjs";import{t as formatCliCommand}from"./command-format-D7KhNLP0.mjs";import{a as loadInstalledPluginIndex}from"./installed-plugin-index-B04a42mO.mjs";import{u as tryReadJsonObjectSync}from"./json-files-BBQ_0Np0.mjs";import{n as resolveInstalledPluginIndexStateDatabaseOptions,r as resolveInstalledPluginIndexStorePath}from"./installed-plugin-index-store-path-Bf4Iuysu.mjs";import{a as hasRetainedManagedNpmInstallMarker,o as markRetainedManagedNpmInstall}from"./managed-npm-retention-Bx6UJx__.mjs";import{s as setPluginInstallRecordMapEntry,t as copyPluginInstallRecordMap}from"./plugin-install-record-map-BULaY3LO.mjs";import{a as isExternallyDistributedPlugin}from"./official-external-plugin-catalog-BkSwu5lo.mjs";import{r as inspectPersistedInstalledPluginIndexInstallRecordsSync}from"./installed-plugin-index-record-state-Dlesa-xK.mjs";import{i as loadInstalledPluginIndexInstallRecordsSync,n as listRecoveredManagedNpmInstallCandidates,o as clearLoadInstalledPluginIndexInstallRecordsCache,r as loadInstalledPluginIndexInstallRecords}from"./installed-plugin-index-record-reader-rJXlMUQ8.mjs";import{a as resolveTrustedOfficialClawHubPackageName,i as isTrustedOfficialPluginInstallRecord,o as resolveTrustedSourceLinkedOfficialClawHubInstall}from"./official-external-install-records-CVYKmVDj.mjs";import{a as resolveInstalledManifestRegistryIndexFingerprint}from"./plugin-control-plane-context-CfwJGrnQ.mjs";import{t as preservePluginSourceAdmissions}from"./installed-plugin-index-source-admissions-Dj2tY3HV.mjs";import{i as readPersistedInstalledPluginIndexSync}from"./installed-plugin-index-store-CP6OETa6.mjs";import{s as resolveControlPlaneRegistryParams}from"./plugin-registry-snapshot-Dz_L4M3w.mjs";import{n as writeJsonTarget}from"./json-file-BedClo2t.mjs";import{u as writePersistedInstalledPluginIndex}from"./installed-plugin-index-store-write-DPCvm0PK.mjs";import{o as withPluginLifecycleLease}from"./plugin-lifecycle-lease-D-y0xYkr.mjs";import{i as withoutPluginInstallRecords,n as removePluginInstallRecordFromRecords}from"./installed-plugin-index-records-DMOoWiOF.mjs";import{t as note}from"./note-e4DtVgg2.mjs";import{n as maybeRepairPluginOpenClawHostLinks,r as resolveDoctorPluginNpmRoots,t as listPluginOpenClawHostLinkIssues}from"./doctor-plugin-host-links-MZ1M5dzL.mjs";import{t as refreshPluginRegistry}from"./plugin-registry-refresh-C4RPWF_Q.mjs";import{t as listStaleLocalBundledPluginInstallRecords}from"./stale-local-bundled-plugin-install-records-D17Iw79n.mjs";import{t as normalizeOptionalTrimmedStringRecord}from"./collection-input-COwEwR-1.mjs";import fs from"node:fs";import path from"node:path";import{isDeepStrictEqual}from"node:util";
//!src/commands/doctor/shared/plugin-registry-migration.ts
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{action:`skip-existing`,filePath:t,current:r};if(n.status!==`missing`)return{action:`migrate`,filePath:t}}return{action:`initialize`,filePath:t}}
//!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))}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(`
`),`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(`
`),`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)}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(`
`),`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(`
`),`Plugin registry`);return{installRecords:r,removedPluginIds:i}}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(`
`),`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}}}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(`
`),`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}:{}}}export{pluginRegistryIssueToRepairEffect as a,pluginRegistryIssueToHealthFinding as i,maybeRepairPluginRegistryState as n,maybeRepairStaleManagedNpmBundledPlugins as r,detectPluginRegistryHealthIssues as t};