UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

327 lines (326 loc) • 13.7 kB
import { o as normalizeLowercaseStringOrEmpty } from "./string-coerce-CCIiB4H7.mjs"; import { a as addTimerTimeoutGraceMs } from "./number-coercion-D6u-4YD8.mjs"; import { t as stableStringify } from "./stable-stringify-vqde_3tT.mjs"; import { b as uniqueStrings } from "./string-normalization-DLmfYZXI.mjs"; import { r as resolveStateDir } from "./state-dir-DiG0gXzD.mjs"; import "./paths-DAcAg5aV.mjs"; import { o as getPluginRuntimeGatewayRequestScope } from "./gateway-request-scope-BvvDhs5D.mjs"; import { i as createPluginCache, w as withPluginCache } from "./plugin-cache-B_eRuqTM.mjs"; import { t as createSubsystemLogger } from "./subsystem-BHJiy01V.mjs"; import { t as createLazyImportLoader } from "./lazy-promise-DiCvjz9w.mjs"; import { t as listDatabaseEngineStores } from "./registry-Dd7FIY0t.mjs"; import { i as installDatabaseEngineSelection, n as getDatabaseEngineSelection } from "./context-DE59wyBs.mjs"; import { r as cloneEnvWithPlatformSemantics } from "./config-env-vars-ByeGN-9N.mjs"; import { u as collectUniqueCommandDescriptors } from "./manifest-Y5vPZPOf.mjs"; import { f as degradedPluginMatchesRoot, m as findActiveDegradedPlugin } from "./discovery-availability-DtlJ7XvT.mjs"; import { t as resolvePluginMetadataEnvFingerprint } from "./plugin-metadata-env-DmZ06vdA.mjs"; import { h as readRuntimeConfig } from "./runtime-snapshot-WbwbY5b7.mjs"; import { i as GATEWAY_CLIENT_NAMES, r as GATEWAY_CLIENT_MODES } from "./client-info-Cm1BcrMm.mjs"; import { p as resolvePluginMetadataSnapshot } from "./plugin-metadata-snapshot-By9ySblt.mjs"; import { n as resolvePluginControlPlaneWorkspace } from "./control-plane-workspace-OscAdfLv.mjs"; import { l as getPluginValueInstance } from "./plugin-instance-scope-oezVdCr2.mjs"; import { t as resolveManifestActivationPluginIds } from "./activation-planner-lvis97qI.mjs"; import { t as createEmptyPluginRegistry } from "./registry-empty-Cv4VTWYA.mjs"; import { p as normalizeOperatorScopeList } from "./operator-scopes-CULmYfyY.mjs"; import { f as bindPluginCliProgram } from "./setup-registry-CgyZCdrJ.mjs"; import { t as resolvePluginActivationSourceConfig } from "./activation-source-config-BX9rE6k7.mjs"; import "./config-CMA-J084.mjs"; import { t as getCliPluginInvocationResources } from "./runtime-cleanup-scope-DuOL68nJ.mjs"; import { n as buildPluginRuntimeLoadOptions } from "./load-context-CwTU1iXB.mjs"; import { t as acquirePluginRegistryForInspection } from "./loader-runtime-load-Ba16vW6K.mjs"; import { n as loadPluginRegistryHandle, t as loadOpenClawPluginCliRegistry } from "./loader--j41eir2.mjs"; import { t as resolvePluginRuntimeLoadContext } from "./load-context.resolve-D0f_6L5E.mjs"; import { u as loadPluginDoctorRecoveryCliRegistrar } from "./doctor-contract-registry-CFzLZXmq.mjs"; import { t as withPluginCliServiceScheduler } from "./cli-service-scheduler-PsK0v0lu.mjs"; import { randomUUID } from "node:crypto"; //#region src/plugins/cli-gateway-nodes-runtime.ts const gatewayCallModuleLoader = createLazyImportLoader(() => import("./call-CT5jlfNe.mjs")); const pluginCliGatewayNodesRuntime = { async list(e) { const { callGateway: t } = await gatewayCallModuleLoader.load(); const n = await t({ method: "node.list", params: {}, clientName: GATEWAY_CLIENT_NAMES.CLI, mode: GATEWAY_CLIENT_MODES.CLI }); const r = Array.isArray(n?.nodes) ? n.nodes : []; return { nodes: e?.connected === true ? r.filter((e) => e !== null && typeof e === "object" && e.connected === true) : r }; }, async invoke(e) { const { callGateway: t } = await gatewayCallModuleLoader.load(); const n = normalizeOperatorScopeList(e.scopes); const r = n ? getPluginRuntimeGatewayRequestScope() : void 0; const i = r?.pluginId && (r.pluginOrigin === "bundled" || r.pluginTrustedOfficialInstall === true) ? n : void 0; return await t({ method: "node.invoke", params: { nodeId: e.nodeId, command: e.command, ...e.params !== void 0 && { params: e.params }, timeoutMs: e.timeoutMs, idempotencyKey: e.idempotencyKey || randomUUID(), ...e.sessionKey ? { sessionKey: e.sessionKey } : {} }, timeoutMs: typeof e.timeoutMs === "number" && Number.isFinite(e.timeoutMs) && e.timeoutMs > 0 ? addTimerTimeoutGraceMs(e.timeoutMs) : void 0, clientName: GATEWAY_CLIENT_NAMES.CLI, mode: GATEWAY_CLIENT_MODES.CLI, ...i ? { scopes: i } : {}, ...e.signal ? { signal: e.signal } : {} }); }, async openDuplex() { throw new Error("Node duplex is unavailable in the CLI; run this plugin inside the Gateway."); } }; //#endregion //#region src/plugins/cli-registry-loader.ts /** Loads plugin CLI registrations lazily for the command tree and plugin-owned subcommands. */ const log = createSubsystemLogger("plugins/cli-registry-loader"); /** Invocation authority closes before actions; its package generation lives through them. */ function createPluginCliLoadSession(e = createPluginCache(), t = { resources: getCliPluginInvocationResources() }) { const { resources: n } = t; const withCache = (t) => withPluginCache(e, t); let r = false; let i; const assertOpen = () => { if (r) throw new Error("Plugin CLI preparation is closed; start a new registration operation."); }; return { resources: n, withCache, readConfig: async (e) => { assertOpen(); const t = await withCache(e); assertOpen(); return t; }, close: () => { r = true; i = void 0; }, resolve: (e) => withCache(() => { assertOpen(); const t = e.cfg ?? readRuntimeConfig(); const r = resolvePluginActivationSourceConfig({ config: t }); const a = e.env ?? process.env; const o = stableStringify([ t, r, a, resolvePluginControlPlaneWorkspace({ config: t, env: a }), resolvePluginMetadataEnvFingerprint(a), resolveStateDir(a), e.primaryCommand ]); const s = e.loaderOptions?.pluginSdkResolution; if (i?.key === o && i.env === a && i.sdk === s && i.prepared.context.rawConfig === t && i.prepared.context.activationSourceConfig === r) return i.prepared; const c = cloneEnvWithPlatformSemantics(a); const { workspaceDir: l } = resolvePluginControlPlaneWorkspace({ config: t, env: c }); const u = resolvePluginMetadataSnapshot({ config: t, env: c, workspaceDir: l, allowCurrent: false }); const d = { context: resolvePluginRuntimeLoadContext({ config: t, activationSourceConfig: r, env: c, workspaceDir: l, metadataSnapshot: u }), withCache, resources: n, assertCurrent: assertOpen }; i = { key: o, sdk: s, env: a, prepared: d }; return d; }) }; } function resolvePreparedPluginCliLoad(e) { return (e.session ?? createPluginCliLoadSession()).resolve(e); } function resolvePrimaryCommandManifestPluginIds(e, t) { const n = normalizeLowercaseStringOrEmpty(t); if (!n) return; return resolveManifestActivationPluginIds({ trigger: { kind: "command", command: n }, config: e.activationSourceConfig, workspaceDir: e.workspaceDir, env: e.env, manifestRecords: e.manifestRegistry?.plugins }); } function pluginCliRegistrarOwnsRoot(e, t) { const n = e.parentPath ?? []; return (n.length > 0 ? [n[0]] : [...e.commands, ...e.descriptors.map((e) => e.name)]).includes(t); } async function resolvePrimaryCommandPluginIds(e, t, n) { const { context: r } = e; const i = normalizeLowercaseStringOrEmpty(t); if (!i) return; const a = resolvePrimaryCommandManifestPluginIds(r, i); if (a && a.length > 0) return a; const o = await loadPluginCliMetadataRegistryWithContext(e, i, n); return uniqueStrings(o.cliRegistrars.filter((e) => pluginCliRegistrarOwnsRoot(e, i)).map((e) => e.pluginId)); } async function loadPluginCliMetadataRegistryWithContext(e, t, n) { let r = resolvePrimaryCommandManifestPluginIds(e.context, t); if (r?.length === 0) r = (e.context.manifestRegistry?.plugins ?? []).filter((e) => e.cliCommands === void 0).map((e) => e.id); e.assertCurrent(); if (r?.length === 0) return createEmptyPluginRegistry(); const i = await (e.metadataRegistry ??= e.withCache(() => { const t = buildPluginRuntimeLoadOptions(e.context, { ...n, cache: false, ...r && r.length > 0 ? { onlyPluginIds: r } : {} }); return e.resources ? e.resources.acquire(() => acquirePluginRegistryForInspection({ ...t, mode: "cli-metadata" })) : loadOpenClawPluginCliRegistry(t); })); return e.withCache(() => appendPluginRecoveryCliRegistrars(e, i)); } /** Recovery uses Doctor's selected source, never the withheld runtime or metadata entrypoint. */ async function appendPluginRecoveryCliRegistrars(e, t) { const { context: n } = e; for (const r of t.plugins) { if (!r.enabled || !t.diagnostics.some((e) => e.pluginId === r.id && e.code === "plugin-state-migration")) continue; const i = n.manifestRegistry?.plugins.find((e) => e.id === r.id && e.source === r.source && e.rootDir === r.rootDir); const a = i?.doctorContract?.recoveryCli; if (!i || !a?.length) continue; const o = findActiveDegradedPlugin(r.id); if (o && degradedPluginMatchesRoot(o, i.rootDir)) continue; e.assertCurrent(); const s = loadPluginDoctorRecoveryCliRegistrar(i); if (!s) continue; const c = getPluginValueInstance(s); if (!c) throw new Error(`Plugin ${r.id} recovery CLI has no prepared source owner`); for (const e of i.cliCommands ?? []) { const i = a.filter((t) => t[0] === e.name); if (!i.length || t.cliRegistrars.some((t) => pluginCliRegistrarOwnsRoot(t, e.name))) continue; t.cliRegistrars.push({ pluginId: r.id, source: r.source, rootDir: r.rootDir, parentPath: [], commands: [e.name], descriptors: [e], register: async ({ program: t, config: a }) => { const [{ createPluginDoctorStateMigrationContext: o }, { toPluginCommandFailure: l }] = await Promise.all([import("./state-migrations.plugin-doctor-context-Cdc0r0JH.mjs"), import("./failure-output-DKniP608.mjs")]); const { openPluginStateKeyedStore: u } = o({ pluginId: r.id, config: a, env: n.env }); const d = t.command(e.name).description(e.description); for (const e of i) { let t = d; for (const n of e.slice(1)) t = t.commands.find((e) => e.name() === n) ?? t.command(n); await c.run(() => withPluginCliServiceScheduler(c, () => { bindPluginCliProgram(t, l); return s({ program: t, parentPath: e, config: a, env: n.env, stateDir: resolveStateDir(n.env), context: { openPluginStateKeyedStore: u } }); })); } } }); } } return t; } async function loadPluginCliCommandRegistryWithContext(e) { const { context: t } = e.prepared; let n; try { n = await resolvePrimaryCommandPluginIds(e.prepared, e.primaryCommand, e.loaderOptions); } catch { n = resolvePrimaryCommandManifestPluginIds(t, e.primaryCommand); } e.prepared.assertCurrent(); if (n && n.length === 0) return createEmptyPluginRegistry(); if (!getDatabaseEngineSelection() && listDatabaseEngineStores().some(({ id: e, postgres: t }) => t && (!n || n.includes(e)))) { const { resolveDatabaseEngineSelection: e } = await import("./config-eNRW_vew.mjs"); installDatabaseEngineSelection(await e(t.config, t.env)); } const r = buildPluginRuntimeLoadOptions(t, { ...e.loaderOptions, ...n && n.length > 0 ? { onlyPluginIds: n } : {}, cache: false, channelPluginLoadIntent: "full", runtimeOptions: { nodes: pluginCliGatewayNodesRuntime } }); const i = e.prepared.resources; const a = await e.prepared.withCache(() => i ? i.acquire(() => acquirePluginRegistryForInspection(r)) : loadPluginRegistryHandle(r)); return e.prepared.withCache(() => appendPluginRecoveryCliRegistrars(e.prepared, a)); } async function loadPluginCliDescriptors(e) { try { const t = await loadPluginCliMetadataRegistryWithContext(resolvePreparedPluginCliLoad(e), e.primaryCommand); return collectUniqueCommandDescriptors(t.cliRegistrars.filter((e) => (e.parentPath ?? []).length === 0).map((e) => e.descriptors)); } catch (e) { log.warn(`plugin CLI descriptor load failed: ${String(e)}`); return []; } } async function loadPluginCliRegistrationEntriesWithDefaults(e, t = "runtime") { const n = resolvePreparedPluginCliLoad(e); const buildEntries = (r) => { const i = t === "metadata" && normalizeLowercaseStringOrEmpty(e.primaryCommand); const a = i ? r.cliRegistrars.filter((e) => pluginCliRegistrarOwnsRoot(e, i)) : r.cliRegistrars; const { config: o, workspaceDir: s, logger: c } = n.context; return a.map((e) => ({ pluginId: e.pluginId, parentPath: e.parentPath ?? [], placeholders: e.descriptors, names: e.commands, register: async (t) => { n.assertCurrent(); const register = () => n.withCache(() => e.register({ program: t, parentPath: e.parentPath ?? [], config: o, workspaceDir: s, logger: c })); await (n.resources ? n.resources.run(register) : register()); } })); }; return t === "metadata" ? buildEntries(await loadPluginCliMetadataRegistryWithContext(n, e.primaryCommand, e.loaderOptions)) : await (n.entries ??= loadPluginCliCommandRegistryWithContext({ prepared: n, primaryCommand: e.primaryCommand, loaderOptions: e.loaderOptions }).then(buildEntries)); } async function resolvePluginCliRootOwnerIds(e) { const t = normalizeLowercaseStringOrEmpty(e.primaryCommand); if (!t) return null; return await resolvePrimaryCommandPluginIds(resolvePreparedPluginCliLoad(e), t) ?? null; } //#endregion export { resolvePluginCliRootOwnerIds as i, loadPluginCliDescriptors as n, loadPluginCliRegistrationEntriesWithDefaults as r, createPluginCliLoadSession as t };