import { Box, Text, useInput } from 'ink'; import React, { useState } from 'react'; import { testModelConnection } from '../../config/configDiagnostics.js'; import type { ApiFormat, ModelConfig } from '../../config/configFile.js'; import { defaultMaxTokens } from '../../config/configFile.js'; import { configService } from '../../config/configService.js'; import { CONFIG_LIMITS, normalizeLimited } from '../../config/numericLimits.js'; import { type FieldDef, FieldForm } from './fieldForm.js'; import { API_FORMAT_CHOICES, PRESETS, REASONING_EFFORT_CHOICES, findPresetIndex, reasoningEffortFromChoice, reasoningEffortToChoice, resolveContextWindow, } from './providerPresets.js'; export type ExistingProvider = Pick< ModelConfig, | 'id' | 'apiFormat' | 'displayName' | 'baseURL' | 'apiKey' | 'model' | 'contextWindow' | 'maxTokens' | 'supportsVision' | 'promptCache' | 'reasoning' | 'reasoningEffort' >; interface Props { existing?: ExistingProvider | null; setAsBase?: boolean; quick?: boolean; onDone: () => void; onCancel: () => void; } const numberValue = (value: unknown, fallback: number) => { const parsed = Number(String(value ?? '').trim()); return Number.isFinite(parsed) ? parsed : fallback; }; export function ProviderWizard({ existing: original, setAsBase = true, quick = false, onDone, onCancel, }: Props): JSX.Element { const initialPresetIndex = original ? PRESETS.findIndex(item => item.baseURL === original.baseURL) : -1; const [phase, setPhase] = useState<'preset' | 'quick-choice' | 'fields'>( 'preset', ); const [advanced, setAdvanced] = useState(false); const [presetIndex, setPresetIndex] = useState(() => { if (original) { const byUrl = PRESETS.findIndex( (item) => item.baseURL === original.baseURL, ); if (byUrl >= 0) return byUrl; } return findPresetIndex(original?.displayName); }); const preset = PRESETS[presetIndex]!; // A provider switch must not send the old provider's credential to a new host. const existing = presetIndex === (initialPresetIndex >= 0 ? initialPresetIndex : findPresetIndex(original?.displayName)) ? original : undefined; useInput((input, key) => { if (phase === 'quick-choice') { if (key.escape) setPhase('preset'); else if (key.upArrow || key.downArrow) setAdvanced((value) => !value); else if (key.return) setPhase('fields'); return; } if (phase !== 'preset') return; if (key.escape || (key.ctrl && input === 'c')) onCancel(); else if (key.upArrow) setPresetIndex((index) => (index - 1 + PRESETS.length) % PRESETS.length); else if (key.downArrow) setPresetIndex((index) => (index + 1) % PRESETS.length); else if (key.return) setPhase(quick ? 'quick-choice' : 'fields'); }); if (phase === 'preset') return ( {quick ? '首次运行 · 配置基座模型' : existing ? '编辑模型' : '添加模型'} ↑↓ 选择服务商 · Enter 继续 · ESC 返回 {PRESETS.map((item, index) => ( {index === presetIndex ? '> ' : ' '} {item.label} ))} ); if (phase === 'quick-choice') return ( 选择配置深度 快速配置使用服务商推荐的窗口、输出上限和缓存策略。 {!advanced ? '> ' : ' '}快速配置(推荐) {advanced ? '> ' : ' '}高级配置 ); // 协议:选了具体服务商就跟服务商走(编辑时换服务商可以顺带换协议); // 「自定义」没有预设,沿用已有模型自己的协议,新建时在完整设置里让用户选。 const presetFormat: ApiFormat | undefined = preset.name === 'custom' ? existing?.apiFormat : (preset.apiFormat ?? 'openai'); const askFormat = preset.name === 'custom'; const knownFormat: ApiFormat = presetFormat ?? 'openai'; // 推理强度是 OpenAI 系模型最常调的一项:快速配置也要问,不藏进高级里。 const showEffort = knownFormat !== 'anthropic' && (preset.supportsReasoningEffort === true || knownFormat === 'openai-responses' || !!existing?.reasoningEffort || !quick || advanced); const defaultModel = existing?.model ?? preset.models[0] ?? ''; const defaultContext = existing?.contextWindow ?? resolveContextWindow(preset, defaultModel); const fields: FieldDef[] = [ { key: 'baseURL', label: 'API 完整端点地址', type: 'text', default: existing?.baseURL ?? preset.baseURL, }, { key: 'apiKey', label: 'API Key', type: 'password', default: existing?.apiKey ?? '', optional: !!existing, hint: existing ? '留空保持原凭据;清除凭据请在模型操作菜单执行' : undefined, }, { key: 'model', label: '模型 ID', type: 'text', default: defaultModel, hint: preset.models.length ? `常用:${preset.models.join('、')}` : undefined, }, ]; if (askFormat) fields.push({ key: 'apiFormat', label: '接口协议', type: 'select', options: API_FORMAT_CHOICES, default: existing?.apiFormat ?? 'openai', hint: 'openai = Chat Completions(多数国内服务商);openai-responses = OpenAI Responses API;anthropic = Messages API(未经真实端点验证)', }); if (showEffort) fields.push({ key: 'reasoningEffort', label: '推理强度', type: 'select', options: REASONING_EFFORT_CHOICES, default: reasoningEffortToChoice( existing ? existing.reasoningEffort : preset.reasoningEffort, ), hint: '越高越慢越贵(推理 Token 照常计费)。各模型支持的档位不同;服务端不接受时会自动去掉该参数重发并告警。', }); if (!quick || advanced) fields.push( { key: 'displayName', label: '显示名称', type: 'text', default: existing?.displayName ?? preset.label, optional: true, }, { key: 'contextWindow', label: '上下文窗口(Token)', type: 'text', default: existing ? String(defaultContext) : '', optional: true, hint: '留空按最终填写的模型 ID 使用预设窗口;自定义模型请确认服务商实际限制。', }, { key: 'maxTokens', label: '单次输出上限(留空使用推荐值)', type: 'text', default: existing?.maxTokens ? String(existing.maxTokens) : '', optional: true, }, { key: 'promptCache', label: 'Prompt Cache 模式', type: 'select', options: ['auto', 'session-key', 'disabled'], default: existing?.promptCache?.mode ?? preset.promptCacheMode ?? 'auto', }, ...(knownFormat === 'openai-responses' ? [] : [ { key: 'reasoning', label: '启用 Reasoning(Provider 支持时)', type: 'boolean' as const, default: existing?.reasoning ?? preset.reasoning ?? false, hint: '仅显式启用时发送 reasoning.enabled=true;普通 OpenAI 端点保持默认行为', }, ]), ); return ( { const baseURL = String(values.baseURL ?? '').trim(); const apiKey = String(values.apiKey ?? existing?.apiKey ?? '').trim(); const model = String(values.model ?? '').trim(); if (!baseURL || !apiKey || !model) throw new Error('Base URL、API Key 和模型 ID 均不能为空'); if (original && apiKey === original.apiKey && new URL(baseURL).origin !== new URL(original.baseURL).origin) throw new Error('端点已换到其他服务商,请显式填写新服务商的 API Key,不能复用旧凭据'); for (const key of ['contextWindow', 'maxTokens']) { const raw = String(values[key] ?? '').trim(); if (raw && (!Number.isSafeInteger(Number(raw)) || Number(raw) <= 0)) throw new Error(`${key} 必须是正整数,或留空使用推荐值`); } const contextWindow = normalizeLimited( quick && !advanced ? resolveContextWindow(preset, model) : String(values.contextWindow ?? '').trim() ? numberValue(values.contextWindow, defaultContext) : resolveContextWindow(preset, model), CONFIG_LIMITS.modelContextWindow, defaultContext, ); const rawMax = quick && !advanced ? '' : String(values.maxTokens ?? '').trim(); const maxTokens = rawMax ? normalizeLimited( numberValue(rawMax, defaultMaxTokens(contextWindow)), CONFIG_LIMITS.modelMaxTokens, defaultMaxTokens(contextWindow), ) : undefined; const apiFormat: ApiFormat = askFormat ? (API_FORMAT_CHOICES.find((item) => item === values.apiFormat) ?? knownFormat) : knownFormat; if (new URL(baseURL).hostname === 'api.openai.com' && model.startsWith('gpt-6.2') && apiFormat !== 'openai-responses') throw new Error('OpenAI 6.2 的工具调用需要 Responses API,请选择 Responses 预设和 /v1/responses 端点'); const reasoningEffort = showEffort ? reasoningEffortFromChoice(values.reasoningEffort) : existing?.reasoningEffort; const draft = { apiFormat, displayName: quick && !advanced ? preset.label : String(values.displayName ?? '').trim() || undefined, baseURL, apiKey, model, contextWindow, maxTokens: maxTokens ?? defaultMaxTokens(contextWindow), supportsVision: existing?.supportsVision !== false, ...(reasoningEffort ? { reasoningEffort } : {}), reasoning: quick && !advanced ? (preset.reasoning ?? false) : values.reasoning === true, promptCache: { mode: quick && !advanced ? (preset.promptCacheMode ?? 'auto') : (values.promptCache as 'auto' | 'session-key' | 'disabled'), }, }; const diagnostic = await testModelConnection(draft); if (!diagnostic.ok) throw new Error(diagnostic.message); if (original) { await configService.savePatch({ // null = 清除之前设的强度(选了「不设置」);不带这个字段则保留旧值。 models: [{ op: 'update', id: original.id, patch: { ...draft, reasoningEffort: reasoningEffort ?? null } }], ...(setAsBase ? { baseModelId: original.id } : {}), }); } else { const before = new Set( (await configService.models()).map((entry) => entry.id), ); const saved = await configService.savePatch({ models: [{ op: 'add', model: { ...draft, enabled: true } }], }); const id = saved.config?.models.find( (entry) => !before.has(entry.id), )?.id; if (!id) throw new Error('模型已保存,但无法确认模型 ID'); if (setAsBase && saved.config?.baseModelId !== id) await configService.savePatch({ baseModelId: id }); } onDone(); }} onCancel={() => setPhase('preset')} /> ); }