openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
388 lines (387 loc) • 16.6 kB
JavaScript
import { p as shortenHomePath } from "./utils-C8YECn2Q.mjs";
import { t as formatErrorMessage } from "./errors-BKzCeTYb.mjs";
import { a as getProcessGatewayPluginMetadataSnapshot } from "./current-plugin-metadata-state-BmYo9Q7A.mjs";
import { c as normalizePluginId } from "./config-state-B1JlHgba.mjs";
import { n as hashStableJson } from "./installed-plugin-index-hash-BfBbMPjv.mjs";
import { a as readPersistedInstalledPluginIndexInstallRecordsAsync } from "./installed-plugin-index-record-reader-B-7uGQZ9.mjs";
import { t as CLAWHUB_INSTALL_ERROR_CODE } from "./clawhub-error-codes-5kIjtf6h.mjs";
import { t as PLUGIN_INSTALL_ERROR_CODE } from "./install-types-BBbGKapR.mjs";
import { n as composeConfigWriteAssertions } from "./write-authority-l37tp55r.mjs";
import { n as resolvePluginControlPlaneWorkspace } from "./control-plane-workspace-OscAdfLv.mjs";
import { t as createInstalledPluginOwnershipResolver } from "./installed-plugin-package-ownership-BAh5IZ9-.mjs";
import { r as isBundledManifestOwner } from "./manifest-owner-policy-B8Brw4Zo.mjs";
import { t as ensurePluginAllowlisted } from "./plugins-allowlist-DW5H7gQB.mjs";
import { t as ManagedPluginLifecycleError } from "./management-lifecycle-error-COJYzrtT.mjs";
import { t as setPluginEnabledInConfig } from "./toggle-config-DgGsLAY5.mjs";
import { t as enableExplicitlySelectedPluginInConfig } from "./enable-BY2SJL8Z.mjs";
import { r as assertConfigWriteAllowedInCurrentMode } from "./config-write-guard-CxNxfJ_I.mjs";
import { l as readConfigFileSnapshotForWrite } from "./io.runtime-DsJ2dLCQ.mjs";
import { r as replaceConfigFile } from "./mutate-DhAOi0-2.mjs";
import "./config-CMA-J084.mjs";
import { s as withPluginLifecycleLeaseAsync } from "./plugin-lifecycle-lease-CXjHGDEI.mjs";
import "./installed-plugin-index-records-MNCNSlg8.mjs";
import { o as isDefaultClawHubBaseUrl, v as resolveClawHubBaseUrl } from "./clawhub-client-BLg-dsn2.mjs";
import { r as resolveManagedPluginInstallRequest } from "./install-source-plan-CS6sfMiy.mjs";
import { s as reportClawHubPluginInstallTelemetry } from "./clawhub-packages-BkEmBO-h.mjs";
import { o as loadOfficialCatalog } from "./management-catalog-CIUzoNKS.mjs";
import { a as resolvePluginCapabilityConsent } from "./capability-consent-ByRkpzSz.mjs";
import { n as withClawPackageLifecycleLease } from "./claw-package-lifecycle-lease-DqLaXnyJ.mjs";
import { n as refreshPluginRegistryAfterConfigMutation } from "./registry-refresh-Bfs6LAit.mjs";
import { i as selectInstallMutationWriteOptions, t as assertRecordsOnlyUpdateConfigFresh } from "./install-config-mutation-BW96uF8m.mjs";
import { t as collectChangedPaths } from "./config-change-paths-ZDrHUVSI.mjs";
import { a as resolvePluginInstallRequestContext, n as loadConfigForInstall, t as PluginInstallConfigError } from "./install-config-aOPpkS0A.mjs";
import { r as capturePluginRuntimeApplications, t as PluginInstallPersistedError } from "./lifecycle-eIKo4FGP.mjs";
import { n as readPluginRuntimeConfig, t as readPluginMutationSnapshot } from "./management-config-B_CRcSEq.mjs";
import { i as refreshManagedPluginMetadata, n as listManagedPlugins, r as loadFreshManagedPluginMetadata } from "./management-service-jpAFCXsG.mjs";
import { t as applySlotSelectionForPlugin } from "./slot-selection-DOD904vP.mjs";
//#region src/plugins/management-mutations.ts
function withManagedPluginMutation(e, t) {
return withPluginLifecycleLeaseAsync({
env: e.env ?? process.env,
signal: e.signal
}, async (n) => {
const r = composeConfigWriteAssertions(() => e.signal?.throwIfAborted(), n.assertCurrent, e.beforePersistentApply);
r();
const prepareEffect = async () => {
await e.beforePersistentEffect?.();
await n.assertOwned();
r();
};
return t(r, prepareEffect);
});
}
function throwInstallFailure(e) {
const t = !e.code || e.code === CLAWHUB_INSTALL_ERROR_CODE.ARTIFACT_UNAVAILABLE || e.code === CLAWHUB_INSTALL_ERROR_CODE.ARTIFACT_DOWNLOAD_UNAVAILABLE || e.code === CLAWHUB_INSTALL_ERROR_CODE.CLAWHUB_SECURITY_UNAVAILABLE;
throw new ManagedPluginLifecycleError(e.error, {
kind: t ? "unavailable" : "invalid-request",
code: e.code,
version: e.version,
warning: e.warning,
installPolicyWarning: e.installPolicyWarning,
installRejected: true,
installSource: e.installSource
});
}
/** Install a ClawHub or curated official plugin through the canonical install pipeline. */
async function installManagedPlugin(e) {
try {
assertConfigWriteAllowedInCurrentMode({ env: e.env });
} catch (e) {
throw new ManagedPluginLifecycleError(formatErrorMessage(e), { cause: e });
}
const t = e.env ?? process.env;
const n = resolveClawHubBaseUrl(void 0, t);
const { installManagedPluginSource: r } = await import("./management-install-B26veG3N.mjs");
return await withManagedPluginMutation(e, async (i, a) => {
const performInstall = async () => {
const o = e.request.source === "official" || e.request.source === "clawhub" && isDefaultClawHubBaseUrl(n) ? await loadOfficialCatalog() : { entries: [] };
const s = [];
const c = resolveManagedPluginInstallRequest(e.request, o.entries, n);
const l = resolvePluginInstallRequestContext({
source: c.source,
rawSpec: c.source === "official" ? c.expectedPluginId ?? c.spec : c.source === "local" ? c.path : c.source === "npm-pack" ? `npm-pack:${c.archivePath}` : c.source === "bundled" ? c.bundledSource.localPath : c.source === "marketplace" ? c.plugin : c.spec,
...c.source === "marketplace" ? { marketplace: c.marketplace } : {},
installKind: "plugin"
});
if (!l.ok) throw new ManagedPluginLifecycleError(l.error);
const u = e.snapshot ?? await loadConfigForInstall(l.request).catch((e) => {
if (!(e instanceof PluginInstallConfigError)) throw e;
throw new ManagedPluginLifecycleError(e.message, {
code: PLUGIN_INSTALL_ERROR_CODE.CONFIG_MUTATION_BLOCKED,
installRejected: true,
...c.source === "official" && c.installSources?.[0] ? { installSource: c.installSources[0] } : {},
cause: e
});
});
i();
if (c.source === "local" && c.link) c.successMessage = `Linked plugin path: ${shortenHomePath(c.path)}`;
if (c.source === "clawhub" && e.confirmInstall) c.confirmInstall = e.confirmInstall;
const d = e.applyRuntime ? capturePluginRuntimeApplications(e.applyRuntime) : void 0;
const f = await r({
applyRuntime: d?.applyRuntime,
deferRuntime: e.deferRuntime,
beforePersistentApply: i,
request: c,
enable: e.request.enable,
snapshot: u,
env: t,
logger: {
...e.logger,
warn: (t) => {
s.push(t);
e.logger?.warn?.(t);
}
},
onCapabilityConsent: e.onCapabilityConsent,
requireCapabilityConsent: e.templateManaged === true,
requireClawHubTrust: e.templateManaged === true,
onBeforePluginArtifactCommit: e.onBeforePluginArtifactCommit,
beforePersistentEffect: a,
...e.request.acknowledgeCapabilities ? { acknowledgeCapabilities: e.request.acknowledgeCapabilities } : {},
...e.request.acknowledgeInstallPolicyWarning ? { safetyOverrides: { onInstallPolicyWarning: async () => ({ status: "approved" }) } } : e.safetyOverrides ? { safetyOverrides: e.safetyOverrides } : {},
invalidateRuntimeCache: e.invalidateRuntimeCache ?? false,
runtime: { log: () => {} }
});
if (!f.ok) return throwInstallFailure(f);
try {
s.push(...f.warnings ?? []);
if (e.request.source === "clawhub" && f.clawhub) await reportClawHubPluginInstallTelemetry({
baseUrl: f.clawhub.clawhubUrl,
packageName: f.clawhub.clawhubPackage,
version: f.clawhub.version
}).catch(() => void 0);
const n = resolvePluginControlPlaneWorkspace({
config: f.config,
env: t
});
if (n.diagnostic && !getProcessGatewayPluginMetadataSnapshot()) s.push(n.diagnostic.message);
const r = await refreshManagedPluginMetadata({
config: f.config,
env: t,
assertCurrent: i
});
const a = await listManagedPlugins({
config: f.config,
env: t,
officialCatalog: o,
metadata: r
});
const c = createInstalledPluginOwnershipResolver(r.index, t).resolvePackage(f.pluginId);
if (!c.ok) throw new ManagedPluginLifecycleError(c.error);
const l = c.value.pluginIds;
const u = l[0];
const p = a.plugins.find((e) => e.id === u);
if (!p) throw new ManagedPluginLifecycleError(`installed plugin missing from refreshed registry: ${f.pluginId}`);
return {
plugin: p,
...d?.application ? { application: d.application } : {},
...l.length > 1 || s.length > 0 ? { warnings: [...l.length > 1 ? [`Installed package "${f.pluginId}" with plugin entries: ${l.join(", ")}.`] : [], ...new Set(s)] } : {}
};
} catch (e) {
throw new PluginInstallPersistedError(f.pluginId, e);
}
};
return e.request.source === "clawhub" && !e.templateManaged ? await withClawPackageLifecycleLease({
kind: "plugin",
source: "clawhub",
ref: e.request.packageName
}, performInstall) : await performInstall();
});
}
/** Commit plugin policy without requiring the management catalog's hosted projection. */
async function mutateManagedPluginEnabled(e) {
const t = e.env ?? process.env;
const n = e.caller === "cli";
const r = n || e.allowlistPolicy === "preserve";
return await withManagedPluginMutation(e, async (i, a) => {
if (n) assertConfigWriteAllowedInCurrentMode({ env: t });
const o = n ? await readConfigFileSnapshotForWrite().then(({ snapshot: e, writeOptions: t }) => ({
config: e.sourceConfig,
baseHash: e.hash,
writeOptions: selectInstallMutationWriteOptions(t)
})) : await readPluginMutationSnapshot(t, i);
const s = await loadFreshManagedPluginMetadata(o.config, t);
const c = s.normalizePluginId(n ? normalizePluginId(e.pluginId) : e.pluginId.trim());
const l = s.index.plugins.find((e) => e.pluginId === c);
if (!l) return {
status: "missing",
pluginId: c
};
const resolveConsent = async () => {
if (e.enabled && (e.applyRuntime || !l.enabled || e.requestCapabilityConsent || e.acknowledgeCapabilities)) await resolvePluginCapabilityConsent({
config: o.config,
env: t,
pluginId: c,
acknowledge: e.acknowledgeCapabilities,
onCapabilityConsent: e.onCapabilityConsent,
beforePersistentApply: e.beforePersistentApply,
beforePersistentEffect: a,
metadata: s
});
};
if (!r) await resolveConsent();
let u = o.config;
let d = normalizePluginId(c);
if (e.enabled) {
if (!r && (u.plugins?.allow?.length ?? 0) > 0) u = ensurePluginAllowlisted(u, c);
const e = enableExplicitlySelectedPluginInConfig(u, c, { updateChannelConfig: false });
if (!e.enabled) return {
status: "blocked",
pluginId: c,
reason: e.reason
};
if (r) await resolveConsent();
u = e.config;
d = e.pluginId;
const t = n && !isBundledManifestOwner(l) ? void 0 : s;
i();
u = await applySlotSelectionForPlugin(u, c, t, i);
} else u = setPluginEnabledInConfig(u, c, false, { updateChannelConfig: false });
const f = /* @__PURE__ */ new Set();
collectChangedPaths(o.config, u, "", f);
const p = f.size > 0 ? await replaceConfigFile({
sourceConfig: u,
baseHash: o.baseHash,
writeOptions: {
...o.writeOptions,
beforeCommit: a,
assertConfigPathForWrite: () => {
o.writeOptions.assertConfigPathForWrite?.();
i();
},
...n || e.applyRuntime ? { explicitSetPaths: [[
"plugins",
"entries",
d
]] } : {},
...e.applyRuntime ? { afterWrite: {
mode: "none",
reason: "plugin lifecycle applies runtime"
} } : {}
}
}) : void 0;
if (!p) {
await assertRecordsOnlyUpdateConfigFresh(o);
i();
}
const m = [];
await refreshPluginRegistryAfterConfigMutation({
configPath: p?.path ?? o.writeOptions.ownedConfigPathForWrite ?? o.writeOptions.expectedConfigPath,
env: t,
reason: "policy-changed",
invalidateRuntimeCache: false,
policyPluginIds: [d],
logger: { warn: (e) => m.push(e) }
});
return {
write: p,
policyPluginId: d,
status: "committed",
pluginId: c,
config: u,
changedPaths: [...f].filter(Boolean).toSorted(),
warnings: m
};
});
}
/** Persist desired policy and project the committed candidate into the management catalog. */
async function setManagedPluginEnabled(e) {
const t = e.env ?? process.env;
return await withManagedPluginMutation(e, async (n, r) => {
const i = await mutateManagedPluginEnabled({
...e,
caller: "management"
});
if (i.status !== "committed") throw new ManagedPluginLifecycleError(i.status === "missing" ? `plugin not installed: ${e.pluginId}` : `plugin "${i.pluginId}" could not be enabled (${i.reason ?? "unknown reason"})`);
const a = await refreshManagedPluginMetadata({
config: i.config,
env: t,
assertCurrent: n
});
await r();
const o = await e.applyRuntime?.({
config: i.config,
write: i.write,
pluginIds: [i.policyPluginId],
reason: e.enabled ? "enable" : "disable",
assertInvokerOwned: n
});
const s = (await listManagedPlugins({
config: i.config,
env: t,
metadata: a
})).plugins.find((e) => e.id === i.pluginId);
if (!s) throw new ManagedPluginLifecycleError(`updated plugin missing from refreshed registry: ${i.pluginId}`);
return {
plugin: s,
changedPaths: i.changedPaths,
...o ? { application: o } : {},
...i.warnings.length > 0 ? { warnings: i.warnings } : {}
};
});
}
/** Reload the selected installed package through the running Gateway's lifecycle owner. */
async function reloadManagedPlugin(e) {
const t = e.env ?? process.env;
return await withManagedPluginMutation(e, async (n, r) => {
const i = await readPluginRuntimeConfig();
const a = await loadFreshManagedPluginMetadata(i, t);
const o = e.plugins;
const s = o.some((e) => e.installHash !== void 0);
const resolveTargets = async () => {
const e = s ? await readPersistedInstalledPluginIndexInstallRecordsAsync({ env: t }) : void 0;
n();
const r = createInstalledPluginOwnershipResolver(a.index, t);
return o.map((t) => {
const n = a.normalizePluginId(t.pluginId.trim());
const i = r.resolveReload(n);
if (!i.ok || i.value.kind === "orphan") throw new ManagedPluginLifecycleError(i.ok ? `plugin not installed: ${n}` : i.error);
const o = i.value.pluginIds;
if (t.installHash !== void 0) {
const r = i.value.installOwner;
if (!r || !e?.[r] || hashStableJson(e[r]) !== t.installHash) throw new ManagedPluginLifecycleError(`Plugin ${n} changed after the installation batch. Inspect it before reloading.`);
}
const s = t.sourceDigests ?? {};
if (Object.keys(s).some((e) => !o.includes(e))) throw new ManagedPluginLifecycleError(`Source expectations for ${n} include a different package owner`);
return {
pluginId: n,
pluginIds: o,
sourceDigests: s
};
});
};
for (const n of new Set((await resolveTargets()).flatMap((e) => e.pluginIds))) await resolvePluginCapabilityConsent({
config: i,
env: t,
pluginId: n,
metadata: a,
acknowledge: e.acknowledgeCapabilities,
beforePersistentApply: e.beforePersistentApply,
beforePersistentEffect: r
});
const c = await resolveTargets();
const l = [...new Set(c.flatMap((e) => e.pluginIds))].toSorted();
const u = /* @__PURE__ */ new Map();
for (const e of c) for (const [t, n] of Object.entries(e.sourceDigests)) {
if (u.has(t) && u.get(t) !== n) throw new ManagedPluginLifecycleError(`Conflicting source expectations for ${t}`);
u.set(t, n);
}
await r();
return {
pluginIds: c.map((e) => e.pluginId),
application: await e.applyRuntime({
config: i,
pluginIds: l,
reason: "reload",
...e.waitForDrain ? {
waitForDrain: true,
drainSignal: e.signal
} : {},
...u.size ? { expectedSourceDigests: Object.fromEntries(u) } : {},
assertInvokerOwned: n
})
};
});
}
/** Apply an explicit metadata refresh under the same cross-process lifecycle lease. */
async function refreshManagedPlugins(e) {
const t = e.env ?? process.env;
return await withManagedPluginMutation(e, async (n, r) => {
const i = await readPluginRuntimeConfig();
n();
await refreshManagedPluginMetadata({
config: i,
env: t,
assertCurrent: n
});
await r();
return { application: await e.applyRuntime({
config: i,
pluginIds: [],
reason: "metadata",
assertInvokerOwned: n
}) };
});
}
//#endregion
export { setManagedPluginEnabled as a, reloadManagedPlugin as i, mutateManagedPluginEnabled as n, refreshManagedPlugins as r, installManagedPlugin as t };