@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
@@ -0,0 +1,265 @@
1
+ /**
2
+ * Provider Clone Command
3
+ * 克隆现有供应商配置
4
+ * @module commands/clone
5
+ */
6
+
7
+ const inquirer = require('inquirer');
8
+ const chalk = require('chalk');
9
+ const { configManager } = require('../config');
10
+ const { validator } = require('../utils/validator');
11
+ const { Logger } = require('../utils/logger');
12
+ const { UIHelper } = require('../utils/ui-helper');
13
+ const { BaseCommand } = require('./BaseCommand');
14
+ const { getCodexLaunchArgs, checkExclusiveArgs } = require('../utils/launch-args');
15
+
16
+ /**
17
+ * 供应商克隆器类
18
+ * @extends BaseCommand
19
+ */
20
+ class ProviderCloner extends BaseCommand {
21
+ constructor() {
22
+ super();
23
+ this.configManager = configManager;
24
+ }
25
+
26
+ async interactive(sourceProviderName) {
27
+ await this.configManager.load();
28
+ const providers = this.configManager.listProviders();
29
+
30
+ if (providers.length === 0) {
31
+ Logger.warning('没有可克隆的供应商配置。请先添加一个。');
32
+ return;
33
+ }
34
+
35
+ // 选择源供应商
36
+ let source;
37
+ if (sourceProviderName) {
38
+ source = this.configManager.getProvider(sourceProviderName);
39
+ if (!source) {
40
+ Logger.error(`供应商 '${sourceProviderName}' 不存在。`);
41
+ return;
42
+ }
43
+ } else {
44
+ let selection;
45
+ try {
46
+ selection = await this.prompt([
47
+ {
48
+ type: 'list',
49
+ name: 'name',
50
+ message: '请选择要克隆的供应商:',
51
+ choices: [
52
+ ...providers.map(p => ({
53
+ name: `${p.displayName || p.name} ${chalk.gray('(' + p.name + ')')}`,
54
+ value: p.name
55
+ })),
56
+ new inquirer.Separator(),
57
+ { name: '取消', value: null }
58
+ ]
59
+ }
60
+ ]);
61
+ } catch (error) {
62
+ if (this.isEscCancelled(error)) return;
63
+ throw error;
64
+ }
65
+ if (!selection.name) {
66
+ Logger.info('操作已取消。');
67
+ return;
68
+ }
69
+ source = this.configManager.getProvider(selection.name);
70
+ }
71
+
72
+ console.log(UIHelper.createTitle(`克隆供应商: ${source.displayName || source.name}`, UIHelper.icons.copy || '📋'));
73
+ console.log();
74
+
75
+ const isCodex = source.ideName === 'codex';
76
+ const escListener = this.createESCListener(() => {
77
+ Logger.info('取消克隆供应商。');
78
+ }, '取消克隆');
79
+
80
+ try {
81
+ // 输入新名称和显示名称
82
+ let basicInfo;
83
+ try {
84
+ basicInfo = await this.prompt([
85
+ {
86
+ type: 'input',
87
+ name: 'name',
88
+ message: '新供应商名称:',
89
+ validate: (input) => {
90
+ if (!input || !input.trim()) return '名称不能为空';
91
+ if (input.trim() === source.name) return '新名称不能与源供应商相同';
92
+ const err = validator.validateName(input.trim());
93
+ if (err) return err;
94
+ if (this.configManager.getProvider(input.trim())) return `供应商 '${input.trim()}' 已存在,请使用其他名称`;
95
+ return true;
96
+ }
97
+ },
98
+ {
99
+ type: 'input',
100
+ name: 'displayName',
101
+ message: '新显示名称:',
102
+ default: `${source.displayName || source.name} (副本)`,
103
+ validate: (input) => validator.validateDisplayName(input) || true
104
+ }
105
+ ]);
106
+ } catch (error) {
107
+ this.removeESCListener(escListener);
108
+ if (this.isEscCancelled(error)) return;
109
+ throw error;
110
+ }
111
+
112
+ // 选择要修改的字段
113
+ let fieldsToModify;
114
+ try {
115
+ const fieldChoices = [
116
+ { name: `🔑 Token(当前: ${source.authToken ? source.authToken.slice(0, 8) + '...' : '未设置'})`, value: 'authToken', checked: true },
117
+ { name: `🌐 基础URL(当前: ${source.baseUrl || '默认'})`, value: 'baseUrl' }
118
+ ];
119
+ if (!isCodex) {
120
+ fieldChoices.push({ name: `🔐 认证模式(当前: ${source.authMode || 'api_key'})`, value: 'authMode' });
121
+ }
122
+ fieldChoices.push({ name: '🚀 启动参数', value: 'launchArgs' });
123
+
124
+ const fieldSelection = await this.prompt([
125
+ {
126
+ type: 'checkbox',
127
+ name: 'fields',
128
+ message: '选择要修改的字段(默认推荐修改 Token):',
129
+ choices: fieldChoices
130
+ }
131
+ ]);
132
+ fieldsToModify = fieldSelection.fields;
133
+ } catch (error) {
134
+ this.removeESCListener(escListener);
135
+ if (this.isEscCancelled(error)) return;
136
+ throw error;
137
+ }
138
+
139
+ // 收集修改值
140
+ const overrides = {};
141
+ if (fieldsToModify.length > 0) {
142
+ const questions = [];
143
+
144
+ if (fieldsToModify.includes('authToken')) {
145
+ questions.push({
146
+ type: 'input',
147
+ name: 'authToken',
148
+ message: isCodex ? 'OpenAI API Key:' : 'Token:',
149
+ default: source.authToken,
150
+ validate: (input) => validator.validateToken(input) || true
151
+ });
152
+ }
153
+
154
+ if (fieldsToModify.includes('baseUrl')) {
155
+ questions.push({
156
+ type: 'input',
157
+ name: 'baseUrl',
158
+ message: 'API 基础URL(留空使用默认):',
159
+ default: source.baseUrl || '',
160
+ validate: (input) => {
161
+ if (!input) return true;
162
+ return validator.validateUrl(input) || true;
163
+ }
164
+ });
165
+ }
166
+
167
+ if (!isCodex && fieldsToModify.includes('authMode')) {
168
+ questions.push({
169
+ type: 'list',
170
+ name: 'authMode',
171
+ message: '认证模式:',
172
+ choices: [
173
+ { name: '🔑 ANTHROPIC_API_KEY - 大多数第三方代理使用', value: 'api_key' },
174
+ { name: '🔐 ANTHROPIC_AUTH_TOKEN - 部分服务商使用', value: 'auth_token' }
175
+ ],
176
+ default: source.authMode || 'api_key'
177
+ });
178
+ }
179
+
180
+ if (fieldsToModify.includes('launchArgs')) {
181
+ if (isCodex) {
182
+ const codexArgs = getCodexLaunchArgs();
183
+ questions.push({
184
+ type: 'checkbox',
185
+ name: 'launchArgs',
186
+ message: 'Codex 启动参数:',
187
+ choices: codexArgs.map(arg => ({
188
+ name: `${arg.label} (${arg.name})${arg.description ? ' - ' + arg.description : ''}`,
189
+ value: arg.name,
190
+ checked: (source.launchArgs || []).includes(arg.name)
191
+ })),
192
+ validate: (selected) => checkExclusiveArgs(selected, codexArgs) || true
193
+ });
194
+ } else {
195
+ questions.push({
196
+ type: 'checkbox',
197
+ name: 'launchArgs',
198
+ message: '启动参数:',
199
+ choices: validator.getAvailableLaunchArgs().map(arg => ({
200
+ name: `${arg.label || arg.name} (${arg.name})${arg.description ? ' - ' + arg.description : ''}`,
201
+ value: arg.name,
202
+ checked: (source.launchArgs || []).includes(arg.name)
203
+ }))
204
+ });
205
+ }
206
+ }
207
+
208
+ if (questions.length > 0) {
209
+ let modifiedValues;
210
+ try {
211
+ modifiedValues = await this.prompt(questions);
212
+ } catch (error) {
213
+ this.removeESCListener(escListener);
214
+ if (this.isEscCancelled(error)) return;
215
+ throw error;
216
+ }
217
+ Object.assign(overrides, modifiedValues);
218
+ }
219
+ }
220
+
221
+ this.removeESCListener(escListener);
222
+
223
+ // 保存克隆的供应商
224
+ const newName = basicInfo.name.trim();
225
+ const authMode = overrides.authMode || source.authMode;
226
+ const baseUrl = overrides.baseUrl !== undefined ? overrides.baseUrl : source.baseUrl;
227
+
228
+ await this.configManager.addProvider(newName, {
229
+ displayName: basicInfo.displayName,
230
+ ideName: source.ideName,
231
+ authToken: overrides.authToken !== undefined ? overrides.authToken : source.authToken,
232
+ baseUrl,
233
+ authMode,
234
+ launchArgs: overrides.launchArgs !== undefined ? overrides.launchArgs : (source.launchArgs || []),
235
+ primaryModel: source.models?.primary || null,
236
+ smallFastModel: source.models?.smallFast || null,
237
+ setAsDefault: false
238
+ });
239
+
240
+ Logger.success(`供应商 '${basicInfo.displayName}' 克隆成功!`);
241
+ console.log(chalk.gray(` 源供应商: ${source.displayName || source.name} → 新供应商: ${basicInfo.displayName} (${newName})`));
242
+ console.log();
243
+
244
+ } catch (error) {
245
+ this.removeESCListener(escListener);
246
+ if (this.isEscCancelled(error)) return;
247
+ throw error;
248
+ }
249
+ }
250
+ }
251
+
252
+ async function cloneCommand(sourceProviderName) {
253
+ const cloner = new ProviderCloner();
254
+ try {
255
+ await cloner.interactive(sourceProviderName);
256
+ } catch (error) {
257
+ if (!cloner.isEscCancelled(error)) {
258
+ Logger.error(`克隆供应商失败: ${error.message}`);
259
+ }
260
+ } finally {
261
+ cloner.destroy();
262
+ }
263
+ }
264
+
265
+ module.exports = { cloneCommand, ProviderCloner };
@@ -1,84 +1,132 @@
1
+ /**
2
+ * Current Config Command
3
+ * 显示当前激活的供应商配置
4
+ * @module commands/current
5
+ */
6
+
1
7
  const chalk = require('chalk');
