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 | 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 { 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 { // 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 { 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 }