@pikecode/api-key-manager 2.0.0 → 2.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (60) hide show
  1. package/README.md +444 -151
  2. package/bin/akm.js +340 -11
  3. package/package.json +29 -12
  4. package/src/CommandRegistry.js +58 -3
  5. package/src/commands/BaseCommand.js +68 -1
  6. package/src/commands/add/prompts.js +280 -0
  7. package/src/commands/add/providerSaver.js +74 -0
  8. package/src/commands/add/summaryPrinter.js +29 -0
  9. package/src/commands/add.js +54 -439
  10. package/src/commands/backup.js +396 -0
  11. package/src/commands/batch.js +313 -0
  12. package/src/commands/benchmark.js +323 -0
  13. package/src/commands/claude-clean.js +253 -0
  14. package/src/commands/clone.js +265 -0
  15. package/src/commands/current.js +89 -41
  16. package/src/commands/edit.js +3 -207
  17. package/src/commands/health.js +264 -0
  18. package/src/commands/list.js +120 -35
  19. package/src/commands/mcp.js +467 -0
  20. package/src/commands/remove.js +89 -26
  21. package/src/commands/stats.js +281 -0
  22. package/src/commands/switch/claude-settings-compatibility.js +113 -0
  23. package/src/commands/switch/launch-args-helper.js +84 -0
  24. package/src/commands/switch/provider-choices-helper.js +72 -0
  25. package/src/commands/switch/provider-details-helper.js +46 -0
  26. package/src/commands/switch/provider-edit-questions-helper.js +124 -0
  27. package/src/commands/switch/provider-launcher.js +20 -0
  28. package/src/commands/switch/provider-manager.js +214 -0
  29. package/src/commands/switch/status-helper.js +124 -0
  30. package/src/commands/switch/ui-screen-renderer.js +77 -0
  31. package/src/commands/switch.js +471 -958
  32. package/src/commands/validate.js +310 -0
  33. package/src/config.js +541 -55
  34. package/src/constants/index.js +234 -0
  35. package/src/constants/ui.js +108 -0
  36. package/src/index.js +11 -4
  37. package/src/navigation/EscNavigationManager.js +5 -5
  38. package/src/utils/atomic-file.js +47 -0
  39. package/src/utils/claude-settings.js +4 -4
  40. package/src/utils/codex-files.js +418 -0
  41. package/src/utils/codex-launcher.js +104 -0
  42. package/src/utils/concurrency.js +30 -0
  43. package/src/utils/config-opener.js +22 -2
  44. package/src/utils/env-launcher.js +50 -44
  45. package/src/utils/env-utils.js +52 -0
  46. package/src/utils/error-handler.js +27 -28
  47. package/src/utils/health-checker.js +350 -0
  48. package/src/utils/import-validator.js +210 -0
  49. package/src/utils/inquirer-setup.js +11 -0
  50. package/src/utils/launch-args.js +155 -0
  51. package/src/utils/logger.js +0 -1
  52. package/src/utils/provider-status-checker.js +211 -64
  53. package/src/utils/secrets.js +22 -0
  54. package/src/utils/shell-snippets.js +32 -0
  55. package/src/utils/terminal-format.js +22 -4
  56. package/src/utils/ui-helper.js +96 -86
  57. package/src/utils/update-checker.js +41 -12
  58. package/src/utils/validator.js +115 -88
  59. package/bin/cc.js +0 -101
  60. package/src/utils/storage.js +0 -55
package/src/config.js CHANGED
@@ -2,16 +2,71 @@ const fs = require('fs-extra');
2
2
  const path = require('path');
3
3
  const os = require('os');
4
4
  const chalk = require('chalk');
5
+ const { writeJsonAtomic } = require('./utils/atomic-file');
6
+ const { validateAndNormalizeConfigData } = require('./utils/import-validator');
5
7
 
