@pikecode/api-key-manager 2.1.5 → 2.1.7

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/README.md CHANGED
@@ -120,6 +120,7 @@ Claude Code 支持两种认证模式:
120
120
  | Auth Token | `ANTHROPIC_AUTH_TOKEN` + `ANTHROPIC_BASE_URL` | 部分服务商 |
121
121
 
122
122
  Codex CLI 使用 `OPENAI_API_KEY` + `OPENAI_BASE_URL`。
123
+ 如果选择官方网页登录模式,AKM 会按供应商名称缓存 Codex 的官方 Session;同一个官方供应商会复用本地 Session,Session 失效时由 Codex CLI 重新触发浏览器授权。需要多个 OpenAI 官方账号时,为每个账号添加一个不同名称的 Codex 官方网页登录供应商即可。
123
124
 
124
125
  ### 切换供应商
125
126
 
@@ -145,6 +146,9 @@ akm my-provider -q
145
146
 
146
147
  # 以空参数启动
147
148
  akm my-provider --no-args
149
+
150
+ # Codex 官方网页登录模式下清理当前 Session 并重新网页登录
151
+ akm openai-work --relogin
148
152
  ```
149
153
 
150
154
  参数优先级:`--no-args` > `--quick`
@@ -334,6 +338,12 @@ API Key (OPENAI_API_KEY): sk-xxxxxxxx
334
338
  基础URL (OPENAI_BASE_URL): https://api.openai.com
335
339
  ```
336
340
 
341
+ 官方网页登录模式可以配置多个供应商名称,例如 `openai-work`、`openai-personal`。AKM 会把它们的 Session 分开缓存,切换时只恢复对应供应商的 Session。需要强制换号或重新授权时运行:
342
+
343
+ ```bash
344
+ akm openai-work --relogin
345
+ ```
346
+
337
347
  ### 多账号配置
338
348
 
