@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/bin/akm.js CHANGED
@@ -7,11 +7,92 @@ const { registry } = require('../src/CommandRegistry');
7
7
  const pkg = require('../package.json');
8
8
  const { checkForUpdates } = require('../src/utils/update-checker');
9
9
 
10
+ // 命令分组定义
11
+ const COMMAND_GROUPS = {
12
+ 核心命令: ['add', 'switch', 'remove', 'list', 'current', 'edit'],
13
+ 运维命令: ['export', 'import', 'backup', 'validate', 'clone'],
14
+ 工具命令: ['stats', 'health', 'batch', 'benchmark', 'claude', 'mcp']
15
+ };
16
+
10
17
  // Set up CLI
11
18
  program
12
19
  .name('akm')
13
20
  .description('API密钥管理工具 - Manage and switch multiple API provider configurations')
14
- .version(pkg.version, '-v, -V, --version', '显示版本号');
21
+ .version(pkg.version, '-V, --version', '显示版本号');
22
+
23
+ // 自定义 help 输出,按分组显示命令
24
+ program.configureHelp({
25
+ formatHelp(cmd, helper) {
26
+ const termWidth = helper.padWidth(cmd, helper);
27
+ const helpWidth = helper.helpWidth || 80;
28
+
29
+ let output = '';
30
+
31
+ // 标题
32
+ output += `${chalk.bold('用法:')} ${helper.commandUsage(cmd)}\n\n`;
33
+
34
+ // 描述
35
+ const desc = helper.commandDescription(cmd);
36
+ if (desc) {
37
+ output += `${desc}\n\n`;
38
+ }
39
+
40
+ // 参数
41
+ const argList = helper.visibleArguments(cmd).map(arg => {
42
+ return helper.formatHelp
43
+ ? ` ${helper.argumentTerm(arg).padEnd(termWidth)} ${helper.argumentDescription(arg)}`
44
+ : '';
45
+ });
46
+ if (argList.length > 0) {
47
+ output += `${chalk.bold('参数:')}\n${argList.join('\n')}\n\n`;
48
+ }
49
+
50
+ // 选项
51
+ const optList = helper.visibleOptions(cmd).map(opt => {
52
+ return ` ${helper.optionTerm(opt).padEnd(termWidth)} ${helper.optionDescription(opt)}`;
53
+ });
54
+ if (optList.length > 0) {
55
+ output += `${chalk.bold('选项:')}\n${optList.join('\n')}\n\n`;
56
+ }
57
+
58
+ // 分组命令
59
+ const commands = helper.visibleCommands(cmd);
60
+ if (commands.length > 0) {
61
+ const commandMap = {};
62
+ commands.forEach(sub => {
63
+ commandMap[sub.name()] = sub;
64
+ });
65
+
66
+ Object.entries(COMMAND_GROUPS).forEach(([groupName, cmdNames]) => {
67
+ const groupCmds = cmdNames
68
+ .filter(name => commandMap[name])
69
+ .map(name => {
70
+ const sub = commandMap[name];
71
+ return ` ${chalk.cyan(helper.subcommandTerm(sub).padEnd(termWidth))} ${helper.subcommandDescription(sub)}`;
72
+ });
73
+
74
+ if (groupCmds.length > 0) {
75
+ output += `${chalk.bold.yellow(groupName + ':')}\n${groupCmds.join('\n')}\n\n`;
76
+ }
77
+ });
78
+
79
+ // 未分组的命令
80
+ const groupedNames = Object.values(COMMAND_GROUPS).flat();
81
+ const ungrouped = commands
82
+ .filter(sub => !groupedNames.includes(sub.name()))
83
+ .map(
84
+ sub =>
85
+ ` ${chalk.cyan(helper.subcommandTerm(sub).padEnd(termWidth))} ${helper.subcommandDescription(sub)}`
86
+ );
87
+
88
+ if (ungrouped.length > 0) {
89
+ output += `${chalk.bold.yellow('其他命令:')}\n${ungrouped.join('\n')}\n\n`;
90
+ }
91
+ }
92
+
93
+ return output;
94
+ }
95
+ });
15
96
 