2
- const { ConfigManager } = require('../config');
8
+ const { configManager } = require('../config');
3
9
  const { Logger } = require('../utils/logger');
10
+ const { formatShellAssignment } = require('../utils/shell-snippets');
11
+ const { AUTH_MODE_DISPLAY } = require('../constants');
4
12
 
13
+ /**
14
+ * 当前配置显示类
15
+ * 用于显示当前激活的 API 供应商配置详情
16
+ */
5
17
  class CurrentConfig {
6
- constructor() {
7
- this.configManager = new ConfigManager();
18
+ /**
19
+ * 创建当前配置显示器实例
20
+ */
21
+ constructor(manager = configManager) {
22
+ this.configManager = manager;
8
23
  }
9
24
 
10
- async show() {
25
+ /**
26
+ * 显示当前供应商配置
27
+ * @returns {Promise<void>}
28
+ */
29
+ async show(options = {}) {
11
30
  try {
12
31
  await this.configManager.ensureLoaded();
13
32
  const currentProvider = this.configManager.getCurrentProvider();
14
-
33
+
15
34
  if (!currentProvider) {
16
35
  Logger.warning('未设置当前供应商');
17
- Logger.info('请使用 "cc <供应商名>" 切换供应商');
36
+ Logger.info('请使用 "akm <供应商名>" 切换供应商');
37
+ return;
38
+ }
39
+
40
+ if (options.json) {
41
+ console.log(
42
+ JSON.stringify(
43
+ { currentProvider: currentProvider.name, provider: currentProvider },
44
+ null,
45
+ 2
46
+ )
47
+ );
18
48
  return;
19
49
  }
20
50
 
51
+ const shell = options.shell;
52
+
21
53
  console.log(chalk.blue('\n📍 当前配置:'));
22
54
  console.log(chalk.gray('═'.repeat(60)));
23
-
55
+
24
56
  console.log(chalk.green(`供应商: ${currentProvider.displayName}`));
25
57
  console.log(chalk.gray(`内部名称: ${currentProvider.name}`));
26
58
 
27
- // 显示认证模式
28
- const authModeDisplay = {
29
- api_key: '通用API密钥模式',
30
- auth_token: '认证令牌模式',
31
- oauth_token: 'OAuth令牌模式'
32
- };
33
- console.log(chalk.gray(`认证模式: ${authModeDisplay[currentProvider.authMode] || currentProvider.authMode}`));
34
-
35
- // 如果是 api_key 模式,显示 tokenType
36
- if (currentProvider.authMode === 'api_key' && currentProvider.tokenType) {
37
- const tokenTypeDisplay = currentProvider.tokenType === 'auth_token' ? 'ANTHROPIC_AUTH_TOKEN' : 'ANTHROPIC_API_KEY';
38
- console.log(chalk.gray(`Token类型: ${tokenTypeDisplay}`));
59
+ if (currentProvider.ideName === 'codex') {
60
+ console.log(chalk.gray('IDE: Codex CLI'));
61
+ if (currentProvider.baseUrl) {
62
+ console.log(chalk.gray(`OPENAI_BASE_URL: ${currentProvider.baseUrl}`));
63
+ }
64
+ if (currentProvider.authToken) {
65
+ console.log(chalk.gray(`OPENAI_API_KEY: ${currentProvider.authToken}`));
66
+ }
67
+ console.log(
68
+ chalk.gray(`创建时间: ${new Date(currentProvider.createdAt).toLocaleString()}`)
69
+ );
70
+ console.log(chalk.gray(`最后使用: ${new Date(currentProvider.lastUsed).toLocaleString()}`));
71
+ console.log(chalk.gray('═'.repeat(60)));
72
+
73
+ console.log(chalk.blue('\n🔧 环境变量设置:'));
74
+ if (currentProvider.baseUrl) {
75
+ console.log(chalk.gray(formatShellAssignment('OPENAI_BASE_URL', currentProvider.baseUrl, shell)));
76
+ }
77
+ if (currentProvider.authToken) {
78
+ console.log(chalk.gray(formatShellAssignment('OPENAI_API_KEY', currentProvider.authToken, shell)));
79
+ }
80
+ console.log(chalk.gray('codex'));
81
+ return;
39
82
  }
40
83
 
84
+ // 显示认证模式
85
+ console.log(
86
+ chalk.gray(
87
+ `认证模式: ${AUTH_MODE_DISPLAY[currentProvider.authMode] || currentProvider.authMode}`
88
+ )
89
+ );
90
+
41
91
  if (currentProvider.baseUrl) {
42
92
  console.log(chalk.gray(`基础URL: ${currentProvider.baseUrl}`));
43
93
  }
44
94
  console.log(chalk.gray(`认证Token: ${currentProvider.authToken}`));
45
95
  console.log(chalk.gray(`创建时间: ${new Date(currentProvider.createdAt).toLocaleString()}`));
46
96
  console.log(chalk.gray(`最后使用: ${new Date(currentProvider.lastUsed).toLocaleString()}`));
47
-
97
+
48
98
  // 显示模型配置
49
- if (currentProvider.models && (currentProvider.models.primary || currentProvider.models.smallFast)) {
99
+ if (
100
+ currentProvider.models &&
101
+ (currentProvider.models.primary || currentProvider.models.smallFast)
102
+ ) {
50
103
  console.log(chalk.gray(`主模型: ${currentProvider.models.primary || '未设置'}`));
51
104
  console.log(chalk.gray(`快速模型: ${currentProvider.models.smallFast || '未设置'}`));
52
105
  }
53
-
106
+
54
107
  console.log(chalk.gray('═'.repeat(60)));
55
-
108
+
56
109
  // 显示环境变量设置方式
57
110
  console.log(chalk.blue('\n🔧 环境变量设置:'));
58
111
  if (currentProvider.baseUrl) {
59
- console.log(chalk.gray(`set ANTHROPIC_BASE_URL=${currentProvider.baseUrl}`));
112
+ console.log(chalk.gray(formatShellAssignment('ANTHROPIC_BASE_URL', currentProvider.baseUrl, shell)));
60
113
  }
61
- if (currentProvider.authMode === 'oauth_token') {
62
- console.log(chalk.gray(`set CLAUDE_CODE_OAUTH_TOKEN=${currentProvider.authToken}`));
63
- } else if (currentProvider.authMode === 'api_key') {
64
- // 根据 tokenType 显示对应的环境变量
65
- if (currentProvider.tokenType === 'auth_token') {
66
- console.log(chalk.gray(`set ANTHROPIC_AUTH_TOKEN=${currentProvider.authToken}`));
67
- } else {
68
- console.log(chalk.gray(`set ANTHROPIC_API_KEY=${currentProvider.authToken}`));
69
- }
114
+ if (currentProvider.authMode === 'auth_token') {
115
+ console.log(chalk.gray(formatShellAssignment('ANTHROPIC_AUTH_TOKEN', currentProvider.authToken, shell)));
70
116
  } else {
71
- // auth_token 模式
72
- console.log(chalk.gray(`set ANTHROPIC_AUTH_TOKEN=${currentProvider.authToken}`));
117
+ console.log(chalk.gray(formatShellAssignment('ANTHROPIC_API_KEY', currentProvider.authToken, shell)));
73
118
  }
74
119
  if (currentProvider.models?.primary) {
75
- console.log(chalk.gray(`set ANTHROPIC_MODEL=${currentProvider.models.primary}`));
120
+ console.log(chalk.gray(formatShellAssignment('ANTHROPIC_MODEL', currentProvider.models.primary, shell)));
76
121
  }
77
122
  if (currentProvider.models?.smallFast) {
78
- console.log(chalk.gray(`set ANTHROPIC_SMALL_FAST_MODEL=${currentProvider.models.smallFast}`));
123
+ console.log(
124
+ chalk.gray(
125
+ formatShellAssignment('ANTHROPIC_SMALL_FAST_MODEL', currentProvider.models.smallFast, shell)
126
+ )
127
+ );
79
128
  }
80
129
  console.log(chalk.gray('claude'));
81
-
82
130
  } catch (error) {
83
131
  Logger.error(`获取当前配置失败: ${error.message}`);
84
132
  throw error;
@@ -86,9 +134,9 @@ class CurrentConfig {
86
134
  }
87
135
  }
88
136
 
89
- async function currentCommand() {
137
+ async function currentCommand(options = {}) {
90
138
  const current = new CurrentConfig();
91
- await current.show();
139
+ await current.show(options);
92
140
  }
93
141
 
94
- module.exports = { currentCommand, CurrentConfig };
142
+ module.exports = { currentCommand, CurrentConfig };
@@ -1,208 +1,4 @@
1
- const inquirer = require('inquirer');
2
- const chalk = require('chalk');
3
- const { ConfigManager } = require('../config');
4
- const { validator } = require('../utils/validator');
5
- const { Logger } = require('../utils/logger');
6
- const { UIHelper } = require('../utils/ui-helper');
7
- const { BaseCommand } = require('./BaseCommand');
1
+ // 兼容旧的模块导入路径,编辑逻辑统一由 switch/ProviderManager 维护。
2
+ const { editCommand } = require('./switch');
8
3
 
9
- class ProviderEditor extends BaseCommand {
10
- constructor() {
11
- super();
12
- this.configManager = new ConfigManager();
13
- }
14
-
15
- async interactive(providerName) {
16
- await this.configManager.load();
17
- const providers = this.configManager.listProviders();
18
-
19
- if (providers.length === 0) {
20
- Logger.warning('没有可编辑的供应商配置。请先添加一个。');
21
- return;
22
- }
23
-
24
- let providerToEdit;
25
- if (providerName) {
26
- providerToEdit = this.configManager.getProvider(providerName);
27
- if (!providerToEdit) {
28
- Logger.error(`供应商 '${providerName}' 不存在。`);
29
- return;
30
- }
31
- } else {
32
- let selection;
33
- try {
34
- selection = await this.prompt([
35
- {
36
- type: 'list',
37
- name: 'selectedProviderName',
38
- message: '请选择要编辑的供应商:',
39
- choices: [
40
- ...providers.map(p => ({ name: p.displayName || p.name, value: p.name })),
41
- new inquirer.Separator(),
42
- { name: '取消', value: null },
43
- ],
44
- },
45
- ]);
46
- } catch (error) {
47
- if (this.isEscCancelled(error)) {
48
- return;
49
- }
50
- throw error;
51
- }
52
-
53
- const { selectedProviderName } = selection;
54
-
55
- if (!selectedProviderName) {
56
- Logger.info('操作已取消。');
57
- return;
58
- }
59
- providerToEdit = this.configManager.getProvider(selectedProviderName);
60
- }
61
-
62
- console.log(UIHelper.createTitle(`编辑供应商: ${providerToEdit.displayName}`, UIHelper.icons.edit));
63
- console.log();
64
- console.log(UIHelper.createTooltip('请更新供应商配置信息。按 Enter 键接受默认值。'));
65
- console.log();
66
-
67
- const escListener = this.createESCListener(() => {
68
- Logger.info('取消编辑供应商。');
69
- const { registry } = require('../CommandRegistry');
70
- registry.executeCommand('switch');
71
- }, '取消编辑');
72
-
73
- try {
74
- let answers;
75
- try {
76
- answers = await this.prompt([
77
- {
78
- type: 'input',
79
- name: 'displayName',
80
- message: '供应商显示名称:',
81
- default: providerToEdit.displayName,
82
- validate: (input) => validator.validateDisplayName(input) || true,
83
- },
84
- {
85
- type: 'list',
86
- name: 'authMode',
87
- message: '认证模式:',
88
- choices: [
89
- { name: '🔑 通用API密钥模式 - 支持 ANTHROPIC_API_KEY 和 ANTHROPIC_AUTH_TOKEN', value: 'api_key' },
90
- { name: '🔐 认证令牌模式 (仅 ANTHROPIC_AUTH_TOKEN) - 适用于某些服务商', value: 'auth_token' },
91
- { name: '🌐 OAuth令牌模式 (CLAUDE_CODE_OAUTH_TOKEN) - 适用于官方Claude Code', value: 'oauth_token' },
92
- ],
93
- default: providerToEdit.authMode,
94
- },
95
- {
96
- type: 'list',
97
- name: 'tokenType',
98
- message: 'Token类型:',
99
- choices: [
100
- { name: '🔑 ANTHROPIC_API_KEY - 通用API密钥', value: 'api_key' },
101
- { name: '🔐 ANTHROPIC_AUTH_TOKEN - 认证令牌', value: 'auth_token' }
102
- ],
103
- default: providerToEdit.tokenType || 'api_key',
104
- when: (answers) => answers.authMode === 'api_key'
105
- },
106
- {
107
- type: 'input',
108
- name: 'baseUrl',
109
- message: 'API基础URL:',
110
- default: providerToEdit.baseUrl,
111
- validate: (input) => validator.validateUrl(input) || true,
112
- when: (answers) => answers.authMode === 'api_key' || answers.authMode === 'auth_token',
113
- },
114
- {
115
- type: 'input',
116
- name: 'authToken',
117
- message: (answers) => {
118
- switch (answers.authMode) {
119
- case 'api_key':
120
- const tokenTypeLabel = answers.tokenType === 'auth_token' ? 'ANTHROPIC_AUTH_TOKEN' : 'ANTHROPIC_API_KEY';
121
- return `Token (${tokenTypeLabel}):`;
122
- case 'auth_token': return '认证令牌 (ANTHROPIC_AUTH_TOKEN):';
123
- case 'oauth_token': return 'OAuth令牌 (CLAUDE_CODE_OAUTH_TOKEN):';
124
- default: return '认证令牌:';
125
- }
126
- },
127
- default: providerToEdit.authToken,
128
- validate: (input) => validator.validateToken(input) || true,
129
- },
130
- {
131
- type: 'checkbox',
132
- name: 'launchArgs',
133
- message: '启动参数:',
134
- choices: validator.getAvailableLaunchArgs().map(arg => ({
135
- name: `${arg.label || arg.name} (${arg.name})${arg.description ? ' - ' + arg.description : ''}`,
136
- value: arg.name,
137
- checked: providerToEdit.launchArgs && providerToEdit.launchArgs.includes(arg.name),
138
- })),
139
- },
140
- ]);
141
- } catch (error) {
142
- this.removeESCListener(escListener);
143
- if (this.isEscCancelled(error)) {
144
- return;
145
- }
146
- throw error;
147
- }
148
-
149
- this.removeESCListener(escListener);
150
- await this.saveProvider(providerToEdit.name, answers);
151
-
152
- } catch (error) {
153
- this.removeESCListener(escListener);
154
- if (this.isEscCancelled(error)) {
155
- return;
156
- }
157
- throw error;
158
- }
159
- }
160
-
161
- async saveProvider(name, answers) {
162
- try {
163
- // Re-use addProvider which can overwrite existing providers
164
- await this.configManager.addProvider(name, {
165
- displayName: answers.displayName,
166
- baseUrl: answers.baseUrl,
167
- authToken: answers.authToken,
168
- authMode: answers.authMode,
169
- tokenType: answers.tokenType, // 仅在 authMode 为 'api_key' 时使用
170
- launchArgs: answers.launchArgs,
171
- // Retain original model settings unless we add editing for them
172
- primaryModel: this.configManager.getProvider(name).models.primary,
173
- smallFastModel: this.configManager.getProvider(name).models.smallFast,
174
- setAsDefault: false, // Don't change default status on edit
175
- });
176
-
177
- Logger.success(`供应商 '${answers.displayName}' 更新成功!`);
178
-
179
- console.log(chalk.green('\n🎉 供应商编辑完成!正在返回主界面...'));
180
- await new Promise(resolve => setTimeout(resolve, 1500));
181
-
182
- const { registry } = require('../CommandRegistry');
183
- return await registry.executeCommand('switch');
184
-
185
- } catch (error) {
186
- if (this.isEscCancelled(error)) {
187
- return;
188
- }
189
- Logger.error(`更新供应商失败: ${error.message}`);
190
- throw error;
191
- }
192
- }
193
- }
194
-
195
- async function editCommand(providerName) {
196
- const editor = new ProviderEditor();
197
- try {
198
- await editor.interactive(providerName);
199
- } catch (error) {
200
- if (!editor.isEscCancelled(error)) {
201
- Logger.error(`编辑供应商失败: ${error.message}`);
202
- }
203
- } finally {
204
- editor.destroy();
205
- }
206
- }
207
-
208
- module.exports = { editCommand, ProviderEditor };
4
+ module.exports = { editCommand };