openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
6 lines • 10.1 kB
JavaScript
import{l as isRecord}from"./record-coerce-BTbqdJ3-.mjs";import{n as safeParseJsonRecord}from"./json-coercion-DNNwq4_v.mjs";import{f as shortenHomePath}from"./utils-Dlk0IYAa.mjs";import{t as hasErrnoCode}from"./errno-DUBt6SQQ.mjs";import{r as normalizeProviderId}from"./provider-id-A-8WTtLA.mjs";import{i as listAgentIds}from"./agent-roster-4XrgUgPK.mjs";import{a as resolveAgentDir,g as resolveDefaultAgentDir}from"./agent-scope-config-CG9CFpGX.mjs";import{r as decodeUtf8Input,t as Utf8InputError}from"./utf8-input-CiFSnxL0.mjs";import{p as resolvePluginMetadataSnapshot}from"./plugin-metadata-snapshot-CDKhemiT.mjs";import"./agent-scope-Dw5XRSEh.mjs";import{t as parseModelCatalogJson}from"./model-catalog-json-D7uWchaX.mjs";import{n as isGeneratedPluginModelCatalog,r as repairPluginModelCatalogTransportMetadata}from"./plugin-model-catalog-repair-CzksjYl4.mjs";import{c as resolvePluginModelCatalogOwnerPluginId,i as migrateLegacyPluginModelCatalogs,n as inspectLegacyPluginModelCatalogs,o as repairPersistedPluginModelCatalogs,r as loadPersistedPluginModelCatalogsReadOnly}from"./plugin-model-catalog-CFTAUpvN.mjs";import{t as privateFileStore}from"./private-file-store-BjRsyVmB.mjs";import{t as note}from"./note-e4DtVgg2.mjs";import fs from"node:fs";import path from"node:path";import{isDeepStrictEqual}from"node:util";
//!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`}}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,n){const r=path.join(e,`models.json`);try{const e=decodeUtf8Input(fs.readFileSync(r),`Model catalog ${r}`);const t=parseModelCatalogJson(e);if(isRecord(t)&&isRecord(t.providers))return{raw:e,root:t,providers:t.providers};n();return}catch(e){if(!hasErrnoCode(e,`ENOENT`))n();if(e instanceof Utf8InputError)t.error(`${e.message} Left source unchanged.`);return}}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.`)]}async function maybeMigrateLegacyPluginModelCatalogs(e){let t=false;const onReadError=()=>{t=true};const n=[];const r=[];const report=(t,n)=>{r.push(...t);e.reportFindings?.(t,n)};const i=[];const a=new Set(Object.keys(e.cfg.models?.providers??{}).map(e=>normalizeProviderId(e)));let o;const reviewRootFile=(n,r)=>{if(!n)return{copies:[],keptPluginOwnedIds:[]};const i=readGeneratedBlocks(r);const s=[];const c=[];for(const[l,u]of Object.entries(n.providers)){if(!isRecord(u)){t=true;continue}if(r.length===0||a.has(normalizeProviderId(l)))continue;o??=resolvePluginMetadataSnapshot({config:e.cfg,env:e.env??process.env});const n=resolvePluginModelCatalogOwnerPluginId({providerId:l,pluginMetadataSnapshot:o});const d=hasOnlyGeneratedProviderKeys(u)?i.find(e=>(n===void 0||n===e.pluginId)&&isDeepStrictEqual(e.block,u)):void 0;if(d)s.push({providerId:l,pluginId:d.pluginId,catalogProviderId:d.providerId});else if(n!==void 0)c.push(l)}return{copies:s,keptPluginOwnedIds:c}};for(const r of resolveMigrationAgentDirs(e)){const a=inspectLegacyPluginModelCatalogs(r);const o=a.warnings.map(e=>shortenHomePath(e));const s=a.catalogs;const c=loadPersistedPluginModelCatalogsReadOnly(r);const l=c.filter(({contents:e})=>{const n=repairPluginModelCatalogTransportMetadata(e);t||=n.inspectionIncomplete;return n.contents!==e}).map(({pluginId:e})=>e);const u=reviewRootFile(readRootModelsFile(r,e.runtime,onReadError),[...c,...s]);i.push({agentDir:r,migrations:s,warnings:o,repairablePluginIds:l,rootCopies:u,inspectionFindings:a.issues.map(catalogMigrationFinding)});n.push(...o);e.reportFindings?.([],o)}const s=i.flatMap(e=>e.migrations);const c=s.length+i.reduce((e,t)=>e+t.repairablePluginIds.length+t.rootCopies.copies.length,0);for(const t of n)e.runtime.error(t);if(c>0){const e=s.length>0?[`Legacy generated provider catalogs contain model and credential state.`,...s.map(e=>`- ${shortenHomePath(e.pathname)}`)]:[];for(const t of i){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(`
`),`Plugin model catalogs`)}if(!(e.prompter.shouldRepair||c>0&&await e.prompter.confirmAutoFix({message:`Repair generated provider model catalogs now?`,initialValue:true}))){report(i.flatMap(e=>e.inspectionFindings),[]);if(c>0)report([{checkId:`core/doctor/plugin-model-catalog/repair-pending`,severity:`warning`,category:`fix-now`,message:`${c} generated provider catalog repair${c===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 t||c>0||n.length>0||r.length>0}let l=0;const u=[];const d=[];for(const t of i){let i;try{i=migrateLegacyPluginModelCatalogs({agentDir:t.agentDir,...t.migrations.length>0?{expectedContents:new Map(t.migrations.map(e=>[e.pluginId,e.contents]))}:{}})}catch(e){report([{checkId:`core/doctor/plugin-model-catalog/import-failed`,target:t.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}l+=i.migrated;e.reportFindings?.([],i.warnings.map(shortenHomePath));report(i.issues.map(catalogMigrationFinding).filter(e=>!r.some(t=>t.checkId===e.checkId&&t.target===e.target)),[]);for(const t of i.warnings){const r=shortenHomePath(t);if(n.includes(r))continue;n.push(r);e.runtime.error(r)}if(i.warnings.length===0)d.push(...repairPersistedPluginModelCatalogs({agentDir:t.agentDir,catalogs:loadPersistedPluginModelCatalogsReadOnly(t.agentDir)}));if(t.rootCopies.copies.length===0)continue;const a=readRootModelsFile(t.agentDir,e.runtime,onReadError);const o=reviewRootFile(a,loadPersistedPluginModelCatalogsReadOnly(t.agentDir));if(!a||o.copies.length===0)continue;try{const e=await removeRootProviderCopies({agentDir:t.agentDir,file:a,review:o});u.push(...o.copies.map(({providerId:n,pluginId:r})=>`Removed provider "${n}" (a copy of plugin ${r}'s generated catalog) from ${shortenHomePath(path.join(t.agentDir,`models.json`))}; backup: ${shortenHomePath(e)}.`))}catch(r){const i=`Could not remove generated provider copies from ${shortenHomePath(t.agentDir)}: ${r instanceof Error?r.message:String(r)}`;n.push(i);e.runtime.error(i)}}if(l>0)note(`Migrated and verified ${l} generated provider catalog${l===1?``:`s`} in agent SQLite.`,`Doctor changes`);if(d.length>0)note(d.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(`
`),`Doctor changes`);if(u.length>0)note(u.join(`
`),`Doctor changes`);return t||c>0||l>0||d.length>0||u.length>0||n.length>0||r.length>0}export{maybeMigrateLegacyPluginModelCatalogs};