16
97
  // Check for updates before any command runs
17
98
  program.hook('preAction', async () => {
@@ -21,9 +102,11 @@ program.hook('preAction', async () => {
21
102
  // Default command - show provider selection
22
103
  program
23
104
  .argument('[provider]', '直接切换到指定供应商')
24
- .action(async (provider) => {
105
+ .option('-q, --quick', '快速启动(使用默认或上次的启动参数)')
106
+ .option('--no-args', '以空参数启动(不使用任何启动参数)')
107
+ .action(async (provider, options) => {
25
108
  try {
26
- await main(provider);
109
+ await main(provider, options);
27
110
  } catch (error) {
28
111
  console.error(chalk.red('❌ 执行失败:'), error.message);
29
112
  process.exit(1);
@@ -34,21 +117,47 @@ program
34
117
  program
35
118
  .command('add')
36
119
  .description('添加新的API密钥配置')
37
- .action(async () => {
120
+ .option('--codex', '直接添加 Codex CLI 供应商')
121
+ .option('--claude', '直接添加 Claude Code 供应商')
122
+ .action(async options => {
38
123
  try {
39
- await registry.executeCommand('add');
124
+ const ideName = options.codex ? 'codex' : options.claude ? 'claude' : null;
125
+ await registry.executeCommand('add', { ideName });
40
126
  } catch (error) {
41
127
  console.error(chalk.red('❌ 添加失败:'), error.message);
42
128
  process.exit(1);
43
129
  }
44
130
  });
45
131
 
132
+ // Switch command
133
+ program
134
+ .command('switch')
135
+ .description('切换到指定供应商')
136
+ .argument('[provider]', '直接切换到指定供应商')
137
+ .option('--codex', '仅显示 Codex CLI 供应商')
138
+ .option('--claude', '仅显示 Claude Code 供应商')
139
+ .option('-q, --quick', '快速启动(使用默认或上次的启动参数)')
140
+ .option('--no-args', '以空参数启动(不使用任何启动参数)')
141
+ .action(async (provider, options) => {
142
+ try {
143
+ const filter = options.codex ? 'codex' : options.claude ? 'claude' : null;
144
+ await registry.executeCommand('switch', provider, {
145
+ filter,
146
+ quick: options.quick,
147
+ noArgs: options.noArgs
148
+ });
149
+ } catch (error) {
150
+ console.error(chalk.red('❌ 切换失败:'), error.message);
151
+ process.exit(1);
152
+ }
153
+ });
154
+
46
155
  // Remove command
47
156
  program
48
157
  .command('remove')
49
158
  .argument('[provider]', '要删除的供应商名称')
50
159
  .description('删除API密钥配置')
51
- .action(async (provider) => {
160
+ .action(async provider => {
52
161
  try {
53
162
  await registry.executeCommand('remove', provider);
54
163
  } catch (error) {
@@ -61,9 +170,18 @@ program
61
170
  program
62
171
  .command('list')
63
172
  .description('列出所有API密钥配置')
64
- .action(async () => {
173
+ .option('--codex', '仅显示 Codex CLI 供应商')
174
+ .option('--claude', '仅显示 Claude Code 供应商')
175
+ .option('--status', '检测供应商在线状态')
176
+ .option('--json', '以 JSON 输出配置')
177
+ .option('--show-token', '兼容参数:Token 默认完整显示')
178
+ .action(async options => {
65
179
  try {
66
- await registry.executeCommand('list');
180
+ const filter = options.codex ? 'codex' : options.claude ? 'claude' : null;
181
+ await registry.executeCommand('list', filter, {
182
+ checkStatus: options.status,
183
+ json: options.json
184
+ });
67
185
  } catch (error) {
68
186
  console.error(chalk.red('❌ 列表失败:'), error.message);
69
187
  process.exit(1);
@@ -74,9 +192,12 @@ program
74
192
  program
75
193
  .command('current')
76
194
  .description('显示当前活跃的配置')
77
- .action(async () => {
195
+ .option('--show-token', '兼容参数:Token 默认完整显示')
196
+ .option('--shell <shell>', '环境变量命令格式: bash/zsh/powershell/cmd')
197
+ .option('--json', '以 JSON 输出当前配置')
198
+ .action(async options => {
78
199
  try {
79
- await registry.executeCommand('current');
200
+ await registry.executeCommand('current', options);
80
201
  } catch (error) {
81
202
  console.error(chalk.red('❌ 获取当前配置失败:'), error.message);
82
203
  process.exit(1);
@@ -88,7 +209,7 @@ program
88
209
  .command('edit')
89
210
  .argument('[provider]', '要编辑的供应商名称')
90
211
  .description('编辑API密钥配置')
91
- .action(async (provider) => {
212
+ .action(async provider => {
92
213
  try {
93
214
  await registry.executeCommand('edit', provider);
94
215
  } catch (error) {
@@ -97,5 +218,213 @@ program
97
218
  }
98
219
  });
99
220
 
221
+ // Export command
222
+ program
223
+ .command('export')
224
+ .argument('[file]', '导出文件路径 (默认: akm-config-{timestamp}.json)')
225
+ .description('导出配置到文件')
226
+ .option('--include-secrets', '导出完整 Token(敏感文件,请妥善保管)')
227
+ .option('--mask', '兼容旧版本:不导出 Token(当前已是默认行为)')
228
+ .option('--dry-run', '只预览导出结果,不写入文件')
229
+ .action(async (file, options) => {
230
+ try {
231
+ await registry.executeCommand('export', file, options);
232
+ } catch (error) {
233
+ console.error(chalk.red('❌ 导出失败:'), error.message);
234
+ process.exit(1);
235
+ }
236
+ });
237
+
238
+ // Import command
239
+ program
240
+ .command('import')
241
+ .argument('<file>', '要导入的配置文件路径')
242
+ .description('从文件导入配置')
243
+ .option('--overwrite', '覆盖已存在的供应商')
244
+ .option('--dry-run', '只校验并预览导入结果,不修改配置')
245
+ .action(async (file, options) => {
246
+ try {
247
+ await registry.executeCommand('import', file, options);
248
+ } catch (error) {
249
+ console.error(chalk.red('❌ 导入失败:'), error.message);
250
+ process.exit(1);
251
+ }
252
+ });
253
+
254
+ // Backup command
255
+ program
256
+ .command('backup')
257
+ .description('备份和恢复配置')
258
+ .option('-l, --list', '列出所有备份')
259
+ .option('-r, --restore <file>', '从备份恢复')
260
+ .option('-d, --dir <path>', '指定备份目录')
261
+ .action(async options => {
262
+ try {
263
+ await registry.executeCommand('backup', options);
264
+ } catch (error) {
265
+ console.error(chalk.red('❌ 备份操作失败:'), error.message);
266
+ process.exit(1);
267
+ }
268
+ });
269
+
270
+ // Validate command
271
+ program
272
+ .command('validate')
273
+ .description('验证供应商配置的有效性')
274
+ .argument('[provider]', '要验证的供应商名称(不指定则验证全部)')
275
+ .option('--codex', '仅验证 Codex CLI 供应商')
276
+ .option('--claude', '仅验证 Claude Code 供应商')
277
+ .action(async (provider, options) => {
278
+ try {
279
+ const filter = options.codex ? 'codex' : options.claude ? 'claude' : null;
280
+ await registry.executeCommand('validate', provider, { filter });
281
+ } catch (error) {
282
+ console.error(chalk.red('❌ 验证失败:'), error.message);
283
+ process.exit(1);
284
+ }
285
+ });
286
+
287
+ // Clone command
288
+ program
289
+ .command('clone')
290
+ .argument('[source]', '要克隆的源供应商名称')
291
+ .description('克隆现有供应商配置')
292
+ .action(async source => {
293
+ try {
294
+ await registry.executeCommand('clone', source);
295
+ } catch (error) {
296
+ console.error(chalk.red('❌ 克隆失败:'), error.message);
297
+ process.exit(1);
298
+ }
299
+ });
300
+
301
+ // Stats command
302
+ program
303
+ .command('stats')
304
+ .description('显示供应商使用统计')
305
+ .argument('[provider]', '要查看统计的供应商名称(不指定则显示全部)')
306
+ .option('--codex', '仅显示 Codex CLI 供应商')
307
+ .option('--claude', '仅显示 Claude Code 供应商')
308
+ .option('-r, --recommend', '显示智能推荐')
309
+ .option('-s, --sort <type>', '排序方式: usage(使用次数), time(最近使用), name(名称)', 'usage')
310
+ .option('-l, --limit <number>', '推荐列表数量限制', '5')
311
+ .action(async (provider, options) => {
312
+ try {
313
+ const filter = options.codex ? 'codex' : options.claude ? 'claude' : null;
314
+ const limit = parseInt(options.limit, 10);
315
+ await registry.executeCommand('stats', provider, {
316
+ filter,
317
+ recommend: options.recommend,
318
+ sort: options.sort,
319
+ limit
320
+ });
321
+ } catch (error) {
322
+ console.error(chalk.red('❌ 统计失败:'), error.message);
323
+ process.exit(1);
324
+ }
325
+ });
326
+
327
+ // Health command
328
+ program
329
+ .command('health')
330
+ .description('检查供应商配置健康状态')
331
+ .argument('[provider]', '要检查的供应商名称(不指定则检查全部)')
332
+ .option('--codex', '仅检查 Codex CLI 供应商')
333
+ .option('--claude', '仅检查 Claude Code 供应商')
334
+ .option('--connectivity', '执行在线 API 检查(可能产生费用)')
335
+ .option('--no-connectivity', '兼容参数:跳过在线 API 检查')
336
+ .option('--json', '以 JSON 输出健康检查结果')
337
+ .action(async (provider, options) => {
338
+ try {
339
+ const filter = options.codex ? 'codex' : options.claude ? 'claude' : null;
340
+ await registry.executeCommand('health', provider, {
341
+ filter,
342
+ connectivity: options.connectivity === true,
343
+ json: options.json
344
+ });
345
+ } catch (error) {
346
+ console.error(chalk.red('❌ 健康检查失败:'), error.message);
347
+ process.exit(1);
348
+ }
349
+ });
350
+
351
+ // Batch command
352
+ program
353
+ .command('batch <operation>')
354
+ .description('批量操作供应商 (operations: update, delete)')
355
+ .option('--codex', '仅操作 Codex CLI 供应商')
356
+ .option('--claude', '仅操作 Claude Code 供应商')
357
+ .option('--unused', '仅操作长期未使用的供应商 (90天以上)')
358
+ .action(async (operation, options) => {
359
+ try {
360
+ const filter = options.codex ? 'codex' : options.claude ? 'claude' : null;
361
+ await registry.executeCommand('batch', operation, {
362
+ filter,
363
+ unused: options.unused
364
+ });
365
+ } catch (error) {
366
+ console.error(chalk.red('❌ 批量操作失败:'), error.message);
367
+ process.exit(1);
368
+ }
369
+ });
370
+
371
+ // Benchmark command
372
+ program
373
+ .command('benchmark')
374
+ .description('供应商性能测试和对比')
375
+ .option('--codex', '仅测试 Codex CLI 供应商')
376
+ .option('--claude', '仅测试 Claude Code 供应商')
377
+ .option('-r, --rounds <number>', '每个供应商测试轮数', '3')
378
+ .option('-p, --parallel', '并行测试(更快但可能不准确)')
379
+ .option('--report [file]', '生成 Markdown 测试报告')
380
+ .action(async options => {
381
+ try {
382
+ const filter = options.codex ? 'codex' : options.claude ? 'claude' : null;
383
+ const rounds = parseInt(options.rounds, 10);
384
+ await registry.executeCommand('benchmark', {
385
+ filter,
386
+ rounds,
387
+ parallel: options.parallel,
388
+ report: options.report
389
+ });
390
+ } catch (error) {
391
+ console.error(chalk.red('❌ 性能测试失败:'), error.message);
392
+ process.exit(1);
393
+ }
394
+ });
395
+
396
+ // Claude command
397
+ program
398
+ .command('claude')
399
+ .argument('<subcommand>', '子命令: clean (清理) | analyze (分析)')
400
+ .description('Claude Code 配置管理 (clean/analyze)')
401
+ .action(async subcommand => {
402
+ try {
403
+ if (subcommand !== 'clean' && subcommand !== 'analyze') {
404
+ console.error(chalk.red(`❌ 未知子命令: ${subcommand}`));
405
+ console.error(chalk.gray(' 可用子命令: clean, analyze'));
406
+ process.exit(1);
407
+ }
408
+ await registry.executeCommand('claude-clean', subcommand);
409
+ } catch (error) {
410
+ console.error(chalk.red('❌ 操作失败:'), error.message);
411
+ process.exit(1);
412
+ }
413
+ });
414
+
415
+ // MCP command
416
+ program
417
+ .command('mcp')
418
+ .argument('<subcommand>', '子命令: list | add | edit | remove')
419
+ .description('MCP 服务器管理 (list/add/edit/remove)')
420
+ .action(async subcommand => {
421
+ try {
422
+ await registry.executeCommand('mcp', subcommand);
423
+ } catch (error) {
424
+ console.error(chalk.red('❌ MCP 操作失败:'), error.message);
425
+ process.exit(1);
426
+ }
427
+ });
428
+
100
429
  // Parse arguments
101
430
  program.parse();
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@pikecode/api-key-manager",
3
- "version": "2.0.0",
4
- "description": "API密钥管理工具 - A powerful CLI tool for managing and switching multiple API provider configurations (supports ANTHROPIC_API_KEY, ANTHROPIC_AUTH_TOKEN, and more)",
3
+ "version": "2.0.1",
4
+ "description": "A CLI tool for managing and switching multiple API provider configurations",
5
5
  "main": "src/index.js",
6
6
  "bin": {
7
7
  "akm": "bin/akm.js"
@@ -16,10 +16,19 @@
16
16
  "start": "node bin/akm.js",
17
17
  "dev": "nodemon bin/akm.js",
18
18
  "test": "jest",
19
+ "test:coverage": "jest --coverage",
20
+ "lint": "eslint src tests",
21
+ "lint:fix": "eslint src tests --fix",
22
+ "format": "prettier --write \"src/**/*.js\" \"tests/**/*.js\"",
23
+ "format:check": "prettier --check \"src/**/*.js\" \"tests/**/*.js\"",
19
24
  "build": "echo 'No build needed'",
20
25
  "prepare": "echo 'Preparing package'",
21
- "prepublishOnly": "npm test",
22
- "release": "npm version patch && npm publish --access public"
26
+ "verify": "npm run lint -- --max-warnings=0 && npm run test:coverage -- --runInBand",
27
+ "prepublishOnly": "npm run verify",
28
+ "release": "npm publish --access public",
29
+ "release:patch": "npm version patch && npm publish --access public",
30
+ "release:minor": "npm version minor && npm publish --access public",
31
+ "release:major": "npm version major && npm publish --access public"
23
32
  },
24
33
  "keywords": [
25
34
  "api",
@@ -29,6 +38,11 @@
29
38
  "anthropic",
30
39
  "anthropic-api-key",
31
40
  "anthropic-auth-token",
41
+ "openai",
42
+ "openai-api-key",
43
+ "codex",
44
+ "codex-cli",
45
+ "claude-code",
32
46
  "environment",
33
47
  "config",
34
48
  "provider",
@@ -37,7 +51,7 @@
37
51
  "command-line",
38
52
  "tool"
39
53
  ],
40
- "author": "Developer",
54
+ "author": "pikecode",
41
55
  "license": "MIT",
42
56
  "repository": {
43
57
  "type": "git",
@@ -48,20 +62,23 @@
48
62
  },
49
63
  "homepage": "https://github.com/pikecode/api-key-manager#readme",
50
64
  "dependencies": {
51
- "@anthropic-ai/sdk": "^0.67.0",
65
+ "@anthropic-ai/sdk": "0.71.2",
66
+ "ajv": "^8.18.0",
52
67
  "chalk": "^4.1.2",
53
- "commander": "^9.4.1",
68
+ "commander": "14.0.2",
54
69
  "cross-spawn": "^7.0.3",
55
70
  "fs-extra": "^11.1.1",
56
- "inquirer": "^8.2.6",
57
- "supports-color": "^9.4.0"
71
+ "inquirer": "^8.2.6"
58
72
  },
59
73
  "devDependencies": {
60
- "jest": "^29.7.0",
61
- "nodemon": "^3.0.1"
74
+ "eslint": "^9.39.2",
75
+ "eslint-config-prettier": "^10.1.8",
76
+ "jest": "30.2.0",
77
+ "nodemon": "^3.0.1",
78
+ "prettier": "^3.8.1"
62
79
  },
63
80
  "engines": {
64
- "node": ">=14.0.0"
81
+ "node": ">=20.0.0"
65
82
  },
66
83
  "os": [
67
84
  "win32",
@@ -22,7 +22,7 @@ class CommandRegistry {
22
22
  return command;
23
23
  }
24
24
 
25
- throw new Error(`命令 '${name}' 未注册`);
25
+ throw new Error(`未知命令 '${name}'\n运行 'akm --help' 查看所有可用命令`);
26
26
  }
27
27
 
28
28
  // 执行命令
@@ -67,8 +67,63 @@ registry.registerLazy('current', async () => {
67
67
  });
68
68
 
69
69
  registry.registerLazy('edit', async () => {
70
- const { editCommand } = require('./commands/edit');
70
+ const { editCommand } = require('./commands/switch');
71
71
  return editCommand;
72
72
  });
73
73
 
74
- module.exports = { CommandRegistry, registry };
74
+ registry.registerLazy('export', async () => {
75
+ const { exportCommand } = require('./commands/backup');
76
+ return exportCommand;
77
+ });
78
+
79
+ registry.registerLazy('import', async () => {
80
+ const { importCommand } = require('./commands/backup');
81
+ return importCommand;
82
+ });
83
+
84
+ registry.registerLazy('backup', async () => {
85
+ const { backupCommand } = require('./commands/backup');
86
+ return backupCommand;
87
+ });
88
+
89
+ registry.registerLazy('validate', async () => {
90
+ const { validateCommand } = require('./commands/validate');
91
+ return validateCommand;
92
+ });
93
+
94
+ registry.registerLazy('stats', async () => {
95
+ const { statsCommand } = require('./commands/stats');
96
+ return statsCommand;
97
+ });
98
+
99
+ registry.registerLazy('health', async () => {
100
+ const { healthCommand } = require('./commands/health');
101
+ return healthCommand;
102
+ });
103
+
104
+ registry.registerLazy('batch', async () => {
105
+ const { batchCommand } = require('./commands/batch');
106
+ return batchCommand;
107
+ });
108
+
109
+ registry.registerLazy('benchmark', async () => {
110
+ const { benchmarkCommand } = require('./commands/benchmark');
111
+ return benchmarkCommand;
112
+ });
113
+
114
+ registry.registerLazy('clone', async () => {
115
+ const { cloneCommand } = require('./commands/clone');
116
+ return cloneCommand;
117
+ });
118
+
119
+ registry.registerLazy('claude-clean', async () => {
120
+ const { claudeCleanCommand } = require('./commands/claude-clean');
121
+ return claudeCleanCommand;
122
+ });
123
+
124
+ registry.registerLazy('mcp', async () => {
125
+ const { mcpCommand } = require('./commands/mcp');
126
+ return mcpCommand;
127
+ });
128
+
129
+ module.exports = { CommandRegistry, registry };
@@ -15,7 +15,7 @@ const resolveInputPrompt = () => {
15
15
  }
16
16
  try {
17
17
  return require('inquirer/lib/prompts/input');
18
- } catch (error) {
18
+ } catch {
19
19
  return null;
20
20
  }
21
21
  };
@@ -57,17 +57,38 @@ if (InputPrompt && !InputPrompt.prototype.__allowEmptyPatched) {
57
57
 
58
58
  const ESC_CANCELLED_ERROR_CODE = 'ESC_CANCELLED';
59
59
 
60
+ /**
61
+ * 命令基类
62
+ * 提供所有命令的通用功能,包括 ESC 键处理、提示交互等
63
+ */
60
64
  class BaseCommand {
65
+ /**
66
+ * 创建命令实例
67
+ * @param {Object} [options={}] - 配置选项
68
+ * @param {NodeJS.ReadStream} [options.input] - 输入流
69
+ */
61
70
  constructor(options = {}) {
62
71
  const input = options.input || process.stdin;
72
+ /** @type {EscNavigationManager} ESC 键管理器 */
63
73
  this.escManager = new EscNavigationManager(input);
74
+ /** @type {Object|null} 当前活动的提示 */
64
75
  this.activePrompt = null;
65
76
  }
66
77
 
78
+ /**
79
+ * 检查错误是否为 ESC 取消错误
80
+ * @param {Error} error - 错误对象
81
+ * @returns {boolean} 是否为 ESC 取消
82
+ */
67
83
  isEscCancelled(error) {
68
84
  return Boolean(error && error.code === ESC_CANCELLED_ERROR_CODE);
69
85
  }
70
86
 
87
+ /**
88
+ * 显示交互式提示
89
+ * @param {Array|Object} questions - Inquirer 问题配置
90
+ * @returns {Promise<Object>} 用户答案
91
+ */
71
92
  async prompt(questions) {
72
93
  const promptPromise = inquirer.prompt(questions);
73
94
  let settled = false;
@@ -204,6 +225,52 @@ class BaseCommand {
204
225
  }
205
226
  }
206
227
 
228
+ /**
229
+ * 带 ESC 监听的 prompt 执行
230
+ * 自动处理 ESC 监听器的创建、移除和错误处理
231
+ * @param {Array} questions - inquirer 问卷配置
232
+ * @param {string} escMessage - ESC 返回信息
233
+ * @param {Function} escCallback - ESC 按下时的回调函数
234
+ * @returns {Promise<Object>} - prompt 答案
235
+ */
236
+ async promptWithESC(questions, escMessage, escCallback) {
237
+ const escListener = this.createESCListener(escCallback, escMessage);
238
+ try {
239
+ return await this.prompt(questions);
240
+ } catch (error) {
241
+ if (this.isEscCancelled(error)) {
242
+ this.removeESCListener(escListener);
243
+ throw error;
244
+ }
245
+ throw error;
246
+ } finally {
247
+ this.removeESCListener(escListener);
248
+ }
249
+ }
250
+
251
+ /**
252
+ * 带 ESC 监听的 prompt 执行,支持返回默认值
253
+ * @param {Array} questions - inquirer 问卷配置
254
+ * @param {string} escMessage - ESC 返回信息
255
+ * @param {Function} escCallback - ESC 按下时的回调函数
256
+ * @param {*} escReturnValue - ESC 按下时返回的值
257
+ * @returns {Promise<Object|*>} - prompt 答案或 escReturnValue
258
+ */
259
+ async promptWithESCAndDefault(questions, escMessage, escCallback, escReturnValue) {
260
+ const escListener = this.createESCListener(escCallback, escMessage);
261
+ try {
262
+ return await this.prompt(questions);
263
+ } catch (error) {
264
+ if (this.isEscCancelled(error)) {
265
+ this.removeESCListener(escListener);
266
+ return escReturnValue;
267
+ }
268
+ throw error;
269
+ } finally {
270
+ this.removeESCListener(escListener);
271
+ }
272
+ }
273
+
207
274
  destroy() {
208
275
  this.cleanupAllListeners();
209
276
  }