@pikecode/api-key-manager 2.2.0 → 2.2.2

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/CHANGELOG.md ADDED
@@ -0,0 +1,45 @@
1
+ # 修改记录
2
+
3
+ 记录项目的功能、修复和兼容性变化。以下历史条目依据 Git 提交补录,不代表已核实 npm 发布状态。
4
+
5
+ ## 未发布(当前目标版本 2.2.2)
6
+
7
+ ### 功能与行为调整
8
+
9
+ - 支持同一 Codex 供应商多窗口运行,以及不同供应商同时运行。
10
+ - 按供应商隔离认证、配置和 SQLite 运行状态,不再覆盖根目录认证或使用全局单窗口锁。
11
+ - 共享会话文件,支持从不同供应商的历史创建新分支;恢复前确认目标供应商,保留原始对话。
12
+ - 迁移同名官方 Session 缓存;重新认证、修改认证和删除账号只受该供应商的运行窗口约束。
13
+ - 更新 README,说明目录布局、历史分叉及异常退出记录的处理。
14
+
15
+ ### 兼容性说明
16
+
17
+ - 从历史继续需要 Codex CLI 支持 `fork`,已用 0.166.0 的原生接口做离线验证。
18
+ - 直接运行原生 `codex` 仍使用原配置;使用 AKM 隔离配置需通过 `akm <供应商>` 启动。
19
+ - 首次复制到供应商目录的配置不会自动跟随根配置更新;共享历史、技能和插件目录保留在原位置。
20
+
21
+ ### 维护
22
+
23
+ - 新增项目维护约定:每次修改同步记录变更,按影响评估版本升级。
24
+ - 保留用户指定的 2.2.2 目标版本,同步锁文件版本元数据。
25
+ - 将修改记录加入 npm 包文件清单,并在 README 中提供入口。
26
+ - 多窗口功能验证:58 个测试套件、591 项测试及项目完整检查通过。
27
+
28
+ ## 2.2.1(历史补录)
29
+
30
+ - 更新包版本至 2.2.1;对应版本提交未包含其他代码变更。
31
+
32
+ ## 2.2.0(历史补录)
33
+
34
+ - 加固 Codex Session 保存与认证切换回滚,修复自动重试时重复清理认证。
35
+ - 未知历史恢复错误保留实际原因,交互确认后才新开会话。
36
+ - 修复测试写入真实用户配置的问题,减少逐层重复报错。
37
+ - 更新检查缓存 24 小时;更新重启后等待新版进程结束,避免重复执行命令。
38
+ - 配置读写使用短时锁和内容冲突检查,降低并发覆盖风险。
39
+ - 删除官方供应商时清理对应 Session 缓存,失败时恢复。
40
+ - 增加真实命令入口、并发保存和删除回滚测试,以及三平台 CI 矩阵。
41
+ - 此版本曾采用 Codex 目录单窗口锁;当前目标版本已改为供应商隔离和多窗口运行。
42
+
43
+ ## 2.1.9(历史补录)
44
+
45
+ - 增加 Claude Code 继续历史失败时的回退处理;后续版本收窄自动重试条件,避免把未知错误误判为无历史。
package/README.md CHANGED
@@ -207,6 +207,8 @@ akm remove my-provider
207
207
  3. 预览将要删除的供应商列表
208
208
  4. 最终确认后批量删除
209
209
 
210
+ 删除 Codex 官方网页登录供应商时,会同时清理该名称的旧 Session 缓存和独立目录中的认证;以后添加同名供应商需要重新认证。只有该供应商仍有窗口运行时才阻止删除,其他供应商不受影响。删除失败会恢复认证;该操作不会撤销服务端 Token,也不会清理共享历史、历史备份或其他账号的缓存。
211
+
210
212
  ### 编辑供应商
211
213
 
