@pikecode/api-key-manager 2.0.0 → 2.0.2

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