import fs from 'fs'; import path from 'path'; import crypto from 'crypto'; import { config } from './config'; import { RevolverConfigFile, ProviderConfig, ProviderKeyConfig, CustomModelConfig, ProviderType } from './revolverTypes'; export class ConfigStore { private configFilePath: string; private data: RevolverConfigFile = { version: 1, defaultModelId: undefined, providers: [], customModels: [] }; private saveTimeout: NodeJS.Timeout | null = null; constructor(filePath?: string) { this.configFilePath = filePath || config.configFilePath; this.ensureDir(); this.loadOrCreate(); process.on('SIGINT', () => this.saveSync()); process.on('SIGTERM', () => this.saveSync()); } private ensureDir(): void { const dir = path.dirname(this.configFilePath); if (!fs.existsSync(dir)) { try { fs.mkdirSync(dir, { recursive: true }); } catch (err) { console.error('[CONFIG_STORE] Failed to create directory for config:', err); } } } private loadOrCreate(): void { if (fs.existsSync(this.configFilePath)) { try { const raw = fs.readFileSync(this.configFilePath, 'utf8'); this.data = JSON.parse(raw); console.log(`[CONFIG_STORE] Loaded configuration from ${this.configFilePath} (${this.data.providers.length} providers, ${this.data.customModels.length} custom models)`); return; } catch (err) { console.error(`[CONFIG_STORE] Error reading ${this.configFilePath}, creating backup and re-initializing:`, err); try { fs.copyFileSync(this.configFilePath, `${this.configFilePath}.bak-${Date.now()}`); } catch {} } } // File does not exist or failed to parse: initialize this.data = { version: 1, defaultModelId: undefined, providers: [], customModels: [] }; // Auto-migrate from .env if GEMINI_API_KEYS are provided if (config.geminiApiKeys && config.geminiApiKeys.length > 0) { console.log(`[CONFIG_STORE] Initializing config with ${config.geminiApiKeys.length} Gemini API keys from .env`); const providerId = 'provider-gemini-default'; const defaultProvider: ProviderConfig = { id: providerId, name: 'Google AI Studio (Migrated)', type: 'gemini', baseUrl: 'https://generativelanguage.googleapis.com', keys: config.geminiApiKeys.map(k => ({ key: k, lastUsed: 0, requestCount: 0, rateLimitedUntil: null, errorCount: 0 })), createdAt: new Date().toISOString(), updatedAt: new Date().toISOString() }; this.data.providers.push(defaultProvider); const modelId = 'model-gemini-default'; const defaultCustomModel: CustomModelConfig = { id: modelId, name: config.model || 'gemini-flash-lite-latest', description: 'Default Gemini Model (auto-migrated from .env)', isDefault: true, tiers: [ { tierIndex: 0, name: 'Main Tier', targets: [ { providerId: providerId, model: config.model || 'gemini-flash-lite-latest' } ] } ], createdAt: new Date().toISOString(), updatedAt: new Date().toISOString() }; this.data.customModels.push(defaultCustomModel); this.data.defaultModelId = modelId; } this.saveSync(); } public saveSync(): void { try { this.ensureDir(); const tmpPath = `${this.configFilePath}.tmp`; fs.writeFileSync(tmpPath, JSON.stringify(this.data, null, 2), 'utf8'); fs.renameSync(tmpPath, this.configFilePath); } catch (err) { console.error('[CONFIG_STORE] Error saving config to file:', err); } } public scheduleSave(): void { if (this.saveTimeout) return; this.saveTimeout = setTimeout(() => { this.saveTimeout = null; this.saveSync(); }, 1000); } public getConfig(): RevolverConfigFile { return JSON.parse(JSON.stringify(this.data)); } public getProviders(): ProviderConfig[] { return this.data.providers; } public getProviderById(id: string): ProviderConfig | undefined { return this.data.providers.find(p => p.id === id); } public saveProvider(providerInput: { id?: string; name: string; type: ProviderType; baseUrl?: string; keys: (string | ProviderKeyConfig)[]; }): ProviderConfig { const now = new Date().toISOString(); const existingIndex = providerInput.id ? this.data.providers.findIndex(p => p.id === providerInput.id) : -1; // Convert string keys to ProviderKeyConfig if needed, preserving existing stats const existingProvider = existingIndex >= 0 ? this.data.providers[existingIndex] : undefined; const existingKeysMap = new Map(); if (existingProvider) { for (const k of existingProvider.keys) { existingKeysMap.set(k.key, k); } } const processedKeys: ProviderKeyConfig[] = providerInput.keys .map(k => { const keyString = typeof k === 'string' ? k.trim() : k.key.trim(); if (!keyString) return null; if (typeof k === 'object' && k.key) { return { key: keyString, lastUsed: k.lastUsed || 0, requestCount: k.requestCount || 0, rateLimitedUntil: k.rateLimitedUntil ?? null, errorCount: k.errorCount || 0 }; } const existing = existingKeysMap.get(keyString); if (existing) return existing; return { key: keyString, lastUsed: 0, requestCount: 0, rateLimitedUntil: null, errorCount: 0 }; }) .filter((k): k is ProviderKeyConfig => k !== null); const defaultBaseUrl = this.getDefaultBaseUrl(providerInput.type); if (existingIndex >= 0) { const updated: ProviderConfig = { ...this.data.providers[existingIndex], name: providerInput.name.trim(), type: providerInput.type, baseUrl: providerInput.baseUrl?.trim() || defaultBaseUrl, keys: processedKeys, updatedAt: now }; this.data.providers[existingIndex] = updated; this.saveSync(); return updated; } else { const newProvider: ProviderConfig = { id: providerInput.id || `prov-${crypto.randomBytes(6).toString('hex')}`, name: providerInput.name.trim(), type: providerInput.type, baseUrl: providerInput.baseUrl?.trim() || defaultBaseUrl, keys: processedKeys, createdAt: now, updatedAt: now }; this.data.providers.push(newProvider); this.saveSync(); return newProvider; } } public deleteProvider(id: string): boolean { const initialLen = this.data.providers.length; this.data.providers = this.data.providers.filter(p => p.id !== id); if (this.data.providers.length !== initialLen) { // Remove any target referencing this deleted provider in custom models for (const model of this.data.customModels) { for (const tier of model.tiers) { tier.targets = tier.targets.filter(t => t.providerId !== id); } } this.saveSync(); return true; } return false; } public getCustomModels(): CustomModelConfig[] { return this.data.customModels; } public getCustomModelById(id: string): CustomModelConfig | undefined { return this.data.customModels.find(m => m.id === id); } public getCustomModelByName(name: string): CustomModelConfig | undefined { return this.data.customModels.find(m => m.name.toLowerCase() === name.toLowerCase()); } public getDefaultModel(): CustomModelConfig | undefined { if (this.data.defaultModelId) { const found = this.data.customModels.find(m => m.id === this.data.defaultModelId); if (found) return found; } const explicitlyDefault = this.data.customModels.find(m => m.isDefault); if (explicitlyDefault) return explicitlyDefault; return this.data.customModels[0]; } public saveCustomModel(modelInput: { id?: string; name: string; description?: string; isDefault?: boolean; tiers: { tierIndex: number; name?: string; targets: { providerId: string; model: string }[]; }[]; }): CustomModelConfig { const now = new Date().toISOString(); const existingIndex = modelInput.id ? this.data.customModels.findIndex(m => m.id === modelInput.id) : -1; // Normalize tiers and targets const processedTiers = (modelInput.tiers || []).map((t, idx) => ({ tierIndex: typeof t.tierIndex === 'number' ? t.tierIndex : idx, name: t.name || (idx === 0 ? 'Main Tier' : `Fallback Tier ${idx}`), targets: (t.targets || []).map(tg => ({ providerId: tg.providerId.trim(), model: tg.model.trim() })).filter(tg => tg.providerId && tg.model) })); // If marked default, unmark others if (modelInput.isDefault) { for (const m of this.data.customModels) { m.isDefault = false; } } if (existingIndex >= 0) { const updated: CustomModelConfig = { ...this.data.customModels[existingIndex], name: modelInput.name.trim(), description: modelInput.description?.trim(), isDefault: !!modelInput.isDefault, tiers: processedTiers, updatedAt: now }; this.data.customModels[existingIndex] = updated; if (updated.isDefault) { this.data.defaultModelId = updated.id; } this.saveSync(); return updated; } else { const newModelId = modelInput.id || `model-${crypto.randomBytes(6).toString('hex')}`; const isFirstModel = this.data.customModels.length === 0; const isDefault = modelInput.isDefault !== undefined ? modelInput.isDefault : isFirstModel; const newModel: CustomModelConfig = { id: newModelId, name: modelInput.name.trim(), description: modelInput.description?.trim(), isDefault: isDefault, tiers: processedTiers, createdAt: now, updatedAt: now }; this.data.customModels.push(newModel); if (isDefault || !this.data.defaultModelId) { this.data.defaultModelId = newModelId; } this.saveSync(); return newModel; } } public deleteCustomModel(id: string): boolean { const initialLen = this.data.customModels.length; this.data.customModels = this.data.customModels.filter(m => m.id !== id); if (this.data.customModels.length !== initialLen) { if (this.data.defaultModelId === id) { this.data.defaultModelId = this.data.customModels[0]?.id; if (this.data.customModels[0]) { this.data.customModels[0].isDefault = true; } } this.saveSync(); return true; } return false; } public updateKeyStats( providerId: string, apiKey: string, updates: { incrementCount?: boolean; rateLimitedUntil?: number | null; incrementError?: boolean; } ): void { const provider = this.data.providers.find(p => p.id === providerId); if (!provider) return; const keyConfig = provider.keys.find(k => k.key === apiKey); if (!keyConfig) return; if (updates.incrementCount) { keyConfig.requestCount = (keyConfig.requestCount || 0) + 1; keyConfig.lastUsed = Date.now(); } if (updates.rateLimitedUntil !== undefined) { keyConfig.rateLimitedUntil = updates.rateLimitedUntil; } if (updates.incrementError) { keyConfig.errorCount = (keyConfig.errorCount || 0) + 1; } this.scheduleSave(); } public getDefaultBaseUrl(type: ProviderType): string { switch (type) { case 'gemini': return 'https://generativelanguage.googleapis.com'; case 'groq': return 'https://api.groq.com/openai/v1'; case 'openai': return 'https://api.openai.com/v1'; case 'custom': return 'https://api.openai.com/v1'; } } public maskKey(key: string): string { if (!key) return ''; if (key.length <= 8) return '****'; return `${key.slice(0, 4)}...${key.slice(-4)}`; } } export const configStore = new ConfigStore();