/** * Provider Configuration Persistence * * 提供商配置持久化 */ import { existsSync } from 'node:fs'; import { readFile, writeFile, mkdir } from 'node:fs/promises'; import { join } from 'node:path'; import type { ProvidersConfigFile, CustomProviderDefinition, ProviderConfig, ServiceConfig, ServiceType } from './types.js'; import { getConfigDir as getGlobalConfigDir } from '../constants/paths.js'; /** 配置文件名 */ const CONFIG_FILE = 'providers.json'; /** * 获取配置文件路径 * 始终使用全局配置目录 ~/.ai-terminal-assistant/ */ export function getConfigPath(): string { return join(getGlobalConfigDir(), CONFIG_FILE); } /** * 加载提供商配置 */ export async function loadProvidersConfig(): Promise { const configPath = getConfigPath(); if (!existsSync(configPath)) { return { providers: {}, configs: {}, services: {} }; } try { const content = await readFile(configPath, 'utf-8'); const config = JSON.parse(content) as ProvidersConfigFile; return { providers: config.providers ?? {}, configs: config.configs ?? {}, services: config.services ?? {}, }; } catch { // 解析失败返回空配置 return { providers: {}, configs: {}, services: {} }; } } /** * 保存提供商配置 */ export async function saveProvidersConfig(config: ProvidersConfigFile): Promise { const configDir = getGlobalConfigDir(); const configPath = getConfigPath(); // 确保目录存在 if (!existsSync(configDir)) { await mkdir(configDir, { recursive: true }); } await writeFile(configPath, JSON.stringify(config, null, 2), 'utf-8'); } /** * 获取提供商的 API Key * 从配置文件获取 */ export function resolveApiKey(config?: ProviderConfig): string | undefined { return config?.apiKey; } /** * 合并自定义提供商定义和配置 */ export function mergeProviderConfig( definition: CustomProviderDefinition, config?: ProviderConfig ): CustomProviderDefinition & { enabled: boolean } { return { ...definition, // 配置可以覆盖 baseUrl baseUrl: config?.baseUrl ?? definition.baseUrl, // 合并模型列表 models: [...(definition.models ?? []), ...(config?.customModels ?? [])], enabled: config?.enabled ?? true, }; } /** * 获取服务配置 */ export async function getServiceConfig(serviceId: ServiceType): Promise { const config = await loadProvidersConfig(); return config.services?.[serviceId]; } /** * 获取服务 API Key */ export async function getServiceApiKey(serviceId: ServiceType): Promise { const serviceConfig = await getServiceConfig(serviceId); if (serviceConfig?.enabled === false) { return undefined; } return serviceConfig?.apiKey; } /** * 保存服务配置 */ export async function saveServiceConfig(serviceId: ServiceType, serviceConfig: Omit): Promise { const config = await loadProvidersConfig(); config.services = config.services ?? {}; config.services[serviceId] = { ...serviceConfig, id: serviceId }; await saveProvidersConfig(config); } /** * 删除服务配置 */ export async function deleteServiceConfig(serviceId: ServiceType): Promise { const config = await loadProvidersConfig(); if (config.services) { delete config.services[serviceId]; await saveProvidersConfig(config); } }