openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
382 lines (381 loc) • 15.6 kB
JavaScript
import { t as expectDefined } from "./expect-DDakjvvQ.mjs";
import { b as uniqueStrings } from "./string-normalization-DLmfYZXI.mjs";
import { s as pathMayExistSync } from "./path-existence-Co7-GyVr.mjs";
import { p as shortenHomePath } from "./utils-C8YECn2Q.mjs";
import { n as ok, t as err } from "./result-CV1-31DB.mjs";
import { o as tracePluginLifecyclePhase, s as tracePluginLifecyclePhaseAsync } from "./discovery-DvJYrQFY.mjs";
import { r as cloneEnvWithPlatformSemantics } from "./config-env-vars-ByeGN-9N.mjs";
import { a as loadInstalledPluginIndex } from "./installed-plugin-index-DYqse_gE.mjs";
import { a as resolveDefaultPluginExtensionsDir } from "./install-paths-Bwm0P5EG.mjs";
import { M as parseClawHubPluginSpec } from "./official-external-plugin-catalog-DtkWz1Xo.mjs";
import { r as loadInstalledPluginIndexInstallRecords } from "./installed-plugin-index-record-reader-B-7uGQZ9.mjs";
import { i as withConfigWriteLock } from "./write-lock-Bg9nHsHM.mjs";
import { n as composeConfigWriteAssertions } from "./write-authority-l37tp55r.mjs";
import { x as createPluginRegistryIdNormalizer } from "./plugin-metadata-snapshot-By9ySblt.mjs";
import { t as createInstalledPluginOwnershipResolver } from "./installed-plugin-package-ownership-BAh5IZ9-.mjs";
import { t as ManagedPluginLifecycleError } from "./management-lifecycle-error-COJYzrtT.mjs";
import { t as createConfigIO } from "./io.factory-DEa_bi2j.mjs";
import { r as assertConfigWriteAllowedInCurrentMode } from "./config-write-guard-CxNxfJ_I.mjs";
import { l as readConfigFileSnapshotForWrite } from "./io.runtime-DsJ2dLCQ.mjs";
import { o as transformConfigFileWithRetry, r as replaceConfigFile } from "./mutate-DhAOi0-2.mjs";
import "./config-CMA-J084.mjs";
import { s as withPluginLifecycleLeaseAsync } from "./plugin-lifecycle-lease-CXjHGDEI.mjs";
import { i as withoutPluginInstallRecords, n as removePluginInstallRecordFromRecords, r as withPluginInstallRecords } from "./installed-plugin-index-records-MNCNSlg8.mjs";
import { t as createInstalledPluginIndexScopeLookup } from "./installed-plugin-index-scope-lookup-BDhPSNdH.mjs";
import { n as withClawPackageLifecycleLease } from "./claw-package-lifecycle-lease-DqLaXnyJ.mjs";
import { a as recordPluginPackageUninstallPlan, i as prepareConfigForDisabledPluginSet, n as formatUninstallActionLabels, r as planPluginUninstall, t as applyPluginUninstallDirectoryRemoval } from "./uninstall-jiiZcP78.mjs";
import { r as commitPluginInstallRecordsWithConfig } from "./install-record-commit-BBhtfevs.mjs";
import { n as refreshPluginRegistryAfterConfigMutation } from "./registry-refresh-Bfs6LAit.mjs";
import { i as selectInstallMutationWriteOptions } from "./install-config-mutation-BW96uF8m.mjs";
import { r as capturePluginRuntimeApplications } from "./lifecycle-eIKo4FGP.mjs";
import { t as readPluginMutationSnapshot } from "./management-config-B_CRcSEq.mjs";
import { i as refreshManagedPluginMetadata, r as loadFreshManagedPluginMetadata } from "./management-service-jpAFCXsG.mjs";
import { o as buildPluginSnapshotReport } from "./status-dU3VsouW.mjs";
import { t as withPluginSourceCleanup } from "./source-cleanup-Bg55Ow2j.mjs";
//#region src/plugins/uninstall-selection.ts
/** Resolve user input to the plugin id that should be removed from config/install records. */
function resolvePluginUninstallId(e) {
const t = e.rawId.trim();
const n = e.config.plugins;
const r = n?.installs ?? {};
const resolveInstalledPlugin = (t) => {
const n = e.plugins.find((e) => e.id === t);
return n ? {
pluginId: t,
plugin: n
} : { pluginId: t };
};
const i = e.plugins.find((e) => e.id === t);
if (i) return ok({
pluginId: i.id,
plugin: i
});
if (Object.hasOwn(r, t) || Object.hasOwn(n?.entries ?? {}, t) || n?.allow?.includes(t) || n?.deny?.includes(t) || n?.slots?.memory === t || n?.slots?.contextEngine === t) return ok(resolveInstalledPlugin(t));
const a = new Set(e.plugins.filter((e) => e.name === t).map((e) => e.id));
for (const [e, n] of Object.entries(r)) if (n.spec === t || n.resolvedSpec === t || n.resolvedName === t || n.marketplacePlugin === t) a.add(e);
const o = parseClawHubPluginSpec(t);
if (o) {
for (const [e, t] of Object.entries(r)) if ((t.clawhubPackage ?? parseClawHubPluginSpec(t.spec ?? "")?.name ?? parseClawHubPluginSpec(t.resolvedSpec ?? "")?.name) === o.name) a.add(e);
}
if (a.size > 1) {
const e = [...a].toSorted().join(", ");
return err(`Plugin uninstall target "${t}" is ambiguous; matches: ${e}. Use an exact plugin id.`);
}
const [s] = a;
return ok(resolveInstalledPlugin(s ?? t));
}
//#endregion
//#region src/plugins/management-uninstall.ts
function runUninstallPhase(e, t, n) {
return e.caller === "cli" ? tracePluginLifecyclePhaseAsync(t, n, { command: "uninstall" }) : n();
}
async function readUninstallSnapshot(e, t) {
return await runUninstallPhase(e, t, async () => {
if (e.caller === "management") return await readPluginMutationSnapshot(e.env ?? process.env);
const { snapshot: t, writeOptions: n } = await readConfigFileSnapshotForWrite();
return {
config: t.sourceConfig,
baseHash: t.hash,
writeOptions: selectInstallMutationWriteOptions(n)
};
});
}
/** Read-only plan; execution always replans under its lease after confirmation. */
async function preparePluginUninstall(e) {
const t = e.env ?? process.env;
const n = e.caller === "cli";
const r = await readUninstallSnapshot(e, "config read");
const i = await runUninstallPhase(e, "install records load", () => loadInstalledPluginIndexInstallRecords(n ? {} : { env: t }));
const a = withPluginInstallRecords(r.config, i);
const o = n ? void 0 : await loadFreshManagedPluginMetadata(a, t);
const s = o?.index ?? loadInstalledPluginIndex({
config: a,
installRecords: i
});
const c = o ? o.index.plugins.map((e) => {
const t = o.byPluginId.get(e.pluginId);
return {
id: e.pluginId,
name: t?.name ?? e.pluginId,
origin: e.origin,
source: t?.source,
channelIds: t?.channels
};
}) : tracePluginLifecyclePhase("plugin registry snapshot", () => buildPluginSnapshotReport({ config: a }), { command: "uninstall" }).plugins;
const l = e.pluginId.trim();
const u = o && !Object.hasOwn(i, l) ? o.normalizePluginId(l) : l;
const d = n ? resolvePluginUninstallId({
rawId: u,
config: a,
plugins: c
}) : ok({
pluginId: u,
plugin: c.find((e) => e.id === u)
});
if (!d.ok) return d;
const { pluginId: f, plugin: p } = d.value;
if (!n) {
if (p?.origin === "bundled") return err(`bundled plugin cannot be uninstalled: ${f}; disable it instead`);
if (!p && !Object.hasOwn(i, f)) return err(`Plugin not found: ${f}`);
}
const m = createInstalledPluginOwnershipResolver(s, t).resolveLifecycle(f);
if (!m.ok) return m;
const { installOwner: h, pluginIds: g } = m.value;
let _ = g.length ? g : [h];
if (m.value.kind === "orphan") {
const e = (o?.normalizePluginId ?? createPluginRegistryIdNormalizer(s))(h);
if (e !== h && c.some((t) => t.id === e)) _ = [];
}
let v;
if (n) {
if (g.length === 1 && g[0] === f) v = p?.channelIds;
else if (g.length) v = uniqueStrings(g.flatMap((e) => c.find((t) => t.id === e)?.channelIds ?? []));
else if (createInstalledPluginIndexScopeLookup(s).hasChannelContributionOwners([h])) v = [];
} else {
const e = g.flatMap((e) => o?.byPluginId.get(e) ?? []);
v = e.length ? uniqueStrings(e.flatMap((e) => e.channels)) : m.value.kind === "orphan" && createInstalledPluginIndexScopeLookup(s).hasChannelContributionOwners([h]) ? [] : void 0;
}
const y = g.flatMap((e) => c.find((t) => t.id === e)?.source ?? []);
const b = resolveDefaultPluginExtensionsDir(n ? void 0 : t);
const planForConfig = (t) => planPluginUninstall(recordPluginPackageUninstallPlan({
config: withPluginInstallRecords(t, i),
pluginId: h,
...v !== void 0 ? { channelIds: v } : {},
deleteFiles: !e.keepFiles,
extensionsDir: b
}, {
runtimePluginIds: _,
runtimeLoadPaths: y
}));
const x = planForConfig(r.config);
if (!x.ok) return err(n && p ? `Plugin "${h}" is not managed by plugins config/install records and cannot be uninstalled.` : x.error);
return ok({
snapshot: r,
installRecords: i,
pluginId: h,
requestedPluginId: f,
pluginIds: g,
policyPluginIds: _,
name: p?.name || h,
channelIds: v,
plan: x,
planForConfig
});
}
/** Shared leased removal; callbacks preserve CLI output at its original mutation boundaries. */
async function uninstallPluginWithPolicy(e) {
const t = e.env ?? process.env;
const n = e.caller === "cli";
const r = e.applyRuntime ? capturePluginRuntimeApplications(e.applyRuntime).applyRuntime : void 0;
return await withPluginLifecycleLeaseAsync({
...n ? {} : { env: t },
signal: e.signal
}, async (i) => {
const a = composeConfigWriteAssertions(() => e.signal?.throwIfAborted(), i.assertCurrent, e.beforePersistentApply);
a();
const prepareEffect = async () => {
await e.beforePersistentEffect?.();
await i.assertOwned();
a();
};
if (n) assertConfigWriteAllowedInCurrentMode();
const o = await preparePluginUninstall(e);
if (!o.ok) return o;
const s = o.value;
await e.onPreview?.(s);
const uninstall = async () => {
const { pluginId: o, requestedPluginId: c, pluginIds: l, policyPluginIds: u, installRecords: d, plan: f } = s;
const p = s.snapshot;
const m = composeConfigWriteAssertions(p.writeOptions.assertConfigPathForWrite, a);
let h = {
directoryRemoved: false,
warnings: []
};
if (f.directoryRemoval || r) {
const i = prepareConfigForDisabledPluginSet(p.config, u, f.config);
const o = await runUninstallPhase(e, "config disable", () => replaceConfigFile({
sourceConfig: i,
baseHash: p.baseHash,
writeOptions: {
...p.writeOptions,
assertConfigPathForWrite: m,
beforeCommit: prepareEffect,
afterWrite: e.applyRuntime || e.deferRuntime ? {
mode: "none",
reason: "plugin lifecycle applies runtime"
} : { mode: "auto" }
}
}));
await prepareEffect();
await r?.({
config: i,
write: o,
pluginIds: u,
reason: "uninstall",
assertInvokerOwned: a
});
a();
if (f.directoryRemoval) {
const e = f.directoryRemoval;
h = await withPluginSourceCleanup(e.target, {
configPath: o.path,
env: t,
assertCurrent: a,
isReferenced: (e) => {
const t = s.planForConfig(e);
if (!t.ok) throw new Error(t.error);
return t.actions.loadPath;
}
}, (t) => applyPluginUninstallDirectoryRemoval(e, t));
}
for (const t of h.warnings) e.onWarning?.(t);
if (f.directoryRemoval && pathMayExistSync(f.directoryRemoval.target)) {
const e = `Failed to remove plugin directory ${n ? shortenHomePath(f.directoryRemoval.target) : f.directoryRemoval.target}; the plugin remains disabled and tracked so uninstall can be retried.`;
throw n ? new Error(e) : new ManagedPluginLifecycleError(e, { kind: "unavailable" });
}
}
const g = removePluginInstallRecordFromRecords(d, o);
const { expectedConfigPath: _, ownedConfigPathForWrite: v, auditOrigin: y } = p.writeOptions;
const b = !n && e.env ? createConfigIO({
configPath: v ?? _,
env: cloneEnvWithPlatformSemantics(t)
}) : void 0;
let x;
const transform = () => transformConfigFileWithRetry({
base: "source",
...b ? { io: {
...b,
readConfigFileSnapshotForWrite: () => createConfigIO({
configPath: b.configPath,
env: cloneEnvWithPlatformSemantics(t)
}).readConfigFileSnapshotForWrite()
} } : {},
writeOptions: {
..._ ? { expectedConfigPath: _ } : {},
...v ? { ownedConfigPathForWrite: v } : {},
...y ? { auditOrigin: y } : {},
assertConfigPathForWrite: m,
assertCurrent: a,
...n || e.applyRuntime ? { allowConfigSizeDrop: true } : {},
...e.applyRuntime || e.deferRuntime ? { afterWrite: {
mode: "none",
reason: "plugin lifecycle applies runtime"
} } : n ? { afterWrite: {
mode: "restart",
reason: "plugin source changed"
} } : {}
},
transform: (e) => {
a();
const t = s.planForConfig(e);
if (!t.ok) throw n ? new Error(t.error) : new ManagedPluginLifecycleError(t.error);
return {
nextConfig: withoutPluginInstallRecords(t.config),
result: t
};
},
commit: async ({ nextConfig: e, baseHash: t, writeOptions: n, afterWrite: r }) => {
const i = await commitPluginInstallRecordsWithConfig({
previousInstallRecords: d,
nextInstallRecords: g,
nextConfig: e,
baseHash: t,
beforePersistentEffect: prepareEffect,
writeOptions: {
...n,
afterWrite: r
}
});
x = i;
return {
config: i.configWrite.nextConfig,
persistedHash: i.configWrite.persistedHash,
persistedSourceConfig: i.configWrite.persistedSourceConfig,
afterWrite: i.configWrite.afterWrite
};
}
});
const S = await runUninstallPhase(e, "config mutation", () => b ? withConfigWriteLock(b.configPath, transform, t, a) : transform());
const C = expectDefined(x, "plugin uninstall commit receipt");
const w = expectDefined(S.result, "committed plugin uninstall plan");
const T = S.nextConfig;
e.deferRuntime?.record({
operation: "uninstall",
pluginId: o,
write: C
});
const E = [...!n && (c !== o || l.length > 1) ? [`Uninstalled package "${o}" and all owned plugin entries: ${l.join(", ")}.`] : [], ...h.warnings];
await refreshPluginRegistryAfterConfigMutation({
configPath: C.configWrite.path,
env: t,
lease: i,
reason: "source-changed",
installRecords: g,
invalidateRuntimeCache: n ? e.invalidateRuntimeCache : false,
...n ? { traceCommand: "uninstall" } : {},
logger: { warn: (t) => {
E.push(t);
e.onWarning?.(t);
} }
});
if (!n) await refreshManagedPluginMetadata({
config: T,
env: t,
assertCurrent: a
});
await prepareEffect();
const D = await r?.({
config: T,
write: C.configWrite,
pluginIds: u,
reason: "uninstall",
assertInvokerOwned: a
});
const O = {
...D ? { application: D } : {},
pluginId: o,
requestedPluginId: c,
pluginIds: l,
removed: formatUninstallActionLabels({
...w.actions,
loadPath: f.actions.loadPath || w.actions.loadPath,
directory: h.directoryRemoved
}),
warnings: [.../* @__PURE__ */ new Set([...E, ...D?.warnings ?? []])]
};
e.onComplete?.(O);
return ok(O);
};
const c = s.installRecords[s.pluginId];
const l = c?.source === "clawhub" ? c.clawhubPackage ?? parseClawHubPluginSpec(c.spec ?? "")?.name : void 0;
if (e.templateManaged || !l || !n && !e.applyRuntime) return await uninstall();
return await withClawPackageLifecycleLease({
kind: "plugin",
source: "clawhub",
ref: l
}, uninstall, n ? void 0 : { env: t });
});
}
/** Preserve the management API's canonical-id admission and response shape. */
async function uninstallManagedPlugin(e) {
const t = e.env ?? process.env;
return await withPluginLifecycleLeaseAsync({
env: t,
signal: e.signal
}, async () => {
const t = await uninstallPluginWithPolicy({
...e,
caller: "management"
});
if (!t.ok) throw new ManagedPluginLifecycleError(t.error);
const { pluginId: n, removed: r, warnings: i, application: a } = t.value;
return {
pluginId: n,
removed: r,
...i.length ? { warnings: i } : {},
...a ? { application: a } : {}
};
});
}
//#endregion
export { uninstallManagedPlugin as n, uninstallPluginWithPolicy as r, preparePluginUninstall as t };