339
349
  ```bash
package/bin/akm.js CHANGED
@@ -104,6 +104,7 @@ program
104
104
  .argument('[provider]', '直接切换到指定供应商')
105
105
  .option('-q, --quick', '快速启动(使用默认或上次的启动参数)')
106
106
  .option('--no-args', '以空参数启动(不使用任何启动参数)')
107
+ .option('--relogin', 'Codex 官方登录模式下清理当前 Session 并重新网页登录')
107
108
  .action(async (provider, options) => {
108
109
  try {
109
110
  await main(provider, options);
@@ -138,13 +139,15 @@ program
138
139
  .option('--claude', '仅显示 Claude Code 供应商')
139
140
  .option('-q, --quick', '快速启动(使用默认或上次的启动参数)')
140
141
  .option('--no-args', '以空参数启动(不使用任何启动参数)')
142
+ .option('--relogin', 'Codex 官方登录模式下清理当前 Session 并重新网页登录')
141
143
  .action(async (provider, options) => {
142
144
  try {
143
145
  const filter = options.codex ? 'codex' : options.claude ? 'claude' : null;
144
146
  await registry.executeCommand('switch', provider, {
145
147
  filter,
146
148
  quick: options.quick,
147
- noArgs: options.noArgs
149
+ noArgs: options.noArgs,
150
+ relogin: options.relogin
148
151
  });
149
152
  } catch (error) {
150
153
  console.error(chalk.red('❌ 切换失败:'), error.message);
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.7",
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,17 @@ 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: answers => (answers.ideName || adder.presetIdeName) === 'codex'
44
+ },
34
45
  {
35
46
  type: 'input',
36
47
  name: 'name',
@@ -39,15 +50,7 @@ async function promptProviderInfo(adder) {
39
50
  const err = validator.validateName(input);
40
51
  return err || true;
41
52
  },
42
- when: answers => {
43
- // 如果选择了官方登录,直接用 "openai-official",不需要输入名称
44
- if ((answers.ideName || adder.presetIdeName) === 'codex' && answers.authMode === 'chatgpt_login') {
45
- return false;
46
- }
47
- return true;
48
- },
49
53
  default: answers => {
50
- // 官方登录模式下返回默认名称
51
54
  if ((answers.ideName || adder.presetIdeName) === 'codex' && answers.authMode === 'chatgpt_login') {
52
55
  return 'openai-official';
53
56
  }
@@ -91,29 +94,6 @@ async function promptProviderInfo(adder) {
91
94
  when: answers => (answers.ideName || adder.presetIdeName) !== 'codex'
92
95
  },
93
96
  // 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
97
  {
118
98
  type: 'input',
119
99
  name: 'baseUrl',
@@ -140,7 +120,7 @@ async function promptProviderInfo(adder) {
140
120
  {
141
121
  type: 'confirm',
142
122
  name: 'confirmCodexLogin',
143
- message: 'Codex 将使用官方 OpenAI 网页登录方式,启动时需要在浏览器中登录。确认继续?',
123
+ message: 'Codex 将使用官方 OpenAI 网页登录方式;首次启动或 Session 失效时需要浏览器登录。确认继续?',
144
124
  default: true,
145
125
  when: answers => (answers.ideName || adder.presetIdeName) === 'codex' && answers.authMode === 'chatgpt_login'
146
126
  },
@@ -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;
@@ -1,9 +1,9 @@
1
1
  const { executeWithEnv } = require('../../utils/env-launcher');
2
2
  const { executeCodexWithEnv } = require('../../utils/codex-launcher');
3
3
 
4
- async function launchProviderProcess(provider, selectedLaunchArgs) {
4
+ async function launchProviderProcess(provider, selectedLaunchArgs, options = {}) {
5
5
  if (provider.ideName === 'codex') {
6
- await executeCodexWithEnv(provider, selectedLaunchArgs);
6
+ await executeCodexWithEnv(provider, selectedLaunchArgs, options);
7
7
  return;
8
8
  }
9
9
 
@@ -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
 
@@ -34,6 +34,7 @@ class EnvSwitcher extends BaseCommand {
34
34
  this.activeStatusRefresh = null;
35
35
  this.filter = null;
36
36
  this.filteredProviders = null;
37
+ this.forceRelogin = false;
37
38
  this._refreshTimer = null;
38
39
  this.providerManager = new ProviderManager(this);
39
40
  }
@@ -183,17 +184,19 @@ class EnvSwitcher extends BaseCommand {
183
184
  const loadingInterval = UIHelper.createLoadingAnimation('正在设置环境...');
184
185
 
185
186
  try {
186
- await markProviderAsCurrent(this.configManager, provider, selectedLaunchArgs);
187
+ const launchProvider = await markProviderAsCurrent(this.configManager, provider, selectedLaunchArgs);
187
188
  UIHelper.clearLoadingAnimation(loadingInterval);
188
189
 
189
190
  console.log(UIHelper.createCard('准备就绪', `环境配置完成,正在启动 🚀 ${ideDisplayName}...`, UIHelper.icons.success));
190
191
  console.log();
191
- await launchProviderProcess(provider, selectedLaunchArgs);
192
+ await launchProviderProcess(launchProvider, selectedLaunchArgs, {
193
+ forceRelogin: this.forceRelogin
194
+ });
192
195
 
193
196
  } catch (error) {
194
197
  UIHelper.clearLoadingAnimation(loadingInterval);
195
198
 
196
- // 如果是 Claude Code 的"没有可恢复的会话"错误,自动移除 --continue 参数并重试
199
+ // Claude Code: 如果是"没有可恢复的会话"错误,自动移除 --continue 参数并重试
197
200
  if (!isCodex &&
198
201
  error.code === 'NO_CONVERSATION_FOUND' &&
199
202
  selectedLaunchArgs.includes('--continue')) {
@@ -204,20 +207,48 @@ class EnvSwitcher extends BaseCommand {
204
207
  const retryLoadingInterval = UIHelper.createLoadingAnimation('正在重新启动(无历史恢复)...');
205
208
 
206
209
  try {
207
- await markProviderAsCurrent(this.configManager, provider, retryArgs);
210
+ const retryProvider = await markProviderAsCurrent(this.configManager, provider, retryArgs);
208
211
  UIHelper.clearLoadingAnimation(retryLoadingInterval);
209
212
 
210
213
  console.log(UIHelper.createCard('准备就绪', `环境配置完成,正在启动 🚀 ${ideDisplayName}(新会话)...`, UIHelper.icons.success));
211
214
  console.log();
212
- await launchProviderProcess(provider, retryArgs);
215
+ await launchProviderProcess(retryProvider, retryArgs, {
216
+ forceRelogin: this.forceRelogin
217
+ });
213
218
  return;
214
219
  } catch (retryError) {
215
220
  UIHelper.clearLoadingAnimation(retryLoadingInterval);
216
221
  throw retryError;
217
222
  }
218
- } else {
219
- throw error;
220
223
  }
224
+
225
+ // Codex: 如果是"会话被锁定"错误,自动移除 resume 参数并重试
226
+ if (isCodex &&
227
+ error.code === 'SESSION_LOCKED' &&
228
+ selectedLaunchArgs.includes('resume')) {
229
+ Logger.info('会话被锁定,自动移除 resume 参数重新启动...');
230
+ console.log();
231
+
232
+ const retryArgs = selectedLaunchArgs.filter(arg => arg !== 'resume');
233
+ const retryLoadingInterval = UIHelper.createLoadingAnimation('正在重新启动(新会话)...');
234
+
235
+ try {
236
+ const retryProvider = await markProviderAsCurrent(this.configManager, provider, retryArgs);
237
+ UIHelper.clearLoadingAnimation(retryLoadingInterval);
238
+
239
+ console.log(UIHelper.createCard('准备就绪', `环境配置完成,正在启动 🚀 ${ideDisplayName}(新会话)...`, UIHelper.icons.success));
240
+ console.log();
241
+ await launchProviderProcess(retryProvider, retryArgs, {
242
+ forceRelogin: this.forceRelogin
243
+ });
244
+ return;
245
+ } catch (retryError) {
246
+ UIHelper.clearLoadingAnimation(retryLoadingInterval);
247
+ throw retryError;
248
+ }
249
+ }
250
+
251
+ throw error;
221
252
  }
222
253
 
223
254
  } catch (error) {
@@ -993,6 +1024,7 @@ class EnvSwitcher extends BaseCommand {
993
1024
  async function switchCommand(providerName, options = {}) {
994
1025
  const switcher = new EnvSwitcher();
995
1026
  switcher.filter = options.filter || null;
1027
+ switcher.forceRelogin = options.relogin === true;
996
1028
 
997
1029
  try {
998
1030
  if (providerName) {
@@ -1,6 +1,7 @@
1
1
  const fs = require('fs-extra');
2
2
  const path = require('path');
3
3
  const os = require('os');
4
+ const crypto = require('crypto');
4
5
  const { validator } = require('./validator');
5
6
  const { writeFileAtomic } = require('./atomic-file');
6
7
 
@@ -8,6 +9,7 @@ const CODEX_DIR_NAME = '.codex';
8
9
  const CONFIG_TOML_FILE = 'config.toml';
9
10
  const AUTH_JSON_FILE = 'auth.json';
10
11
  const BACKUP_DIR_NAME = 'akm-backups';
12
+ const SESSION_CACHE_DIR_NAME = 'akm-session-cache';
11
13
  const BACKUP_LIMIT = 10;
12
14
  let backupSequence = 0;
13
15
 
@@ -298,6 +300,187 @@ async function readExistingAuthJson(authJsonPath) {
298
300
  }
299
301
  }
300
302
 
303
+ async function shouldRemoveAuthJsonForChatGptLogin(authJsonPath) {
304
+ if (!(await fs.pathExists(authJsonPath))) {
305
+ return false;
306
+ }
307
+
308
+ let data;
309
+ try {
310
+ data = await fs.readJson(authJsonPath);
311
+ } catch {
312
+ return false;
313
+ }
314
+
315
+ if (!data || typeof data !== 'object' || Array.isArray(data)) {
316
+ return false;
317
+ }
318
+
319
+ if (data.auth_mode && data.auth_mode !== 'apikey') {
320
+ return false;
321
+ }
322
+
323
+ return data.auth_mode === 'apikey' || Object.prototype.hasOwnProperty.call(data, 'OPENAI_API_KEY');
324
+ }
325
+
326
+ function isChatGptLoginAuth(data) {
327
+ return Boolean(
328
+ data &&
329
+ typeof data === 'object' &&
330
+ !Array.isArray(data) &&
331
+ data.auth_mode &&
332
+ data.auth_mode !== 'apikey' &&
333
+ Object.prototype.hasOwnProperty.call(data, 'tokens')
334
+ );
335
+ }
336
+
337
+ function normalizeSessionKey(sessionKey) {
338
+ if (typeof sessionKey !== 'string' || sessionKey.trim().length === 0) {
339
+ return null;
340
+ }
341
+
342
+ return sessionKey.trim();
343
+ }
344
+
345
+ function buildSessionCacheAuthPath(codexHome, sessionKey = null) {
346
+ const normalizedKey = normalizeSessionKey(sessionKey);
347
+ if (!normalizedKey) {
348
+ return path.join(codexHome, SESSION_CACHE_DIR_NAME, AUTH_JSON_FILE);
349
+ }
350
+
351
+ const safePrefix = normalizedKey
352
+ .toLowerCase()
353
+ .replace(/[^a-z0-9._-]+/g, '-')
354
+ .replace(/^-+|-+$/g, '')
355
+ .slice(0, 48) || 'official';
356
+ const hash = crypto.createHash('sha256').update(normalizedKey).digest('hex').slice(0, 12);
357
+ return path.join(codexHome, SESSION_CACHE_DIR_NAME, `${safePrefix}-${hash}.auth.json`);
358
+ }
359
+
360
+ async function readJsonObjectIfExists(filePath) {
361
+ if (!(await fs.pathExists(filePath))) {
362
+ return null;
363
+ }
364
+
365
+ const data = await fs.readJson(filePath);
366
+ if (!data || typeof data !== 'object' || Array.isArray(data)) {
367
+ return null;
368
+ }
369
+
370
+ return data;
371
+ }
372
+
373
+ async function cacheChatGptLoginAuth(codexHome, authData, sessionKey = null) {
374
+ if (!isChatGptLoginAuth(authData)) {
375
+ return null;
376
+ }
377
+
378
+ const cacheAuthPath = buildSessionCacheAuthPath(codexHome, sessionKey);
379
+ const cacheDir = path.dirname(cacheAuthPath);
380
+ await fs.ensureDir(cacheDir);
381
+ await setSecureDirectoryPermissions(cacheDir);
382
+ await writeFileAtomic(cacheAuthPath, JSON.stringify(authData, null, 2), {
383
+ encoding: 'utf8',
384
+ mode: 0o600
385
+ });
386
+ await setSecurePermissions(cacheAuthPath);
387
+ return cacheAuthPath;
388
+ }
389
+
390
+ async function cacheCurrentChatGptLoginAuth(codexHome, authJsonPath, sessionKey = null) {
391
+ let authData;
392
+ try {
393
+ authData = await readJsonObjectIfExists(authJsonPath);
394
+ } catch {
395
+ return null;
396
+ }
397
+
398
+ return await cacheChatGptLoginAuth(codexHome, authData, sessionKey);
399
+ }
400
+
401
+ async function findCachedChatGptLoginAuth(codexHome, sessionKey = null) {
402
+ const candidatePaths = [];
403
+ if (normalizeSessionKey(sessionKey)) {
404
+ candidatePaths.push(buildSessionCacheAuthPath(codexHome, sessionKey));
405
+ } else {
406
+ candidatePaths.push(buildSessionCacheAuthPath(codexHome));
407
+ }
408
+
409
+ for (const cacheAuthPath of candidatePaths) {
410
+ try {
411
+ const data = await readJsonObjectIfExists(cacheAuthPath);
412
+ if (isChatGptLoginAuth(data)) {
413
+ return cacheAuthPath;
414
+ }
415
+ } catch {
416
+ // 忽略损坏缓存,继续尝试其他来源。
417
+ }
418
+ }
419
+
420
+ return null;
421
+ }
422
+
423
+ async function clearCachedChatGptLoginAuth(codexHome, sessionKey = null) {
424
+ const targetPaths = [buildSessionCacheAuthPath(codexHome, sessionKey)];
425
+ if (normalizeSessionKey(sessionKey)) {
426
+ targetPaths.push(buildSessionCacheAuthPath(codexHome));
427
+ }
428
+
429
+ await Promise.all([...new Set(targetPaths)].map(filePath => fs.remove(filePath)));
430
+ }
431
+
432
+ async function shouldRemoveAuthJsonForRelogin(authJsonPath) {
433
+ if (!(await fs.pathExists(authJsonPath))) {
434
+ return false;
435
+ }
436
+
437
+ try {
438
+ const data = await readJsonObjectIfExists(authJsonPath);
439
+ return isChatGptLoginAuth(data) || await shouldRemoveAuthJsonForChatGptLogin(authJsonPath);
440
+ } catch {
441
+ return false;
442
+ }
443
+ }
444
+
445
+ async function findLatestChatGptLoginAuthBackup(codexHome) {
446
+ const backupRoot = path.join(codexHome, BACKUP_DIR_NAME);
447
+ if (!(await fs.pathExists(backupRoot))) {
448
+ return null;
449
+ }
450
+
451
+ const backupDirectories = (await fs.readdir(backupRoot))
452
+ .filter(name => name.startsWith('backup-'))
453
+ .sort()
454
+ .reverse();
455
+
456
+ for (const backupName of backupDirectories) {
457
+ const backupAuthPath = path.join(backupRoot, backupName, AUTH_JSON_FILE);
458
+ if (!(await fs.pathExists(backupAuthPath))) {
459
+ continue;
460
+ }
461
+
462
+ try {
463
+ const data = await fs.readJson(backupAuthPath);
464
+ if (isChatGptLoginAuth(data)) {
465
+ return backupAuthPath;
466
+ }
467
+ } catch {
468
+ // 跳过损坏的备份,继续寻找更早的可用登录态。
469
+ }
470
+ }
471
+
472
+ return null;
473
+ }
474
+
475
+ async function findChatGptLoginAuthSource(codexHome, sessionKey = null) {
476
+ const cachedAuth = await findCachedChatGptLoginAuth(codexHome, sessionKey);
477
+ if (cachedAuth || normalizeSessionKey(sessionKey)) {
478
+ return cachedAuth;
479
+ }
480
+
481
+ return await findLatestChatGptLoginAuthBackup(codexHome);
482
+ }
483
+
301
484
  async function readFileSnapshot(filePath) {
302
485
  if (!(await fs.pathExists(filePath))) {
303
486
  return { exists: false, content: null, mode: 0o600 };
@@ -361,7 +544,7 @@ async function applyCodexConfig(config, options = {}) {
361
544
  };
362
545
 
363
546
  // 所有旧文件必须在任何写入发生前完成校验和目标内容计算。
364
- await readExistingAuthJson(authJsonPath);
547
+ const existingAuthJson = await readExistingAuthJson(authJsonPath);
365
548
  const authJsonContent = buildAuthJson(config.authToken);
366
549
  let nextConfigToml = null;
367
550
  const existingToml = snapshots.configToml.exists
@@ -377,6 +560,9 @@ async function applyCodexConfig(config, options = {}) {
377
560
  }
378
561
  }
379
562
 
563
+ // API Key 模式会覆盖 auth.json,先持久缓存官方网页登录态,避免备份轮转后丢失。
564
+ await cacheChatGptLoginAuth(codexHome, existingAuthJson);
565
+
380
566
  // 修改用户 Codex 文件前保留最近备份,便于恢复登录态和自定义配置。
381
567
  await backupCodexFiles(codexHome);
382
568
 
@@ -415,13 +601,33 @@ async function clearCodexAkmConfig(options = {}) {
415
601
  try {
416
602
  const codexHome = await ensureCodexHome(options.codexHome);
417
603
  const { configTomlPath, authJsonPath } = buildCodexPaths(codexHome);
604
+ const sessionKey = normalizeSessionKey(options.sessionKey);
605
+ const forceRelogin = options.forceRelogin === true;
418
606
 
419
607
  // 备份当前配置
420
608
  await backupCodexFiles(codexHome);
609
+ if (forceRelogin) {
610
+ await clearCachedChatGptLoginAuth(codexHome, sessionKey);
611
+ } else {
612
+ await cacheCurrentChatGptLoginAuth(codexHome, authJsonPath, sessionKey);
613
+ }
421
614
 
422
- // 如果 auth.json 存在就删除它(chatgpt_login 模式不需要)
423
- if (await fs.pathExists(authJsonPath)) {
424
- await fs.remove(authJsonPath);
615
+ // 只移除 API Key 认证文件,避免破坏 Codex 官方网页登录态。
616
+ const shouldRemoveAuthJson = forceRelogin
617
+ ? await shouldRemoveAuthJsonForRelogin(authJsonPath)
618
+ : await shouldRemoveAuthJsonForChatGptLogin(authJsonPath);
619
+
620
+ if (shouldRemoveAuthJson) {
621
+ const authSourcePath = forceRelogin
622
+ ? null
623
+ : await findChatGptLoginAuthSource(codexHome, sessionKey);
624
+ if (authSourcePath) {
625
+ await fs.copy(authSourcePath, authJsonPath);
626
+ await setSecurePermissions(authJsonPath);
627
+ await cacheCurrentChatGptLoginAuth(codexHome, authJsonPath, sessionKey);
628
+ } else {
629
+ await fs.remove(authJsonPath);
630
+ }
425
631
  }
426
632
 
427
633
  // 清理 config.toml 中的 AKM 配置
@@ -441,12 +647,19 @@ async function clearCodexAkmConfig(options = {}) {
441
647
  }
442
648
  }
443
649
 
650
+ async function cacheCodexOfficialSession(options = {}) {
651
+ const codexHome = await ensureCodexHome(options.codexHome);
652
+ const { authJsonPath } = buildCodexPaths(codexHome);
653
+ return await cacheCurrentChatGptLoginAuth(codexHome, authJsonPath, options.sessionKey);
654
+ }
655
+
444
656
  module.exports = {
445
657
  resolveCodexHome,
446
658
  buildCodexPaths,
447
659
  readCodexFiles,
448
660
  applyCodexConfig,
449
661
  clearCodexAkmConfig,
662
+ cacheCodexOfficialSession,
450
663
  backupCodexFiles,
451
664
  removeTopLevelApiBaseUrl,
452
665
  removeAkmModelProvider,
@@ -1,6 +1,10 @@
1
1
  const spawn = require('cross-spawn');
2
2
  const { sanitizeEnvValue, clearTerminal } = require('./env-utils');
3
- const { applyCodexConfig, clearCodexAkmConfig } = require('./codex-files');
3
+ const {
4
+ applyCodexConfig,
5
+ clearCodexAkmConfig,
6
+ cacheCodexOfficialSession
7
+ } = require('./codex-files');
4
8
  const { assertSupportedLaunchArgs } = require('./launch-args');
5
9
  const { validator } = require('./validator');
6
10
 
@@ -53,9 +57,11 @@ function buildCodexEnvVariables(config) {
53
57
  * 使用环境变量注入方式执行 Codex CLI
54
58
  * @param {object} config - 供应商配置
55
59
  * @param {string[]} launchArgs - 启动参数
60
+ * @param {object} options - 启动选项
61
+ * @param {boolean} options.forceRelogin - 是否强制清理官方登录态并重新网页登录
56
62
  * @returns {Promise<void>}
57
63
  */
58
- async function executeCodexWithEnv(config, launchArgs = []) {
64
+ async function executeCodexWithEnv(config, launchArgs = [], launchOptions = {}) {
59
65
  if (!config || config.ideName !== 'codex') {
60
66
  throw new Error('无效的 Codex 供应商配置');
61
67
  }
@@ -80,7 +86,10 @@ async function executeCodexWithEnv(config, launchArgs = []) {
80
86
  await applyCodexConfig(config);
81
87
  } else if (authMode === 'chatgpt_login') {
82
88
  // chatgpt_login 模式:清理 AKM 的配置,让 Codex 使用官方登录
83
- await clearCodexAkmConfig();
89
+ await clearCodexAkmConfig({
90
+ sessionKey: config.name,
91
+ forceRelogin: launchOptions.forceRelogin === true
92
+ });
84
93
  }
85
94
 
86
95
  // 处理参数:子命令放前面,选项放后面
@@ -99,16 +108,47 @@ async function executeCodexWithEnv(config, launchArgs = []) {
99
108
 
100
109
  return new Promise((resolve, reject) => {
101
110
  const child = spawn('codex', args, {
102
- stdio: 'inherit',
111
+ stdio: ['inherit', 'inherit', 'pipe'],
103
112
  env,
104
113
  shell: false
105
114
  });
106
115
 
107
- child.on('close', (code, signal) => {
116
+ let stderrOutput = '';
117
+
118
+ // 捕获 stderr 用于检查错误信息
119
+ child.stderr.on('data', (data) => {
120
+ const output = data.toString();
121
+ stderrOutput += output;
122
+ process.stderr.write(data);
123
+ });
124
+
125
+ child.on('close', async (code, signal) => {
108
126
  if (code === 0 || code === 130 || signal === 'SIGINT') {
127
+ try {
128
+ if (authMode === 'chatgpt_login') {
129
+ await cacheCodexOfficialSession({ sessionKey: config.name });
130
+ }
131
+ } catch (error) {
132
+ reject(new Error(`保存 Codex 官方登录 Session 失败: ${error.message}`));
133
+ return;
134
+ }
109
135
  resolve();
110
136
  } else {
111
- reject(new Error(`Codex CLI 异常退出,退出代码: ${code}\n提示: 请检查 API 配置是否正确`));
137
+ // 检查是否是"会话被锁定"或"已有活跃写入者"的错误
138
+ const errorOutput = stderrOutput.toLowerCase();
139
+ const isResumeLaunch = rawArgs.includes('resume');
140
+ const isSessionLockedError =
141
+ errorOutput.includes('already has an active writer') ||
142
+ errorOutput.includes('failed to resume session') ||
143
+ errorOutput.includes('thread already has an active');
144
+
145
+ if (isSessionLockedError || (isResumeLaunch && code === 1)) {
146
+ const error = new Error('Codex 会话被锁定或无法恢复\n提示: 已尝试不带 resume 参数重新开始');
147
+ error.code = 'SESSION_LOCKED';
148
+ reject(error);
149
+ } else {
150
+ reject(new Error(`Codex CLI 异常退出,退出代码: ${code}\n提示: 请检查 API 配置是否正确`));
151
+ }
112
152
  }
113
153
  });
114
154