UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

504 lines (503 loc) • 15.3 kB
import { t as isPlainObject } from "./plain-object-CGY5w7fM.mjs"; import "./utils-C8YECn2Q.mjs"; import { t as DEFAULT_ACCOUNT_ID } from "./account-id-BqKT3GuY.mjs"; import { d as getActivePluginRegistryVersion, l as getActivePluginRegistry } from "./runtime-ezCEpumg.mjs"; import { o as resolveConfiguredTalkRealtimeProviderId, s as resolveConfiguredTalkSpeechProviderId } from "./talk-CqEDzucG.mjs"; import { r as listChannelPlugins } from "./registry-ByqVE5S3.mjs"; import "./plugins-BoMiRtiY.mjs"; import { t as canHotReloadGatewayAuthCredentials } from "./auth-resolve-C6_i-P4T.mjs"; import { t as haveSameOperatorRoleSourcePolicies } from "./operator-role-source-policy-CRYRV_Bv.mjs"; import { isDeepStrictEqual } from "node:util"; //#region src/gateway/config-diff.ts function collectConfigDiffPaths(e, t, n, r, i) { if (e === t) return; const a = isPlainObject(e); const o = isPlainObject(t); if (a && o || (a || o) && r.some((e) => n ? e.startsWith(`${n}.`) : true)) { const s = a ? e : {}; const c = o ? t : {}; const l = /* @__PURE__ */ new Set([...Object.keys(s), ...Object.keys(c)]); for (const e of l) { const t = s[e]; const a = c[e]; if (t === void 0 && a === void 0) continue; collectConfigDiffPaths(t, a, n ? `${n}.${e}` : e, r, i); } return; } if (Array.isArray(e) && Array.isArray(t)) { if (isDeepStrictEqual(e, t)) return; } i.push(n || "<root>"); } /** Return dotted config paths whose values differ between two config snapshots. */ function diffConfigPaths(e, t, n = "", r = []) { const i = []; collectConfigDiffPaths(e, t, n, r, i); return i; } function projectGatewayReloadBoundaries(e) { return { talk: { provider: resolveConfiguredTalkSpeechProviderId(e), realtime: { provider: resolveConfiguredTalkRealtimeProviderId(e) } } }; } /** Preserve declared reload boundaries and derived capability-owner changes. */ function diffGatewayReloadPaths(e, t, n) { const r = new Set(n); for (const n of [e, t]) for (const e of Object.keys(n.plugins?.entries ?? {})) r.add(`plugins.entries.${e}`); const i = []; if (e.agents?.entries === void 0 !== (t.agents?.entries === void 0)) i.push("agents.entries"); const a = r.delete("agents.entries.*.decisionModel"); for (const [n, o] of [[e, t], [t, e]]) for (const [e, t] of Object.entries(n.agents?.entries ?? {})) { if (!Object.hasOwn(o.agents?.entries ?? {}, e)) i.push(`agents.entries.${e}`); if (a && t.decisionModel !== void 0) r.add(`agents.entries.${e}.decisionModel`); } const o = diffConfigPaths(e, t, "", [...r]); const s = diffConfigPaths(projectGatewayReloadBoundaries(e), projectGatewayReloadBoundaries(t)); return [...o, ...[...i, ...s].filter((e) => !o.includes(e))]; } //#endregion //#region src/gateway/config-reload-plan.ts const RELOAD_ACTIONS = [ "reloadHooks", "reloadInternalHooks", "refreshHooksPolicy", "restartGmailWatcher", "restartCron", "reloadPlugins", "disposeMcpRuntimes" ]; function isNoopGatewayReloadPlan(e) { return !e.restartGateway && e.hotReasons.length === 0 && RELOAD_ACTIONS.every((t) => !e[t]) && e.restartChannels.size === 0 && (e.restartServices?.size ?? 0) === 0 && (e.restartChannelAccounts?.size ?? 0) === 0; } const PLUGIN_INSTALL_TIMESTAMP_KEYS = ["installedAt", "resolvedAt"]; const AUTH_CREDENTIAL_PATHS = ["gateway.auth.token", "gateway.auth.password"]; const SHARED_CHANNEL_PREFIXES = [ "agents.defaults.mediaMaxMb", "channels.defaults", "channels.modelByChannel", "messages.inbound", "messages.ackReactionScope", "commands", "accessGroups", "tts", "surfaces", "acp.stream", "diagnostics.flags" ]; function matchesReloadPrefix(e, t, n = false) { if (t.includes("*")) { const r = e.split("."); return t.split(".").every((e, t) => n && t >= r.length || (e === "*" ? Boolean(r[t]) : e === r[t])); } return e === t || e.startsWith(`${t}.`) || n && t.startsWith(`${e}.`); } function compareReloadRules(e, t) { const n = e.prefix.split("."); const r = t.prefix.split("."); return r.length - n.length || n.filter((e) => e === "*").length - r.filter((e) => e === "*").length; } function expandReloadPolicies(e) { return e.flatMap(({ prefixes: e, ...t }) => e.map((e) => ({ ...t, prefix: e }))).toSorted(compareReloadRules); } const AGENT_ROSTER_RELOAD_ACTIONS = ["refreshHooksPolicy", "reloadInternalHooks"]; const CORE_RELOAD_POLICIES = [ { prefixes: ["gateway.remote", "gateway.reload"], kind: "none" }, { prefixes: [ ...AUTH_CREDENTIAL_PATHS, "mcp.apps", "secrets.egressProxy", "gateway.portals" ], kind: "restart" }, { prefixes: ["tools.gatewayPolicy"], kind: "restart" }, { prefixes: [ "gateway.http.endpoints", "gateway.http.securityHeaders.strictTransportSecurity", "gateway.tools", "gateway.uploads", "gateway.cliAgents", "gateway.controlUi.enabled", "gateway.controlUi.environment", "gateway.controlUi.communityInvite", "gateway.controlUi.newSessionModelDefaults", "gateway.controlUi.github", "gateway.controlUi.sessionObserver", "gateway.controlUi.embedSandbox", "gateway.controlUi.allowExternalEmbedUrls", "gateway.controlUi.automaticallyFetchFavicons", "gateway.controlUi.experimental.customPlugins", "gateway.controlUi.experimental.templates", "gateway.controlUi.experimental.chatBubbles", "gateway.controlUi.allowedOrigins", "gateway.controlUi.dangerouslyAllowHostHeaderOriginFallback", "gateway.nodes.browser", "gateway.nodes.pairing", "gateway.nodes.commands", "gateway.nodes.pluginTools.enabled", "gateway.nodes.allowSkills", "gateway.push.apns.relay", "gateway.terminal", "gateway.auth.rateLimit", "gateway.roles", "gateway.trustedProxies", "gateway.allowRealIpFallback", "gateway.auth.allowTailscale", "gateway.auth.identityScopes", "gateway.auth.trustedProxy", "diagnostics.enabled", "discovery.mdns.mode", "mcp.apps.sandboxOrigin", "agents.defaults", "models", "desktop.host", "cloudWorkers" ], kind: "hot" }, { prefixes: ["hooks.gmail"], kind: "hot", actions: ["restartGmailWatcher", "reloadHooks"] }, { prefixes: ["hooks.internal", "agents.defaults.workspace"], kind: "hot", actions: ["reloadInternalHooks"] }, { prefixes: ["hooks"], kind: "hot", actions: ["reloadHooks"] }, { prefixes: ["agents.entries"], kind: "hot", actions: AGENT_ROSTER_RELOAD_ACTIONS }, { prefixes: ["agents.entries.*.decisionModel"], kind: "hot", actions: [...AGENT_ROSTER_RELOAD_ACTIONS, "reloadPlugins"] }, { prefixes: ["agents.defaults.sessionStore", "agents.ownership"], kind: "hot", actions: ["refreshHooksPolicy"] }, { prefixes: ["agents.defaults.decisionModel"], kind: "hot", actions: ["reloadPlugins"] }, { prefixes: ["plugins.load", "plugins.installs"], kind: "hot", actions: ["reloadPlugins"] }, { prefixes: ["cron"], kind: "hot", actions: ["restartCron"] }, { prefixes: ["transcripts", "cloudWorkers.profiles"], kind: "hot", actions: ["reloadPlugins"] }, { prefixes: ["mcp", "gateway.publicOrigin"], kind: "hot", actions: ["disposeMcpRuntimes"] }, { prefixes: ["talk.provider", "talk.realtime.provider"], kind: "hot", actions: ["reloadPlugins"] } ]; const DEFAULT_RELOAD_POLICIES = [ { prefixes: [ "meta", "identity", "wizard", "logging", "agents", "bindings", "audio", "agent", "routing", "messages", "session", "talk", "skills", "secrets", "tui", "ui" ], kind: "none" }, { prefixes: [ "tools", "approvals.exec", "approvals.plugin", "auth.order", "auth.profiles", "broadcast", "memory.citations", "worktreeRoot", "worktreeMaxCount", "worktreeAcceleration", "security.audit.suppressions", "security.installPolicy", "diagnostics.cacheTrace.enabled", "acp", "attachments.ttlHours", "update.checkOnStart", "update.channel", "update.auto.enabled", "telemetry.enabled", "telemetry.consentedAt" ], kind: "hot" }, { prefixes: ["plugins"], kind: "hot", actions: ["reloadPlugins", "disposeMcpRuntimes"] }, { prefixes: ["channels"], kind: "hot", actions: ["reloadPlugins"], replaceChannelPlugins: true }, { prefixes: [ "gateway", "discovery", "database" ], kind: "restart" } ]; let cachedCatalog; function getReloadPolicyCatalog() { const e = getActivePluginRegistry(); const t = getActivePluginRegistryVersion(); if (cachedCatalog?.registry === e && cachedCatalog.version === t) return cachedCatalog; const n = listChannelPlugins(); const r = (e?.services ?? []).map(({ id: e, service: t }) => ({ id: e, prefixes: t.reload?.configPrefixes ?? [] })); const i = n.flatMap((e) => [{ prefixes: e.reload?.configPrefixes ?? [], kind: "hot", channels: [e], accountScoped: e.reload?.accountScopedRestart }, { prefixes: e.reload?.noopPrefixes ?? [], kind: "none", channels: [e] }]); const a = expandReloadPolicies(i); const o = /* @__PURE__ */ new Set([...SHARED_CHANNEL_PREFIXES, ...a.filter(({ prefix: e }) => SHARED_CHANNEL_PREFIXES.some((t) => matchesReloadPrefix(e, t))).map(({ prefix: e }) => e)]); const s = expandReloadPolicies([ ...CORE_RELOAD_POLICIES, ...(e?.reloads ?? []).flatMap(({ registration: e }) => [ ["restart", e.restartPrefixes], ["hot", e.hotPrefixes], ["none", e.noopPrefixes] ].map(([e, t]) => ({ kind: e, prefixes: t ?? [] }))), ...Array.from(o, (e) => { const t = n.filter((t) => a.find((n) => n.channels?.includes(t) && matchesReloadPrefix(e, n.prefix))?.kind !== "none"); const i = r.some(({ prefixes: t }) => t.some((t) => matchesReloadPrefix(e, t))); return { prefixes: [e], kind: t.length || i ? "hot" : "none", channels: t }; }), ...i, ...n.map((e) => ({ prefixes: [`plugins.entries.${e.id}`], kind: "hot", actions: ["reloadPlugins", "disposeMcpRuntimes"], channels: [e] })), { prefixes: ["session.scope", "session.store"], kind: "hot", actions: ["refreshHooksPolicy"] }, ...DEFAULT_RELOAD_POLICIES ]); const c = [...s, ...r.flatMap(({ prefixes: e }) => e.map((e) => ({ ...s.find((t) => matchesReloadPrefix(e, t.prefix)), kind: "hot", prefix: e })))]; c.sort(compareReloadRules); cachedCatalog = { registry: e, version: t, rules: c, servicePolicies: r, refinementPrefixes: c.map((e) => e.prefix) }; return cachedCatalog; } function listConfigReloadRefinementPrefixes() { return getReloadPolicyCatalog().refinementPrefixes; } function matchRule(e) { return getReloadPolicyCatalog().rules.find(({ prefix: t }) => matchesReloadPrefix(e, t)); } function resolveConfigReloadMetadata(e) { if (isPluginInstallTimestampPath(e)) return { kind: "none" }; return { kind: matchRule(e)?.kind ?? "restart" }; } function isPluginInstallTimestampPath(e) { return /^plugins\.installs\..+\.(installedAt|resolvedAt)$/.test(e); } function getPluginInstallRecords(e) { if (!isPlainObject(e)) return {}; const t = e.plugins; if (!isPlainObject(t)) return {}; const n = t.installs; return isPlainObject(n) ? n : {}; } function resolvePluginInstallReloadMetadata(e, t) { const n = getPluginInstallRecords(e); const r = getPluginInstallRecords(t); const i = /* @__PURE__ */ new Set([...Object.keys(n), ...Object.keys(r)]); const a = []; const o = []; for (const e of i) { const t = n[e]; const i = r[e]; if (!isPlainObject(t) || !isPlainObject(i)) { o.push(`plugins.installs.${e}`); continue; } for (const n of PLUGIN_INSTALL_TIMESTAMP_KEYS) if (t[n] !== i[n]) a.push(`plugins.installs.${e}.${n}`); } return { noopPaths: a, forceChangedPaths: o }; } function extractAccountIdFromPath(e, t) { const n = `channels.${e}.accounts.`; const r = t.startsWith(n) ? t.slice(n.length).split(".", 1)[0] : void 0; return r && r !== "default" ? r : null; } function isInspectableChannelAccount(e) { try { if (!e.plugin.config.listAccountIds(e.config).includes(e.accountId)) return false; if (!e.plugin.config.inspectAccount && e.plugin.config.resolveAccountAsync) return false; (e.plugin.config.inspectAccount ?? e.plugin.config.resolveAccount)(e.config, e.accountId); return true; } catch { return false; } } function buildGatewayReloadPlan(e, t = {}) { const n = new Set(t.noopPaths); const r = new Set(t.forceChangedPaths); const i = haveSameOperatorRoleSourcePolicies(t.previousConfig?.gateway?.roles, t.candidateConfig?.gateway?.roles) && (!t.previousCompareConfig && !t.candidateCompareConfig || haveSameOperatorRoleSourcePolicies(t.previousCompareConfig?.gateway?.roles, t.candidateCompareConfig?.gateway?.roles)); const a = /* @__PURE__ */ new Map(); const o = { changedPaths: e, restartGateway: false, restartReasons: [], hotReasons: [], reloadHooks: false, reloadInternalHooks: false, restartGmailWatcher: false, restartCron: false, reloadPlugins: false, restartChannels: /* @__PURE__ */ new Set(), restartServices: /* @__PURE__ */ new Set(), disposeMcpRuntimes: false, restartChannelAccounts: a, noopPaths: [] }; for (const s of e) { if (i && matchesReloadPrefix(s, "gateway.roles") && !r.has(s)) { o.noopPaths.push(s); continue; } if (!r.has(s) && (n.size > 0 ? n.has(s) : isPluginInstallTimestampPath(s))) { o.noopPaths.push(s); continue; } const e = matchRule(s); const c = e?.kind ?? "restart"; const l = e && AUTH_CREDENTIAL_PATHS.includes(e.prefix) && canHotReloadGatewayAuthCredentials(t.previousConfig, t.candidateConfig); if (c === "restart" && !l) { o.restartGateway = true; o.restartReasons.push(s); continue; } if (c === "none") { o.noopPaths.push(s); continue; } o.hotReasons.push(s); for (const t of e?.actions ?? []) { o[t] = true; if (t === "reloadPlugins") (o.reloadPluginPaths ??= []).push(s); } if (e?.replaceChannelPlugins) { for (const e of getReloadPolicyCatalog().registry?.plugins ?? []) if (e.channelIds.some((e) => s === "channels" || matchesReloadPrefix(s, `channels.${e}`))) (o.reloadPluginIds ??= /* @__PURE__ */ new Set()).add(e.id); } for (const e of getReloadPolicyCatalog().servicePolicies) if (e.prefixes.some((e) => matchesReloadPrefix(s, e, true))) o.restartServices?.add(e.id); for (const n of e?.channels ?? []) { const r = e?.accountScoped ? extractAccountIdFromPath(n.id, s) : null; if (r === null || t.candidateConfig && !isInspectableChannelAccount({ plugin: n, accountId: r, config: t.candidateConfig })) { o.restartChannels.add(n.id); continue; } const i = a.get(n.id) ?? /* @__PURE__ */ new Set(); i.add(r); a.set(n.id, i); } } for (const e of o.restartChannels) a.delete(e); const { pluginLifecycle: s } = t; if (s) { o.pluginLifecycle = s; o.reloadPlugins = true; const e = o.restartReasons.find((e) => e !== "plugins" && !e.startsWith("plugins.")); if (e) throw new Error(`Cannot apply plugin change while ${e} requires a Gateway restart.`); o.restartGateway = false; o.restartReasons = []; } return o; } //#endregion export { resolvePluginInstallReloadMetadata as a, resolveConfigReloadMetadata as i, isNoopGatewayReloadPlan as n, diffConfigPaths as o, listConfigReloadRefinementPrefixes as r, diffGatewayReloadPaths as s, buildGatewayReloadPlan as t };