Files
cline-multi-mirror/src/core/controller/models/refreshModelsDevModels.ts
T
Adam-PAN d8bb3527ea
E2E Tests / matrix_prep (push) Canceled after 0s
E2E Tests / e2e (push) Canceled after 0s
Tests / Quality Checks (push) Canceled after 0s
Tests / test (push) Canceled after 0s
Tests / test (windows-latest) (push) Canceled after 0s
Tests / test-platform-integration (push) Canceled after 0s
Tests / qlty (push) Canceled after 0s
feat: 通过 models.dev 在启动时自动更新各厂商最新模型与定价
- 设置 新增两个开关:通过 models.dev 更新模型(默认开)、通过 models.dev 更新定价(默认关)- 勾选时每次启动从 models.dev/models.json 与 api.json 拉取最新模型目录与价格,合并进各厂商模型列表(保留本地精调元数据)- 目录缓存至磁盘作为离线回退,并通过 gRPC 订阅 + 订阅后主动拉取推送至 webview,消除启动竞态- 新增 RPC:refreshModelsDevModelsRpc / subscribeToModelsDevModels- 版本升级至 4.4.0,更新 CHANGELOG
2026-09-29 15:13:59 +08:00

146 lines
5.1 KiB
TypeScript

import { ensureCacheDirectoryExists, GlobalFileNames } from "@core/storage/disk"
import { fileExistsAtPath } from "@utils/fs"
import axios from "axios"
import fs from "fs/promises"
import path from "path"
import { StateManager } from "@/core/storage/StateManager"
import {
applyModelsDevCatalog,
deserializeModelsDevCatalog,
type ModelsDevCatalog,
parseModelsDevCatalog,
serializeModelsDevCatalog,
} from "@/shared/models-dev"
import { getAxiosSettings } from "@/shared/net"
import { Logger } from "@/shared/services/Logger"
import { sendModelsDevModelsEvent } from "./subscribeToModelsDevModels"
// Track pending refresh promise to prevent duplicate concurrent fetches
let pendingRefresh: Promise<string> | null = null
// Last successfully fetched/loaded catalog for this process run.
// The webview may subscribe AFTER the startup fetch has completed, so it
// actively requests the catalog via RPC; serve it from here without refetching.
let lastCatalogJson: string | null = null
/**
* Reads the models.dev settings (update models / update pricing toggles).
*/
function getModelsDevOptions(): { updateModels: boolean; updatePricing: boolean } {
const stateManager = StateManager.get()
return {
updateModels: stateManager.getGlobalSettingsKey("modelsDevUpdateModels") ?? true,
updatePricing: stateManager.getGlobalSettingsKey("modelsDevUpdatePricing") ?? false,
}
}
/**
* Returns the last cached models.dev catalog as serialized JSON (without fetching).
*/
export async function readModelsDevCatalogJson(): Promise<string | null> {
const filePath = path.join(await ensureCacheDirectoryExists(), GlobalFileNames.modelsDevModels)
if (await fileExistsAtPath(filePath)) {
try {
const contents = await fs.readFile(filePath, "utf8")
if (deserializeModelsDevCatalog(contents)) {
return contents
}
} catch (error) {
Logger.error("Error reading cached models.dev catalog:", error)
}
}
return null
}
/**
* Fetches the models.dev catalogs (models + pricing), applies them onto the static
* model constants in this process, caches them to disk, and pushes the result to
* webview subscribers.
*
* Both toggles OFF short-circuits (returns cached data if present).
* On network failure the disk cache is used as fallback so models stay consistent.
*
* @returns Serialized ModelsDevCatalog JSON
*/
export async function refreshModelsDevModels(force = false): Promise<string> {
// Already fetched during this process run: serve cached result without refetching
// (unless force is requested, e.g. a toggle was just re-enabled)
if (lastCatalogJson && !force) {
return lastCatalogJson
}
if (force) {
lastCatalogJson = null
}
// If a fetch is already in progress, return the same promise
if (pendingRefresh) {
return pendingRefresh
}
// Start new fetch and track the promise
pendingRefresh = (async () => {
try {
return await fetchAndCacheModels()
} finally {
pendingRefresh = null
}
})()
return pendingRefresh
}
async function fetchAndCacheModels(): Promise<string> {
const filePath = path.join(await ensureCacheDirectoryExists(), GlobalFileNames.modelsDevModels)
const { updateModels, updatePricing } = getModelsDevOptions()
// Both toggles off: nothing to do, return cached catalog if present
if (!updateModels && !updatePricing) {
const cached = await readModelsDevCatalogJson()
return cached ?? serializeModelsDevCatalog({ fetchedAt: new Date(0).toISOString(), providers: {} })
}
let catalog: ModelsDevCatalog | null = null
try {
// models.json contains limits/modalities/reasoning for every provider/model
// api.json contains per-provider pricing (cost) — both are per-million USD
const [modelsRes, apiRes] = await Promise.all([
axios.get("https://models.dev/models.json?type=all", { timeout: 15000, ...getAxiosSettings() }),
axios.get("https://models.dev/api.json", { timeout: 15000, ...getAxiosSettings() }),
])
catalog = parseModelsDevCatalog(modelsRes.data, apiRes.data)
if (!catalog.providers || Object.keys(catalog.providers).length === 0) {
throw new Error("models.dev catalog parsed to zero providers")
}
// Persist to disk cache for offline fallback
await fs.writeFile(filePath, serializeModelsDevCatalog(catalog))
} catch (error) {
Logger.error("Error fetching models.dev catalog:", error)
// Fall back to disk cache so previously fetched data stays effective
const cached = await readModelsDevCatalogJson()
if (cached) {
catalog = deserializeModelsDevCatalog(cached)
}
}
if (!catalog) {
// Nothing fetched and nothing cached: keep static defaults untouched
return serializeModelsDevCatalog({ fetchedAt: new Date(0).toISOString(), providers: {} })
}
// Apply onto this process's static model constants
const applied = applyModelsDevCatalog(catalog, { updateModels, updatePricing })
Logger.log(
`[models.dev] catalog applied: ${applied.added} new models added, ${applied.priced} models repriced ` +
`(updateModels=${updateModels}, updatePricing=${updatePricing})`,
)
const serialized = serializeModelsDevCatalog(catalog)
lastCatalogJson = serialized
// Push to webview subscribers (they apply the catalog onto their own copies)
await sendModelsDevModelsEvent(serialized)
return serialized
}