8
+ /**
9
+ * @typedef {Object} ProviderConfig
10
+ * @property {string} name - 供应商名称
11
+ * @property {string} displayName - 显示名称
12
+ * @property {string} ideName - IDE 名称 ('claude' 或 'codex')
13
+ * @property {string} authMode - 认证模式
14
+ * @property {string} authToken - 认证令牌
15
+ * @property {string|null} baseUrl - API 基础 URL
16
+ * @property {Object|null} models - 模型配置
17
+ * @property {string[]} launchArgs - 启动参数
18
+ * @property {boolean} current - 是否为当前供应商
19
+ * @property {number} usageCount - 使用次数
20
+ * @property {string} lastUsed - 最后使用时间
21
+ * @property {string} createdAt - 创建时间
22
+ */
23
+
24
+ /**
25
+ * @typedef {Object} Config
26
+ * @property {string} version - 配置版本
27
+ * @property {string|null} currentProvider - 当前供应商名称
28
+ * @property {Object.<string, ProviderConfig>} providers - 供应商配置对象
29
+ */
30
+
31
+ /**
32
+ * 配置管理器
33
+ * 管理 API 供应商配置的加载、保存和操作
34
+ */
6
35
  class ConfigManager {
7
36
  constructor() {
37
+ /** @type {string} 配置文件路径 */
8
38
  this.configPath = path.join(os.homedir(), '.akm-config.json');
9
- this.config = null; // 延迟加载
39
+ /** @type {Config|null} 配置数据 */
40
+ this.config = null;
41
+ /** @type {boolean} 是否已加载 */
10
42
  this.isLoaded = false;
43
+ /** @type {Date|null} 最后修改时间 */
11
44
  this.lastModified = null;
12
- this.loadPromise = null; // 防止并发加载
45
+ /** @type {Promise<Config>|null} 加载 Promise,防止并发加载 */
46
+ this.loadPromise = null;
13
47
  }
14
48
 
49
+ /**
50
+ * 标准化可选字符串值
51
+ * @private
52
+ * @param {*} value - 输入值
53
+ * @returns {string|null} 标准化后的值
54
+ */
55
+ _normalizeOptionalString(value) {
56
+ if (value === null || value === undefined) {
57
+ return null;
58
+ }
59
+ if (typeof value !== 'string') {
60
+ return value;
61
+ }
62
+ const trimmed = value.trim();
63
+ return trimmed.length === 0 ? null : trimmed;
64
+ }
65
+
66
+ /**
67
+ * 获取默认配置
68
+ * @returns {Config} 默认配置对象
69
+ */
15
70
  getDefaultConfig() {
16
71
  return {
17
72
  version: '1.0.0',
@@ -20,6 +75,11 @@ class ConfigManager {
20
75
  };
21
76
  }
22
77
 
78
+ /**
79
+ * 加载配置文件
80
+ * @param {boolean} [forceReload=false] - 是否强制重新加载
81
+ * @returns {Promise<Config>} 配置对象
82
+ */
23
83
  async load(forceReload = false) {
24
84
  // 如果正在加载,等待当前加载完成
25
85
  if (this.loadPromise) {
@@ -50,24 +110,42 @@ class ConfigManager {
50
110
  async _performLoad() {
51
111
  try {
52
112
  if (await fs.pathExists(this.configPath)) {
53
- const data = await fs.readJSON(this.configPath);
113
+ // 检查并修复文件权限(仅 Unix 系统)
114
+ await this._checkAndFixPermissions();
115
+
116
+ let data;
117
+ try {
118
+ data = await fs.readJSON(this.configPath);
119
+ } catch {
120
+ // 配置文件损坏,创建备份并重置
121
+ const backupPath = `${this.configPath}.corrupted.${Date.now()}`;
122
+ await fs.copy(this.configPath, backupPath);
123
+ console.log(chalk.yellow('⚠️ 配置文件损坏,已备份到:'), backupPath);
124
+
125
+ this.config = this.getDefaultConfig();
126
+ await this._performSave(this.config, { skipConflictCheck: true });
127
+ this.isLoaded = true;
128
+ return this.config;
129
+ }
54
130
 
55
131
  if (!data || typeof data !== 'object' || Array.isArray(data)) {
56
132
  // 配置文件被写成非对象内容时,重置为默认配置
57
133
  this.config = this.getDefaultConfig();
58
- await this._performSave();
134
+ await this._performSave(this.config, { skipConflictCheck: true });
59
135
  } else {
60
- this.config = { ...this.getDefaultConfig(), ...data };
136
+ this.config = validateAndNormalizeConfigData({ ...this.getDefaultConfig(), ...data });
61
137
  }
62
138
 
63
139
  // 迁移旧的认证模式
64
140
  this._migrateAuthModes();
141
+ // 修复 current 标记与 currentProvider 不一致的问题(兼容旧版本写入的脏数据)
142
+ this._syncCurrentFlags();
65
143
 
66
144
  const stat = await fs.stat(this.configPath);
67
145
  this.lastModified = stat.mtime;
68
146
  } else {
69
147
  this.config = this.getDefaultConfig();
70
- await this._performSave();
148
+ await this._performSave(this.config, { skipConflictCheck: true });
71
149
  }
72
150
  this.isLoaded = true;
73
151
  return this.config;
@@ -75,7 +153,7 @@ class ConfigManager {
75
153
  if (error.message.includes('Unexpected end of JSON input')) {
76
154
  // 处理空文件或损坏的JSON文件
77
155
  this.config = this.getDefaultConfig();
78
- await this._performSave();
156
+ await this._performSave(this.config, { skipConflictCheck: true });
79
157
  this.isLoaded = true;
80
158
  return this.config;
81
159
  }
@@ -84,26 +162,64 @@ class ConfigManager {
84
162
  }
85
163
  }
86
164
 
165
+ async _checkAndFixPermissions() {
166
+ // Windows 不支持 Unix 文件权限
167
+ if (process.platform === 'win32') {
168
+ return;
169
+ }
170
+
171
+ try {
172
+ const stat = await fs.stat(this.configPath);
173
+ const mode = stat.mode & 0o777;
174
+
175
+ // 检查权限是否为 600 (仅所有者可读写) 或 400 (仅所有者可读)
176
+ if (mode !== 0o600 && mode !== 0o400) {
177
+ console.log(
178
+ chalk.yellow('⚠️ 配置文件权限不安全:'),
179
+ mode.toString(8),
180
+ chalk.gray('建议: 0600')
181
+ );
182
+
183
+ try {
184
+ await fs.chmod(this.configPath, 0o600);
185
+ console.log(chalk.green('✅ 已自动修复文件权限为: 0600'));
186
+ } catch {
187
+ console.log(chalk.red('❌ 无法自动修复权限,请手动执行:'));
188
+ console.log(chalk.gray(` chmod 600 ${this.configPath}`));
189
+ }
190
+ }
191
+ } catch {
192
+ // 忽略权限检查错误,不影响主流程
193
+ }
194
+ }
195
+
87
196
  _migrateAuthModes() {
88
- // 迁移旧的 api_token 模式到新的 auth_token 模式
197
+ // 迁移旧配置以保持向后兼容
89
198
  if (this.config.providers) {
90
199
  Object.keys(this.config.providers).forEach(key => {
91
200
  const provider = this.config.providers[key];
201
+
202
+ // 迁移旧的 api_token 模式到新的 auth_token 模式
92
203
  if (provider.authMode === 'api_token') {
93
204
  provider.authMode = 'auth_token';
94
205
  }
206
+
207
+ // 为旧配置添加 ideName 字段(历史兼容性字段,默认为 'claude')
208
+ if (!provider.ideName) {
209
+ provider.ideName = 'claude';
210
+ }
95
211
  });
96
212
  }
97
213
  }
98
214
 
99
215
  async checkIfModified() {
100
216
  try {
101
- if (!this.lastModified || !await fs.pathExists(this.configPath)) {
217
+ if (!this.lastModified || !(await fs.pathExists(this.configPath))) {
102
218
  return true;
103
219
  }
104
220
  const stat = await fs.stat(this.configPath);
105
- return stat.mtime > this.lastModified;
106
- } catch (error) {
221
+ return stat.mtime.getTime() !== this.lastModified.getTime();
222
+ } catch {
107
223
  return true; // 出错时重新加载
108
224
  }
109
225
  }
@@ -111,15 +227,18 @@ class ConfigManager {
111
227
  async save(config = this.config) {
112
228
  // 确保配置已加载
113
229
  await this.ensureLoaded();
114
- if (config) {
115
- this.config = config;
116
- }
117
- return await this._performSave();
230
+ return await this._performSave(config);
118
231
  }
119
232
 
120
- async _performSave() {
233
+ async _performSave(config = this.config, options = {}) {
121
234
  try {
122
- await fs.writeJSON(this.configPath, this.config, { spaces: 2 });
235
+ const normalizedConfig = validateAndNormalizeConfigData(config);
236
+ if (!options.skipConflictCheck) {
237
+ await this._assertConfigUnchanged();
238
+ }
239
+ await writeJsonAtomic(this.configPath, normalizedConfig, { spaces: 2, mode: 0o600 });
240
+ this.config = normalizedConfig;
241
+
123
242
  // 更新最后修改时间
124
243
  const stat = await fs.stat(this.configPath);
125
244
  this.lastModified = stat.mtime;
@@ -130,6 +249,21 @@ class ConfigManager {
130
249
  }
131
250
  }
132
251
 
252
+ async _assertConfigUnchanged() {
253
+ if (!this.lastModified) {
254
+ return;
255
+ }
256
+
257
+ if (!(await fs.pathExists(this.configPath))) {
258
+ throw new Error('配置文件已被其他进程删除,请重新执行当前操作');
259
+ }
260
+
261
+ const stat = await fs.stat(this.configPath);
262
+ if (stat.mtime.getTime() !== this.lastModified.getTime()) {
263
+ throw new Error('配置文件已被其他进程修改,请重新执行当前操作以避免覆盖最新配置');
264
+ }
265
+ }
266
+
133
267
  // 确保配置已加载的辅助方法
134
268
  async ensureLoaded() {
135
269
  if (!this.isLoaded) {
@@ -137,79 +271,403 @@ class ConfigManager {
137
271
  }
138
272
  }
139
273
 
274
+ _syncCurrentFlags() {
275
+ if (!this.config || !this.config.providers) {
276
+ return;
277
+ }
278
+
279
+ const current = this.config.currentProvider;
280
+ const providers = this.config.providers;
281
+ const keys = Object.keys(providers);
282
+
283
+ // 创建新的 providers 对象,不直接修改原对象
284
+ const updatedProviders = {};
285
+
286
+ if (current && providers[current]) {
287
+ keys.forEach(key => {
288
+ updatedProviders[key] = {
289
+ ...providers[key],
290
+ current: key === current
291
+ };
292
+ });
293
+ } else {
294
+ keys.forEach(key => {
295
+ updatedProviders[key] = {
296
+ ...providers[key],
297
+ current: false
298
+ };
299
+ });
300
+ }
301
+
302
+ // 只在最外层更新 config
303
+ this.config = {
304
+ ...this.config,
305
+ providers: updatedProviders
306
+ };
307
+ }
308
+
140
309
  async addProvider(name, providerConfig) {
141
310
  await this.ensureLoaded();
142
311
 
143
- this.config.providers[name] = {
312
+ const existing = this.config.providers[name];
313
+ const now = new Date().toISOString();
314
+
315
+ const ideName = providerConfig.ideName || existing?.ideName || 'claude';
316
+ const isCodex = ideName === 'codex';
317
+
318
+ const baseUrl = this._normalizeOptionalString(
319
+ providerConfig.baseUrl !== undefined ? providerConfig.baseUrl : existing?.baseUrl
320
+ );
321
+
322
+ const authToken =
323
+ providerConfig.authToken !== undefined ? providerConfig.authToken : existing?.authToken;
324
+
325
+ const launchArgs = Array.isArray(providerConfig.launchArgs)
326
+ ? providerConfig.launchArgs
327
+ : existing?.launchArgs || [];
328
+
329
+ // 处理别名
330
+ const alias =
331
+ providerConfig.alias !== undefined
332
+ ? this._normalizeOptionalString(providerConfig.alias)
333
+ : existing?.alias || null;
334
+
335
+ // 创建新的 provider 对象
336
+ const newProvider = {
144
337
  name,
145
- displayName: providerConfig.displayName || name,
146
- baseUrl: providerConfig.baseUrl,
147
- authToken: providerConfig.authToken,
148
- authMode: providerConfig.authMode || 'api_key',
149
- tokenType: providerConfig.tokenType || 'api_key', // 'api_key' 或 'auth_token' - 仅在 authMode 为 'api_key' 时使用
150
- launchArgs: providerConfig.launchArgs || [],
151
- models: {
152
- primary: providerConfig.primaryModel || null,
153
- smallFast: providerConfig.smallFastModel || null
154
- },
155
- createdAt: new Date().toISOString(),
156
- lastUsed: new Date().toISOString(),
157
- current: false
338
+ displayName: providerConfig.displayName || existing?.displayName || name,
339
+ alias,
340
+ ideName,
341
+ baseUrl,
342
+ authToken,
343
+ launchArgs,
344
+ lastUsedArgs: existing?.lastUsedArgs || null,
345
+ createdAt: existing?.createdAt || now,
346
+ lastUsed: existing?.lastUsed || now,
347
+ usageCount: existing?.usageCount || 0,
348
+ current: Boolean(existing?.current || this.config.currentProvider === name)
158
349
  };
159
350
 
351
+ // Claude Code 特定字段
352
+ if (!isCodex) {
353
+ const authMode = providerConfig.authMode || existing?.authMode || 'api_key';
354
+ const primaryModel =
355
+ providerConfig.primaryModel !== undefined
356
+ ? providerConfig.primaryModel
357
+ : (existing?.models?.primary ?? null);
358
+ const smallFastModel =
359
+ providerConfig.smallFastModel !== undefined
360
+ ? providerConfig.smallFastModel
361
+ : (existing?.models?.smallFast ?? null);
362
+
363
+ newProvider.authMode = authMode;
364
+ newProvider.models = {
365
+ primary: primaryModel,
366
+ smallFast: smallFastModel
367
+ };
368
+ } else {
369
+ // Codex 不需要这些字段,设置为 null 以保持向后兼容
370
+ newProvider.authMode = null;
371
+ newProvider.models = null;
372
+ }
373
+
160
374
  // 如果是第一个供应商或设置为默认,则设为当前供应商
161
- if (Object.keys(this.config.providers).length === 1 || providerConfig.setAsDefault) {
162
- // 重置所有供应商的current状态
163
- Object.keys(this.config.providers).forEach(key => {
164
- this.config.providers[key].current = false;
165
- });
166
-
167
- // 设置新的当前供应商
168
- this.config.providers[name].current = true;
169
- this.config.providers[name].lastUsed = new Date().toISOString();
170
- this.config.currentProvider = name;
375
+ const shouldSetCurrent =
376
+ (!existing && Object.keys(this.config.providers).length === 0) || providerConfig.setAsDefault;
377
+
378
+ let newCurrentProvider = this.config.currentProvider;
379
+ if (shouldSetCurrent) {
380
+ newCurrentProvider = name;
381
+ newProvider.lastUsed = now;
171
382
  }
172
383
 
384
+ // 使用不可变方式更新 config
385
+ this.config = {
386
+ ...this.config,
387
+ currentProvider: newCurrentProvider,
388
+ providers: {
389
+ ...this.config.providers,
390
+ [name]: newProvider
391
+ }
392
+ };
393
+
394
+ // 保证 current 标记与 currentProvider 一致,避免出现多个 current 或丢失 current 的情况
395
+ this._syncCurrentFlags();
396
+
173
397
  return await this.save();
174
398
  }
175
399
 
176
400
  async removeProvider(name) {
177
401
  await this.ensureLoaded();
178
-
402
+
179
403
  if (!this.config.providers[name]) {
180
- throw new Error(`供应商 '${name}' 不存在`);
404
+ throw new Error(`供应商 '${name}' 不存在\n使用 'akm list' 查看所有已配置的供应商`);
181
405
  }
182
406
 
183
- delete this.config.providers[name];
407
+ // 创建新的 providers 对象,排除要删除的供应商
408
+ const remainingProviders = { ...this.config.providers };
409
+ delete remainingProviders[name];
184
410
 
185
411
  // 如果删除的是当前供应商,清空当前供应商
186
- if (this.config.currentProvider === name) {
187
- this.config.currentProvider = null;
412
+ const newCurrentProvider =
413
+ this.config.currentProvider === name ? null : this.config.currentProvider;
414
+
415
+ // 使用不可变方式更新 config
416
+ this.config = {
417
+ ...this.config,
418
+ currentProvider: newCurrentProvider,
419
+ providers: remainingProviders
420
+ };
421
+
422
+ return await this.save();
423
+ }
424
+
425
+ async activateProvider(name, lastUsedArgs = []) {
426
+ await this.ensureLoaded();
427
+
428
+ if (!this.config.providers[name]) {
429
+ throw new Error(`供应商 '${name}' 不存在\n使用 'akm list' 查看所有已配置的供应商`);
188
430
  }
189
431
 
432
+ const now = new Date().toISOString();
433
+ const updatedProviders = {};
434
+ Object.keys(this.config.providers).forEach(key => {
435
+ const p = this.config.providers[key];
436
+ if (key === name) {
437
+ updatedProviders[key] = {
438
+ ...p,
439
+ current: true,
440
+ lastUsed: now,
441
+ lastUsedArgs,
442
+ usageCount: (p.usageCount || 0) + 1
443
+ };
444
+ } else {
445
+ updatedProviders[key] = { ...p, current: false };
446
+ }
447
+ });
448
+
449
+ this.config = { ...this.config, currentProvider: name, providers: updatedProviders };
190
450
  return await this.save();
191
451
  }
192
452
 
193
453
  async setCurrentProvider(name) {
194
454
  await this.ensureLoaded();
195
-
455
+
196
456
  if (!this.config.providers[name]) {
197
- throw new Error(`供应商 '${name}' 不存在`);
457
+ throw new Error(`供应商 '${name}' 不存在\n使用 'akm list' 查看所有已配置的供应商`);
198
458
  }
199
459
 
200
- // 重置所有供应商的current状态
460
+ const now = new Date().toISOString();
461
+
462
+ // 创建新的 providers 对象,重置所有 current 状态
463
+ const updatedProviders = {};
201
464
  Object.keys(this.config.providers).forEach(key => {
202
- this.config.providers[key].current = false;
465
+ updatedProviders[key] = {
466
+ ...this.config.providers[key],
467
+ current: key === name,
468
+ lastUsed: key === name ? now : this.config.providers[key].lastUsed
469
+ };
203
470
  });
204
471
 
205
- // 设置新的当前供应商
206
- this.config.providers[name].current = true;
207
- this.config.providers[name].lastUsed = new Date().toISOString();
208
- this.config.currentProvider = name;
472
+ // 使用不可变方式更新 config
473
+ this.config = {
474
+ ...this.config,
475
+ currentProvider: name,
476
+ providers: updatedProviders
477
+ };
478
+
479
+ return await this.save();
480
+ }
481
+
482
+ /**
483
+ * 更新供应商的上次使用启动参数
484
+ * @param {string} name - 供应商名称
485
+ * @param {string[]} args - 启动参数数组
486
+ * @returns {Promise<void>}
487
+ */
488
+ async updateLastUsedArgs(name, args) {
489
+ await this.ensureLoaded();
490
+
491
+ if (!this.config.providers[name]) {
492
+ throw new Error(`供应商 '${name}' 不存在`);
493
+ }
494
+
495
+ const now = new Date().toISOString();
496
+ const provider = this.config.providers[name];
497
+
498
+ // 创建更新后的 provider 对象
499
+ const updatedProvider = {
500
+ ...provider,
501
+ lastUsedArgs: args,
502
+ lastUsed: now,
503
+ usageCount: (provider.usageCount || 0) + 1
504
+ };
505
+
506
+ // 使用不可变方式更新 config
507
+ this.config = {
508
+ ...this.config,
509
+ providers: {
510
+ ...this.config.providers,
511
+ [name]: updatedProvider
512
+ }
513
+ };
514
+
515
+ return await this.save();
516
+ }
517
+
518
+ /**
519
+ * 记录供应商使用会话
520
+ * @param {string} name - 供应商名称
521
+ * @param {number} durationMs - 使用时长(毫秒)
522
+ */
523
+ async recordUsageSession(name, durationMs = 0) {
524
+ await this.ensureLoaded();
525
+
526
+ if (!this.config.providers[name]) {
527
+ throw new Error(`供应商 '${name}' 不存在`);
528
+ }
529
+
530
+ const provider = this.config.providers[name];
531
+ const now = new Date().toISOString();
532
+
533
+ // 初始化或更新统计数据
534
+ const existingStats = provider.stats || {
535
+ totalSessions: 0,
536
+ totalDurationMs: 0,
537
+ averageDurationMs: 0,
538
+ lastSessionDuration: 0,
539
+ firstUsed: now
540
+ };
541
+
542
+ const newTotalSessions = (existingStats.totalSessions || 0) + 1;
543
+ const newTotalDurationMs = (existingStats.totalDurationMs || 0) + durationMs;
544
+
545
+ const updatedStats = {
546
+ ...existingStats,
547
+ totalSessions: newTotalSessions,
548
+ totalDurationMs: newTotalDurationMs,
549
+ lastSessionDuration: durationMs,
550
+ averageDurationMs: Math.round(newTotalDurationMs / newTotalSessions)
551
+ };
552
+
553
+ // 创建更新后的 provider 对象
554
+ const updatedProvider = {
555
+ ...provider,
556
+ stats: updatedStats,
557
+ lastUsed: now
558
+ };
559
+
560
+ // 使用不可变方式更新 config
561
+ this.config = {
562
+ ...this.config,
563
+ providers: {
564
+ ...this.config.providers,
565
+ [name]: updatedProvider
566
+ }
567
+ };
209
568
 
210
569
  return await this.save();
211
570
  }
212
571
 
572
+ /**
573
+ * 获取使用统计信息
574
+ * @param {string|null} name - 供应商名称,null 表示获取所有
575
+ * @returns {Object} 统计信息
576
+ */
577
+ getUsageStats(name = null) {
578
+ if (!this.isLoaded) {
579
+ throw new Error('配置未加载,请先调用 load() 方法');
580
+ }
581
+
582
+ if (name) {
583
+ const provider = this.getProvider(name);
584
+ if (!provider) {
585
+ return null;
586
+ }
587
+ return {
588
+ name: provider.name,
589
+ displayName: provider.displayName,
590
+ usageCount: provider.usageCount || 0,
591
+ lastUsed: provider.lastUsed || null,
592
+ stats: provider.stats || null
593
+ };
594
+ }
595
+
596
+ // 返回所有供应商的统计
597
+ const allStats = Object.entries(this.config.providers).map(([name, provider]) => ({
598
+ name,
599
+ displayName: provider.displayName,
600
+ usageCount: provider.usageCount || 0,
601
+ lastUsed: provider.lastUsed || null,
602
+ stats: provider.stats || null
603
+ }));
604
+
605
+ // 按使用次数降序排序
606
+ return allStats.sort((a, b) => (b.usageCount || 0) - (a.usageCount || 0));
607
+ }
608
+
609
+ /**
610
+ * 获取智能推荐的供应商列表
611
+ * @param {Object} options - 选项
612
+ * @param {number} options.limit - 返回数量限制
613
+ * @param {string|null} options.filter - 过滤器 ('codex', 'claude', 或 null)
614
+ * @returns {Array} 推荐的供应商列表
615
+ */
616
+ getRecommendedProviders(options = {}) {
617
+ if (!this.isLoaded) {
618
+ throw new Error('配置未加载,请先调用 load() 方法');
619
+ }
620
+
621
+ const { limit = 5, filter = null } = options;
622
+ let providers = this.listProviders();
623
+
624
+ // 应用过滤器
625
+ if (filter === 'codex') {
626
+ providers = providers.filter(p => p.ideName === 'codex');
627
+ } else if (filter === 'claude') {
628
+ providers = providers.filter(p => p.ideName !== 'codex');
629
+ }
630
+
631
+ // 计算推荐分数
632
+ const scoredProviders = providers.map(provider => {
633
+ let score = 0;
634
+
635
+ // 使用次数权重 (40%)
636
+ const usageCount = provider.usageCount || 0;
637
+ score += usageCount * 0.4;
638
+
639
+ // 最近使用时间权重 (30%)
640
+ if (provider.lastUsed) {
641
+ const daysSinceLastUse =
642
+ (Date.now() - new Date(provider.lastUsed).getTime()) / (1000 * 60 * 60 * 24);
643
+ // 越近使用分数越高,超过30天分数衰减
644
+ const recencyScore = Math.max(0, 30 - daysSinceLastUse) / 30;
645
+ score += recencyScore * 30;
646
+ }
647
+
648
+ // 会话平均时长权重 (20%)
649
+ if (provider.stats?.averageDurationMs) {
650
+ // 平均使用时长越长,说明使用越频繁,最高20分
651
+ const avgMinutes = provider.stats.averageDurationMs / (1000 * 60);
652
+ const durationScore = Math.min(avgMinutes / 60, 1) * 20; // 最多1小时算满分
653
+ score += durationScore;
654
+ }
655
+
656
+ // 总会话数权重 (10%)
657
+ if (provider.stats?.totalSessions) {
658
+ score += Math.min(provider.stats.totalSessions / 10, 1) * 10;
659
+ }
660
+
661
+ return {
662
+ ...provider,
663
+ recommendScore: Math.round(score * 100) / 100
664
+ };
665
+ });
666
+
667
+ // 按推荐分数降序排序并限制数量
668
+ return scoredProviders.sort((a, b) => b.recommendScore - a.recommendScore).slice(0, limit);
669
+ }
670
+
213
671
  getProvider(name) {
214
672
  // 同步方法,但需要先确保配置已加载
215
673
  if (!this.isLoaded) {
@@ -218,6 +676,31 @@ class ConfigManager {
218
676
  return this.config.providers[name];
219
677
  }
220
678
 
679
+ /**
680
+ * 通过名称或别名获取供应商
681
+ * @param {string} nameOrAlias - 供应商名称或别名
682
+ * @returns {ProviderConfig|null} 供应商配置对象,未找到返回 null
683
+ */
684
+ getProviderByNameOrAlias(nameOrAlias) {
685
+ // 同步方法,但需要先确保配置已加载
686
+ if (!this.isLoaded) {
687
+ throw new Error('配置未加载,请先调用 load() 方法');
688
+ }
689
+
690
+ // 先尝试按名称查找
691
+ if (this.config.providers[nameOrAlias]) {
692
+ return this.config.providers[nameOrAlias];
693
+ }
694
+
695
+ // 再尝试按别名查找
696
+ const providerEntry = Object.entries(this.config.providers).find(
697
+ ([_, provider]) =>
698
+ provider.alias && provider.alias.toLowerCase() === nameOrAlias.toLowerCase()
699
+ );
700
+
701
+ return providerEntry ? providerEntry[1] : null;
702
+ }
703
+
221
704
  listProviders() {
222
705
  // 同步方法,但需要先确保配置已加载
223
706
  if (!this.isLoaded) {
@@ -247,4 +730,7 @@ class ConfigManager {
247
730
  }
248
731
  }
249
732
 
250
- module.exports = { ConfigManager };
733
+ // 单例实例
734
+ const configManager = new ConfigManager();
735
+
736
+ module.exports = { ConfigManager, configManager };