openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
427 lines (426 loc) • 18.4 kB
JavaScript
import { l as normalizeOptionalString } from "./string-coerce-CCIiB4H7.mjs";
import { n as parseBooleanValue } from "./boolean-2vRuVafy.mjs";
import { a as extractErrorCode, r as collectErrorGraphCandidates } from "./error-coercion-hDrHOSGy.mjs";
import { n as groupPluginRecords } from "./record-groups-DII71OvH.mjs";
import { i as readErrorCause } from "./errors-BKzCeTYb.mjs";
import { _ as recordPluginCandidateInstallOwner, a as isPluginLifecycleTraceEnabled } from "./discovery-DvJYrQFY.mjs";
import { t as VERSION } from "./version-GlxUMdxI.mjs";
import { t as isPluginEnabledByDefaultForPlatform } from "./default-enablement-DLXVIwwO.mjs";
import { t as normalizePluginPolicyId } from "./plugin-policy-id-CkilMowp.mjs";
import { D as hasKind, f as resolveEffectiveEnableState, k as normalizeSlotValue, p as resolveEffectivePluginActivationState } from "./config-state-B1JlHgba.mjs";
import { u as collectPluginManifestCompatCodes } from "./installed-plugin-index-DYqse_gE.mjs";
import { h as formatPluginVerificationDiagnostic } from "./discovery-availability-DtlJ7XvT.mjs";
import { i as resolvePluginManifestInstallOwner, r as isPluginManifestInstallOwnerAmbiguous } from "./manifest-registry-build-BbYTyBDW.mjs";
import { r as formatDeferredPluginMigration } from "./deferred-plugin-migrations-C_CU0aKR.mjs";
import { a as capturePluginLifecycleAuthority } from "./registry-lifecycle-CJjWnl-y.mjs";
import { S as rollbackStagedPluginRegistry, i as commitStagedPluginRegistry, n as captureActivePluginRegistrySnapshot, w as stageActivePluginRegistry } from "./runtime-ezCEpumg.mjs";
import { r as validatePluginConfig } from "./schema-validator-NvoOmaWr.mjs";
import { o as shippedNativeSessionCatalogs } from "./native-session-catalog-config-CCzXMHUi.mjs";
import { a as initializeGlobalHookRunner, o as resetGlobalHookRunner, r as getGlobalPluginRegistry } from "./hook-runner-global-DmYyIVDp.mjs";
import { t as isBundleCapabilitySupported } from "./bundle-capability-support-BXvfrEHi.mjs";
import { t as recordPluginLoadDiagnostic } from "./load-diagnostics-t12s35CB.mjs";
import { t as createManifestProviderIdLists } from "./manifest-provider-ids-ShNycIUa.mjs";
import { t as activateContextEngineRegistrations } from "./registry-BNPXTWdk.mjs";
import { b as resolveMemoryDreamingConfig, s as DEFAULT_MEMORY_DREAMING_PLUGIN_ID, x as resolveMemoryDreamingPluginConfig } from "./dreaming-C72ZWZJr.mjs";
import { t as encodeStartupTraceSegment } from "./startup-trace-segment-uV5tTGWs.mjs";
//#region src/plugins/loader-records.ts
/** Builds the registry record shape shared by plugin loading, status, and diagnostics. */
function createPluginRecord(e) {
return {
id: e.id,
nativeSessionCatalog: e.nativeSessionCatalog,
name: e.name ?? e.id,
description: e.description,
packageVersion: e.packageVersion,
version: e.version,
builtWithOpenClawVersion: e.builtWithOpenClawVersion,
packageName: e.packageName,
format: e.format ?? "openclaw",
bundleFormat: e.bundleFormat,
bundleCapabilities: e.bundleCapabilities,
source: e.source,
rootDir: e.rootDir,
origin: e.origin,
workspaceDir: e.workspaceDir,
trustedOfficialInstall: e.trustedOfficialInstall,
trust: e.trust,
enabled: e.enabled,
compat: e.compat,
explicitlyEnabled: e.activationState?.explicitlyEnabled,
activated: e.activationState?.activated,
activationSource: e.activationState?.source,
activationReason: e.activationState?.reason,
syntheticAuthRefs: e.syntheticAuthRefs ?? [],
status: e.enabled ? "loaded" : "disabled",
toolNames: [],
hookNames: [],
channelIds: [...e.channelIds ?? []],
cliBackendIds: [],
providerIds: [...e.providerIds ?? []],
...createManifestProviderIdLists(e.contracts),
contextEngineIds: [],
declaredContextEngineIds: e.declaredContextEngineIds,
...e.turnHandover ? { turnHandover: true } : {},
agentHarnessIds: [],
cliCommands: [],
services: [],
gatewayDiscoveryServiceIds: [],
commands: [],
httpRoutes: 0,
hookCount: 0,
configSchema: e.configSchema,
configUiHints: void 0,
configJsonSchema: void 0,
contracts: e.contracts,
dashboard: e.dashboard,
controlUi: e.controlUi,
uiCapabilities: e.uiCapabilities,
mcpServers: e.mcpServers
};
}
/** Marks a discovered plugin inactive without discarding its metadata record. */
function markPluginActivationDisabled(e, t) {
e.status = "disabled";
e.error = t;
e.activated = false;
e.activationSource = "disabled";
e.activationReason = t;
}
/** Records runtime admission refusal without importing or activating the plugin. */
function recordPluginConfiguredUnavailable(e) {
const t = "pendingStateMigration" in e;
const n = t ? formatDeferredPluginMigration(e.pendingStateMigration, e.env) : formatPluginVerificationDiagnostic(e.degradedPlugin.diagnostic);
const r = t ? "pending-state-migration" : e.degradedPlugin.diagnostic.reason;
e.record.status = "error";
e.record.error = n;
e.record.failurePhase = "validation";
e.record.activated = false;
e.record.activationReason = `configured-unavailable: ${r}`;
e.registry.plugins.push(e.record);
e.seenIds.set(e.record.id, e.record.origin);
e.registry.diagnostics.push({
level: "error",
pluginId: e.record.id,
source: e.record.source,
code: t ? "plugin-state-migration" : "plugin-verification",
message: n
});
return n;
}
/** Joins auto-enable reasons into the single registry field shown by status surfaces. */
function formatAutoEnabledActivationReason(e) {
return e?.length ? e.join("; ") : void 0;
}
function readCauseOrNothing(e) {
try {
return [readErrorCause(e)];
} catch {
return [];
}
}
function resolvePluginImportHint(e, t, n) {
try {
const r = String(e).replaceAll("\\", "/");
const i = /(?:The requested module ['"]openclaw\/|Package subpath ['"]\.\/)(plugin-sdk\/[\w./-]{1,160})['"] (?:does not provide an export named|is not defined by ["']exports["'] in .*\/openclaw\/package\.json)/.exec(r)?.[1];
if (i) {
const e = {
seam: `openclaw/${i}`,
coreVersion: VERSION,
builtWithOpenClawVersion: t.builtWithOpenClawVersion,
nestedSdk: Boolean(t.rootDir && r.includes(`${t.rootDir.replaceAll("\\", "/")}/node_modules/openclaw/package.json`))
};
const n = e.nestedSdk ? "this plugin bundles an incompatible OpenClaw SDK; update it or contact its author" : /^[a-z0-9_][a-z0-9_.-]*$/i.test(t.id) ? `run \`openclaw plugins update ${t.id}\`` : "update this plugin or contact its author";
return {
hint: `Plugin ${t.id} cannot import ${e.seam} (built with OpenClaw ${t.builtWithOpenClawVersion ?? "unknown"}; running core ${VERSION}); ${n}`,
sdkCompatibility: e
};
}
const a = extractErrorCode(e);
return n && (a === "MODULE_NOT_FOUND" || a === "ERR_MODULE_NOT_FOUND") ? { hint: n } : void 0;
} catch {
return;
}
}
/** Records a loader failure in the registry, diagnostics list, and operator log consistently. */
function recordPluginError(e) {
const t = isPluginLifecycleTraceEnabled() && e.error instanceof Error && typeof e.error.stack === "string" ? e.error.stack : String(e.error);
const n = t.includes("api.registerHttpHandler") && t.includes("is not a function") ? "deprecated api.registerHttpHandler(...) was removed; use api.registerHttpRoute(...) for plugin-owned routes or registerPluginHttpRoute(...) for dynamic lifecycle routes" : null;
const r = collectErrorGraphCandidates(e.error, readCauseOrNothing);
const i = r.map(extractErrorCode).find((e) => e !== void 0);
const a = e.phase === "validation" ? void 0 : r.map((t) => resolvePluginImportHint(t, e.record, e.missingDependencyHint)).find((e) => e !== void 0);
const o = i === "ENOSPC" ? "ENOSPC: no space left on device; free space on the filesystem used by the plugin load and rerun Doctor" : e.phase === "validation" ? void 0 : n ?? a?.hint;
const s = o ? `${o} (${t})` : t;
e.record.status = "error";
e.record.error = s;
e.record.failedAt = /* @__PURE__ */ new Date();
e.record.failurePhase = e.phase;
e.registry.plugins.push(e.record);
e.seenIds.set(e.record.id, e.record.origin);
const c = {
level: "error",
pluginId: e.record.id,
source: e.record.source,
message: `${e.diagnosticMessagePrefix ?? ""}${s}`,
...i ? { errorCode: i } : {},
...a?.sdkCompatibility ? {
code: e.diagnosticCode ?? "sdk-incompatible",
sdkCompatibility: a.sdkCompatibility
} : e.diagnosticCode ? { code: e.diagnosticCode } : {}
};
e.registry.diagnostics.push(c);
recordPluginLoadDiagnostic(c);
e.logger?.error(`${e.logPrefix ?? ""}${s}`);
}
/** Groups failed plugin ids by loader phase for compact startup summaries. */
function formatPluginFailureSummary(e) {
return [...groupPluginRecords(e, (e) => e.failurePhase ?? "load")].map(([e, t]) => `${e}: ${t.map((e) => e.id).join(", ")}`).join("; ");
}
function describePluginModuleExportShape(e, t = "export", n = /* @__PURE__ */ new Set()) {
if (e === null) return [`${t}:null`];
if (typeof e !== "object") return [`${t}:${typeof e}`];
if (n.has(e)) return [`${t}:circular`];
n.add(e);
const r = e;
const i = Object.keys(r).toSorted();
const a = i.slice(0, 8);
const o = i.length - a.length;
const s = [`${t}:object keys=${a.length > 0 ? `${a.join(",")}${o > 0 ? `,+${o}` : ""}` : "none"}`];
for (const e of [
"default",
"module",
"register",
"activate"
]) if (Object.hasOwn(r, e)) s.push(...describePluginModuleExportShape(r[e], `${t}.${e}`, n));
return s;
}
function formatMissingPluginRegisterError(e, t) {
const n = "plugin export missing register/activate";
if (parseBooleanValue(t.OPENCLAW_PLUGIN_LOAD_DEBUG) !== true) return n;
return `${n} (module shape: ${describePluginModuleExportShape(e).join("; ")})`;
}
function recordBundleDiagnostics(e) {
const warn = (t) => e.registry.diagnostics.push({
level: "warn",
pluginId: e.record.id,
source: e.record.source,
message: t
});
const t = (e.record.bundleCapabilities ?? []).filter((t) => !e.record.bundleFormat || !isBundleCapabilitySupported(e.record.bundleFormat, t));
for (const e of t) warn(`bundle capability detected but not wired into OpenClaw yet: ${e}`);
if (e.record.enabled && e.record.rootDir && e.record.bundleFormat && (e.record.bundleCapabilities ?? []).includes("mcpServers")) {
const t = e.inspectMcp({
pluginId: e.record.id,
rootDir: e.record.rootDir,
bundleFormat: e.record.bundleFormat
});
for (const e of t.diagnostics) warn(e);
if (t.unsupportedServerNames.length > 0) warn(`bundle MCP servers use unsupported transports or incomplete configs (${t.unsupportedServerNames.join(", ")})`);
}
e.registry.plugins.push(e.record);
}
//#endregion
//#region src/plugins/loader-shared.ts
function prepareRuntimePluginConfig(e) {
const { candidate: t, manifestRecord: n, context: r, preparedConfig: i } = e;
if (!i.validation) {
const e = normalizePluginPolicyId(n.id);
i.validation = validatePluginConfig({
origin: t.origin,
schema: n.configSchema,
cacheKey: n.schemaCacheKey,
value: r.normalized.entries[e]?.config,
sourceValue: n.configContracts?.secretInputs ? r.activationSource.plugins.entries[e]?.config : void 0
});
i.input = JSON.stringify(i.validation);
}
return i.validation;
}
function detailPluginStartupTrace(e, t, n) {
e?.detail(`plugins.gateway-load.plugin.${encodeStartupTraceSegment(t)}`, n);
}
function resolveAuthorizedDreamingSidecar(e) {
const t = normalizeSlotValue(e.memorySlot);
if (!t || t === "memory-core") return null;
if (!resolveMemoryDreamingConfig({
pluginConfig: resolveMemoryDreamingPluginConfig(e.cfg),
cfg: e.cfg
}).enabled || !e.normalized.enabled || !e.activationSource.plugins.enabled) return null;
const n = DEFAULT_MEMORY_DREAMING_PLUGIN_ID;
if (e.normalized.deny.includes(n) || e.activationSource.plugins.deny.includes(n) || e.normalized.entries[n]?.enabled === false || e.activationSource.plugins.entries[n]?.enabled === false) return null;
const r = e.manifestRegistry.plugins.find((e) => e.id === t);
const i = e.manifestRegistry.plugins.find((e) => e.id === n);
if (!r || !i || !hasKind(r.kind, "memory") || !hasKind(i.kind, "memory")) return null;
return resolveEffectiveEnableState({
id: r.id,
origin: r.origin,
config: e.normalized,
rootConfig: e.cfg,
enabledByDefault: isPluginEnabledByDefaultForPlatform(r),
activationSource: e.activationSource
}).enabled ? {
engineId: n,
selectedMemoryPluginId: t
} : null;
}
function matchesScopedPluginOrDreamingSidecar(e) {
if (!e.onlyPluginIdSet || e.onlyPluginIdSet.has(e.pluginId)) return true;
return e.pluginId === e.sidecar?.engineId && e.onlyPluginIdSet.has(e.sidecar.selectedMemoryPluginId);
}
function createPluginCandidatesFromManifestRegistry(e) {
return e.plugins.map((e) => {
const t = resolvePluginManifestInstallOwner(e);
return recordPluginCandidateInstallOwner({
idHint: e.id,
effectivePluginId: e.id,
rootDir: e.rootDir,
source: e.source,
...e.setupSource !== void 0 ? { setupSource: e.setupSource } : {},
origin: e.origin,
...e.sourcePreferred ? { sourcePreferred: true } : {},
...e.workspaceDir !== void 0 ? { workspaceDir: e.workspaceDir } : {},
...e.format !== void 0 ? { format: e.format } : {},
...e.bundleFormat !== void 0 ? { bundleFormat: e.bundleFormat } : {},
...e.packageManifest !== void 0 ? { packageManifest: e.packageManifest } : {}
}, t, isPluginManifestInstallOwnerAmbiguous(e));
});
}
var PluginLoadFailureError = class extends Error {
constructor(e, t) {
const n = t.map((e) => `${e.id}: ${e.error ?? "unknown plugin load error"}`).join("; ");
super(`plugin load failed: ${n}`);
this.name = "PluginLoadFailureError";
this.registry = e;
this.onlyPendingStateMigrations = t.every((t) => e.diagnostics.some((e) => e.pluginId === t.id && e.code === "plugin-state-migration"));
}
};
/** Builds the common manifest-backed record shape used by runtime and CLI loaders. */
function createManifestPluginRecord(e) {
const { candidate: t, manifestRecord: n } = e;
const r = createPluginRecord({
...n,
nativeSessionCatalog: n.setup?.nativeSessionCatalog ?? shippedNativeSessionCatalogs.find(({ pluginId: e }) => e === n.id),
builtWithOpenClawVersion: normalizeOptionalString(t.packageManifest?.build?.openclawVersion),
source: t.source,
rootDir: t.rootDir,
origin: t.origin,
workspaceDir: t.workspaceDir,
enabled: e.enabled,
compat: collectPluginManifestCompatCodes(n),
activationState: e.activationState,
channelIds: n.channels,
providerIds: n.providers,
declaredContextEngineIds: n.contextEngineIds,
turnHandover: n.reload?.turnHandover === true,
configSchema: Boolean(n.configSchema)
});
if (!e.shouldLoadModules) {
r.cliBackendIds = [...n.cliBackends ?? [], ...n.setup?.cliBackends ?? []];
r.commands = (n.commandAliases ?? []).map((e) => e.name);
}
return r;
}
/** Prepares one candidate; import and registration policy stays with each loader. */
function preparePluginLoadRecord(e) {
const { candidate: t, manifestRecord: n, context: r, dreamingSidecar: i } = e;
const a = n.id;
const o = normalizePluginPolicyId(a);
if (!matchesScopedPluginOrDreamingSidecar({
onlyPluginIdSet: e.onlyPluginIdSet,
pluginId: a,
sidecar: i
})) return null;
const s = i?.engineId === a;
const c = s ? {
enabled: true,
activated: true,
explicitlyEnabled: false,
source: "auto",
reason: `dreaming sidecar for selected memory slot "${i?.selectedMemoryPluginId ?? ""}"`
} : resolveEffectivePluginActivationState({
id: a,
origin: t.origin,
config: r.normalized,
rootConfig: r.cfg,
enabledByDefault: isPluginEnabledByDefaultForPlatform(n),
channelIds: n.channels,
activationSource: r.activationSource,
autoEnabledReason: formatAutoEnabledActivationReason(r.autoEnabledReasons[a])
});
const l = e.seenIds.get(a);
if (l) {
const i = createManifestPluginRecord({
candidate: t,
manifestRecord: n,
enabled: false,
activationState: c,
shouldLoadModules: r.shouldLoadModules
});
markPluginActivationDisabled(i, `overridden by ${l} plugin`);
e.registry.plugins.push(i);
return null;
}
const u = s ? { enabled: true } : resolveEffectiveEnableState({
id: a,
origin: t.origin,
config: r.normalized,
rootConfig: r.cfg,
enabledByDefault: isPluginEnabledByDefaultForPlatform(n),
channelIds: n.channels,
activationSource: r.activationSource
});
const d = r.normalized.entries[o];
const f = createManifestPluginRecord({
candidate: t,
manifestRecord: n,
enabled: u.enabled,
activationState: c,
shouldLoadModules: r.shouldLoadModules
});
f.kind = n.kind;
f.configUiHints = n.configUiHints;
f.configJsonSchema = n.configSchema;
f.commandAliases = n.commandAliases;
return {
pluginId: a,
isDreamingSidecar: s,
activationState: c,
enableState: u,
entry: d,
record: f
};
}
function maybeThrowOnPluginLoadError(e, t, n, r, i) {
if (!t) return;
const a = e.plugins.filter((e) => {
if (e.status !== "error" || n?.get(e.id) === e) return false;
const t = r?.plugins.find((t) => t.id === e.id);
return i?.has(e.id) || t?.status !== "error" || t.source !== e.source || t.failurePhase !== e.failurePhase || t.error !== e.error;
});
if (a.length > 0) throw new PluginLoadFailureError(e, a);
}
function activatePluginRegistry(e, t, n, r, i, a) {
const o = captureActivePluginRegistrySnapshot();
const s = i ?? o.activeRegistry;
const c = getGlobalPluginRegistry();
let l = false;
try {
stageActivePluginRegistry(e, t, n, r);
const i = capturePluginLifecycleAuthority(e);
initializeGlobalHookRunner(e);
activateContextEngineRegistrations(e, {
trackCleanup: (e) => a?.(e),
assertCurrent: () => {
if (l || !i?.()) throw new Error("Plugin registry activation was superseded");
}
});
commitStagedPluginRegistry(s, e);
} catch (e) {
l = true;
rollbackStagedPluginRegistry(o, s);
if (c) initializeGlobalHookRunner(c);
else resetGlobalHookRunner();
throw e;
}
}
//#endregion
export { matchesScopedPluginOrDreamingSidecar as a, prepareRuntimePluginConfig as c, formatPluginFailureSummary as d, markPluginActivationDisabled as f, recordPluginError as h, detailPluginStartupTrace as i, resolveAuthorizedDreamingSidecar as l, recordPluginConfiguredUnavailable as m, activatePluginRegistry as n, maybeThrowOnPluginLoadError as o, recordBundleDiagnostics as p, createPluginCandidatesFromManifestRegistry as r, preparePluginLoadRecord as s, PluginLoadFailureError as t, formatMissingPluginRegisterError as u };