-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconfig_clean.txt
More file actions
809 lines (713 loc) · 25.2 KB
/
Copy pathconfig_clean.txt
File metadata and controls
809 lines (713 loc) · 25.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
import fs from "node:fs";
import path from "node:path";
import os from "node:os";
import type { McpServerConfig } from "./mcp/types.js";
import { isPlainRecord } from "./utils.js";
/**
* 单个模型条目
* @property id - 模型ID(如 gpt-4、claude-3 等)
* @property name - 模型显示名称(可选)
* @property description - 模型描述(可选)
*/
export type ModelEntry = {
id: string;
name?: string;
description?: string;
};
/**
* 提供商配置
* @property models - 该提供商支持的模型列表
* @property apiKey - API密钥(可选,支持OAuth时可不填)
* @property baseURL - API基础地址
* @property apiMode - API模式:responses(新模式)或 chat-completions(传统模式)
* @property auth - 认证配置,支持 OAuth
*/
export type ModelProfile = {
models: (string | ModelEntry)[];
apiKey?: string;
baseURL?: string;
apiMode?: "responses" | "chat-completions";
auth?: ProviderAuthConfig;
};
/** OAuth 认证配置 */
export type ProviderAuthConfig = {
type: "oauth";
};
/**
* 完整设置结构
* @property providers - 所有提供商的配置
* @property defaultProvider - 默认使用的提供商名称
* @property defaultModel - 默认模型ID
* @property showThinking - 是否显示模型的思考过程
* @property mcp - MCP服务器配置
*/
export type Settings = {
providers: Record<string, ModelProfile>;
defaultProvider?: string;
defaultModel?: string;
showThinking?: boolean;
mcp?: {
servers: McpServerConfig[];
};
};
/**
* 解析后的运行时配置
* 这是从 settings.json 和环境变量综合计算得出的最终配置
*/
export type ResolvedConfig = {
model: string; // 选中的模型ID
apiKey: string; // API密钥
baseURL: string; // API基础地址
apiMode: "responses" | "chat-completions"; // API模式
showThinking: boolean; // 是否显示思考过程
providerName: string; // 当前提供商名称
availableModels: string[]; // 该提供商的所有可用模型
};
export type StoredOAuthCredentials = {
type: "oauth";
access_token?: string;
refresh_token?: string;
id_token?: string;
expires_at?: string;
client_id?: string;
email?: string;
chatgpt_account_id?: string;
};
export type CredentialsFile = {
providers: Record<string, StoredOAuthCredentials>;
};
export type ProviderAuthState = {
authMode: "oauth" | "apiKey" | "none";
bearerToken: string;
apiKey: string;
oauth?: StoredOAuthCredentials;
};
export type RuntimeAuthResolution = {
state: ProviderAuthState;
credentials: CredentialsFile;
didRefresh: boolean;
};
export type ResolveRuntimeAuthArgs = {
settings: Settings;
providerName: string;
credentials?: CredentialsFile;
refreshOAuthToken?: (credentials: StoredOAuthCredentials) => Promise<StoredOAuthCredentials>;
onCredentialsUpdated?: (credentials: CredentialsFile) => Promise<void> | void;
now?: Date;
};
/**
* 配置文件目录:~/.weber/
*
* 该目录包含:
* - settings.json: 提供商配置(模型、API地址、API模式等)
* - credentials.json: 凭证配置(OAuth token、API Key等敏感信息)
*/
const CONFIG_DIR = path.join(os.homedir(), ".weber");
const SETTINGS_PATH = path.join(CONFIG_DIR, "settings.json");
const CREDENTIALS_PATH = path.join(CONFIG_DIR, "credentials.json");
let cachedSettings: Settings | null = null;
let cachedSettingsWarnings: string[] = [];
export function getSettingsPath(): string {
return SETTINGS_PATH;
}
export function getCredentialsPath(): string {
return CREDENTIALS_PATH;
}
/**
* MiniMax 默认配置
* API Key 从环境变量 MINIMAX_API_KEY 读取
* 也可在 settings.json 中覆盖配置
*/
const DEFAULT_MINIMAX_PROVIDER: ModelProfile = {
models: ["MiniMax-M2.7-highspeed", "MiniMax-M2.7", "MiniMax-M2.5-highspeed", "MiniMax-M2.5"],
apiKey: process.env.MINIMAX_API_KEY ?? "",
baseURL: process.env.MINIMAX_BASEURL,
};
/**
* DeepSeek 默认配置
* API Key 从环境变量 DEEPSEEK_API_KEY 读取
* DeepSeek 使用 chat-completions 模式
*/
const DEFAULT_DEEPSEEK_PROVIDER: ModelProfile = {
models: ["deepseek-v4-pro", "deepseek-v4-flash"],
apiKey: process.env.DEEPSEEK_API_KEY ?? "",
baseURL: "https://api.deepseek.com/v1",
};
export function loadSettings(): Settings {
if (cachedSettings) return cachedSettings;
// 默认配置:包含 MiniMax 和 DeepSeek providers
const defaultSettings: Settings = {
providers: {
minimax: DEFAULT_MINIMAX_PROVIDER,
deepseek: DEFAULT_DEEPSEEK_PROVIDER,
},
mcp: { servers: [] },
};
try {
if (!fs.existsSync(SETTINGS_PATH)) {
cachedSettingsWarnings = [];
cachedSettings = defaultSettings;
return defaultSettings;
}
const raw = fs.readFileSync(SETTINGS_PATH, "utf8");
const parsed = JSON.parse(raw);
const warnings: string[] = [];
cachedSettings = normalizeSettings(parsed, warnings);
cachedSettingsWarnings = warnings;
return cachedSettings!;
} catch (error) {
cachedSettingsWarnings = [`[config] Failed to load settings: ${error instanceof Error ? error.message : String(error)}`];
cachedSettings = defaultSettings;
return defaultSettings;
}
}
/**
* Read and normalize a settings file from an explicit path.
*
* Why this exists:
* - Most runtime code uses the global settings path, but targeted update helpers
* and tests need the same normalization behavior for arbitrary files.
* - Keeping the file-path variant local to this module avoids exposing another
* caching surface while still reusing the exact same parser rules.
*/
function loadSettingsFromFile(filePath: string): Settings {
const defaultSettings: Settings = { providers: {}, mcp: { servers: [] } };
try {
if (!fs.existsSync(filePath)) {
return defaultSettings;
}
const raw = fs.readFileSync(filePath, "utf8");
return normalizeSettings(JSON.parse(raw), []);
} catch {
return defaultSettings;
}
}
export function reloadSettings(): Settings {
cachedSettings = null;
cachedSettingsWarnings = [];
return loadSettings();
}
export function getSettingsWarnings(): string[] {
return [...cachedSettingsWarnings];
}
export function getProviderNames(): string[] {
const settings = loadSettings();
return Object.keys(settings.providers);
}
export function normalizeModelEntry(entry: string | ModelEntry): ModelEntry {
if (typeof entry === "string") return { id: entry };
return entry;
}
export function getProviderModels(providerName: string): string[] {
const settings = loadSettings();
return (settings.providers[providerName]?.models ?? []).map((m) => normalizeModelEntry(m).id);
}
export function loadCredentialsFile(filePath = CREDENTIALS_PATH): CredentialsFile {
const empty: CredentialsFile = { providers: {} };
try {
if (!fs.existsSync(filePath)) {
return empty;
}
const raw = JSON.parse(fs.readFileSync(filePath, "utf8"));
return normalizeCredentialsFile(raw);
} catch {
return empty;
}
}
export async function writeCredentialsFile(filePath: string, credentials: CredentialsFile): Promise<void> {
await fs.promises.mkdir(path.dirname(filePath), { recursive: true });
await fs.promises.writeFile(filePath, `${JSON.stringify(normalizeCredentialsFile(credentials), null, 2)}\n`, "utf8");
}
/**
* Persist normalized settings back to disk.
*
* Why this exists:
* - Runtime flows such as OAuth model discovery need to update the user's
* provider configuration after the process has already started.
* - Writing normalized settings keeps the stored file aligned with the same
* schema validation rules used during reads, which avoids persisting partial
* or malformed provider state.
* - Resetting the cache after the write ensures later reads in the same process
* see the new configuration immediately.
*/
export async function writeSettingsFile(filePath: string, settings: Settings): Promise<void> {
const normalized = normalizeSettings(settings, []);
await fs.promises.mkdir(path.dirname(filePath), { recursive: true });
await fs.promises.writeFile(filePath, `${JSON.stringify(normalized, null, 2)}\n`, "utf8");
cachedSettings = null;
cachedSettingsWarnings = [];
}
/**
* Update the model list for a single provider while preserving the rest of the
* settings file as-is.
*
* Why this exists:
* - OAuth login can discover the exact API-visible model IDs for the active
* provider and should write only that slice of configuration.
* - Reusing a focused helper keeps the login flow small and avoids duplicating
* settings-file merge logic in UI code.
* - The helper normalizes incoming model IDs so callers can pass any raw API
* list without worrying about duplicate whitespace or empty entries.
*/
export async function updateProviderModels(filePath: string, providerName: string, modelIds: string[]): Promise<void> {
const settings = loadSettingsFromFile(filePath);
const provider = settings.providers[providerName];
if (!provider) {
return;
}
const normalizedModels = modelIds
.map((modelId) => modelId.trim())
.filter((modelId, index, values) => Boolean(modelId) && values.indexOf(modelId) === index);
await writeSettingsFile(filePath, {
...settings,
providers: {
...settings.providers,
[providerName]: {
...provider,
models: normalizedModels,
},
},
});
}
export async function clearProviderCredentials(filePath: string, providerName: string): Promise<void> {
const current = loadCredentialsFile(filePath);
if (!(providerName in current.providers)) {
return;
}
const nextProviders = { ...current.providers };
delete nextProviders[providerName];
await writeCredentialsFile(filePath, { providers: nextProviders });
}
/**
* 根据 baseURL 和显式配置自动判断 API 模式
*
* 支持的 API 模式:
* - responses: OpenAI 新推出的 Responses API
*
* @param baseURL - API 基础地址
* @param explicit - 显式指定的模式(优先级最高)
* @returns API 模式类型
*/
function resolveApiMode(baseURL: string, explicit?: string): "responses" | "chat-completions" {
const mode = (explicit ?? "").trim().toLowerCase();
// 1. 如果显式指定了模式,直接使用
if (["chat", "chat-completions", "chat_completions"].includes(mode)) {
return "chat-completions";
}
if (mode === "responses") {
return "responses";
}
// 2. 根据 baseURL 自动检测模式
// DeepSeek 使用 chat-completions 模式
if (baseURL.toLowerCase().includes("deepseek.com")) {
return "chat-completions";
}
// MiniMax 使用 chat-completions 模式
// MiniMax API: https://platform.minimax.chat/
if (baseURL.toLowerCase().includes("minimax.com")) {
return "chat-completions";
}
// 3. 默认为 responses 模式(OpenAI 标准)
return "responses";
}
/**
* 解析配置,确定运行时使用的提供商和模型
*
* 提供商优先级:explicit arg > defaultProvider > 第一个可用的提供商
* 模型优先级:explicit arg > MODEL_ID 环境变量 > defaultModel 配置
*/
export function resolveConfig(providerName?: string, modelName?: string): ResolvedConfig {
const settings = loadSettings();
// 确定使用哪个提供商:explicit参数 > defaultProvider > 第一个可用key
const providerKeys = Object.keys(settings.providers);
const targetProvider = providerName || settings.defaultProvider || providerKeys[0] || "";
const provider = settings.providers[targetProvider];
// 获取该提供商的所有可用模型
const availableModels = (provider?.models ?? []).map((m) => normalizeModelEntry(m).id);
/**
* 模型解析优先级(从高到低):
* 1. modelName 参数 - 明确的运行时切换
* 2. MODEL_ID 环境变量 - Shell级别覆盖
* 3. settings.defaultModel - settings.json 中的持久化默认
*/
const model = modelName ?? process.env.MODEL_ID ?? settings.defaultModel ?? "";
// API Key 优先级:settings.json > 环境变量 MINIMAX_API_KEY
const apiKey = provider?.apiKey ?? process.env.MINIMAX_API_KEY ?? "";
const baseURL = provider?.baseURL ?? process.env.MINIMAX_BASEURL ?? "https://api.openai.com/v1";
const apiMode = resolveApiMode(baseURL, provider?.apiMode ?? process.env.MINIMAX_API_MODE);
const showThinking = settings.showThinking ?? false;
// 调试
console.log(`[DEBUG] resolveConfig: provider=${targetProvider}, baseURL=${baseURL}, apiMode=${apiMode}`);
return {
model,
apiKey,
baseURL,
apiMode,
showThinking,
providerName: targetProvider,
availableModels,
};
}
/**
* Evaluate whether a resolved startup config is complete enough to skip the
* interactive model picker.
*
* Why this exists:
* - The UI needs a deterministic rule, but tests should not have to depend on
* the real `~/.weber/settings.json` on the current machine.
* - Splitting the pure decision from filesystem-backed config loading keeps the
* startup path easy to verify without mutating user state.
* - The shell-level override must remain a first-class bypass so ad-hoc runs
* can pin a model even before settings metadata catches up.
*/
export function shouldPromptForModelSelection(
resolved: Pick<ResolvedConfig, "providerName" | "model" | "availableModels">,
hasShellModelOverride = false,
): boolean {
if (!resolved.providerName || !resolved.model) {
return true;
}
if (hasShellModelOverride) {
return false;
}
return !resolved.availableModels.includes(resolved.model);
}
/**
* Decide whether startup must ask the user to pick a model interactively.
*
* Why this exists:
* - Startup needs one consistent rule that matches the documented precedence:
* explicit arg > `MODEL_ID` > `settings.defaultModel`.
* - `MODEL_ID` is intentionally a shell-level override, so it must be allowed to
* bypass the picker even when the local settings file has not listed that
* model yet.
* - Persistent config values should still be validated against the configured
* provider model list so broken saved settings continue to fall back to the
* chooser instead of failing later with a surprising runtime state.
*/
export function needsModelSelection(providerName?: string, modelName?: string): boolean {
const resolved = resolveConfig(providerName, modelName);
return shouldPromptForModelSelection(resolved, !modelName && Boolean(process.env.MODEL_ID));
}
function normalizeAuthConfig(
value: unknown,
warningPrefix: string,
warnings: string[],
): ProviderAuthConfig | undefined {
if (value === undefined) {
return undefined;
}
if (!isPlainRecord(value)) {
warnings.push(`${warningPrefix} must be an object.`);
return undefined;
}
if (value.type === "oauth") {
return { type: "oauth" };
}
warnings.push(`${warningPrefix}.type must be "oauth".`);
return undefined;
}
function normalizeModelProfile(
value: unknown,
providerName: string,
warnings: string[],
): ModelProfile | null {
if (!isPlainRecord(value)) {
warnings.push(`[config] provider "${providerName}" must be an object.`);
return null;
}
const models = Array.isArray(value.models) ? value.models : [];
if (!Array.isArray(value.models)) {
warnings.push(`[config] provider "${providerName}".models must be an array.`);
}
const normalizedModels: (string | ModelEntry)[] = [];
for (const entry of models) {
if (typeof entry === "string") {
normalizedModels.push(entry);
continue;
}
if (isPlainRecord(entry) && typeof entry.id === "string" && entry.id.trim()) {
normalizedModels.push({
id: entry.id.trim(),
name: typeof entry.name === "string" ? entry.name : undefined,
description: typeof entry.description === "string" ? entry.description : undefined,
});
continue;
}
warnings.push(`[config] provider "${providerName}" has an invalid model entry.`);
}
return {
models: normalizedModels,
apiKey: typeof value.apiKey === "string" ? value.apiKey : undefined,
baseURL: typeof value.baseURL === "string" ? value.baseURL : undefined,
apiMode: value.apiMode === "responses" || value.apiMode === "chat-completions"
? value.apiMode
: undefined,
auth: normalizeAuthConfig(value.auth, `[config] provider "${providerName}".auth`, warnings),
};
}
function normalizeStoredOAuthCredentials(value: unknown): StoredOAuthCredentials | null {
if (!isPlainRecord(value) || value.type !== "oauth") {
return null;
}
return {
type: "oauth",
access_token: typeof value.access_token === "string" ? value.access_token : undefined,
refresh_token: typeof value.refresh_token === "string" ? value.refresh_token : undefined,
id_token: typeof value.id_token === "string" ? value.id_token : undefined,
expires_at: typeof value.expires_at === "string" ? value.expires_at : undefined,
client_id: typeof value.client_id === "string" ? value.client_id : undefined,
email: typeof value.email === "string" ? value.email : undefined,
chatgpt_account_id: typeof value.chatgpt_account_id === "string" ? value.chatgpt_account_id : undefined,
};
}
export function normalizeCredentialsFile(raw: unknown): CredentialsFile {
if (!isPlainRecord(raw) || !isPlainRecord(raw.providers)) {
return { providers: {} };
}
const providers = Object.entries(raw.providers)
.map(([providerName, value]) => [providerName, normalizeStoredOAuthCredentials(value)] as const)
.filter((entry): entry is readonly [string, StoredOAuthCredentials] => entry[1] !== null);
return { providers: Object.fromEntries(providers) };
}
function isCredentialExpired(value: string | undefined, now = new Date()): boolean {
if (!value) {
return false;
}
const expiresAt = Date.parse(value);
if (Number.isNaN(expiresAt)) {
return false;
}
return expiresAt - now.getTime() <= 60_000;
}
export function resolveProviderAuthState(
settings: Settings,
providerName: string,
credentials: CredentialsFile,
now = new Date(),
): ProviderAuthState {
const provider = settings.providers[providerName];
const apiKey = provider?.apiKey ?? "";
const oauth = credentials.providers[providerName];
if (provider?.auth?.type === "oauth" && oauth?.type === "oauth") {
const accessToken = oauth.access_token?.trim() ?? "";
if (accessToken && !isCredentialExpired(oauth.expires_at, now)) {
return {
authMode: "oauth",
bearerToken: accessToken,
apiKey,
oauth,
};
}
}
if (apiKey.trim()) {
return {
authMode: "apiKey",
bearerToken: apiKey,
apiKey,
oauth,
};
}
return {
authMode: "none",
bearerToken: "",
apiKey,
oauth,
};
}
export async function resolveRuntimeAuth({
settings,
providerName,
credentials = loadCredentialsFile(),
refreshOAuthToken,
onCredentialsUpdated,
now = new Date(),
}: ResolveRuntimeAuthArgs): Promise<RuntimeAuthResolution> {
const provider = settings.providers[providerName];
const oauth = credentials.providers[providerName];
const initialState = resolveProviderAuthState(settings, providerName, credentials, now);
if (provider?.auth?.type !== "oauth" || oauth?.type !== "oauth" || !refreshOAuthToken) {
return { state: initialState, credentials, didRefresh: false };
}
const accessToken = oauth.access_token?.trim() ?? "";
if (accessToken && !isCredentialExpired(oauth.expires_at, now)) {
return { state: initialState, credentials, didRefresh: false };
}
const refreshToken = oauth.refresh_token?.trim() ?? "";
if (!refreshToken) {
return { state: initialState, credentials, didRefresh: false };
}
try {
const refreshed = await refreshOAuthToken(oauth);
const nextCredentials: CredentialsFile = {
providers: {
...credentials.providers,
[providerName]: refreshed,
},
};
if (onCredentialsUpdated) {
await onCredentialsUpdated(nextCredentials);
}
return {
state: resolveProviderAuthState(settings, providerName, nextCredentials, now),
credentials: nextCredentials,
didRefresh: true,
};
} catch {
return { state: initialState, credentials, didRefresh: false };
}
}
function normalizeStringRecord(
value: unknown,
warningPrefix: string,
warnings: string[],
): Record<string, string> | undefined {
if (value === undefined) {
return undefined;
}
if (!isPlainRecord(value)) {
warnings.push(`${warningPrefix} must be an object.`);
return undefined;
}
const entries = Object.entries(value)
.filter(([, entryValue]) => entryValue !== undefined && entryValue !== null)
.map(([key, entryValue]) => [key, String(entryValue)] as const);
return Object.fromEntries(entries);
}
function normalizeStringArray(
value: unknown,
warningPrefix: string,
warnings: string[],
): string[] | undefined {
if (value === undefined) {
return undefined;
}
if (!Array.isArray(value)) {
warnings.push(`${warningPrefix} must be an array.`);
return undefined;
}
return value.map((entry) => String(entry));
}
function normalizeMcpServer(
value: unknown,
index: number,
warnings: string[],
seenNames: Set<string>,
): McpServerConfig | null {
if (!isPlainRecord(value)) {
warnings.push(`[mcp] server[${index}] must be an object.`);
return null;
}
const name = String(value.name ?? "").trim();
if (!name) {
warnings.push(`[mcp] server[${index}] is missing a non-empty name.`);
return null;
}
if (seenNames.has(name)) {
warnings.push(`[mcp] duplicate server name "${name}" was ignored.`);
return null;
}
const transport = value.transport === "stdio" || value.transport === "streamable-http"
? value.transport
: null;
if (!transport) {
warnings.push(`[mcp] server "${name}" has unsupported transport "${String(value.transport ?? "")}".`);
return null;
}
const timeoutValue = value.timeoutMs;
const timeoutMs = typeof timeoutValue === "number" && Number.isFinite(timeoutValue) && timeoutValue > 0
? timeoutValue
: 30_000;
if (timeoutValue !== undefined && timeoutMs !== timeoutValue) {
warnings.push(`[mcp] server "${name}" has invalid timeoutMs; defaulting to 30000.`);
}
const enabled = value.enabled === undefined ? true : Boolean(value.enabled);
if (transport === "stdio") {
const command = String(value.command ?? "").trim();
if (!command) {
warnings.push(`[mcp] stdio server "${name}" is missing command.`);
return null;
}
const cwd = typeof value.cwd === "string" ? value.cwd.trim() : undefined;
if (value.cwd !== undefined && typeof value.cwd !== "string") {
warnings.push(`[mcp] server "${name}".cwd must be a string.`);
} else if (cwd && !fs.existsSync(cwd)) {
warnings.push(`[mcp] stdio server "${name}" cwd does not exist: ${cwd}.`);
}
seenNames.add(name);
return {
name,
enabled,
transport,
command,
args: normalizeStringArray(value.args, `[mcp] server "${name}".args`, warnings) ?? [],
env: normalizeStringRecord(value.env, `[mcp] server "${name}".env`, warnings),
cwd: cwd || undefined,
timeoutMs,
};
}
const url = String(value.url ?? "").trim();
if (!url) {
warnings.push(`[mcp] streamable-http server "${name}" is missing url.`);
return null;
}
seenNames.add(name);
return {
name,
enabled,
transport,
url,
headers: normalizeStringRecord(value.headers, `[mcp] server "${name}".headers`, warnings),
timeoutMs,
};
}
/**
* 规范化设置数据
*
* 此函数负责:
* 1. 验证 settings.json 的数据结构
* 2. 规范化每个提供商的配置
* 3. 规范化 MCP 服务器配置
* 4. 收集并报告任何警告信息
*
* @param raw - 原始 JSON 数据
* @param warnings - 警告信息数组(输出参数)
*/
export function normalizeSettings(raw: unknown, warnings: string[]): Settings {
const root = isPlainRecord(raw) ? raw : {};
// 验证 providers 结构
if (root.providers !== undefined && !isPlainRecord(root.providers)) {
warnings.push("[config] providers must be an object.");
}
// 规范化每个提供商的配置
const providers = isPlainRecord(root.providers)
? Object.fromEntries(
Object.entries(root.providers)
.map(([providerName, value]) => [providerName, normalizeModelProfile(value, providerName, warnings)] as const)
.filter((entry): entry is readonly [string, ModelProfile] => entry[1] !== null),
)
: {};
// 验证 MCP 配置
const mcpRoot = isPlainRecord(root.mcp) ? root.mcp : undefined;
if (root.mcp !== undefined && !mcpRoot) {
warnings.push("[mcp] mcp must be an object.");
}
const rawServers = mcpRoot?.servers;
if (rawServers !== undefined && !Array.isArray(rawServers)) {
warnings.push("[mcp] mcp.servers must be an array.");
}
// 规范化 MCP 服务器配置
const seenNames = new Set<string>();
const servers = Array.isArray(rawServers)
? rawServers
.map((value, index) => normalizeMcpServer(value, index, warnings, seenNames))
.filter((value): value is McpServerConfig => value !== null)
: [];
return {
providers,
defaultProvider: typeof root.defaultProvider === "string" ? root.defaultProvider : undefined,
defaultModel: typeof root.defaultModel === "string" ? root.defaultModel : undefined,
showThinking: typeof root.showThinking === "boolean" ? root.showThinking : undefined,
mcp: { servers },
};
}