@pikecode/api-key-manager 2.1.5 → 2.1.6

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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pikecode/api-key-manager",
3
- "version": "2.1.5",
3
+ "version": "2.1.6",
4
4
  "description": "A CLI tool for managing and switching multiple API provider configurations",
5
5
  "main": "src/index.js",
6
6
  "bin": {
@@ -31,6 +31,27 @@ async function promptProviderInfo(adder) {
31
31
  default: adder.presetIdeName || 'claude',
32
32
  when: () => !adder.presetIdeName
33
33
  },
34
+ {
35
+ type: 'list',
36
+ name: 'authMode',
37
+ message: UI_MESSAGES.SELECT_CODEX_AUTH_MODE,
38
+ choices: [
39
+ { name: UI_MESSAGES.AUTH_MODE_CODEX_API_KEY, value: 'api_key' },
40
+ { name: UI_MESSAGES.AUTH_MODE_CODEX_CHATGPT_LOGIN, value: 'chatgpt_login' }
41
+ ],
42
+ default: 'api_key',
43
+ when: async answers => {
44
+ const isCodex = (answers.ideName || adder.presetIdeName) === 'codex';
45
+ if (!isCodex) return false;
46
+ try {
47
+ await adder.configManager.ensureLoaded();
48
+ const hasOfficialConfig = adder.configManager.getProvider('openai-official');
49
+ return !hasOfficialConfig;
50
+ } catch {
51
+ return true;
52
+ }
53
+ }
54
+ },
34
55
  {
35
56
  type: 'input',
36
57
  name: 'name',
@@ -91,29 +112,6 @@ async function promptProviderInfo(adder) {
91
112
  when: answers => (answers.ideName || adder.presetIdeName) !== 'codex'
92
113
  },
93
114
  // Codex‑specific prompts (manual entry)
94
- {
95
- type: 'list',
96
- name: 'authMode',
97
- message: UI_MESSAGES.SELECT_CODEX_AUTH_MODE,
98
- choices: [
99
- { name: UI_MESSAGES.AUTH_MODE_CODEX_API_KEY, value: 'api_key' },
100
- { name: UI_MESSAGES.AUTH_MODE_CODEX_CHATGPT_LOGIN, value: 'chatgpt_login' }
101
- ],
102
- default: 'api_key',
103
- when: async answers => {
104
- const isCodex = (answers.ideName || adder.presetIdeName) === 'codex';
105
- if (!isCodex) return false;
106
- // 如果已经有官方配置了,就用 api_key 模式,不提示选择
107
- try {
108
- await adder.configManager.ensureLoaded();
109
- const hasOfficialConfig = adder.configManager.getProvider('openai-official');
110
- return !hasOfficialConfig;
111
- } catch {
112
- // 如果加载失败,仍然显示选择提示
113
- return true;
114
- }
115
- }
116
- },
117
115
  {
118
116
  type: 'input',
119
117
  name: 'baseUrl',
@@ -77,6 +77,11 @@ class ProviderAdder extends BaseCommand {
77
77
  answers.name = 'openai-official';
78
78
  }
79
79
 
80
+ if (answers.authMode === 'chatgpt_login' && answers.confirmCodexLogin === false) {
81
+ Logger.info('已取消添加 Codex 官方登录配置');
82
+ return;
83
+ }
84
+
80
85
  answers.codexFiles = null;
81
86
 
82
87
  // Codex 启动参数配置
@@ -8,6 +8,8 @@ class ProviderEditQuestionsHelper {
8
8
 
9
9
  if (!isCodex) {
10
10
  questions.push(...this.buildClaudeQuestions(provider, validator));
11
+ } else {
12
+ questions.push(this.buildCodexAuthModeQuestion(provider));
11
13
  }
12
14
 
13
15
  questions.push(
@@ -86,6 +88,19 @@ class ProviderEditQuestionsHelper {
86
88
  ];
87
89
  }
88
90
 
91
+ static buildCodexAuthModeQuestion(provider) {
92
+ return {
93
+ type: 'list',
94
+ name: 'authMode',
95
+ message: 'Codex 认证方式:',
96
+ choices: [
97
+ { name: '🔑 API Key - 使用 OpenAI API Key', value: 'api_key' },
98
+ { name: '🌐 官方网页登录 - 使用 OpenAI 账号登录', value: 'chatgpt_login' }
99
+ ],
100
+ default: provider.authMode || 'api_key'
101
+ };
102
+ }
103
+
89
104
  static buildBaseUrlQuestion(provider, isCodex, validator) {
90
105
  return {
91
106
  type: 'input',
@@ -93,6 +108,7 @@ class ProviderEditQuestionsHelper {
93
108
  message: isCodex ? '基础URL (OPENAI_BASE_URL):' : '基础URL:',
94
109
  default: provider.baseUrl,
95
110
  prefillDefault: true,
111
+ when: answers => !isCodex || (answers.authMode || provider.authMode || 'api_key') !== 'chatgpt_login',
96
112
  validate: input => {
97
113
  if (typeof validator?.validateUrl !== 'function') return true;
98
114
  return validator.validateUrl(input, false) || true;
@@ -113,6 +129,7 @@ class ProviderEditQuestionsHelper {
113
129
  },
114
130
  default: provider.authToken,
115
131
  prefillDefault: true,
132
+ when: answers => !isCodex || (answers.authMode || provider.authMode || 'api_key') !== 'chatgpt_login',
116
133
  validate: input => {
117
134
  if (typeof validator?.validateToken !== 'function') return true;
118
135
  return validator.validateToken(input) || true;
@@ -11,7 +11,23 @@ async function launchProviderProcess(provider, selectedLaunchArgs) {
11
11
  }
12
12
 
13
13
  async function markProviderAsCurrent(configManager, provider, lastUsedArgs = []) {
14
- await configManager.activateProvider(provider.name, lastUsedArgs);
14
+ if (typeof configManager.load === 'function') {
15
+ await configManager.load(true);
16
+ }
17
+
18
+ const latestProvider =
19
+ typeof configManager.getProvider === 'function'
20
+ ? configManager.getProvider(provider.name)
21
+ : provider;
22
+
23
+ if (!latestProvider) {
24
+ throw new Error(`供应商 '${provider.name}' 不存在\n使用 'akm list' 查看所有已配置的供应商`);
25
+ }
26
+
27
+ await configManager.activateProvider(latestProvider.name, lastUsedArgs);
28
+ return typeof configManager.getProvider === 'function'
29
+ ? configManager.getProvider(latestProvider.name)
30
+ : latestProvider;
15
31
  }
16
32
 
17
33
  module.exports = {
@@ -139,7 +139,11 @@ class ProviderManager {
139
139
  smallFast: answers.smallFastModel || null
140
140
  };
141
141
  } else {
142
- updatedProvider.authMode = null;
142
+ updatedProvider.authMode = answers.authMode || provider.authMode || 'api_key';
143
+ if (updatedProvider.authMode === 'chatgpt_login') {
144
+ updatedProvider.baseUrl = null;
145
+ updatedProvider.authToken = null;
146
+ }
143
147
  updatedProvider.models = null;
144
148
  }
145
149
 
@@ -183,17 +183,17 @@ class EnvSwitcher extends BaseCommand {
183
183
  const loadingInterval = UIHelper.createLoadingAnimation('正在设置环境...');
184
184
 
185
185
  try {
186
- await markProviderAsCurrent(this.configManager, provider, selectedLaunchArgs);
186
+ const launchProvider = await markProviderAsCurrent(this.configManager, provider, selectedLaunchArgs);
187
187
  UIHelper.clearLoadingAnimation(loadingInterval);
188
188
 
189
189
  console.log(UIHelper.createCard('准备就绪', `环境配置完成,正在启动 🚀 ${ideDisplayName}...`, UIHelper.icons.success));
190
190
  console.log();
191
- await launchProviderProcess(provider, selectedLaunchArgs);
191
+ await launchProviderProcess(launchProvider, selectedLaunchArgs);
192
192
 
193
193
  } catch (error) {
194
194
  UIHelper.clearLoadingAnimation(loadingInterval);
195
195
 
196
- // 如果是 Claude Code 的"没有可恢复的会话"错误,自动移除 --continue 参数并重试
196
+ // Claude Code: 如果是"没有可恢复的会话"错误,自动移除 --continue 参数并重试
197
197
  if (!isCodex &&
198
198
  error.code === 'NO_CONVERSATION_FOUND' &&
199
199
  selectedLaunchArgs.includes('--continue')) {
@@ -204,20 +204,44 @@ class EnvSwitcher extends BaseCommand {
204
204
  const retryLoadingInterval = UIHelper.createLoadingAnimation('正在重新启动(无历史恢复)...');
205
205
 
206
206
  try {
207
- await markProviderAsCurrent(this.configManager, provider, retryArgs);
207
+ const retryProvider = await markProviderAsCurrent(this.configManager, provider, retryArgs);
208
208
  UIHelper.clearLoadingAnimation(retryLoadingInterval);
209
209
 
210
210
  console.log(UIHelper.createCard('准备就绪', `环境配置完成,正在启动 🚀 ${ideDisplayName}(新会话)...`, UIHelper.icons.success));
211
211
  console.log();
212
- await launchProviderProcess(provider, retryArgs);
212
+ await launchProviderProcess(retryProvider, retryArgs);
213
+ return;
214
+ } catch (retryError) {
215
+ UIHelper.clearLoadingAnimation(retryLoadingInterval);
216
+ throw retryError;
217
+ }
218
+ }
219
+
220
+ // Codex: 如果是"会话被锁定"错误,自动移除 resume 参数并重试
221
+ if (isCodex &&
222
+ error.code === 'SESSION_LOCKED' &&
223
+ selectedLaunchArgs.includes('resume')) {
224
+ Logger.info('会话被锁定,自动移除 resume 参数重新启动...');
225
+ console.log();
226
+
227
+ const retryArgs = selectedLaunchArgs.filter(arg => arg !== 'resume');
228
+ const retryLoadingInterval = UIHelper.createLoadingAnimation('正在重新启动(新会话)...');
229
+
230
+ try {
231
+ const retryProvider = await markProviderAsCurrent(this.configManager, provider, retryArgs);
232
+ UIHelper.clearLoadingAnimation(retryLoadingInterval);
233
+
234
+ console.log(UIHelper.createCard('准备就绪', `环境配置完成,正在启动 🚀 ${ideDisplayName}(新会话)...`, UIHelper.icons.success));
235
+ console.log();
236
+ await launchProviderProcess(retryProvider, retryArgs);
213
237
  return;
214
238
  } catch (retryError) {
215
239
  UIHelper.clearLoadingAnimation(retryLoadingInterval);
216
240
  throw retryError;
217
241
  }
218
- } else {
219
- throw error;
220
242
  }
243
+
244
+ throw error;
221
245
  }
222
246
 
223
247
  } catch (error) {
@@ -298,6 +298,29 @@ async function readExistingAuthJson(authJsonPath) {
298
298
  }
299
299
  }
300
300
 
301
+ async function shouldRemoveAuthJsonForChatGptLogin(authJsonPath) {
302
+ if (!(await fs.pathExists(authJsonPath))) {
303
+ return false;
304
+ }
305
+
306
+ let data;
307
+ try {
308
+ data = await fs.readJson(authJsonPath);
309
+ } catch {
310
+ return false;
311
+ }
312
+
313
+ if (!data || typeof data !== 'object' || Array.isArray(data)) {
314
+ return false;
315
+ }
316
+
317
+ if (data.auth_mode && data.auth_mode !== 'apikey') {
318
+ return false;
319
+ }
320
+
321
+ return data.auth_mode === 'apikey' || Object.prototype.hasOwnProperty.call(data, 'OPENAI_API_KEY');
322
+ }
323
+
301
324
  async function readFileSnapshot(filePath) {
302
325
  if (!(await fs.pathExists(filePath))) {
303
326
  return { exists: false, content: null, mode: 0o600 };
@@ -419,8 +442,8 @@ async function clearCodexAkmConfig(options = {}) {
419
442
  // 备份当前配置
420
443
  await backupCodexFiles(codexHome);
421
444
 
422
- // 如果 auth.json 存在就删除它(chatgpt_login 模式不需要)
423
- if (await fs.pathExists(authJsonPath)) {
445
+ // 只移除 API Key 认证文件,避免破坏 Codex 官方网页登录态。
446
+ if (await shouldRemoveAuthJsonForChatGptLogin(authJsonPath)) {
424
447
  await fs.remove(authJsonPath);
425
448
  }
426
449
 
@@ -99,16 +99,39 @@ async function executeCodexWithEnv(config, launchArgs = []) {
99
99
 
100
100
  return new Promise((resolve, reject) => {
101
101
  const child = spawn('codex', args, {
102
- stdio: 'inherit',
102
+ stdio: ['inherit', 'inherit', 'pipe'],
103
103
  env,
104
104
  shell: false
105
105
  });
106
106
 
107
+ let stderrOutput = '';
108
+
109
+ // 捕获 stderr 用于检查错误信息
110
+ child.stderr.on('data', (data) => {
111
+ const output = data.toString();
112
+ stderrOutput += output;
113
+ process.stderr.write(data);
114
+ });
115
+
107
116
  child.on('close', (code, signal) => {
108
117
  if (code === 0 || code === 130 || signal === 'SIGINT') {
109
118
  resolve();
110
119
  } else {
111
- reject(new Error(`Codex CLI 异常退出,退出代码: ${code}\n提示: 请检查 API 配置是否正确`));
120
+ // 检查是否是"会话被锁定"或"已有活跃写入者"的错误
121
+ const errorOutput = stderrOutput.toLowerCase();
122
+ const isResumeLaunch = rawArgs.includes('resume');
123
+ const isSessionLockedError =
124
+ errorOutput.includes('already has an active writer') ||
125
+ errorOutput.includes('failed to resume session') ||
126
+ errorOutput.includes('thread already has an active');
127
+
128
+ if (isSessionLockedError || (isResumeLaunch && code === 1)) {
129
+ const error = new Error('Codex 会话被锁定或无法恢复\n提示: 已尝试不带 resume 参数重新开始');
130
+ error.code = 'SESSION_LOCKED';
131
+ reject(error);
132
+ } else {
133
+ reject(new Error(`Codex CLI 异常退出,退出代码: ${code}\n提示: 请检查 API 配置是否正确`));
134
+ }
112
135
  }
113
136
  });
114
137