212
214
  ```bash
@@ -386,16 +388,26 @@ akm switch openai-work --relogin
386
388
 
387
389
  ### 会话恢复与运行保护
388
390
 
389
- Codex 的不同账号共享历史目录,但 AKM 会对同一 `CODEX_HOME`(默认 `~/.codex`)限制同时运行一个 Codex 会话,防止认证信息互相覆盖。退出当前会话后再切换账号。该保护仅覆盖通过 AKM 启动的进程,请勿同时用原生 `codex` 命令切换同一目录的认证。
391
+ 同一供应商可以打开多个窗口,不同供应商也可以同时运行。一个窗口退出当前 Codex 会话后,可以再启动任意供应商,不影响其他窗口。
392
+
393
+ AKM 使用 `<CODEX_HOME>/akm-providers/<供应商标识>/` 保存各供应商独立的 `auth.json`、`config.toml` 和 SQLite 运行状态,根目录默认为 `~/.codex`。不再覆盖根目录认证,也不再使用旧的 `.akm-launch.lock` 限制窗口数量。直接运行原生 `codex` 仍使用其原有配置;请通过 `akm <供应商>` 使用隔离配置。
394
+
395
+ 首次启动会复制根目录的配置与 `AGENTS.md`,并迁移同名官方 Session 缓存;不会继承其他账号的认证。后续 Codex 刷新的 Token 直接保存在该供应商目录,不再在窗口退出时覆盖回共享认证文件。根目录后续配置修改不会自动覆盖已创建的独立配置。
390
396
 
391
- 正常退出会释放目录锁;强制杀死 AKM 后可能留下 `.akm-launch.lock`。只有确认该目录相关的 AKM 和 Codex 进程都已退出,才可手动删除此锁文件后重试。
397
+ `sessions` 和 `archived_sessions` 通过目录链接共享,历史文件无需搬迁;SQLite 数据库与认证保持隔离。已有的 `skills`、`rules`、`plugins` 目录也会链接到原位置。Windows 使用目录联接(junction)。
392
398
 
393
- `--relogin` 只在首次启动时清理本地认证;历史恢复失败后的自动重试会保留新登录态。该选项不会撤销服务端 Token 或清理浏览器登录状态。
399
+ 选择“从历史继续”后,AKM 列出共享历史(包含其他供应商和项目),显示时间、目录、原模型供应商和对话 ID。确认目标供应商后使用 `codex fork <ID>` 创建新对话,原历史保持不变,多个窗口可以从同一历史分叉。跨供应商继续会向新供应商发送恢复所需的上下文,因此默认不确认;非交互终端不会自动选择历史。此功能需要支持 `codex fork` 的 Codex CLI,已使用 0.166.0 的原生接口验证。分叉失败会显示原因,不静默丢弃历史。
394
400
 
395
- 恢复历史时,明确的历史缺失或锁定错误会自动改为新会话;其他退出码为 1 的错误会保留原因,在交互终端询问是否新开会话,默认不重试。非交互环境直接返回错误。
401
+ 同一供应商的首次网页登录未完成时,先完成该窗口认证,再打开更多窗口。`--relogin`、修改密钥或认证配置、删除官方账号需要先退出该供应商的所有窗口,其他供应商可继续运行。该选项不会撤销服务端 Token 或清理浏览器登录状态。
402
+
403
+ 正常退出会清除运行记录;强杀后可能在供应商目录的 `.akm-runs/` 留下记录,或留下短时 `.akm-settings.lock`。仅在确认该供应商相关 AKM/Codex 进程均已退出后清理这些记录;不要删除历史目录。
396
404
 
397
405
  更新检查结果(包括失败结果)缓存在 `~/.akm-update-check.json`,24 小时内不重复请求 npm。可通过 `CC_NO_UPDATE_CHECK=1` 禁用检查。
398
406
 
407
+ 选择更新并重启后,旧进程会等待新版命令结束,再以相同退出码退出,不重复执行原命令。重启失败时会提示手动重新运行。
408
+
409
+ 配置读写使用短时文件锁,多个终端同时修改时会提示重试,避免后保存的配置覆盖先前修改。异常强杀后若遗留 `~/.akm-config.json.lock`,须确认相关 AKM 进程已退出后再清理。
410
+
399
411
  ### 多账号配置
400
412
 
401
413
  ```bash
@@ -478,7 +490,7 @@ akm personal -q
478
490
  **切换原理:**
479
491
 
480
492
  - **Claude Code** — 通过环境变量注入启动子进程,不修改配置文件,切换只在当前会话生效
481
- - **Codex CLI** — 写入 `~/.codex/auth.json` 和 `config.toml`,切换后直接运行 `codex` 也能使用新配置
493
+ - **Codex CLI** — 按供应商设置独立 `CODEX_HOME`,认证和运行状态隔离,会话文件共享,支持多窗口并行
482
494
 
483
495
  **环境变量映射:**
484
496
 
@@ -528,14 +540,14 @@ Codex CLI:
528
540
 
529
541
  ### 切换 Codex 后提示 "Token data is not available"
530
542
 
531
- `~/.codex/auth.json` 格式不正确。重新切换即可:
543
+ 检查对应供应商独立目录中的 `auth.json`。退出该供应商的所有窗口后再启动;官方账号可使用 `--relogin` 重新认证:
532
544
 
533
545
  ```bash
534
546
  akm my-codex
535
547
  ```
536
548
 
537
- akm 会把活跃认证切换为 `auth_mode = "apikey"`,并写入新的 `OPENAI_API_KEY`。
538
- 原 ChatGPT 登录态不会混入活跃认证文件,修改前内容会保存在 `~/.codex/akm-backups/`。
549
+ API Key 模式会在对应供应商目录写入 `auth_mode = "apikey"` 和 `OPENAI_API_KEY`。
550
+ 修改前内容保存在该供应商目录的 `akm-backups/` 中,不改动其他供应商认证。
539
551
  `auth.json` 与 `config.toml` 作为一组更新;任一文件写入失败时会自动恢复两者的原始内容。
540
552
 
541
553
  ### Claude Code 切换后环境变量不生效
@@ -582,6 +594,7 @@ MIT License
582
594
 
583
595
  ## 链接
584
596
 
