UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

255 lines (254 loc) • 12.1 kB
import { l as isRecord } from "./record-coerce-CVPuDqcc.mjs"; import { n as safeParseJsonRecord } from "./json-coercion-CaJLaav-.mjs"; import { p as shortenHomePath } from "./utils-C8YECn2Q.mjs"; import { r as normalizeProviderId } from "./provider-id-b5XGSf9C.mjs"; import { i as listAgentIds } from "./agent-roster-t1ooUdXp.mjs"; import { a as resolveAgentDir, g as resolveDefaultAgentDir } from "./agent-scope-config-DmXgFGKP.mjs"; import { r as decodeUtf8Input, t as Utf8InputError } from "./utf8-input-BHczGT8v.mjs"; import { p as resolvePluginMetadataSnapshot } from "./plugin-metadata-snapshot-By9ySblt.mjs"; import "./agent-scope-BwB8YH6y.mjs"; import { t as parseModelCatalogJson } from "./model-catalog-json-DfeKlndn.mjs"; import { n as isGeneratedPluginModelCatalog, r as repairPluginModelCatalogTransportMetadata } from "./plugin-model-catalog-repair-B3GKtPvY.mjs"; import { c as resolvePluginModelCatalogOwnerPluginId, i as migrateLegacyPluginModelCatalogs, n as inspectLegacyPluginModelCatalogs, o as repairPersistedPluginModelCatalogs, r as loadPersistedPluginModelCatalogsReadOnly } from "./plugin-model-catalog-BafTZg7-.mjs"; import { t as privateFileStore } from "./private-file-store-D564pKJx.mjs"; import { t as note } from "./note-CnLgHvug.mjs"; import fs from "node:fs"; import path from "node:path"; import { isDeepStrictEqual } from "node:util"; //#region src/commands/doctor-plugin-model-catalog.ts function catalogMigrationFinding(e) { const t = e.kind === "superseded-source" || e.kind === "cleanup-failed"; const n = e.kind === "conflicting-sources" ? "Keep every retained source. Compare their accounts and credentials with the current catalog before selecting an authoritative recovery source; do not overwrite either copy. Rerun openclaw doctor --fix after reconciling the conflict." : e.kind === "superseded-source" ? "No cleanup is required merely because this older source was retained. Keep it for recovery and verify your expected accounts with openclaw models status." : e.kind === "cleanup-failed" ? "The catalog was verified in SQLite, but its source could not be removed. Keep the source, correct its directory permissions, and rerun openclaw doctor --fix to retry cleanup. Verify current accounts with openclaw models status." : "Keep the retained catalog sources and recovery copy. Correct the reported source access or concurrent-writer problem, then rerun openclaw doctor --fix to verify the import. Check openclaw models status for the expected providers."; return { checkId: `core/doctor/plugin-model-catalog/${e.kind}`, target: e.pathname, severity: e.kind === "superseded-source" ? "info" : "warning", category: t ? "historical" : "fix-now", message: shortenHomePath(e.message), fixHint: n, docsUrl: "https://docs.openclaw.ai/cli/doctor/running#auth-migration-recovery" }; } /** * Finds generated plugin catalog blocks that older writers copied into the author-owned root * models.json. * * Discovery copies a plugin's provider under its hook aliases (`claude-cli` received the * `anthropic` catalog). When the owner lookup failed, the writer sent that copy to the root file, * and the merge kept it forever. Its frozen prices, including zero placeholders for unpriced * models, then outranked the live catalog. Only exact copies of a generated block qualify; * anything a user could have edited stays. Generated blocks carry exactly these keys; * credentials or request overrides mean authorship. */ const GENERATED_PROVIDER_KEYS = [ "api", "baseUrl", "models" ]; function readGeneratedBlocks(e) { return e.flatMap(({ pluginId: e, contents: t }) => { const n = safeParseJsonRecord(t); if (!isGeneratedPluginModelCatalog(n) || !isRecord(n.providers)) return []; return Object.entries(n.providers).map(([t, n]) => ({ pluginId: e, providerId: t, block: n })); }); } function hasOnlyGeneratedProviderKeys(e) { return isDeepStrictEqual(Object.keys(e).toSorted(), GENERATED_PROVIDER_KEYS) && Array.isArray(e.models); } function resolveMigrationAgentDirs(e) { let t = e.agentDirs; const n = e.env ?? process.env; if (!t) { const r = listAgentIds(e.cfg); t = r.length > 0 ? r.map((t) => resolveAgentDir(e.cfg, t, n)) : [resolveDefaultAgentDir(e.cfg, n)]; } return [...new Set(t)].toSorted((e, t) => e.localeCompare(t)); } function readRootModelsFile(e, t) { const n = path.join(e, "models.json"); try { const e = decodeUtf8Input(fs.readFileSync(n), `Model catalog ${n}`); const t = parseModelCatalogJson(e); return isRecord(t) && isRecord(t.providers) ? { raw: e, root: t, providers: t.providers } : void 0; } catch (e) { if (e instanceof Utf8InputError) t.error(`${e.message} Left source unchanged.`); return; } } /** * Removes generated plugin copies from the root file. The exact previous bytes stay beside it as * `models.json.bak-<ms>`; the file is rewritten, never deleted, because registry reads require it. */ async function removeRootProviderCopies(e) { const t = { ...e.file.providers }; for (const { providerId: n } of e.review.copies) delete t[n]; const n = privateFileStore(e.agentDir); const r = `models.json.bak-${Date.now()}`; await n.writeText(r, e.file.raw); await n.writeText("models.json", `${JSON.stringify({ ...e.file.root, providers: t }, null, 2)}\n`); return path.join(e.agentDir, r); } function describeRootProviderCopies(e, t) { const n = shortenHomePath(path.join(e, "models.json")); return [...t.copies.map(({ providerId: e, pluginId: t, catalogProviderId: r }) => `${n} provider "${e}" is an exact copy of plugin ${t} catalog block "${r}"; its frozen rows override current model metadata and prices.`), ...t.keptPluginOwnedIds.map((e) => `${n} provider "${e}" stays: it differs from every generated catalog block.`)]; } /** Imports released sidecars and repairs persisted SQLite catalogs only with Doctor authority. */ async function maybeMigrateLegacyPluginModelCatalogs(e) { const t = []; const n = []; const report = (t, r) => { n.push(...t); e.reportFindings?.(t, r); }; const r = []; const i = new Set(Object.keys(e.cfg.models?.providers ?? {}).map((e) => normalizeProviderId(e))); let a; const reviewRootFile = (t, n) => { if (!t || n.length === 0) return { copies: [], keptPluginOwnedIds: [] }; a ??= resolvePluginMetadataSnapshot({ config: e.cfg, env: e.env ?? process.env }); const r = readGeneratedBlocks(n); const o = []; const s = []; for (const [e, n] of Object.entries(t.providers)) { if (i.has(normalizeProviderId(e))) continue; const t = resolvePluginModelCatalogOwnerPluginId({ providerId: e, pluginMetadataSnapshot: a }); const c = isRecord(n) && hasOnlyGeneratedProviderKeys(n) ? r.find((e) => (t === void 0 || t === e.pluginId) && isDeepStrictEqual(e.block, n)) : void 0; if (c) o.push({ providerId: e, pluginId: c.pluginId, catalogProviderId: c.providerId }); else if (t !== void 0) s.push(e); } return { copies: o, keptPluginOwnedIds: s }; }; for (const n of resolveMigrationAgentDirs(e)) { const i = inspectLegacyPluginModelCatalogs(n); const a = i.warnings.map((e) => shortenHomePath(e)); const o = i.catalogs; const s = loadPersistedPluginModelCatalogsReadOnly(n); const c = s.filter(({ contents: e }) => { return repairPluginModelCatalogTransportMetadata(e).contents !== e; }).map(({ pluginId: e }) => e); const l = reviewRootFile(readRootModelsFile(n, e.runtime), [...s, ...o]); r.push({ agentDir: n, migrations: o, warnings: a, repairablePluginIds: c, rootCopies: l, inspectionFindings: i.issues.map(catalogMigrationFinding) }); t.push(...a); e.reportFindings?.([], a); } const o = r.flatMap((e) => e.migrations); const s = o.length + r.reduce((e, t) => e + t.repairablePluginIds.length + t.rootCopies.copies.length, 0); for (const n of t) e.runtime.error(n); if (s > 0) { const e = o.length > 0 ? ["Legacy generated provider catalogs contain model and credential state.", ...o.map((e) => `- ${shortenHomePath(e.pathname)}`)] : []; for (const t of r) { for (const n of t.repairablePluginIds) e.push(`Generated catalog ${n} in ${shortenHomePath(t.agentDir)} contains repairable model rows (missing transport API metadata or an incomplete cost).`); if (t.rootCopies.copies.length > 0) e.push(...describeRootProviderCopies(t.agentDir, t.rootCopies)); } e.push("Run openclaw doctor --fix to verify and repair these catalogs."); note(e.join("\n"), "Plugin model catalogs"); } if (!(e.prompter.shouldRepair || s > 0 && await e.prompter.confirmAutoFix({ message: "Repair generated provider model catalogs now?", initialValue: true }))) { report(r.flatMap((e) => e.inspectionFindings), []); if (s > 0) report([{ checkId: "core/doctor/plugin-model-catalog/repair-pending", severity: "warning", category: "fix-now", message: `${s} generated provider catalog repair${s === 1 ? "" : "s"} remain pending.`, fixHint: "Run openclaw doctor --fix to verify legacy catalog imports and repair model transport metadata. Keep the original catalogs and recovery copies until verification completes.", docsUrl: "https://docs.openclaw.ai/cli/doctor/running#auth-migration-recovery" }]); return; } let c = 0; const l = []; const u = []; for (const i of r) { let r; try { r = migrateLegacyPluginModelCatalogs({ agentDir: i.agentDir, ...i.migrations.length > 0 ? { expectedContents: new Map(i.migrations.map((e) => [e.pluginId, e.contents])) } : {} }); } catch (e) { report([{ checkId: "core/doctor/plugin-model-catalog/import-failed", target: i.agentDir, severity: "warning", category: "fix-now", message: `Generated provider catalog migration could not complete: ${e instanceof Error ? e.message : String(e)}`, fixHint: "Keep the retained catalog sources and recovery copy. Resolve the reported changed source or database error, then rerun openclaw doctor --fix. Avoid running an older catalog writer during migration.", docsUrl: "https://docs.openclaw.ai/cli/doctor/running#auth-migration-recovery" }]); throw e; } c += r.migrated; e.reportFindings?.([], r.warnings.map(shortenHomePath)); report(r.issues.map(catalogMigrationFinding).filter((e) => !n.some((t) => t.checkId === e.checkId && t.target === e.target)), []); for (const n of r.warnings) { const r = shortenHomePath(n); if (t.includes(r)) continue; t.push(r); e.runtime.error(r); } if (r.warnings.length === 0) u.push(...repairPersistedPluginModelCatalogs({ agentDir: i.agentDir, catalogs: loadPersistedPluginModelCatalogsReadOnly(i.agentDir) })); if (i.rootCopies.copies.length === 0) continue; const a = readRootModelsFile(i.agentDir, e.runtime); const o = reviewRootFile(a, loadPersistedPluginModelCatalogsReadOnly(i.agentDir)); if (!a || o.copies.length === 0) continue; try { const e = await removeRootProviderCopies({ agentDir: i.agentDir, file: a, review: o }); l.push(...o.copies.map(({ providerId: t, pluginId: n }) => `Removed provider "${t}" (a copy of plugin ${n}'s generated catalog) from ${shortenHomePath(path.join(i.agentDir, "models.json"))}; backup: ${shortenHomePath(e)}.`)); } catch (n) { const r = `Could not remove generated provider copies from ${shortenHomePath(i.agentDir)}: ${n instanceof Error ? n.message : String(n)}`; t.push(r); e.runtime.error(r); } } if (c > 0) note(`Migrated and verified ${c} generated provider catalog${c === 1 ? "" : "s"} in agent SQLite.`, "Doctor changes"); if (u.length > 0) note(u.map(({ pluginId: e, removedModelCount: t, completedCostModelCount: n }) => { return `Repaired generated model catalog ${e}: ${[t > 0 ? `removed ${t} model row(s) without transport API metadata` : void 0, n > 0 ? `completed the cost of ${n} model row(s)` : void 0].filter((e) => e !== void 0).join("; ")}.`; }).join("\n"), "Doctor changes"); if (l.length > 0) note(l.join("\n"), "Doctor changes"); } //#endregion export { maybeMigrateLegacyPluginModelCatalogs };