@pikecode/api-key-manager 1.2.0 → 1.3.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.
@@ -4,22 +4,23 @@
4
4
  * @module commands/switch
5
5
  */
6
6
 
7
- const path = require('path');
8
7
  const inquirer = require('inquirer');
9
8
  const chalk = require('chalk');
10
9
  const Choices = require('inquirer/lib/objects/choices');
11
10
  const { configManager } = require('../config');
12
- const { executeWithEnv } = require('../utils/env-launcher');
13
- const { executeCodexWithEnv } = require('../utils/codex-launcher');
14
11
  const { Logger } = require('../utils/logger');
15
12
  const { UIHelper } = require('../utils/ui-helper');
16
- const { findSettingsConflict, backupSettingsFile, clearConflictKeys, saveSettingsFile } = require('../utils/claude-settings');
17
13
  const { BaseCommand } = require('./BaseCommand');
18
14
  const { validator } = require('../utils/validator');
19
15
  const { ProviderStatusChecker } = require('../utils/provider-status-checker');
20
16
  const { AUTH_MODE_DISPLAY, BASE_URL } = require('../constants');
21
- const { LaunchArgsHelper } = require('./switch/launch-args-helper');
22
17
  const { StatusHelper } = require('./switch/status-helper');
18
+ const { LaunchArgsHelper } = require('./switch/launch-args-helper');
19
+ const { ProviderChoicesHelper } = require('./switch/provider-choices-helper');
20
+ const { ProviderDetailsHelper } = require('./switch/provider-details-helper');
21
+ const { ProviderEditQuestionsHelper } = require('./switch/provider-edit-questions-helper');
22
+ const { ensureClaudeSettingsCompatibility } = require('./switch/claude-settings-compatibility');
23
+ const { launchProviderProcess, markProviderAsCurrent } = require('./switch/provider-launcher');
23
24
 
