openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
742 lines (741 loc) • 30.2 kB
JavaScript
import { c as resolveUserPath } from "./home-dir-EKmgmdPG.mjs";
import { m as normalizeTrimmedStringList } from "./string-normalization-DLmfYZXI.mjs";
import { i as stripAnsi } from "./ansi-CZa2t0Hf.mjs";
import { n as sanitizeTerminalText } from "./safe-text-C80HAQ2e.mjs";
import "./utils-C8YECn2Q.mjs";
import { t as formatCliCommand } from "./command-format-CqdwUgPk.mjs";
import { b as retirePluginCache, i as createPluginCache, w as withPluginCache } from "./plugin-cache-B_eRuqTM.mjs";
import { a as resolveCompatibilityHostVersion } from "./version-GlxUMdxI.mjs";
import { f as resolveEffectiveEnableState, u as normalizePluginsConfig } from "./config-state-B1JlHgba.mjs";
import { n as hashStableJson } from "./installed-plugin-index-hash-BfBbMPjv.mjs";
import { b as resolveInstalledPluginIndexPolicyHash } from "./installed-plugin-index-DYqse_gE.mjs";
import { a as resolveDefaultPluginExtensionsDir, c as resolvePluginInstallDir, d as resolvePluginNpmPackageDir, s as resolveDefaultPluginNpmDir } from "./install-paths-Bwm0P5EG.mjs";
import { A as resolvePluginInstallSources, C as NpmChannelResolutionError, D as resolveClawHubInstallSpecsForUpdateChannel, M as parseClawHubPluginSpec, T as installWithSourceFallback, k as resolveNpmInstallSpecsForUpdateChannel, w as installWithChannelFallback } from "./official-external-plugin-catalog-DtkWz1Xo.mjs";
import { s as parseRegistryNpmSpec, t as buildNpmResolutionFields } from "./npm-registry-spec-HKkAvl6N.mjs";
import { a as markRetainedManagedNpmInstall, i as hasRetainedManagedNpmInstallMarker, n as clearRetainedManagedNpmInstallMarker } from "./managed-npm-retention-1zEp6KL9.mjs";
import { r as isUnavailableClawHubTarget } from "./clawhub-error-codes-5kIjtf6h.mjs";
import { n as isUnavailableNpmTarget, t as PLUGIN_INSTALL_ERROR_CODE } from "./install-types-BBbGKapR.mjs";
import { o as resolveTrustedSourceLinkedOfficialClawHubInstall } from "./official-external-install-records-DHqBi8wk.mjs";
import { n as readPersistedInstalledPluginIndex } from "./installed-plugin-index-store-fgfm3NWB.mjs";
import { t as ManagedPluginLifecycleError } from "./management-lifecycle-error-COJYzrtT.mjs";
import { t as PLUGIN_CAPABILITY_CONSENT_REQUIRED } from "./capability-consent-error-details-Blq5S4vw.mjs";
import { s as withPluginLifecycleLeaseAsync } from "./plugin-lifecycle-lease-CXjHGDEI.mjs";
import { a as writePersistedInstalledPluginIndexInstallRecordsWithLease, u as resolveNpmInstallRecordSpec } from "./installed-plugin-index-records-MNCNSlg8.mjs";
import { n as VERSION_BOUND_RUNTIME_PLUGIN_IDS } from "./official-runtime-plugins-m31mbS3Z.mjs";
import { t as retainMutationAuthority } from "./mutation-authority-CnUaJq0v.mjs";
import { n as isRemovalIoError, r as removePathWithinRoot, t as capturePathRemovalGuard } from "./fs-safe-remove-mw1k_RwN.mjs";
import { F as attachPluginInstallTransaction, I as copyPluginInstallTransactionRequest, V as retainPluginInstallTransaction, W as withPluginInstallTransactions } from "./npm-managed-root-BtsiBsIh.mjs";
import { r as installPluginFromNpmSpec } from "./install-Xai3w73h.mjs";
import { a as readInstalledPackageVersion, t as comparePackageUpdateVersions } from "./package-update-utils-9Q0D2cR2.mjs";
import { n as isPayloadMissing } from "./payload-verification-BFPGDf3M.mjs";
import { a as collectConfiguredChannelIds, i as collectBlockedPluginIds, o as collectConfiguredPluginIds, r as resolveConfiguredPluginInstallContext } from "./missing-configured-plugin-install.candidates-Bdz7t8z-.mjs";
import { r as prepareManagedPluginArtifactConsentHandler, t as capturePluginCapabilityConsentHandlerErrors } from "./capability-consent-ByRkpzSz.mjs";
import { t as buildClawHubPluginInstallRecordFields } from "./clawhub-install-records-DSHcVKgw.mjs";
import { t as installPluginFromClawHub } from "./clawhub-CBghJS2i.mjs";
import { a as forceNpmInstallRecordRepair, c as resolveLegacyNpmPackageInstallPath, i as resolveRecordedInstallCandidate, l as resolveSafeBrokenOfficialInstallRemovalPath, n as resolveConfiguredPluginCandidateRepair, o as installPathsEqual, r as resolveConfiguredPluginRepairVersions, s as planBundledInstallRecordRepair } from "./missing-configured-plugin-install.targets-Dlre_4v-.mjs";
import { n as updateNpmInstalledPlugins, r as isClawHubTrustSkippedOutcome } from "./update-BagSUcSV.mjs";
import { existsSync, lstatSync, realpathSync } from "node:fs";
import path from "node:path";
import { assertDirectoryIdentitySync } from "@openclaw/fs-safe/advanced";
import { FsSafeError } from "@openclaw/fs-safe/errors";
//#region src/commands/doctor/shared/missing-configured-plugin-install.install.ts
function isClawHubReviewNotice(e) {
const t = stripAnsi(e);
return t.includes("ClawHub Security Audit") && t.includes("Outcome: Review");
}
async function installCandidate(e) {
const t = capturePluginCapabilityConsentHandlerErrors(e.onCapabilityConsent);
try {
const n = await installCandidatePackage({
...e,
onCapabilityConsent: t.onCapabilityConsent
});
t.rethrowCallbackError();
return n;
} catch (n) {
t.rethrowCallbackError();
if (n instanceof ManagedPluginLifecycleError) {
if (n.kind === "invalid-request" && !n.capabilityConsent) throw n;
} else if (!(n instanceof NpmChannelResolutionError)) throw n;
return {
records: e.records,
changes: [],
notices: [],
warnings: [sanitizeTerminalText(n.message)],
failedPluginId: e.candidate.pluginId,
...n instanceof NpmChannelResolutionError ? { code: n.code } : n.capabilityConsent ? { code: PLUGIN_CAPABILITY_CONSENT_REQUIRED } : {}
};
}
}
async function installCandidatePackage(e) {
const t = e.records[e.candidate.pluginId];
const n = t?.source === "npm" || t?.source === "clawhub" ? t.source : void 0;
const r = e.repairReason === "stale-version-bound-runtime";
const i = resolveRecordedInstallCandidate({
candidate: e.candidate,
record: t,
repairReason: e.repairReason
});
const a = resolveDefaultPluginExtensionsDir(e.env);
const o = [];
const s = [];
const c = r && parseRegistryNpmSpec(e.records[i.pluginId]?.spec ?? "")?.selectorKind === "exact-version";
const l = i.clawhubSpec ? resolveClawHubInstallSpecsForUpdateChannel({
spec: i.clawhubSpec,
updateChannel: e.updateChannel,
officialPackageName: i.trustedSourceLinkedOfficialInstall ? parseClawHubPluginSpec(i.clawhubSpec)?.name : void 0,
coreVersion: resolveCompatibilityHostVersion(e.env),
versionBoundToCore: i.versionBoundToOpenClaw
}) : null;
const u = i.npmSpec ? await resolveNpmInstallSpecsForUpdateChannel({
spec: i.npmSpec,
timeoutMs: e.timeoutMs,
updateChannel: e.updateChannel,
officialPackageName: i.trustedSourceLinkedOfficialInstall ? parseRegistryNpmSpec(i.npmSpec)?.name : void 0,
coreVersion: resolveCompatibilityHostVersion(e.env),
versionBoundToCore: i.versionBoundToOpenClaw
}) : null;
const d = l?.installSpec ?? i.clawhubSpec;
const f = u?.installSpec ?? i.npmSpec;
const prepareConsent = (t, n, r) => prepareManagedPluginArtifactConsentHandler({
config: e.config,
env: e.env,
source: t,
spec: n,
previousRecords: e.records,
expectedIntegrity: r,
onCapabilityConsent: e.onCapabilityConsent,
beforePersistentEffect: e.beforePersistentEffect
});
const p = resolveDefaultPluginNpmDir(e.env);
const m = d ? resolveExistingCandidateClawHubPackagePath({
candidate: i,
extensionsDir: a
}) : null;
const h = f ? resolveExistingCandidateNpmPackagePath({
candidate: i,
npmDir: p
}) : null;
if (r && u?.npmResolution?.version) {
const n = resolveRecordInstallPath(t, e.env) ?? h;
const r = n ? await readInstalledPackageVersion(n) : void 0;
const a = u.npmResolution.version;
if (u.channelReason) s.push(`Plugin "${i.pluginId}" refresh: tag-behind-latest; beta follows latest ${a}.`);
if (r && comparePackageUpdateVersions(a, r) <= 0) return {
records: e.records,
changes: [],
notices: [...s, `Plugin "${i.pluginId}" refresh: already-current (${r}).`],
warnings: []
};
s.push(`Plugin "${i.pluginId}" refresh: newer-available (${r ?? "unknown"} -> ${a}).`);
}
const g = resolvePluginInstallSources(i, n);
if (g.length === 0) return {
records: e.records,
changes: [],
notices: [],
warnings: [`Failed to install missing configured plugin "${i.pluginId}": no declared remote source.`],
failedPluginId: i.pluginId
};
const { attempt: { result: _, capabilityConsent: v }, source: y } = await installWithSourceFallback({
sources: g,
install: async (r) => {
const c = r.source === "npm" ? u : l;
const d = c?.installSpec ?? r.spec;
return await installWithChannelFallback({
installSpec: d,
...r.expectedIntegrity ? {} : { fallbackSpec: c?.fallbackSpec },
install: async (s) => {
const c = await prepareConsent(r.source, s, r.expectedIntegrity);
const l = copyPluginInstallTransactionRequest(e, {
spec: s,
config: e.config,
timeoutMs: e.timeoutMs,
workTimeoutMs: e.workTimeoutMs,
extensionsDir: a,
expectedPluginId: i.pluginId,
expectedIntegrity: r.expectedIntegrity,
onBeforePluginArtifactCommit: c.onBeforePluginArtifactCommit
});
if (r.source === "clawhub") {
const r = await installPluginFromClawHub({
...l,
env: e.env,
...n === "clawhub" ? { baseUrl: t?.clawhubUrl } : {},
mode: e.mode === "update" || m ? "update" : "install",
logger: {
terminalLinks: false,
warn: (e) => o.push(stripAnsi(e))
}
});
retainPluginInstallTransaction(e, r);
return {
result: r,
capabilityConsent: c
};
}
const u = e.mode === "update" || h ? "update" : "install";
const install = (e) => installPluginFromNpmSpec({
...l,
npmDir: p,
mode: e,
trustedSourceLinkedOfficialInstall: i.trustedSourceLinkedOfficialInstall
});
let d = await install(u);
if (!d.ok && u === "install" && /\bplugin already exists:/.test(d.error)) d = await install("update");
retainPluginInstallTransaction(e, d);
return {
result: d,
capabilityConsent: c
};
},
isRetryable: (e) => !e.result.ok && (r.source === "npm" ? isUnavailableNpmTarget(e.result) : isUnavailableClawHubTarget(e.result)),
onFallback: (e) => void s.push(e)
});
},
result: (e) => e.result,
onFallback: (e) => void s.push(e)
});
if (!_.ok) return {
records: e.records,
changes: [],
notices: [],
warnings: [
...o,
...s,
`Failed to install missing configured plugin "${i.pluginId}" from ${y.spec}: ${_.error}`
],
failedPluginId: i.pluginId
};
const b = _.pluginId;
const x = (t?.source === y.source ? t.spec : void 0) ?? (y.source === "npm" ? u : l)?.recordSpec ?? y.spec;
const S = "clawhub" in _ ? {
...buildClawHubPluginInstallRecordFields(_.clawhub),
spec: x,
installPath: _.targetDir
} : {
source: "npm",
spec: resolveNpmInstallRecordSpec({
requestedSpec: x,
resolution: _.npmResolution,
pinResolvedRegistrySpec: c
}),
installPath: _.targetDir,
version: _.version,
...buildNpmResolutionFields(_.npmResolution)
};
const C = (y.source === "npm" ? u : l)?.installSpec ?? y.spec;
return {
records: {
...e.records,
[b]: v.applyAcceptedSurface(b, {
...S,
installedAt: (/* @__PURE__ */ new Date()).toISOString()
})
},
changes: [r ? `Refreshed stale configured plugin "${b}" from ${C}.` : `Installed missing configured plugin "${b}" from ${C}.`],
notices: [...s, ...o],
warnings: []
};
}
function resolveExistingCandidateNpmPackagePath(e) {
const t = e.candidate.npmSpec ? parseRegistryNpmSpec(e.candidate.npmSpec)?.name : void 0;
if (!t) return null;
const n = resolvePluginNpmPackageDir({
packageName: t,
npmDir: e.npmDir
});
if (existsSync(n)) return n;
const r = resolveLegacyNpmPackageInstallPath({
packageName: t,
npmRoot: e.npmDir
});
return existsSync(r) ? r : null;
}
function resolveExistingCandidateClawHubPackagePath(e) {
try {
const t = resolvePluginInstallDir(e.candidate.pluginId, e.extensionsDir);
return existsSync(t) ? t : null;
} catch {
return null;
}
}
function resolveRecordInstallPath(e, t) {
const n = e?.installPath?.trim();
return n ? resolveUserPath(n, t) : void 0;
}
//#endregion
//#region src/commands/doctor/shared/missing-configured-plugin-install.health.ts
const CONFIGURED_PLUGIN_INSTALLS_CHECK_ID = "core/doctor/configured-plugin-installs";
function recordedInstallIdentity(e) {
return {
installSpec: e?.resolvedSpec ?? e?.spec,
installSource: e?.source
};
}
/** Detect configured plugin installs that Doctor can repair without mutating package state. */
async function detectConfiguredPluginInstallHealthIssues(e) {
const t = e.env ?? process.env;
const n = collectConfiguredPluginIds(e.cfg, t);
const r = collectConfiguredChannelIds(e.cfg, t);
const i = collectBlockedPluginIds(e.cfg);
const a = await resolveConfiguredPluginInstallContext({
cfg: e.cfg,
env: t,
configuredPluginIds: n,
configuredChannelIds: r,
blockedPluginIds: i
});
const { configuredPluginIdsWithStaleDescriptors: o, records: s, installedPluginIdsWithRepairablePackageDiagnostics: c, installedPluginIdsWithStaleVersionBoundRuntimePackages: l, installedPluginMissingRequiredDependencies: u } = a;
const d = [];
const { pluginIds: f, repairPluginIds: p } = a.collectDeferredRepairs(s);
for (const e of p) {
const n = resolveRecordInstallPath(s[e], t);
d.push({
kind: "deferred-package-manager-repair",
pluginId: e,
...n ? { installPath: n } : {}
});
}
for (const [e] of a.collectRecordedRepairs(s, f)) {
const n = s[e];
const r = u.get(e);
if (r) {
d.push({
kind: "missing-required-dependencies",
pluginId: e,
installPath: resolveRecordInstallPath(n, t),
...recordedInstallIdentity(n),
missingRequired: r.missingRequired
});
continue;
}
const i = l.has(e) ? "stale-version-bound-runtime" : c.has(e) ? "repairable-installed-plugin" : o.has(e) ? "stale-channel-config-descriptor" : "missing-installed-payload";
const a = resolveRecordInstallPath(n, t);
d.push({
kind: i,
pluginId: e,
...a ? { installPath: a } : {},
...i === "stale-channel-config-descriptor" ? {} : recordedInstallIdentity(n)
});
}
const m = new Set(d.map((e) => e.pluginId));
for (const e of a.collectInstallCandidates(s, f)) {
if (m.has(e.pluginId)) continue;
const n = resolveConfiguredPluginCandidateRepair({
candidate: e,
records: s,
env: t,
context: a
});
if (!n) continue;
const r = s[e.pluginId];
const i = resolvePluginInstallSources(e)[0]?.spec;
if (n.shouldReplaceBrokenOfficialInstall || r) {
const i = resolveRecordInstallPath(r, t);
d.push({
kind: n.shouldReplaceBrokenOfficialInstall ? l.has(e.pluginId) ? "stale-version-bound-runtime" : "repairable-installed-plugin" : "missing-installed-payload",
pluginId: e.pluginId,
...i ? { installPath: i } : {},
...recordedInstallIdentity(r)
});
} else if (i) d.push({
kind: "missing-install-record",
pluginId: e.pluginId,
installSpec: i
});
}
return d.toSorted((e, t) => e.pluginId.localeCompare(t.pluginId));
}
const CONFIGURED_PLUGIN_INSTALL_ISSUE_DETAILS = {
"missing-install-record": {
message: "is not installed.",
fixHint: "",
action: "would-install-configured-plugin"
},
"missing-installed-payload": {
message: "has an install record but its package payload is missing.",
fixHint: null,
action: "would-reinstall-configured-plugin"
},
"missing-required-dependencies": {
message: "is missing required dependencies:",
fixHint: null,
action: "would-repair-configured-plugin-dependencies"
},
"repairable-installed-plugin": {
message: "has a repairable package install problem.",
fixHint: null,
action: "would-repair-configured-plugin-install"
},
"stale-version-bound-runtime": {
message: "is older than this OpenClaw version.",
fixHint: "Run `openclaw doctor --fix` to refresh the configured runtime plugin.",
action: "would-refresh-configured-runtime-plugin"
},
"stale-channel-config-descriptor": {
message: "has stale channel config metadata.",
fixHint: "Run `openclaw doctor --fix` to repair the configured plugin install metadata.",
action: "would-repair-configured-plugin-install"
},
"deferred-package-manager-repair": {
message: "package repair is deferred until the package update finishes.",
fixHint: "Rerun `openclaw doctor --fix` after the package update completes.",
action: "would-defer-configured-plugin-install-repair"
}
};
function configuredPluginInstallIssueToHealthFinding(e) {
const t = CONFIGURED_PLUGIN_INSTALL_ISSUE_DETAILS[e.kind];
const n = "installSpec" in e ? e.installSpec : void 0;
const r = "installSource" in e && e.installSource === "npm" ? `npm:${n}` : n;
const i = `Configured ${e.kind === "stale-version-bound-runtime" ? "runtime plugin" : "plugin"} ${e.pluginId} ${t.message}`;
return {
checkId: CONFIGURED_PLUGIN_INSTALLS_CHECK_ID,
severity: "warning",
message: e.kind === "missing-required-dependencies" ? `${i} ${e.missingRequired.join(", ")}.` : i,
target: e.pluginId,
..."installSource" in e ? { source: e.installSource } : {},
..."installPath" in e && e.installPath ? { path: e.installPath } : {},
fixHint: e.kind === "missing-install-record" ? `Run \`openclaw doctor --fix\` to install ${e.installSpec}.` : t.fixHint ?? (n ? `Run \`openclaw plugins install ${r} --force\` to reinstall the configured plugin package.` : "Run `openclaw doctor --fix` to repair the configured plugin install. An exact reinstall command is unavailable because the install record has no package spec.")
};
}
function configuredPluginInstallIssueToRepairEffect(e) {
return {
kind: "package",
action: CONFIGURED_PLUGIN_INSTALL_ISSUE_DETAILS[e.kind].action,
target: e.pluginId,
dryRunSafe: e.kind === "deferred-package-manager-repair"
};
}
//#endregion
//#region src/commands/doctor/shared/missing-configured-plugin-install.repair.ts
async function repairMissingConfiguredPluginInstalls(e) {
return repairMissingPluginInstalls(copyPluginInstallTransactionRequest(e, {
...e,
pluginIds: collectConfiguredPluginIds(e.cfg, e.env),
channelIds: collectConfiguredChannelIds(e.cfg, e.env),
blockedPluginIds: collectBlockedPluginIds(e.cfg)
}));
}
async function repairMissingPluginInstallsForIds(e) {
return repairMissingPluginInstalls(copyPluginInstallTransactionRequest(e, {
...e,
pluginIds: new Set(normalizeTrimmedStringList([...e.pluginIds])),
channelIds: new Set(normalizeTrimmedStringList([...e.channelIds ?? []])),
blockedPluginIds: new Set(normalizeTrimmedStringList([...e.blockedPluginIds ?? []]))
}));
}
async function repairMissingPluginInstalls(e) {
if (!e.baselineRecords) {
const t = createPluginCache();
try {
const n = await withPluginCache(t, async () => {
const t = e.env ?? process.env;
const n = await resolveConfiguredPluginInstallContext({
cfg: e.cfg,
env: t,
configuredPluginIds: e.pluginIds,
configuredChannelIds: e.channelIds,
blockedPluginIds: e.blockedPluginIds
});
const { records: r, persistedRecords: i } = n;
const a = planBundledInstallRecordRepair(n);
let o = false;
const { driftedPluginIds: s } = resolveConfiguredPluginRepairVersions({
cfg: e.cfg,
env: t,
context: n,
repairVersionDrift: e.repairVersionDrift,
onWarning: () => {
o = true;
}
});
const c = n.collectDeferredRepairs(r);
if (r === i && !o && n.stalePathInstallPluginIds.size === 0 && a.nextRecords === r && c.repairPluginIds.length === 0 && n.collectRecordedRepairs(r, c.pluginIds, s).length === 0 && !n.collectInstallCandidates(r, c.pluginIds).some((e) => resolveConfiguredPluginCandidateRepair({
candidate: e,
records: r,
env: t,
context: n
}))) return {
changes: [],
warnings: [],
records: r,
...a.notices.length ? { notices: a.notices } : {},
...a.sourceOutcomes.length ? { outcomes: a.sourceOutcomes } : {}
};
});
if (n) return n;
} finally {
await retirePluginCache(t);
}
}
return await withPluginLifecycleLeaseAsync({ env: e.env }, (t) => withPluginInstallTransactions(e, t, async (e, n, r) => {
const i = /* @__PURE__ */ new Map();
let a;
let o;
try {
a = await repairMissingPluginInstallsWithLease(e, t, i, n, r);
} catch (e) {
o = e;
}
const s = [];
for (const [e, t] of i) {
if (a?.repairedPluginIds?.includes(e)) continue;
try {
await clearRetainedManagedNpmInstallMarker(t, r);
} catch (e) {
n();
s.push(e);
}
}
if (!a) {
if (s.length > 0) throw new AggregateError([o, ...s], "Plugin dependency repair failed and its retention markers could not be cleared.");
throw o;
}
a.warnings.push(...s.map((e) => `Failed to clear dependency repair retention marker: ${String(e)}`));
return a;
}));
}
async function repairMissingPluginInstallsWithLease(e, t, n, r, i) {
const a = e.env ?? process.env;
const o = await resolveConfiguredPluginInstallContext({
cfg: e.cfg,
env: a,
configuredPluginIds: e.pluginIds,
configuredChannelIds: e.channelIds,
blockedPluginIds: e.blockedPluginIds,
baselineRecords: e.baselineRecords
});
const { knownIds: s, configuredPluginIdsWithStaleDescriptors: c, stalePathInstallPluginIds: l, records: u, persistedRecords: d, updateChannel: f, installedPluginIdsWithRepairablePackageDiagnostics: p, installedPluginIdsWithStaleVersionBoundRuntimePackages: m, installedPluginMissingRequiredDependencies: h } = o;
const { changes: g, notices: _, sourceOutcomes: v, nextRecords: y } = planBundledInstallRecordRepair(o);
const b = [];
const warn = (t, n) => {
b.push(t);
e.onWarning?.({
message: t,
...n ? { pluginId: n } : {}
});
};
const x = [];
const S = /* @__PURE__ */ new Map();
const C = /* @__PURE__ */ new Set();
const { coreVersion: w, cohortSpecs: T, newerRecordedPluginIds: E, driftedPluginIds: D } = resolveConfiguredPluginRepairVersions({
cfg: e.cfg,
env: a,
context: o,
repairVersionDrift: e.repairVersionDrift,
onWarning: warn
});
let O = y;
const k = normalizePluginsConfig(e.cfg.plugins);
const recordFailure = (t, n, r) => {
let i = S.get(t);
if ((r === "PLUGIN_CAPABILITY_CONSENT_REQUIRED" || r === PLUGIN_INSTALL_ERROR_CODE.NPM_METADATA_FAILURE) && s.has(t) && !isPayloadMissing(a, u[t]?.installPath) && !p.has(t) && !h.has(t) && !c.has(t) && resolveEffectiveEnableState({
id: t,
origin: "global",
config: k,
rootConfig: e.cfg
}).enabled) _.push(`Kept installed plugin "${t}"; replacement deferred. ${n.join(" ")}`);
else {
for (const e of n) warn(e, t);
if (r === "PLUGIN_CAPABILITY_CONSENT_REQUIRED") i = {
pluginId: t,
status: "error",
code: r,
message: n.join(" ")
};
}
S.set(t, i);
};
for (const e of l) g.push(`Removed stale path-install record for plugin "${e}" (loaded from a configured load path).`);
const { pluginIds: A, repairPluginIds: j } = o.collectDeferredRepairs(O);
for (const e of j) {
const t = `Skipped package-manager repair for configured plugin "${e}" during package update; rerun "openclaw doctor --fix" after the update completes.`;
g.push(t);
x.push(t);
}
const M = o.collectRecordedRepairs(O, A, D);
const N = M.map(([e]) => e);
if (N.length > 0) {
const t = { ...O };
for (const [o, s] of M) {
const l = h.get(o);
if (l || !m.has(o) && !D.has(o) || p.has(o) || c.has(o) || isPayloadMissing(a, s.installPath)) t[o] = forceNpmInstallRecordRepair(s);
if (l) {
await e.beforePersistentEffect?.();
r();
if (!hasRetainedManagedNpmInstallMarker(l.rootDir)) {
n.set(o, l.rootDir);
await markRetainedManagedNpmInstall({
packageDir: l.rootDir,
pluginId: o,
reason: "doctor-missing-required-dependencies",
assertCurrent: i
});
}
}
}
const o = await updateNpmInstalledPlugins(copyPluginInstallTransactionRequest(e, {
config: {
...e.cfg,
plugins: {
...e.cfg.plugins,
installs: t
}
},
pluginIds: N,
timeoutMs: e.timeoutMs,
workTimeoutMs: e.workTimeoutMs,
npmInstallSpecOverrides: Object.fromEntries(Object.entries(T).filter(([e]) => D.has(e) && !E.has(e))),
versionBoundPluginIds: new Set(M.filter(([t, n]) => (f === "stable" || f === "extended-stable") && e.pluginIds.has(t) && VERSION_BOUND_RUNTIME_PLUGIN_IDS.has(t) && (n.source === "npm" && Boolean(T[t]) || Boolean(resolveTrustedSourceLinkedOfficialClawHubInstall({
pluginId: t,
record: n
}))) && !E.has(t) && (m.has(t) || isPayloadMissing(a, n.installPath))).map(([e]) => e)),
retainOnUnavailable: true,
skipDisabledPlugins: true,
updateChannel: f,
coreVersion: w,
logger: {
terminalLinks: false,
warn: (e) => {
if (isClawHubReviewNotice(e)) {
_.push(stripAnsi(e));
return;
}
warn(e);
},
error: (e) => warn(e)
},
...e.onCapabilityConsent ? { onCapabilityConsent: e.onCapabilityConsent } : {},
beforePersistentEffect: e.beforePersistentEffect
}));
for (const e of o.outcomes) {
if (e.status === "unchanged" && e.code === "plugin-target-unavailable") {
recordFailure(e.pluginId, [e.message], e.code);
continue;
}
if (e.status === "unchanged" && o.config.plugins?.installs?.[e.pluginId] === t[e.pluginId]) _.push(e.message);
else if (e.status === "updated" || e.status === "unchanged") {
C.add(e.pluginId);
S.delete(e.pluginId);
g.push(h.has(e.pluginId) ? `Repaired missing dependencies for installed plugin "${e.pluginId}".` : D.has(e.pluginId) ? `Updated official plugin "${e.pluginId}" from ${e.currentVersion ?? u[e.pluginId]?.version} to ${e.nextVersion ?? w}.` : m.has(e.pluginId) ? `Refreshed stale configured plugin "${e.pluginId}".` : p.has(e.pluginId) ? `Repaired broken installed plugin "${e.pluginId}".` : `Repaired missing configured plugin "${e.pluginId}".`);
} else if (e.status === "error" || isClawHubTrustSkippedOutcome(e) || e.status === "skipped" && h.has(e.pluginId)) recordFailure(e.pluginId, [e.message], e.code);
}
if (C.size > 0) {
O = { ...o.config.plugins?.installs ?? O };
for (const [e, t] of M) if (!C.has(e)) O[e] = t;
}
}
for (const t of o.collectInstallCandidates(O, A)) {
const n = resolveConfiguredPluginCandidateRepair({
candidate: t,
records: O,
env: a,
context: o
});
if (!n) continue;
const { shouldReplaceBrokenOfficialInstall: i, repairReason: s } = n;
const c = O[t.pluginId];
const l = i ? resolveSafeBrokenOfficialInstallRemovalPath({
pluginId: t.pluginId,
candidate: t,
record: c,
env: a
}) : null;
const u = l ? capturePathRemovalGuard(l) : void 0;
const d = l ? path.dirname(l) : void 0;
const p = u && d ? capturePathRemovalGuard(d) : void 0;
const m = p && d ? realpathSync(d) : void 0;
const h = m ? lstatSync(m, { bigint: true }) : void 0;
const v = O;
const y = await installCandidate(copyPluginInstallTransactionRequest(e, {
candidate: t,
config: e.cfg,
timeoutMs: e.timeoutMs,
workTimeoutMs: e.workTimeoutMs,
records: O,
env: a,
updateChannel: f,
mode: i ? "update" : "install",
repairReason: s,
...e.onCapabilityConsent ? { onCapabilityConsent: e.onCapabilityConsent } : {},
beforePersistentEffect: e.beforePersistentEffect
}));
if (i) {
const n = y.records[t.pluginId];
if (y.records !== v && l && u && d && p && m && h && (!n?.installPath || !installPathsEqual(resolveUserPath(n.installPath, a), l))) {
const n = retainMutationAuthority(() => {
r();
p();
if (realpathSync(d) !== m) throw new FsSafeError("path-mismatch", "plugin retirement parent changed");
assertDirectoryIdentitySync(m, {
dev: h.dev,
ino: h.ino,
realPath: m
});
u();
});
retainPluginInstallTransaction(e, attachPluginInstallTransaction({}, {
commit: async () => {
await e.beforePersistentEffect?.();
n();
try {
await removePathWithinRoot({
rootDir: m,
relativePath: path.basename(l),
recursive: true,
force: true,
symlinks: "unlink",
assertBeforeMutation: n
});
} catch (e) {
n();
if (!isRemovalIoError(e)) throw e;
warn(`Failed to remove broken installed plugin "${t.pluginId}" at ${l}: ${String(e)}`);
}
},
rollback: async () => {}
}));
}
}
O = y.records;
g.push(...y.changes);
_.push(...y.notices);
if (!y.failedPluginId && y.records !== v && y.records[t.pluginId]) {
C.add(t.pluginId);
S.delete(t.pluginId);
}
if (y.failedPluginId) recordFailure(y.failedPluginId, y.warnings, y.code);
else for (const e of y.warnings) warn(e);
}
const P = {
config: e.cfg,
env: a,
filePath: t.databasePath,
lease: t
};
if (O !== d || e.baselineRecords) {
if (e.beforePersistentEffect) {
const t = await readPersistedInstalledPluginIndex(P);
if (!t || hashStableJson(O) !== hashStableJson(t.installRecords) || t.policyHash !== resolveInstalledPluginIndexPolicyHash(e.cfg, a)) await e.beforePersistentEffect();
}
await t.assertOwned();
await writePersistedInstalledPluginIndexInstallRecordsWithLease(O, P);
}
const F = O !== d || C.size > 0;
if ([...D].some((e) => C.has(e))) g.push(`If the Gateway is not restarted by Doctor, run ${formatCliCommand("openclaw gateway restart", a)} to load the updated plugins.`);
const I = [...v, ...[...S.values()].filter((e) => e !== void 0)];
return {
changes: g,
warnings: b,
...I.length > 0 ? { outcomes: I } : {},
..._.length > 0 ? { notices: _ } : {},
...x.length > 0 ? { deferredRepairDetails: x } : {},
...C.size > 0 ? { repairedPluginIds: [...C].toSorted((e, t) => e.localeCompare(t)) } : {},
...F ? { pluginInventoryChanged: true } : {},
...S.size > 0 ? { failedPluginIds: [...S.keys()].toSorted((e, t) => e.localeCompare(t)) } : {},
records: O
};
}
//#endregion
export { detectConfiguredPluginInstallHealthIssues as a, configuredPluginInstallIssueToRepairEffect as i, repairMissingPluginInstallsForIds as n, configuredPluginInstallIssueToHealthFinding as r, repairMissingConfiguredPluginInstalls as t };