import fs from 'node:fs'; import path from 'node:path'; import os from 'node:os'; import { createHash, randomUUID } from 'node:crypto'; import { DatabaseSync } from 'node:sqlite'; import { parse as parseToml } from 'smol-toml'; import { modelEndpoint } from './model-hub.mjs'; import { MODEL_PROTOCOLS } from '../../shared/contracts/model-capabilities.mjs'; import { messagesAuthSettings, validateProtocolEndpoint } from '../../shared/contracts/model-endpoint.mjs'; import { nativeParameterSettings } from '../../shared/contracts/native-parameters.mjs'; const digest = value => createHash('sha256').update(JSON.stringify(value)).digest('hex'); export class ConfigImporter { constructor(hub) { this.hub = hub; this.previews = new Map(); } discover() { const root = os.homedir(); const sourcePath = path.join(root, '.cc-switch', 'cc-switch.db'); return { sources: [{ source: 'ccswitch', path: sourcePath, available: fs.existsSync(sourcePath), supported: true, detail: '导入已核对格式的Chat Completions/Responses API配置;Anthropic和客户端登录态当前不支持。' }, { source: 'workbuddy', path: '', available: false, supported: false, detail: '当前尚未取得固定版本的WorkBuddy模型配置契约。可通过连接JSON导入已知API配置;不读取其登录态。' }] }; } read(source, filename) { if (!path.isAbsolute(filename)) throw new Error('请选择配置文件的绝对路径。'); const stat = fs.lstatSync(filename); if (!stat.isFile() || stat.isSymbolicLink() || stat.size > 64 * 1024 * 1024) throw new Error('配置必须为64MB以内的普通文件。'); const rows = [], notices = []; if (source === 'workbench-json') { const value = JSON.parse(fs.readFileSync(filename, 'utf8').replace(/^\uFEFF/, '')); if (value.schema !== 1 || !Array.isArray(value.connections) || value.connections.length > 100) throw new Error('连接JSON需要schema:1与connections数组(最多100项)。'); for (const [index, item] of value.connections.entries()) { if (item.protocol && !MODEL_PROTOCOLS.includes(item.protocol)) { notices.push('第' + (index + 1) + '项协议暂不支持,已跳过。'); continue; } rows.push({ sourceId: String(item.id ?? index), name: item.name, model: item.model, protocol: item.protocol ?? 'chat-completions', streaming: item.streaming === true, capabilityDeclarations: item.capabilityDeclarations, ...(item.nativeParameters !== undefined ? { nativeParameters: item.nativeParameters } : {}), ...(item.outputTokenField !== undefined ? { outputTokenField: item.outputTokenField } : {}), ...(item.parameterProfile !== undefined ? { parameterProfile: item.parameterProfile } : {}), ...(item.protocol === 'anthropic-messages' ? { messagesAuth: item.messagesAuth ?? 'api-key' } : {}), baseUrl: item.baseUrl, apiKey: item.apiKey, requiresKey: item.requiresKey !== false, brand: item.brand }); } } else if (source === 'ccswitch') { const db = new DatabaseSync(filename, { readOnly: true }); try { const columns = db.prepare('PRAGMA table_info(providers)').all().map(value => value.name); if (!['id', 'app_type', 'name', 'settings_config'].every(value => columns.includes(value))) throw new Error('CCSwitch providers表不符合已验证格式。'); const providers = db.prepare('SELECT id,app_type,name,settings_config FROM providers ORDER BY app_type,id LIMIT 101').all(); if (providers.length > 100) throw new Error('来源超过100个provider,请缩小导入范围。'); for (const provider of providers) { let config; try { config = JSON.parse(provider.settings_config); } catch { notices.push(provider.name + '配置不是有效JSON,已跳过。'); continue; } if (provider.app_type === 'codex') { let parsed; try { parsed = typeof config.config === 'string' ? parseToml(config.config) : null; } catch { notices.push(provider.name + '的Codex TOML无法解析。'); continue; } const selected = parsed?.model_providers?.[parsed.model_provider]; if (!selected?.base_url || !['chat', 'responses'].includes(selected.wire_api)) { notices.push(provider.name + '使用未知协议,需对应的独立适配器。'); continue; } rows.push({ sourceId: 'codex:' + provider.id, name: provider.name, baseUrl: selected.base_url, model: parsed.model, protocol: selected.wire_api === 'responses' ? 'responses' : 'chat-completions', apiKey: config.auth?.OPENAI_API_KEY, requiresKey: true, brand: 'CCSwitch' }); } else notices.push(provider.name + '(' + provider.app_type + ')不属于已验证的导入格式,已跳过。'); } } finally { db.close(); } } else throw new Error('不支持该来源格式。'); const entries = []; for (const row of rows) { try { if (!String(row.model ?? '').trim() || !String(row.name ?? '').trim()) throw new Error('缺少名称或模型'); if (row.apiKey !== undefined && typeof row.apiKey !== 'string') throw new Error('凭据不是字符串'); const native = row.nativeParameters !== undefined || row.outputTokenField !== undefined || row.parameterProfile !== undefined ? nativeParameterSettings(row.protocol, row.nativeParameters ?? {}, row.outputTokenField, row.parameterProfile) : {}; entries.push({ ...row, ...native, ...messagesAuthSettings(row.protocol, row.messagesAuth), name: String(row.name).slice(0, 100), model: String(row.model).slice(0, 200), baseUrl: validateProtocolEndpoint(row.protocol, modelEndpoint(row.baseUrl)), origin: digest({ source, path: path.resolve(filename), id: row.sourceId }), apiKey: row.apiKey?.trim() ?? '' }); } catch { notices.push(String(row.name ?? '某项配置').slice(0, 100) + '缺少有效的接口或模型,已跳过。'); } } return { entries, notices, fingerprint: digest(entries) }; } preview(source, filename) { const contents = this.read(source, filename), id = randomUUID(); for (const [key, value] of this.previews) if (Date.now() - value.created > 300000) this.previews.delete(key); if (this.previews.size >= 8) throw new Error('预览数量过多,请先完成已有导入。'); this.previews.set(id, { source, path: path.resolve(filename), created: Date.now(), ...contents }); return { id, entries: contents.entries.map(({ apiKey, sourceId, origin, ...value }, index) => ({ ...value, id: String(index), hasKey: !!apiKey })), notices: contents.notices, expiresInMs: 300000 }; } apply(id, autoSync, persistCredentials = false) { const preview = this.previews.get(id); if (!preview || Date.now() - preview.created > 300000) throw new Error('导入预览已过期,请重新预览。'); const current = this.read(preview.source, preview.path); if (current.fingerprint !== preview.fingerprint) { this.previews.delete(id); throw new Error('来源配置已变化,请重新预览再导入。'); } const result = this.hub.editRegistry(() => { const imported = [], conflicts = []; const sourceId = digest({ source: preview.source, path: preview.path }); for (const item of current.entries) { const previous = this.hub.state.connections.find(value => value.importOrigin === item.origin); if (previous && previous.importRevision !== previous.revision) { conflicts.push(previous.name); continue; } const value = this.hub.upsert({ ...(previous ?? {}), ...item, id: previous?.id, revision: previous?.revision, enabled: previous ? previous.enabled : true, persistKey: persistCredentials === true && !!item.apiKey, ...(item.apiKey ? { apiKey: item.apiKey } : { apiKey: '' }) }); const stored = this.hub.connection(value.id); stored.source = preview.source; stored.importOrigin = item.origin; stored.importRevision = stored.revision; imported.push(value.id); } const previousSource = this.hub.state.imports[sourceId]; const checkedAt = new Date().toISOString(); this.hub.state.imports[sourceId] = { source: preview.source, path: preview.path, enabled: autoSync === undefined ? previousSource?.enabled === true : autoSync === true, lastFingerprint: current.fingerprint, lastCheckedAt: checkedAt, lastSyncedAt: imported.length ? checkedAt : previousSource?.lastSyncedAt ?? null, lastResult: { imported: imported.length, conflicts } }; this.hub.save(); return { imported, conflicts, sourceId }; }); this.previews.delete(id); return result; } toggle(id, enabled) { const source = this.hub.state.imports[id]; if (!source) throw new Error('导入来源不存在。'); source.enabled = enabled === true; this.hub.save(); return { id, enabled: source.enabled }; } sync() { const reports = []; for (const [id, source] of Object.entries(this.hub.state.imports)) { if (!source.enabled) continue; try { const read = this.read(source.source, source.path); source.lastCheckedAt = new Date().toISOString(); if (read.fingerprint === source.lastFingerprint) { this.hub.save(); continue; } const preview = this.preview(source.source, source.path); reports.push(this.apply(preview.id, true)); } catch (cause) { const current = this.hub.state.imports[id]; current.lastError = '来源暂不可读取或格式变化,请重新预览核对。'; current.lastCheckedAt = new Date().toISOString(); this.hub.save(); reports.push({ id, error: current.lastError }); } } return reports; } }