24
25
  /**
25
26
  * 环境切换器类
@@ -35,22 +36,29 @@ class EnvSwitcher extends BaseCommand {
35
36
  this.currentPromptContext = null;
36
37
  this.activeStatusRefresh = null;
37
38
  this.filter = null;
38
- this.filteredProviders = null; // 保存过滤后的供应商列表用于状态更新
39
+ this.filteredProviders = null;
40
+ this._refreshTimer = null;
41
+ }
42
+
43
+ _getPageSize(itemCount) {
44
+ const rows = process.stdout.rows || 24;
45
+ const reserved = 8;
46
+ return Math.min(itemCount, Math.max(5, rows - reserved));
39
47
  }
40
48
 
41
49
  async validateProvider(providerName) {
42
50
  await this.configManager.load();
43
-
51
+
44
52
  // 先尝试按名称查找,再尝试按别名查找
45
53
  let provider = this.configManager.getProvider(providerName);
46
54
  if (!provider) {
47
55
  provider = this.configManager.getProviderByNameOrAlias(providerName);
48
56
  }
49
-
57
+
50
58
  if (!provider) {
51
59
  throw new Error(`供应商 '${providerName}' 不存在\n使用 'akm list' 查看所有已配置的供应商`);
52
60
  }
53
-
61
+
54
62
  return provider;
55
63
  }
56
64
 
@@ -59,36 +67,15 @@ class EnvSwitcher extends BaseCommand {
59
67
  this.clearScreen();
60
68
  const provider = await this.validateProvider(providerName);
61
69
  const isCodex = provider.ideName === 'codex';
62
- const availableArgs = isCodex ? this.getCodexLaunchArgs() : this.getAvailableLaunchArgs();
70
+ const availableArgs = LaunchArgsHelper.getAvailableLaunchArgs(isCodex);
63
71
 
64
72
  // 优先使用上次使用的参数,如果没有则使用默认的 launchArgs
65
73
  const defaultLaunchArgs = Array.isArray(provider.lastUsedArgs) && provider.lastUsedArgs.length > 0
66
74
  ? provider.lastUsedArgs
67
75
  : (Array.isArray(provider.launchArgs) ? provider.launchArgs : []);
68
76
 
69
- const knownArgNames = new Set(availableArgs.map(arg => arg.name));
70
- const customLaunchArgs = defaultLaunchArgs
71
- .filter(arg => typeof arg === 'string' && !knownArgNames.has(arg));
72
- const mergedArgs = [
73
- ...availableArgs.map(arg => ({
74
- ...arg,
75
- checked: defaultLaunchArgs.includes(arg.name) || Boolean(arg.checked)
76
- })),
77
- ...customLaunchArgs.map(name => ({
78
- name,
79
- label: name,
80
- description: '自定义启动参数',
81
- checked: true
82
- }))
83
- ];
84
- const ideDisplayName = isCodex ? 'Codex CLI' : 'Claude Code';
85
-
86
- // 显示提示:是否使用上次的参数
87
- const isUsingLastUsed = Array.isArray(provider.lastUsedArgs) && provider.lastUsedArgs.length > 0;
88
- if (isUsingLastUsed) {
89
- console.log(UIHelper.colors.muted('💡 正在使用上次的启动参数'));
90
- console.log();
91
- }
77
+ const mergedArgs = LaunchArgsHelper.mergeArgsWithDefaults(availableArgs, defaultLaunchArgs);
78
+ const ideDisplayName = LaunchArgsHelper.getIDEDisplayName(isCodex);
92
79
 
93
80
  console.log(UIHelper.createTitle('启动配置', UIHelper.icons.launch));
94
81
  console.log();
@@ -115,18 +102,7 @@ class EnvSwitcher extends BaseCommand {
115
102
  type: 'checkbox',
116
103
  name: 'selectedArgs',
117
104
  message: '选择启动参数:',
118
- choices: mergedArgs.map(arg => {
119
- const commandText = UIHelper.colors.muted(`(${arg.name})`);
120
- const descriptionText = arg.description
121
- ? ` ${UIHelper.colors.muted(arg.description)}`
122
- : '';
123
-
124
- return {
125
- name: `${UIHelper.colors.accent(arg.label || arg.name)} ${commandText}${descriptionText}`,
126
- value: arg.name,
127
- checked: Boolean(arg.checked)
128
- };
129
- })
105
+ choices: LaunchArgsHelper.formatArgsForDisplay(mergedArgs, UIHelper)
130
106
  }
131
107
  ];
132
108
 
@@ -144,16 +120,12 @@ class EnvSwitcher extends BaseCommand {
144
120
  this.removeESCListener(escListener);
145
121
 
146
122
  // 检查互斥参数
147
- const conflictError = this.checkExclusiveArgs(answers.selectedArgs, availableArgs);
123
+ const conflictError = LaunchArgsHelper.validateArgsConflict(answers.selectedArgs, availableArgs);
148
124
  if (conflictError) {
149
125
  Logger.warning(conflictError);
150
126
  return await this.showLaunchArgsSelection(providerName);
151
127
  }
152
128
 
153
- // 保存上次使用的启动参数
154
- await this.configManager.updateLastUsedArgs(providerName, answers.selectedArgs);
155
-
156
- // 选择参数后直接启动
157
129
  await this.launchProvider(provider, answers.selectedArgs);
158
130
 
159
131
  } catch (error) {
@@ -161,112 +133,13 @@ class EnvSwitcher extends BaseCommand {
161
133
  }
162
134
  }
163
135
 
164
- async ensureClaudeSettingsCompatibility(provider) {
165
- try {
166
- const conflict = await findSettingsConflict();
167
- if (!conflict) {
168
- return true;
169
- }
170
-
171
- const keyList = conflict.keys.map((key) => `• ${key}`).join('\n');
172
-
173
- const backupDir = path.dirname(conflict.filePath);
174
-
175
- this.clearScreen();
176
- console.log(UIHelper.createTitle('检测到环境变量冲突', UIHelper.icons.warning));
177
- console.log();
178
- console.log(UIHelper.createCard('冲突文件', conflict.filePath, UIHelper.icons.info));
179
- console.log();
180
- console.log(UIHelper.createCard('备份目录', `${backupDir}\n备份文件将命名为 settings.backup-YYYYMMDD_HHmmss.json`, UIHelper.icons.info));
181
- console.log();
182
- console.log(UIHelper.createCard('可能覆盖的变量', keyList, UIHelper.icons.warning));
183
- console.log();
184
- console.log(UIHelper.createTooltip('Claude 会优先读取该设置文件中的 env 配置,可能覆盖本次为供应商设置的变量。'));
185
- console.log();
186
-
187
- let answer;
188
- try {
189
- answer = await this.prompt([
190
- {
191
- type: 'list',
192
- name: 'action',
193
- message: `在 ${conflict.filePath} 中发现 env 配置会覆盖供应商 '${provider.displayName || provider.name}' 的变量,选择处理方式:`,
194
- choices: [
195
- { name: '🔧 备份并清空这些变量', value: 'fix' },
196
- { name: '⚠️ 忽略并继续(可能导致切换失败)', value: 'ignore' },
197
- { name: '❌ 取消启动', value: 'cancel' }
198
- ],
199
- default: 'fix'
200
- }
201
- ]);
202
- } catch (error) {
203
- if (this.isEscCancelled(error)) {
204
- Logger.info('已取消启动');
205
- return false;
206
- }
207
- throw error;
208
- }
209
-
210
- if (answer.action === 'fix') {
211
- let confirmBackup;
212
- try {
213
- confirmBackup = await this.prompt([
214
- {
215
- type: 'confirm',
216
- name: 'confirmed',
217
- message: `将在 ${backupDir} 中创建备份文件 (settings.backup-YYYYMMDD_HHmmss.json),并清空冲突变量。是否继续?`,
218
- default: true
219
- }
220
- ]);
221
- } catch (error) {
222
- if (this.isEscCancelled(error)) {
223
- Logger.info('已取消启动');
224
- return false;
225
- }
226
- throw error;
227
- }
228
-
229
- if (!confirmBackup.confirmed) {
230
- Logger.info('已取消启动');
231
- return false;
232
- }
233
-
234
- try {
235
- const backupPath = await backupSettingsFile(conflict.filePath);
236
- const updatedSettings = clearConflictKeys(
237
- {
238
- ...conflict.settings,
239
- env: conflict.settings.env ? { ...conflict.settings.env } : undefined
240
- },
241
- conflict.keys
242
- );
243
- await saveSettingsFile(conflict.filePath, updatedSettings);
244
- Logger.success(`已将 ${conflict.filePath} 备份至 '${backupPath}' 并清空冲突变量。`);
245
- } catch (error) {
246
- throw new Error(`清理 Claude 设置文件失败: ${error.message}`);
247
- }
248
- return true;
249
- }
250
-
251
- if (answer.action === 'ignore') {
252
- Logger.warning(`已忽略 ${conflict.filePath} 中的冲突,Claude 可能仍会使用该文件里的旧变量。`);
253
- return true;
254
- }
255
-
256
- Logger.info('已取消启动');
257
- return false;
258
- } catch (error) {
259
- throw error;
260
- }
261
- }
262
-
263
136
  async launchProvider(provider, selectedLaunchArgs) {
264
137
  try {
265
138
  const isCodex = provider.ideName === 'codex';
266
139
 
267
140
  // Claude Code 才需要检测设置冲突
268
141
  if (!isCodex) {
269
- const shouldContinue = await this.ensureClaudeSettingsCompatibility(provider);
142
+ const shouldContinue = await ensureClaudeSettingsCompatibility(this, provider);
270
143
  if (!shouldContinue) {
271
144
  return;
272
145
  }
@@ -287,25 +160,12 @@ class EnvSwitcher extends BaseCommand {
287
160
  const loadingInterval = UIHelper.createLoadingAnimation('正在设置环境...');
288
161
 
289
162
  try {
290
- // 设置为当前供应商
291
- await this.configManager.setCurrentProvider(provider.name);
292
-
293
- // 更新使用统计
294
- provider.usageCount = (provider.usageCount || 0) + 1;
295
- provider.lastUsed = new Date().toISOString();
296
- await this.configManager.save();
297
-
163
+ await markProviderAsCurrent(this.configManager, provider, selectedLaunchArgs);
298
164
  UIHelper.clearLoadingAnimation(loadingInterval);
299
165
 
300
166
  console.log(UIHelper.createCard('准备就绪', `环境配置完成,正在启动 🚀 ${ideDisplayName}...`, UIHelper.icons.success));
301
167
  console.log();
302
-
303
- if (isCodex) {
304
- await executeCodexWithEnv(provider, selectedLaunchArgs);
305
- } else {
306
- // 设置环境变量并启动 Claude Code
307
- await executeWithEnv(provider, selectedLaunchArgs);
308
- }
168
+ await launchProviderProcess(provider, selectedLaunchArgs);
309
169
 
310
170
  } catch (error) {
311
171
  UIHelper.clearLoadingAnimation(loadingInterval);
@@ -334,7 +194,7 @@ class EnvSwitcher extends BaseCommand {
334
194
  async quickLaunchProvider(providerName, options) {
335
195
  try {
336
196
  await this.configManager.ensureLoaded();
337
-
197
+
338
198
  // 支持别名查找
339
199
  let provider = this.configManager.getProvider(providerName);
340
200
  if (!provider) {
@@ -356,7 +216,7 @@ class EnvSwitcher extends BaseCommand {
356
216
  selectedArgs = Array.isArray(provider.lastUsedArgs) && provider.lastUsedArgs.length > 0
357
217
  ? provider.lastUsedArgs
358
218
  : (Array.isArray(provider.launchArgs) ? provider.launchArgs : []);
359
-
219
+
360
220
  if (Array.isArray(provider.lastUsedArgs) && provider.lastUsedArgs.length > 0) {
361
221
  console.log(UIHelper.colors.muted('💡 使用上次的启动参数: ' + selectedArgs.join(' ')));
362
222
  } else {
@@ -364,9 +224,6 @@ class EnvSwitcher extends BaseCommand {
364
224
  }
365
225
  }
366
226
 
367
- // 更新上次使用的参数(使用真实的 provider.name 而不是别名)
368
- await this.configManager.updateLastUsedArgs(provider.name, selectedArgs);
369
-
370
227
  // 直接启动供应商
371
228
  await this.launchProvider(provider, selectedArgs);
372
229
 
@@ -375,21 +232,6 @@ class EnvSwitcher extends BaseCommand {
375
232
  }
376
233
  }
377
234
 
378
- getAvailableLaunchArgs() {
379
- const { getClaudeLaunchArgs } = require('../utils/launch-args');
380
- return getClaudeLaunchArgs();
381
- }
382
-
383
- checkExclusiveArgs(selectedArgs, availableArgs) {
384
- const { checkExclusiveArgs } = require('../utils/launch-args');
385
- return checkExclusiveArgs(selectedArgs, availableArgs);
386
- }
387
-
388
- getCodexLaunchArgs() {
389
- const { getCodexLaunchArgs } = require('../utils/launch-args');
390
- return getCodexLaunchArgs();
391
- }
392
-
393
235
  async showProviderSelection() {
394
236
  try {
395
237
  // 并行加载配置和准备界面
@@ -461,14 +303,7 @@ class EnvSwitcher extends BaseCommand {
461
303
  message: promptMessage,
462
304
  choices,
463
305
  default: defaultChoice,
464
- pageSize: 12
465
- }
466
- ]);
467
-
468
- // 移除 ESC 键监听
469
- this.removeESCListener(escListener);
470
-
471
- this._cancelStatusRefresh();
306
+ pageSize: this._getPageSize(choices.length)
472
307
 
473
308
  if (answer.provider === '__OPEN_CONFIG__') {
474
309
  await this.openConfigFile();
@@ -499,7 +334,7 @@ class EnvSwitcher extends BaseCommand {
499
334
  }
500
335
  }
501
336
 
502
- showWelcomeScreen(providers, statusMap = {}, statusError = null) {
337
+ showWelcomeScreen(providers, _statusMap = {}, statusError = null) {
503
338
  this.clearScreen();
504
339
 
505
340
  if (providers.length > 0) {
@@ -549,8 +384,6 @@ class EnvSwitcher extends BaseCommand {
549
384
  console.log();
550
385
  const choices = [
551
386
  { name: `${UIHelper.icons.search} 搜索供应商`, value: 'search' },
552
- { name: `${UIHelper.icons.edit} 批量编辑`, value: 'batch' },
553
- { name: `${UIHelper.icons.settings} 全局设置`, value: 'global' },
554
387
  { name: `${UIHelper.icons.info} 查看统计`, value: 'stats' },
555
388
  { name: `${UIHelper.icons.back} 返回主菜单`, value: 'back' }
556
389
  ];
@@ -716,14 +549,17 @@ class EnvSwitcher extends BaseCommand {
716
549
  );
717
550
 
718
551
  if (searchResults.length === 0) {
719
- Logger.warning('未找到匹配的供应商');
720
- return await this.showQuickSettings();
552
+ Logger.warning(`未找到匹配"${answer.search}"的供应商,请重新搜索`);
553
+ return await this.showSearchProvider();
721
554
  }
722
555
 
723
- const choices = searchResults.map(p => ({
724
- name: UIHelper.formatProvider(p),
725
- value: p.name
726
- }));
556
+ const choices = ProviderChoicesHelper.buildProviderChoices(searchResults, {
557
+ statusMap: this._buildInitialStatusMap(searchResults),
558
+ UIHelper,
559
+ StatusHelper,
560
+ chalk,
561
+ Separator: inquirer.Separator
562
+ });
727
563
 
728
564
  choices.push(
729
565
  new inquirer.Separator(),
@@ -799,12 +635,6 @@ class EnvSwitcher extends BaseCommand {
799
635
 
800
636
  console.log(UIHelper.createTable(['项目', '数据'], stats));
801
637
  console.log();
802
- console.log(UIHelper.createHintLine([
803
- ['Enter', '返回快速设置'],
804
- ['ESC', '返回快速设置']
805
- ]));
806
- console.log();
807
-
808
638
  // 设置 ESC 键监听
809
639
  const escListener = this.createESCListener(() => {
810
640
  Logger.info('返回快速设置');
@@ -814,9 +644,10 @@ class EnvSwitcher extends BaseCommand {
814
644
  try {
815
645
  await this.prompt([
816
646
  {
817
- type: 'input',
818
- name: 'continue',
819
- message: '按回车键继续...'
647
+ type: 'list',
648
+ name: 'action',
649
+ message: '操作:',
650
+ choices: [{ name: `${UIHelper.icons.back} 返回`, value: 'back' }]
820
651
  }
821
652
  ]);
822
653
  } catch (error) {
@@ -828,7 +659,6 @@ class EnvSwitcher extends BaseCommand {
828
659
  }
829
660
 
830
661
  this.removeESCListener(escListener);
831
-
832
662
  return await this.showQuickSettings();
833
663
  }
834
664
 
@@ -891,9 +721,10 @@ class EnvSwitcher extends BaseCommand {
891
721
  try {
892
722
  await this.prompt([
893
723
  {
894
- type: 'input',
895
- name: 'continue',
896
- message: '按回车键返回主菜单'
724
+ type: 'list',
725
+ name: 'action',
726
+ message: '操作:',
727
+ choices: [{ name: `${UIHelper.icons.back} 返回主菜单`, value: 'back' }]
897
728
  }
898
729
  ]);
899
730
  } catch (error) {
@@ -954,12 +785,7 @@ class EnvSwitcher extends BaseCommand {
954
785
  name: 'action',
955
786
  message: `选择供应商或操作 (总计 ${providers.length} 个):`,
956
787
  choices,
957
- pageSize: 12
958
- }
959
- ]);
960
- } catch (error) {
961
- this.removeESCListener(escListener);
962
- if (this.isEscCancelled(error)) {
788
+ pageSize: this._getPageSize(choices.length)
963
789
  return;
964
790
  }
965
791
  throw error;
@@ -984,44 +810,14 @@ class EnvSwitcher extends BaseCommand {
984
810
  }
985
811
 
986
812
  createProviderChoices(providers, includeActions = false, statusMap = {}) {
987
- const lastUsedProvider = providers.reduce((latest, current) => {
988
- if (!current || !current.lastUsed) {
989
- return latest;
990
- }
991
- if (!latest || !latest.lastUsed) {
992
- return current;
993
- }
994
- return new Date(current.lastUsed) > new Date(latest.lastUsed) ? current : latest;
995
- }, null);
996
-
997
- const choices = providers.map(provider => {
998
- const isLastUsed = lastUsedProvider && lastUsedProvider.name === provider.name;
999
- const availability = statusMap[provider.name];
1000
- const icon = this._iconForState(availability?.state);
1001
- const statusText = this._formatAvailability(availability);
1002
- const statusLabel = chalk.gray('-') + ' ' + statusText;
1003
- // IDE 类型标签
1004
- const ideTag = provider.ideName === 'codex'
1005
- ? chalk.cyan('[Codex]')
1006
- : chalk.magenta('[Claude]');
1007
- const label = `${icon} ${ideTag} ${UIHelper.formatProvider(provider)}${isLastUsed ? UIHelper.colors.muted(' --- 上次使用') : ''} ${statusLabel}`;
1008
-
1009
- return {
1010
- name: label,
1011
- value: provider.name,
1012
- short: provider.name
1013
- };
813
+ return ProviderChoicesHelper.buildProviderChoices(providers, {
814
+ includeActions,
815
+ statusMap,
816
+ UIHelper,
817
+ StatusHelper,
818
+ chalk,
819
+ Separator: inquirer.Separator
1014
820
  });
1015
-
1016
- if (includeActions) {
1017
- choices.push(
1018
- new inquirer.Separator(),
1019
- { name: `${UIHelper.icons.back} 返回供应商选择`, value: 'back' },
1020
- { name: `${UIHelper.icons.error} 退出`, value: 'exit' }
1021
- );
1022
- }
1023
-
1024
- return choices;
1025
821
  }
1026
822
 
1027
823
  _iconForState(state) {
@@ -1076,6 +872,10 @@ class EnvSwitcher extends BaseCommand {
1076
872
 
1077
873
  _cancelStatusRefresh() {
1078
874
  this.activeStatusRefresh = null;
875
+ if (this._refreshTimer) {
876
+ clearTimeout(this._refreshTimer);
877
+ this._refreshTimer = null;
878
+ }
1079
879
  }
1080
880
 
1081
881
  _applyStatusUpdate(providers, statusMap, error, refreshToken = null) {
@@ -1091,56 +891,7 @@ class EnvSwitcher extends BaseCommand {
1091
891
  return;
1092
892
  }
1093
893
 
1094
- const includeActions = this.currentPromptContext === 'manage';
1095
- const updatedChoicesBase = this.createProviderChoices(providers, includeActions, statusMap);
1096
- const updatedChoices = [...updatedChoicesBase];
1097
-
1098
- if (!includeActions) {
1099
- updatedChoices.push(
1100
- new inquirer.Separator(),
1101
- { name: `${UIHelper.icons.add} 添加新供应商`, value: '__ADD__' },
1102
- { name: `${UIHelper.icons.list} 供应商管理 (编辑/删除)`, value: '__MANAGE__' },
1103
- { name: `${UIHelper.icons.config} 打开配置文件`, value: '__OPEN_CONFIG__' },
1104
- { name: `${UIHelper.icons.error} 退出`, value: '__EXIT__' }
1105
- );
1106
- }
1107
-
1108
- const previousValue = (() => {
1109
- try {
1110
- return activePrompt.opt.choices?.getChoice(activePrompt.selected)?.value ?? null;
1111
- } catch (err) {
1112
- return null;
1113
- }
1114
- })();
1115
-
1116
- activePrompt.opt.choices = new Choices(updatedChoices, activePrompt.answers);
1117
-
1118
- if (previousValue != null) {
1119
- const newIndex = activePrompt.opt.choices.realChoices.findIndex(choice => choice.value === previousValue);
1120
- if (newIndex >= 0) {
1121
- activePrompt.selected = newIndex;
1122
- } else if (activePrompt.selected >= activePrompt.opt.choices.realLength) {
1123
- activePrompt.selected = Math.max(activePrompt.opt.choices.realLength - 1, 0);
1124
- }
1125
- } else if (activePrompt.selected >= activePrompt.opt.choices.realLength) {
1126
- activePrompt.selected = Math.max(activePrompt.opt.choices.realLength - 1, 0);
1127
- }
1128
-
1129
- if (error) {
1130
- if (this.currentPromptContext === 'selection') {
1131
- activePrompt.opt.message = `请选择要切换的供应商 (总计 ${providers.length} 个,状态检测失败,使用默认配置):`;
1132
- } else if (this.currentPromptContext === 'manage') {
1133
- activePrompt.opt.message = `选择供应商或操作 (总计 ${providers.length} 个,状态检测失败,使用默认配置):`;
1134
- }
1135
- } else {
1136
- if (this.currentPromptContext === 'selection') {
1137
- activePrompt.opt.message = `请选择要切换的供应商 (总计 ${providers.length} 个):`;
1138
- } else if (this.currentPromptContext === 'manage') {
1139
- activePrompt.opt.message = `选择供应商或操作 (总计 ${providers.length} 个):`;
1140
- }
1141
- }
1142
-
1143
- activePrompt.render();
894
+ this._refreshPromptChoices(activePrompt, providers, statusMap, { hasError: Boolean(error) });
1144
895
  }
1145
896
 
1146
897
  _applyIncrementalStatus(providerName, status, refreshToken) {
@@ -1156,10 +907,23 @@ class EnvSwitcher extends BaseCommand {
1156
907
  return;
1157
908
  }
1158
909
 
910
+ // 节流:80ms 内的多次回调合并为一次 render,避免高频刷新导致 ANSI 光标错位
911
+ if (this._refreshTimer) {
912
+ clearTimeout(this._refreshTimer);
913
+ }
914
+ this._refreshTimer = setTimeout(() => {
915
+ this._refreshTimer = null;
916
+ if (this.activeStatusRefresh !== refreshToken) return;
917
+ const activeP = this.activePrompt?.promise?.ui?.activePrompt;
918
+ if (!activeP || activeP.status === 'answered') return;
919
+ const providers = this.filteredProviders || this.configManager.listProviders();
920
+ const statusMap = this.latestStatusMap || {};
921
+ this._refreshPromptChoices(activeP, providers, statusMap);
922
+ }, 80);
923
+ }
924
+
925
+ _refreshPromptChoices(activePrompt, providers, statusMap, options = {}) {
1159
926
  const includeActions = this.currentPromptContext === 'manage';
1160
- // 使用保存的过滤后供应商列表,而不是重新获取全部
1161
- const providers = this.filteredProviders || this.configManager.listProviders();
1162
- const statusMap = this.latestStatusMap || {};
1163
927
  const updatedChoicesBase = this.createProviderChoices(providers, includeActions, statusMap);
1164
928
  const updatedChoices = [...updatedChoicesBase];
1165
929
 
@@ -1173,16 +937,25 @@ class EnvSwitcher extends BaseCommand {
1173
937
  );
1174
938
  }
1175
939
 
1176
- const previousValue = (() => {
1177
- try {
1178
- return activePrompt.opt.choices?.getChoice(activePrompt.selected)?.value ?? null;
1179
- } catch (err) {
1180
- return null;
1181
- }
1182
- })();
940
+ const previousValue = this._getActivePromptPreviousValue(activePrompt);
1183
941
 
1184
942
  activePrompt.opt.choices = new Choices(updatedChoices, activePrompt.answers);
1185
943
 
944
+ this._restorePromptSelection(activePrompt, previousValue);
945
+ activePrompt.opt.message = this._buildStatusPromptMessage(providers.length, options.hasError);
946
+
947
+ activePrompt.render();
948
+ }
949
+
950
+ _getActivePromptPreviousValue(activePrompt) {
951
+ try {
952
+ return activePrompt.opt.choices?.getChoice(activePrompt.selected)?.value ?? null;
953
+ } catch {
954
+ return null;
955
+ }
956
+ }
957
+
958
+ _restorePromptSelection(activePrompt, previousValue) {
1186
959
  if (previousValue != null) {
1187
960
  const newIndex = activePrompt.opt.choices.realChoices.findIndex(choice => choice.value === previousValue);
1188
961
  if (newIndex >= 0) {
@@ -1193,14 +966,17 @@ class EnvSwitcher extends BaseCommand {
1193
966
  } else if (activePrompt.selected >= activePrompt.opt.choices.realLength) {
1194
967
  activePrompt.selected = Math.max(activePrompt.opt.choices.realLength - 1, 0);
1195
968
  }
969
+ }
1196
970
 
971
+ _buildStatusPromptMessage(providerCount, hasError = false) {
972
+ const errorSuffix = hasError ? ',状态检测失败,使用默认配置' : '';
1197
973
  if (this.currentPromptContext === 'selection') {
1198
- activePrompt.opt.message = `请选择要切换的供应商 (总计 ${providers.length} 个):`;
1199
- } else if (this.currentPromptContext === 'manage') {
1200
- activePrompt.opt.message = `选择供应商或操作 (总计 ${providers.length} 个):`;
974
+ return `请选择要切换的供应商 (总计 ${providerCount} 个${errorSuffix}):`;
1201
975
  }
1202
-
1203
- activePrompt.render();
976
+ if (this.currentPromptContext === 'manage') {
977
+ return `选择供应商或操作 (总计 ${providerCount} 个${errorSuffix}):`;
978
+ }
979
+ return '';
1204
980
  }
1205
981
 
1206
982
  async handleManageAction(action) {
@@ -1232,33 +1008,18 @@ class EnvSwitcher extends BaseCommand {
1232
1008
  ]));
1233
1009
  console.log();
1234
1010
 
1235
- const details = [
1236
- ['供应商名称', provider.name],
1237
- ['显示名称', provider.displayName],
1238
- ['认证模式', AUTH_MODE_DISPLAY[provider.authMode] || provider.authMode]
1239
- ];
1240
-
1241
- // 继续添加其他信息
1242
- const baseUrlDisplay = provider.baseUrl
1243
- || (provider.authMode === 'auth_token'
1244
- ? BASE_URL.OFFICIAL_DEFAULT
1245
- : '⚠️ 未设置');
1246
- details.push(
1247
- ['基础URL', baseUrlDisplay],
1248
- ['认证令牌', provider.authToken || '未设置'],
1249
- ['主模型', provider.models?.primary || '未设置'],
1250
- ['快速模型', provider.models?.smallFast || '未设置'],
1251
- ['创建时间', UIHelper.formatTime(provider.createdAt)],
1252
- ['最后使用', UIHelper.formatTime(provider.lastUsed)],
1253
- ['当前状态', provider.current ? '✅ 使用中' : '⚫ 未使用'],
1254
- ['使用次数', provider.usageCount || 0]
1255
- );
1011
+ const details = ProviderDetailsHelper.buildDetailsRows(provider, {
1012
+ authModeDisplay: AUTH_MODE_DISPLAY,
1013
+ baseUrl: BASE_URL,
1014
+ formatTime: UIHelper.formatTime
1015
+ });
1256
1016
 
1257
1017
  console.log(UIHelper.createTable(['项目', '信息'], details));
1258
1018
  console.log();
1259
1019
 
1260
- if (provider.launchArgs && provider.launchArgs.length > 0) {
1261
- console.log(UIHelper.createCard('默认启动参数', provider.launchArgs.join(', '), UIHelper.icons.settings));
1020
+ const launchArgsText = ProviderDetailsHelper.formatLaunchArgs(provider);
1021
+ if (launchArgsText) {
1022
+ console.log(UIHelper.createCard('默认启动参数', launchArgsText, UIHelper.icons.settings));
1262
1023
  console.log();
1263
1024
  }
1264
1025
 
@@ -1275,12 +1036,7 @@ class EnvSwitcher extends BaseCommand {
1275
1036
  type: 'list',
1276
1037
  name: 'action',
1277
1038
  message: '选择操作:',
1278
- choices: [
1279
- { name: `${UIHelper.icons.launch} 立即启动`, value: 'launch' },
1280
- { name: `${UIHelper.icons.edit} 编辑供应商`, value: 'edit' },
1281
- { name: `${UIHelper.icons.delete} 删除供应商`, value: 'remove' },
1282
- { name: `${UIHelper.icons.back} 返回管理列表`, value: 'back' }
1283
- ]
1039
+ choices: ProviderDetailsHelper.buildActionChoices(UIHelper.icons)
1284
1040
  }
1285
1041
  ]);
1286
1042
  } catch (error) {
@@ -1337,104 +1093,7 @@ class EnvSwitcher extends BaseCommand {
1337
1093
 
1338
1094
  // 根据 IDE 类型构建不同的问卷
1339
1095
  const isCodex = provider.ideName === 'codex';
1340
- const questions = [
1341
- {
1342
- type: 'input',
1343
- name: 'name',
1344
- message: '请输入供应商名称 (用于命令行):',
1345
- default: provider.name,
1346
- validate: (input) => {
1347
- const error = validator.validateName(input);
1348
- if (error) return error;
1349
- return true;
1350
- }
1351
- },
1352
- {
1353
- type: 'input',
1354
- name: 'displayName',
1355
- message: '显示名称:',
1356
- default: provider.displayName,
1357
- prefillDefault: true
1358
- },
1359
- {
1360
- type: 'input',
1361
- name: 'alias',
1362
- message: '别名 (用于快速切换):',
1363
- default: provider.alias,
1364
- prefillDefault: true,
1365
- validate: (input) => {
1366
- if (!input) return true; // 别名是可选的
1367
- const error = validator.validateName(input);
1368
- if (error) return error;
1369
- return true;
1370
- }
1371
- }
1372
- ];
1373
-
1374
- // Claude Code 特定的字段
1375
- if (!isCodex) {
1376
- questions.push(
1377
- {
1378
- type: 'list',
1379
- name: 'authMode',
1380
- message: '认证模式:',
1381
- choices: [
1382
- { name: '🔑 ANTHROPIC_API_KEY - 大多数第三方代理使用', value: 'api_key' },
1383
- { name: '🔐 ANTHROPIC_AUTH_TOKEN - 部分服务商使用', value: 'auth_token' }
1384
- ],
1385
- default: provider.authMode || 'api_key'
1386
- },
1387
- {
1388
- type: 'input',
1389
- name: 'primaryModel',
1390
- message: '主模型 (ANTHROPIC_MODEL):',
1391
- default: provider.models?.primary || '',
1392
- prefillDefault: true,
1393
- allowEmpty: true,
1394
- validate: (input) => {
1395
- const error = validator.validateModel(input);
1396
- if (error) return error;
1397
- return true;
1398
- }
1399
- },
1400
- {
1401
- type: 'input',
1402
- name: 'smallFastModel',
1403
- message: '快速模型 (ANTHROPIC_SMALL_FAST_MODEL):',
1404
- default: provider.models?.smallFast || '',
1405
- prefillDefault: true,
1406
- allowEmpty: true,
1407
- validate: (input) => {
1408
- const error = validator.validateModel(input);
1409
- if (error) return error;
1410
- return true;
1411
- }
1412
- }
1413
- );
1414
- }
1415
-
1416
- // 通用字段(Claude 和 Codex 都需要)
1417
- questions.push({
1418
- type: 'input',
1419
- name: 'baseUrl',
1420
- message: isCodex ? '基础URL (OPENAI_BASE_URL):' : '基础URL:',
1421
- default: provider.baseUrl,
1422
- prefillDefault: true
1423
- });
1424
-
1425
- questions.push({
1426
- type: 'input',
1427
- name: 'authToken',
1428
- message: (answers) => {
1429
- if (isCodex) {
1430
- return 'API Key (OPENAI_API_KEY):';
1431
- }
1432
- const envVar = answers.authMode === 'auth_token' ? 'ANTHROPIC_AUTH_TOKEN' : 'ANTHROPIC_API_KEY';
1433
- return `Token (${envVar}):`;
1434
- },
1435
- default: provider.authToken,
1436
- prefillDefault: true
1437
- });
1096
+ const questions = ProviderEditQuestionsHelper.buildQuestions(provider, validator);
1438
1097
 
1439
1098
  let answers;
1440
1099
  try {
@@ -1477,8 +1136,7 @@ class EnvSwitcher extends BaseCommand {
1477
1136
  }
1478
1137
 
1479
1138
  // 更新供应商配置
1480
- provider.displayName = answers.displayName || newName;
1481
- provider.alias = answers.alias || null;
1139
+ provider.displayName = newName;
1482
1140
  provider.baseUrl = answers.baseUrl;
1483
1141
  provider.authToken = answers.authToken;
1484
1142