597
+ - [修改记录](CHANGELOG.md)
585
598
  - [NPM](https://www.npmjs.com/package/@pikecode/api-key-manager)
586
599
  - [GitHub](https://github.com/pikecode/api-key-manager)
587
600
  - [Issues](https://github.com/pikecode/api-key-manager/issues)
package/bin/akm.js CHANGED
@@ -96,7 +96,8 @@ program.configureHelp({
96
96
 
97
97
  // Check for updates before any command runs
98
98
  program.hook('preAction', async () => {
99
- await checkForUpdates({ packageName: pkg.name, currentVersion: pkg.version });
99
+ const exitCode = await checkForUpdates({ packageName: pkg.name, currentVersion: pkg.version });
100
+ if (Number.isInteger(exitCode)) process.exit(exitCode);
100
101
  });
101
102
 
102
103
  // Default command - show provider selection
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pikecode/api-key-manager",
3
- "version": "2.2.0",
3
+ "version": "2.2.2",
4
4
  "description": "A CLI tool for managing and switching multiple API provider configurations",
5
5
  "main": "src/index.js",
6
6
  "bin": {
@@ -10,6 +10,7 @@
10
10
  "bin/",
11
11
  "src/",
12
12
  "README.md",
13
+ "CHANGELOG.md",
13
14
  "LICENSE"
14
15
  ],
15
16
  "scripts": {
@@ -250,7 +250,7 @@ async function batchDelete(options = {}) {
250
250
  {
251
251
  type: 'input',
252
252
  name: 'confirmAgain',
253
- message: '请输入 "DELETE" 以确认删除:',
253
+ message: '请输入 "DELETE" 以确认删除(官方 Codex 配置会同时清理对应的 Session 缓存):',
254
254
  validate: (input) => {
255
255
  if (input !== 'DELETE') {
256
256
  return '请输入 "DELETE" 以确认';
@@ -50,7 +50,7 @@ class ProviderRemover extends BaseCommand {
50
50
  {
51
51
  type: 'confirm',
52
52
  name: 'confirm',
53
- message: `确定要删除供应商 '${provider.displayName}' 吗?`,
53
+ message: `确定要删除供应商 '${provider.displayName}' 吗?(官方 Codex 配置会同时清理该名称的 Session 缓存)`,
54
54
  default: false
55
55
  }
56
56
  ]);
@@ -157,7 +157,7 @@ class ProviderRemover extends BaseCommand {
157
157
  {
158
158
  type: 'confirm',
159
159
  name: 'confirm',
160
- message: `确定要删除这 ${answer.providers.length} 个供应商吗?`,
160
+ message: `确定要删除这 ${answer.providers.length} 个供应商吗?(官方 Codex 配置会同时清理对应的 Session 缓存)`,
161
161
  default: false
162
162
  }
163
163
  ]);
@@ -187,7 +187,7 @@ class ProviderManager {
187
187
  {
188
188
  type: 'confirm',
189
189
  name: 'confirmed',
190
- message: `确定要删除供应商 '${provider.displayName || providerName}' 吗?`,
190
+ message: `确定要删除供应商 '${provider.displayName || providerName}' 吗?(官方 Codex 配置会同时清理该名称的 Session 缓存)`,
191
191
  default: false
192
192
  }
193
193
  ], '取消删除', () => {
package/src/config.js CHANGED
@@ -5,6 +5,8 @@ const chalk = require('chalk');
5
5
  const { writeJsonAtomic } = require('./utils/atomic-file');
6
6
  const { validateAndNormalizeConfigData } = require('./utils/import-validator');
7
7
  const { validator } = require('./utils/validator');
8
+ const { acquireFileLock } = require('./utils/file-lock');
9
+ const { withCodexSessionRemoval } = require('./utils/codex-files');
8
10
 
9
11
  /**
10
12
  * @typedef {Object} ProviderConfig
@@ -43,6 +45,7 @@ class ConfigManager {
43
45
  this.isLoaded = false;
44
46
  /** @type {Date|null} 最后修改时间 */
45
47
  this.lastModified = null;
48
+ this.lastSavedContent = null;
46
49
  /** @type {Promise<Config>|null} 加载 Promise,防止并发加载 */
47
50
  this.loadPromise = null;
48
51
  }
@@ -109,6 +112,7 @@ class ConfigManager {
109
112
  }
110
113
 
111
114
  async _performLoad() {
115
+ const release = await acquireFileLock(`${this.configPath}.lock`, '配置正在被其他进程读写,请稍后重试。');
112
116
  try {
113
117
  if (await fs.pathExists(this.configPath)) {
114
118
  // 检查并修复文件权限(仅 Unix 系统)
@@ -117,6 +121,7 @@ class ConfigManager {
117
121
  let data;
118
122
  try {
119
123
  data = await fs.readJSON(this.configPath);
124
+ this.lastSavedContent = JSON.stringify(data);
120
125
  } catch {
121
126
  // 配置文件损坏,创建备份并重置
122
127
  const backupPath = `${this.configPath}.corrupted.${Date.now()}`;
@@ -124,7 +129,7 @@ class ConfigManager {
124
129
  console.log(chalk.yellow('⚠️ 配置文件损坏,已备份到:'), backupPath);
125
130
 
126
131
  this.config = this.getDefaultConfig();
127
- await this._performSave(this.config, { skipConflictCheck: true });
132
+ await this._performSave(this.config, { skipConflictCheck: true, lockHeld: true });
128
133
  this.isLoaded = true;
129
134
  return this.config;
130
135
  }
@@ -132,7 +137,7 @@ class ConfigManager {
132
137
  if (!data || typeof data !== 'object' || Array.isArray(data)) {
133
138
  // 配置文件被写成非对象内容时,重置为默认配置
134
139
  this.config = this.getDefaultConfig();
135
- await this._performSave(this.config, { skipConflictCheck: true });
140
+ await this._performSave(this.config, { skipConflictCheck: true, lockHeld: true });
136
141
  } else {
137
142
  this.config = validateAndNormalizeConfigData({ ...this.getDefaultConfig(), ...data });
138
143
  this._warnAboutInsecureRemoteHttpProviders();
@@ -147,7 +152,7 @@ class ConfigManager {
147
152
  this.lastModified = stat.mtime;
148
153
  } else {
149
154
  this.config = this.getDefaultConfig();
150
- await this._performSave(this.config, { skipConflictCheck: true });
155
+ await this._performSave(this.config, { skipConflictCheck: true, lockHeld: true });
151
156
  }
152
157
  this.isLoaded = true;
153
158
  return this.config;
@@ -155,12 +160,14 @@ class ConfigManager {
155
160
  if (error.message.includes('Unexpected end of JSON input')) {
156
161
  // 处理空文件或损坏的JSON文件
157
162
  this.config = this.getDefaultConfig();
158
- await this._performSave(this.config, { skipConflictCheck: true });
163
+ await this._performSave(this.config, { skipConflictCheck: true, lockHeld: true });
159
164
  this.isLoaded = true;
160
165
  return this.config;
161
166
  }
162
167
  console.error(chalk.red('❌ 加载配置失败:'), error.message);
163
168
  throw error;
169
+ } finally {
170
+ await release();
164
171
  }
165
172
  }
166
173
 
@@ -248,6 +255,7 @@ class ConfigManager {
248
255
  }
249
256
 
250
257
  async _performSave(config = this.config, options = {}) {
258
+ const release = options.lockHeld ? null : await acquireFileLock(`${this.configPath}.lock`, '配置正在被其他进程保存,请稍后重试。');
251
259
  try {
252
260
  const normalizedConfig = validateAndNormalizeConfigData(config);
253
261
  if (!options.skipConflictCheck) {
@@ -255,6 +263,7 @@ class ConfigManager {
255
263
  }
256
264
  await writeJsonAtomic(this.configPath, normalizedConfig, { spaces: 2, mode: 0o600 });
257
265
  this.config = normalizedConfig;
266
+ this.lastSavedContent = JSON.stringify(normalizedConfig);
258
267
 
259
268
  // 更新最后修改时间
260
269
  const stat = await fs.stat(this.configPath);
@@ -263,6 +272,8 @@ class ConfigManager {
263
272
  } catch (error) {
264
273
  console.error(chalk.red('❌ 保存配置失败:'), error.message);
265
274
  throw error;
275
+ } finally {
276
+ if (release) await release();
266
277
  }
267
278
  }
268
279
 
@@ -276,7 +287,8 @@ class ConfigManager {
276
287
  }
277
288
 
278
289
  const stat = await fs.stat(this.configPath);
279
- if (stat.mtime.getTime() !== this.lastModified.getTime()) {
290
+ if (stat.mtime.getTime() !== this.lastModified.getTime() ||
291
+ (this.lastSavedContent !== null && JSON.stringify(await fs.readJSON(this.configPath)) !== this.lastSavedContent)) {
280
292
  throw new Error('配置文件已被其他进程修改,请重新执行当前操作以避免覆盖最新配置');
281
293
  }
282
294
  }
@@ -422,6 +434,8 @@ class ConfigManager {
422
434
  throw new Error(`供应商 '${name}' 不存在\n使用 'akm list' 查看所有已配置的供应商`);
423
435
  }
424
436
 
437
+ const provider = this.config.providers[name];
438
+ const previousConfig = this.config;
425
439
  // 创建新的 providers 对象,排除要删除的供应商
426
440
  const remainingProviders = { ...this.config.providers };
427
441
  delete remainingProviders[name];
@@ -431,13 +445,22 @@ class ConfigManager {
431
445
  this.config.currentProvider === name ? null : this.config.currentProvider;
432
446
 
433
447
  // 使用不可变方式更新 config
434
- this.config = {
448
+ const nextConfig = {
435
449
  ...this.config,
436
450
  currentProvider: newCurrentProvider,
437
451
  providers: remainingProviders
438
452
  };
439
453
 
440
- return await this.save();
454
+ const saveRemoval = () => this.save(nextConfig);
455
+ try {
456
+ if (provider.ideName === 'codex' && provider.authMode === 'chatgpt_login') {
457
+ return await withCodexSessionRemoval(name, saveRemoval);
458
+ }
459
+ return await saveRemoval();
460
+ } catch (error) {
461
+ this.config = previousConfig;
462
+ throw error;
463
+ }
441
464
  }
442
465
 
443
466
  async activateProvider(name, lastUsedArgs = []) {
@@ -668,13 +668,34 @@ async function cacheCodexOfficialSession(options = {}) {
668
668
  return await cacheCurrentChatGptLoginAuth(codexHome, authJsonPath, options.sessionKey);
669
669
  }
670
670
 
671
+ async function withCodexSessionRemoval(sessionKey, removeProvider) {
672
+ const { removeProviderRuntime } = require('./codex-runtime');
673
+ return removeProviderRuntime(sessionKey, async () => {
674
+ const cachePath = buildSessionCacheAuthPath(resolveCodexHome(), sessionKey);
675
+ const snapshot = await readFileSnapshot(cachePath);
676
+ try {
677
+ await fs.remove(cachePath);
678
+ return await removeProvider();
679
+ } catch (error) {
680
+ try {
681
+ await restoreFileSnapshot(cachePath, snapshot);
682
+ } catch (rollbackError) {
683
+ throw new Error(`删除失败且 Session 缓存恢复失败: ${error.message}; ${rollbackError.message}`, { cause: error });
684
+ }
685
+ throw error;
686
+ }
687
+ });
688
+ }
689
+
671
690
  module.exports = {
672
691
  resolveCodexHome,
673
692
  buildCodexPaths,
693
+ buildSessionCacheAuthPath,
674
694
  readCodexFiles,
675
695
  applyCodexConfig,
676
696
  clearCodexAkmConfig,
677
697
  cacheCodexOfficialSession,
698
+ withCodexSessionRemoval,
678
699
  backupCodexFiles,
679
700
  removeTopLevelApiBaseUrl,
680
701
  removeAkmModelProvider,
@@ -0,0 +1,74 @@
1
+ const fs = require('fs-extra');
2
+ const path = require('path');
3
+ const inquirer = require('inquirer');
4
+ const { resolveCodexHome } = require('./codex-files');
5
+
6
+ async function listCodexHistory(root = resolveCodexHome()) {
7
+ const history = [];
8
+ async function scan(directory) {
9
+ let entries;
10
+ try { entries = await fs.readdir(directory, { withFileTypes: true }); }
11
+ catch (error) { if (error.code === 'ENOENT') return; throw error; }
12
+ for (const entry of entries) {
13
+ const file = path.join(directory, entry.name);
14
+ if (entry.isDirectory()) await scan(file);
15
+ else if (entry.isFile() && entry.name.endsWith('.jsonl')) {
16
+ // 只读头部元数据,避免把完整对话加载进内存或显示在列表中。
17
+ let handle;
18
+ try {
19
+ try { handle = await fs.open(file, 'r'); }
20
+ catch (error) { if (error.code === 'ENOENT') continue; throw error; }
21
+ const chunks = [];
22
+ let offset = 0;
23
+ // 元数据可能包含长指令,分块读至首行结束,上限 4 MiB。
24
+ while (offset < 4 * 1024 * 1024) {
25
+ const buffer = Buffer.alloc(16384);
26
+ const { bytesRead } = await fs.read(handle, buffer, 0, buffer.length, offset);
27
+ if (!bytesRead) break;
28
+ chunks.push(buffer.subarray(0, bytesRead));
29
+ offset += bytesRead;
30
+ if (buffer.subarray(0, bytesRead).includes(10)) break;
31
+ }
32
+ const line = Buffer.concat(chunks).toString('utf8').split('\n')[0];
33
+ let meta;
34
+ try { meta = JSON.parse(line); } catch { continue; }
35
+ const data = meta.payload;
36
+ if (meta.type !== 'session_meta' || !/^[0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12}$/i.test(data?.id)) continue;
37
+ history.push({ id: data.id, cwd: String(data.cwd || ''), timestamp: String(data.timestamp || meta.timestamp || ''), provider: String(data.model_provider || '未知') });
38
+ } finally {
39
+ if (handle !== undefined) await fs.close(handle);
40
+ }
41
+ }
42
+ }
43
+ }
44
+ await scan(path.join(root, 'sessions'));
45
+ await scan(path.join(root, 'archived_sessions'));
46
+ return [...new Map(history.sort((a, b) => b.timestamp.localeCompare(a.timestamp)).map(item => [item.id, item])).values()];
47
+ }
48
+
49
+ async function selectCodexHistory(config, args) {
50
+ if (!args.includes('resume')) return args;
51
+ const history = await listCodexHistory();
52
+ if (!history.length) {
53
+ const error = new Error('没有可用的 Codex 历史对话');
54
+ error.code = 'SESSION_LOCKED';
55
+ throw error;
56
+ }
57
+ if (!process.stdin.isTTY || !process.stdout.isTTY) throw new Error('恢复历史需要交互终端,请交互选择历史或使用 --no-args 新建会话');
58
+ const { sessionId } = await inquirer.prompt({
59
+ type: 'list', name: 'sessionId', message: '选择历史对话(创建新分支,原记录保留)', pageSize: 15,
60
+ choices: [
61
+ { name: '取消', value: null },
62
+ ...history.map(item => ({ name: `${item.timestamp} | ${item.cwd} | ${item.provider} | ${item.id}`, value: item.id }))
63
+ ]
64
+ });
65
+ if (!sessionId) return null;
66
+ const { confirmed } = await inquirer.prompt({
67
+ type: 'confirm', name: 'confirmed', default: false,
68
+ message: `将以供应商「${config.displayName || config.name}」处理所选历史上下文并创建新对话;若原供应商不同,历史内容会发送给新供应商。是否继续?`
69
+ });
70
+ if (!confirmed) return null;
71
+ return ['fork', sessionId, ...args.filter(arg => arg !== 'resume')];
72
+ }
73
+
74
+ module.exports = { listCodexHistory, selectCodexHistory };
@@ -1,13 +1,9 @@
1
1
  const spawn = require('cross-spawn');
2
2
  const { sanitizeEnvValue, clearTerminal } = require('./env-utils');
3
- const {
4
- applyCodexConfig,
5
- clearCodexAkmConfig,
6
- cacheCodexOfficialSession
7
- } = require('./codex-files');
3
+ const { prepareCodexRuntime } = require('./codex-runtime');
4
+ const { selectCodexHistory } = require('./codex-history');
8
5
  const { assertSupportedLaunchArgs } = require('./launch-args');
9
6
  const { validator } = require('./validator');
10
- const { acquireCodexLock } = require('./codex-lock');
11
7
 
12
8
  /**
13
9
  * 构建 Codex CLI 环境变量
@@ -79,25 +75,20 @@ async function executeCodexWithEnv(config, launchArgs = [], launchOptions = {})
79
75
 
80
76
  // 在写入 Codex 配置文件前完成全部输入校验。
81
77
  const env = buildCodexEnvVariables(config);
82
- const releaseLock = await acquireCodexLock();
78
+ const selectedArgs = await selectCodexHistory(config, launchArgs);
79
+ if (!selectedArgs) return;
80
+ const runtime = await prepareCodexRuntime(config, launchOptions);
81
+ env.CODEX_HOME = runtime.home;
83
82
  try {
84
- // 根据认证模式处理配置文件
85
- if (authMode === 'api_key') {
86
- // 写入 ~/.codex/config.toml 和 ~/.codex/auth.json。
87
- await applyCodexConfig(config);
88
- } else if (authMode === 'chatgpt_login') {
89
- // 清理 AKM 的配置,让 Codex 使用官方登录。
90
- await clearCodexAkmConfig({
91
- sessionKey: config.name,
92
- forceRelogin: launchOptions.forceRelogin === true
93
- });
94
- }
95
-
96
83
  // 处理参数:子命令放前面,选项放后面
97
- const rawArgs = Array.isArray(launchArgs) ? [...launchArgs] : [];
84
+ const rawArgs = [...selectedArgs];
98
85
  const subcommands = rawArgs.filter(arg => !arg.startsWith('-'));
99
86
  const options = rawArgs.filter(arg => arg.startsWith('-'));
100
- const args = [...subcommands, ...options];
87
+ const args = [...subcommands, ...options,
88
+ '-c', 'cli_auth_credentials_store="file"',
89
+ '-c', `sqlite_home=${JSON.stringify(runtime.home)}`,
90
+ '-c', `model_provider="${authMode === 'chatgpt_login' || !config.baseUrl ? 'openai' : 'akm'}"`
91
+ ];
101
92
 
102
93
  clearTerminal();
103
94
 
@@ -135,14 +126,6 @@ async function executeCodexWithEnv(config, launchArgs = [], launchOptions = {})
135
126
  child.on('close', async (code, signal) => {
136
127
  cleanupSignals();
137
128
  if (spawnFailed) return;
138
- try {
139
- if (authMode === 'chatgpt_login') {
140
- await cacheCodexOfficialSession({ sessionKey: config.name });
141
- }
142
- } catch (error) {
143
- reject(new Error(`保存 Codex 官方登录 Session 失败: ${error.message}`));
144
- return;
145
- }
146
129
  if (code === 0 || code === 130 || signal === 'SIGINT') {
147
130
  resolve();
148
131
  } else {
@@ -153,13 +136,13 @@ async function executeCodexWithEnv(config, launchArgs = [], launchOptions = {})
153
136
  errorOutput.includes('failed to resume session') ||
154
137
  errorOutput.includes('thread already has an active');
155
138
 
156
- if (isSessionLockedError) {
139
+ if (isSessionLockedError && !rawArgs.includes('fork')) {
157
140
  const error = new Error('Codex 会话被锁定或无法恢复');
158
141
  error.code = 'SESSION_LOCKED';
159
142
  reject(error);
160
143
  } else {
161
144
  const error = new Error(`Codex CLI 异常退出,退出代码: ${code}${stderrOutput.trim() ? `\n${stderrOutput.trim()}` : ''}`);
162
- if (rawArgs.includes('resume') && code === 1) error.code = 'RESUME_FAILED';
145
+ if (launchArgs.includes('resume') && code === 1) error.code = 'RESUME_FAILED';
163
146
  reject(error);
164
147
  }
165
148
  }
@@ -176,7 +159,7 @@ async function executeCodexWithEnv(config, launchArgs = [], launchOptions = {})
176
159
  });
177
160
  });
178
161
  } finally {
179
- await releaseLock();
162
+ await runtime.release();
180
163
  }
181
164
  }
182
165
 
@@ -0,0 +1,118 @@
1
+ const fs = require('fs-extra');
2
+ const path = require('path');
3
+ const crypto = require('crypto');
4
+ const { acquireFileLock } = require('./file-lock');
5
+ const { writeJsonAtomic, writeFileAtomic } = require('./atomic-file');
6
+ const {
7
+ resolveCodexHome, buildSessionCacheAuthPath, applyCodexConfig, clearCodexAkmConfig
8
+ } = require('./codex-files');
9
+
10
+ function providerHome(name, root = resolveCodexHome()) {
11
+ if (typeof name !== 'string' || !name.trim()) throw new Error('Codex 供应商名称不能为空');
12
+ const key = path.basename(buildSessionCacheAuthPath(root, name), '.auth.json');
13
+ return path.join(root, 'akm-providers', key);
14
+ }
15
+
16
+ async function lockProvider(name, root = resolveCodexHome()) {
17
+ const home = providerHome(name, root);
18
+ await fs.ensureDir(home, { mode: 0o700 });
19
+ for (let attempt = 0; ; attempt++) {
20
+ try {
21
+ const release = await acquireFileLock(path.join(home, '.akm-settings.lock'), '该供应商正在初始化或修改认证,请稍后重试。');
22
+ return { home, release };
23
+ } catch (error) {
24
+ if (error.code !== 'LOCK_BUSY' || attempt >= 40) throw error;
25
+ await new Promise(resolve => setTimeout(resolve, 50));
26
+ }
27
+ }
28
+ }
29
+
30
+ async function activeRuns(home) {
31
+ const directory = path.join(home, '.akm-runs');
32
+ await fs.ensureDir(directory, { mode: 0o700 });
33
+ // 不自动删除强杀后留下的记录,父进程退出不代表 Codex 子进程已退出。
34
+ return (await fs.readdir(directory)).length;
35
+ }
36
+
37
+ async function shareDirectory(root, home, name) {
38
+ const source = path.join(root, name);
39
+ const target = path.join(home, name);
40
+ await fs.ensureDir(source);
41
+ try {
42
+ await fs.symlink(path.resolve(source), target, process.platform === 'win32' ? 'junction' : 'dir');
43
+ } catch (error) {
44
+ if (error.code !== 'EEXIST') throw error;
45
+ if (await fs.realpath(target) !== await fs.realpath(source)) {
46
+ throw new Error(`历史或资源目录已存在且指向其他位置,请先检查:${target}`);
47
+ }
48
+ }
49
+ }
50
+
51
+ async function prepareCodexRuntime(config, { forceRelogin = false } = {}) {
52
+ const root = resolveCodexHome();
53
+ const { home, release } = await lockProvider(config.name, root);
54
+ try {
55
+ const markerPath = path.join(home, '.akm-config.json');
56
+ const authPath = path.join(home, 'auth.json');
57
+ const authMode = config.authMode || 'api_key';
58
+ const fingerprint = crypto.createHash('sha256').update(JSON.stringify([
59
+ authMode, config.authToken || null, config.baseUrl || null, config.models || null
60
+ ])).digest('hex');
61
+ const marker = await fs.pathExists(markerPath) ? await fs.readJson(markerPath) : null;
62
+ const running = await activeRuns(home);
63
+ const changed = marker?.fingerprint !== fingerprint;
64
+ if (running && (changed || forceRelogin || !(await fs.pathExists(authPath)))) {
65
+ throw new Error(`该供应商仍有窗口运行或首次认证尚未完成,不能更改认证。请退出该供应商的窗口后重试;异常退出记录位于 ${path.join(home, '.akm-runs')}`);
66
+ }
67
+
68
+ for (const name of ['sessions', 'archived_sessions']) await shareDirectory(root, home, name);
69
+ for (const name of ['skills', 'rules', 'plugins']) {
70
+ if (await fs.pathExists(path.join(root, name))) await shareDirectory(root, home, name);
71
+ }
72
+ if (!marker) {
73
+ for (const name of ['config.toml', 'AGENTS.md']) {
74
+ if (await fs.pathExists(path.join(root, name))) {
75
+ await writeFileAtomic(path.join(home, name), await fs.readFile(path.join(root, name)));
76
+ }
77
+ }
78
+ // 仅迁移同名旧缓存,绝不继承根目录里其他账号的活跃认证。
79
+ const legacy = buildSessionCacheAuthPath(root, config.name);
80
+ if (authMode === 'chatgpt_login' && !forceRelogin && await fs.pathExists(legacy)) {
81
+ await writeFileAtomic(authPath, await fs.readFile(legacy));
82
+ }
83
+ }
84
+ if (changed || forceRelogin || (authMode === 'api_key' && !(await fs.pathExists(authPath)))) {
85
+ if (authMode === 'chatgpt_login') {
86
+ await clearCodexAkmConfig({ codexHome: home, forceRelogin: forceRelogin || Boolean(marker && changed) });
87
+ } else {
88
+ await applyCodexConfig(config, { codexHome: home });
89
+ }
90
+ await writeJsonAtomic(markerPath, { fingerprint });
91
+ }
92
+ const lease = path.join(home, '.akm-runs', `${process.pid}-${crypto.randomUUID()}.json`);
93
+ await writeJsonAtomic(lease, { pid: process.pid, startedAt: new Date().toISOString() });
94
+ return { home, release: () => fs.remove(lease) };
95
+ } finally {
96
+ await release();
97
+ }
98
+ }
99
+
100
+ async function removeProviderRuntime(name, operation) {
101
+ const { home, release } = await lockProvider(name);
102
+ try {
103
+ if (await activeRuns(home)) throw new Error('该供应商仍有窗口运行,请先退出后再删除');
104
+ const authPath = path.join(home, 'auth.json');
105
+ const snapshot = await fs.pathExists(authPath) ? await fs.readFile(authPath) : null;
106
+ await fs.remove(authPath);
107
+ try {
108
+ return await operation();
109
+ } catch (error) {
110
+ if (snapshot !== null) await writeFileAtomic(authPath, snapshot);
111
+ throw error;
112
+ }
113
+ } finally {
114
+ await release();
115
+ }
116
+ }
117
+
118
+ module.exports = { providerHome, prepareCodexRuntime, removeProviderRuntime };
@@ -0,0 +1,25 @@
1
+ const fs = require('fs-extra');
2
+
3
+ async function acquireFileLock(lockPath, busyMessage) {
4
+ let handle;
5
+ try {
6
+ handle = await fs.open(lockPath, 'wx', 0o600);
7
+ } catch (error) {
8
+ if (error.code !== 'EEXIST') throw error;
9
+ const busy = new Error(`${busyMessage}\n若进程异常终止,请确认相关进程均已退出后手动删除锁文件:${lockPath}`);
10
+ busy.code = 'LOCK_BUSY';
11
+ throw busy;
12
+ }
13
+ try {
14
+ await fs.write(handle, String(process.pid));
15
+ } catch (error) {
16
+ await fs.close(handle);
17
+ await fs.remove(lockPath);
18
+ throw error;
19
+ }
20
+ await fs.close(handle);
21
+ // shortcut: 强杀后的锁须人工确认进程退出后清理,避免误删仍被使用的锁。
22
+ return () => fs.remove(lockPath);
23
+ }
24
+
25
+ module.exports = { acquireFileLock };
@@ -25,8 +25,8 @@ const claudeLaunchArgs = [
25
25
  const codexLaunchArgs = [
26
26
  {
27
27
  name: 'resume',
28
- label: '继续上次对话',
29
- description: '恢复之前的会话',
28
+ label: '从历史继续',
29
+ description: '选择历史并创建新分支,保留原对话',
30
30
  checked: false,
31
31
  isSubcommand: true
32
32
  },
@@ -157,11 +157,11 @@ async function hasCodexSessionHistory() {
157
157
  const codexHome = process.env.CODEX_HOME || path.join(os.homedir(), '.codex');
158
158
 
159
159
  // 检查会话目录中是否有实际的会话数据
160
- const sessionsDir = path.join(codexHome, 'sessions');
161
- if (await fs.pathExists(sessionsDir)) {
162
- const entries = await fs.readdir(sessionsDir);
163
- if (entries.length > 0) {
164
- return true;
160
+ for (const directory of ['sessions', 'archived_sessions']) {
161
+ const sessionsDir = path.join(codexHome, directory);
162
+ if (await fs.pathExists(sessionsDir)) {
163
+ const entries = await fs.readdir(sessionsDir);
164
+ if (entries.length > 0) return true;
165
165
  }
166
166
  }
167
167
 
@@ -132,31 +132,33 @@ async function checkForUpdates({ packageName, currentVersion }) {
132
132
  if (!doUpdate) return;
133
133
 
134
134
  console.log(chalk.yellow('开始更新,请稍候...'));
135
- await new Promise((resolve) => {
135
+ const installed = await new Promise((resolve) => {
136
136
  const child = spawn('npm', ['i', '-g', `${packageName}@latest`], {
137
137
  shell: false,
138
138
  stdio: 'inherit'
139
139
  });
140
140
  child.on('close', (code) => resolve(code === 0));
141
- }).then((ok) => {
142
- if (!ok) {
143
- console.log(chalk.red('更新失败,请稍后重试或手动执行: ') + chalk.cyan(installCmd));
144
- return;
145
- }
146
- console.log(chalk.green('更新成功,正在重启...'));
147
- const scriptPath = process.argv[1];
148
- const restartCommand = scriptPath ? process.execPath : packageName;
149
- const restartArgs = scriptPath
150
- ? [scriptPath, ...process.argv.slice(2)]
151
- : process.argv.slice(2);
141
+ child.on('error', () => resolve(false));
142
+ });
143
+ if (!installed) {
144
+ console.log(chalk.red('更新失败,请稍后重试或手动执行: ') + chalk.cyan(installCmd));
145
+ return;
146
+ }
147
+ console.log(chalk.green('更新成功,正在重启...'));
148
+ const scriptPath = process.argv[1];
149
+ const restartCommand = scriptPath ? process.execPath : packageName;
150
+ const restartArgs = scriptPath
151
+ ? [scriptPath, ...process.argv.slice(2)]
152
+ : process.argv.slice(2);
152
153
 
153
- const child = spawn(restartCommand, restartArgs, {
154
- shell: false,
155
- stdio: 'inherit'
156
- });
157
- child.on('close', (code) => {
158
- process.exit(code || 0);
159
- });
154
+ // 等新版命令完成,由入口退出旧进程,防止原命令执行两次。
155
+ return await new Promise((resolve, reject) => {
156
+ const child = spawn(restartCommand, restartArgs, { shell: false, stdio: 'inherit' });
157
+ child.on('error', reject);
158
+ child.on('close', (code, signal) => resolve(code ?? (signal === 'SIGINT' ? 130 : 1)));
159
+ }).catch(error => {
160
+ console.log(chalk.red(`重启失败,请手动重新运行命令: ${error.message}`));
161
+ return 1;
160
162
  });
161
163
  }
162
164
  } catch {
@@ -1,28 +0,0 @@
1
- const fs = require('fs-extra');
2
- const path = require('path');
3
- const { resolveCodexHome } = require('./codex-files');
4
-
5
- async function acquireCodexLock() {
6
- const home = resolveCodexHome();
7
- await fs.ensureDir(home);
8
- const lockPath = path.join(home, '.akm-launch.lock');
9
- let handle;
10
- try {
11
- handle = await fs.open(lockPath, 'wx', 0o600);
12
- } catch (error) {
13
- if (error.code !== 'EEXIST') throw error;
14
- throw new Error(`此 Codex 目录已有 AKM 会话运行,请先退出该会话。若进程异常终止,请确认相关 Codex 进程均已退出后手动删除锁文件:${lockPath}`);
15
- }
16
- try {
17
- await fs.write(handle, String(process.pid));
18
- } catch (error) {
19
- await fs.remove(lockPath);
20
- throw error;
21
- } finally {
22
- await fs.close(handle);
23
- }
24
- // shortcut: 异常强杀后保留锁,避免遗留子进程仍在写认证文件;需要自动恢复时再跟踪子进程身份。
25
- return () => fs.remove(lockPath);
26
- }
27
-
28
- module.exports = { acquireCodexLock };