@pikecode/api-key-manager 2.2.1 → 2.2.3

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,71 @@
1
+ # 修改记录
2
+
3
+ 记录项目的功能、修复和兼容性变化。以下历史条目依据 Git 提交补录,不代表已核实 npm 发布状态。
4
+
5
+ ## 未发布(当前目标版本 2.2.3)
6
+
7
+ ### 修复
8
+
9
+ - 配置添加、激活、切换、参数记忆、统计、重置和导入使用候选配置,保存成功后才更新内存,防止失败修改被后续操作写入。
10
+ - 显式 `--relogin` 可备份并清理损坏的认证文件;普通启动仍拒绝损坏认证,保留原内容。
11
+ - 历史列表跳过 `null`、数组、非对象和非法会话元数据,单条异常记录不再阻断全部正常历史。
12
+ - 子进程创建后才记录当前供应商、使用次数和启动参数;取消历史选择或未创建进程时不记录。状态保存失败单独提示,不中断已创建的进程。
13
+ - 历史按会话文件最近修改时间排序,并保留创建时间展示;重复 ID 优先使用最近修改的记录。
14
+ - 历史选择优先匹配当前工作目录,默认选中该目录最近使用的对话;无匹配时默认新建,其他项目历史需主动进入查看。使用规范化完整路径及真实路径匹配,避免同名目录误匹配,并兼容目录链接。
15
+
16
+ - 终端列表状态刷新保持顺序和选中项,连续回调合并刷新、相同内容跳过重绘,过期提示不再刷新;检测失败通过提示行展示。
17
+ - Codex 历史每批展示 20 条并支持加载更多,短条目按终端宽度截断,完整信息在确认页展示;统一 ESC 返回/取消,列表页大小按终端高度调整。首次仍扫描全部历史头部元数据。
18
+
19
+ - 移除 ESC 识别后的两层延迟回调,避免旧菜单通知或清屏落入新菜单;保留组合键识别等待,方向键不会直接触发返回。
20
+ - 供应商条目按终端宽度截断,状态文字限制长度并转义控制字符,避免长错误信息改变列表行数;修正管理列表将在线状态 `0` 当作空值的初始排序错误。
21
+
22
+ - ESC 监听结束时恢复输入流状态:原本未流动的 stdin 在清理时暂停,原本已流动的输入保持不变,修复交互终端运行测试后进程无法自然退出的问题。
23
+
24
+ ### 验证
25
+
26
+ - 60 个测试套件、632 项测试、Lint 和项目覆盖率门槛通过。
27
+ - 伪终端使用真实 Inquirer 验证 ESC 取消、下一菜单连续下移跨页及回车,返回预期条目;未覆盖所有终端模拟器与动态缩放。
28
+ - 交互终端普通测试可自然退出;`--detectOpenHandles` 模式仍可能列出 stdin 的 `TTYWRAP`,但修复后进程也能自行结束。新增输入流三种初始状态的清理回归测试。
29
+ - 版本元数据同步为 2.2.3;未执行发布。
30
+
31
+ ## 2.2.2(历史补录)
32
+
33
+ ### 功能与行为调整
34
+
35
+ - 支持同一 Codex 供应商多窗口运行,以及不同供应商同时运行。
36
+ - 按供应商隔离认证、配置和 SQLite 运行状态,不再覆盖根目录认证或使用全局单窗口锁。
37
+ - 共享会话文件,支持从不同供应商的历史创建新分支;恢复前确认目标供应商,保留原始对话。
38
+ - 迁移同名官方 Session 缓存;重新认证、修改认证和删除账号只受该供应商的运行窗口约束。
39
+ - 更新 README,说明目录布局、历史分叉及异常退出记录的处理。
40
+
41
+ ### 兼容性说明
42
+
43
+ - 从历史继续需要 Codex CLI 支持 `fork`,已用 0.166.0 的原生接口做离线验证。
44
+ - 直接运行原生 `codex` 仍使用原配置;使用 AKM 隔离配置需通过 `akm <供应商>` 启动。
45
+ - 首次复制到供应商目录的配置不会自动跟随根配置更新;共享历史、技能和插件目录保留在原位置。
46
+
47
+ ### 维护
48
+
49
+ - 新增项目维护约定:每次修改同步记录变更,按影响评估版本升级。
50
+ - 保留用户指定的 2.2.2 目标版本,同步锁文件版本元数据。
51
+ - 将修改记录加入 npm 包文件清单,并在 README 中提供入口。
52
+ - 多窗口功能验证:58 个测试套件、591 项测试及项目完整检查通过。
53
+
54
+ ## 2.2.1(历史补录)
55
+
56
+ - 更新包版本至 2.2.1;对应版本提交未包含其他代码变更。
57
+
58
+ ## 2.2.0(历史补录)
59
+
60
+ - 加固 Codex Session 保存与认证切换回滚,修复自动重试时重复清理认证。
61
+ - 未知历史恢复错误保留实际原因,交互确认后才新开会话。
62
+ - 修复测试写入真实用户配置的问题,减少逐层重复报错。
63
+ - 更新检查缓存 24 小时;更新重启后等待新版进程结束,避免重复执行命令。
64
+ - 配置读写使用短时锁和内容冲突检查,降低并发覆盖风险。
65
+ - 删除官方供应商时清理对应 Session 缓存,失败时恢复。
66
+ - 增加真实命令入口、并发保存和删除回滚测试,以及三平台 CI 矩阵。
67
+ - 此版本曾采用 Codex 目录单窗口锁;当前目标版本已改为供应商隔离和多窗口运行。
68
+
69
+ ## 2.1.9(历史补录)
70
+
71
+ - 增加 Claude Code 继续历史失败时的回退处理;后续版本收窄自动重试条件,避免把未知错误误判为无历史。
package/README.md CHANGED
@@ -207,7 +207,7 @@ akm remove my-provider
207
207
  3. 预览将要删除的供应商列表
208
208
  4. 最终确认后批量删除
209
209
 
210
- 删除 Codex 官方网页登录供应商时,会同时清理该名称的本地 Session 缓存;以后添加同名供应商需要重新认证。若同一 Codex 目录仍有 AKM 会话运行,删除会被阻止,请先退出会话。删除失败会恢复缓存;该操作不会撤销服务端 Token,也不会清理历史备份或其他账号的缓存。
210
+ 删除 Codex 官方网页登录供应商时,会同时清理该名称的旧 Session 缓存和独立目录中的认证;以后添加同名供应商需要重新认证。只有该供应商仍有窗口运行时才阻止删除,其他供应商不受影响。删除失败会恢复认证;该操作不会撤销服务端 Token,也不会清理共享历史、历史备份或其他账号的缓存。
211
211
 
212
212
  ### 编辑供应商
213
213
 
@@ -388,13 +388,23 @@ akm switch openai-work --relogin
388
388
 
389
389
  ### 会话恢复与运行保护
390
390
 
391
- Codex 的不同账号共享历史目录,但 AKM 会对同一 `CODEX_HOME`(默认 `~/.codex`)限制同时运行一个 Codex 会话,防止认证信息互相覆盖。退出当前会话后再切换账号。该保护仅覆盖通过 AKM 启动的进程,请勿同时用原生 `codex` 命令切换同一目录的认证。
391
+ 同一供应商可以打开多个窗口,不同供应商也可以同时运行。一个窗口退出当前 Codex 会话后,可以再启动任意供应商,不影响其他窗口。
392
392
 
393
- 正常退出会释放目录锁;强制杀死 AKM 后可能留下 `.akm-launch.lock`。只有确认该目录相关的 AKM 和 Codex 进程都已退出,才可手动删除此锁文件后重试。
393
+ AKM 使用 `<CODEX_HOME>/akm-providers/<供应商标识>/` 保存各供应商独立的 `auth.json`、`config.toml` 和 SQLite 运行状态,根目录默认为 `~/.codex`。不再覆盖根目录认证,也不再使用旧的 `.akm-launch.lock` 限制窗口数量。直接运行原生 `codex` 仍使用其原有配置;请通过 `akm <供应商>` 使用隔离配置。
394
394
 
395
- `--relogin` 只在首次启动时清理本地认证;历史恢复失败后的自动重试会保留新登录态。该选项不会撤销服务端 Token 或清理浏览器登录状态。
395
+ 首次启动会复制根目录的配置与 `AGENTS.md`,并迁移同名官方 Session 缓存;不会继承其他账号的认证。后续 Codex 刷新的 Token 直接保存在该供应商目录,不再在窗口退出时覆盖回共享认证文件。根目录后续配置修改不会自动覆盖已创建的独立配置。
396
396
 
397
- 恢复历史时,明确的历史缺失或锁定错误会自动改为新会话;其他退出码为 1 的错误会保留原因,在交互终端询问是否新开会话,默认不重试。非交互环境直接返回错误。
397
+ `sessions` 和 `archived_sessions` 通过目录链接共享,历史文件无需搬迁;SQLite 数据库与认证保持隔离。已有的 `skills`、`rules`、`plugins` 目录也会链接到原位置。Windows 使用目录联接(junction)。
398
+
399
+ 选择“从历史继续”后,AKM 优先列出当前工作目录的历史(包括不同供应商),按会话文件最近修改时间排序,默认选中最近的一条;只有一条时默认选中该条。目录按规范化完整路径与真实路径匹配,不按文件夹名称匹配。当前目录没有历史时,默认选择新建会话;需要跨项目继续时,可主动选择“查看其他项目历史”,也可返回当前目录列表。列表每批展示 20 条,可选择“加载更多”,默认定位到新增批次第一条。列表使用短 ID、最近使用时间、项目名和原供应商,按终端宽度截断;确认页展示完整 ID、路径及创建时间。在其他项目列表按 ESC 返回当前目录,在当前目录列表或确认页按 ESC 取消。列表页大小按显示时的终端高度调整,最多 15 行。分批展示只减少菜单条目,首次仍扫描共享历史文件的头部元数据。单条非法元数据会被跳过。确认目标供应商后使用 `codex fork <ID>` 创建新对话,原历史保持不变,多个窗口可以从同一历史分叉。跨供应商继续会向新供应商发送恢复所需的上下文,因此默认不确认;非交互终端不会自动选择历史。此功能需要支持 `codex fork` 的 Codex CLI,已使用 0.166.0 的原生接口验证。分叉失败会显示原因,不静默丢弃历史。
400
+
401
+ 供应商列表异步检测状态时保持顺序和选中项不变,合并连续刷新并跳过相同内容;状态检测失败显示在提示行,避免日志插入活动菜单。供应商条目按终端宽度截断,状态文字限制长度;截断仅影响显示,选择仍使用完整供应商名称。ESC 识别后立即取消当前提示并执行返回通知,不再延迟写入下一菜单。
402
+
403
+ 取消历史选择不会改变当前供应商或使用统计。AKM 在操作系统确认子进程创建后记录使用状态;这表示进程已创建,不代表模型认证或请求已经成功。
404
+
405
+ 同一供应商的首次网页登录未完成时,先完成该窗口认证,再打开更多窗口。`--relogin`、修改密钥或认证配置、删除官方账号需要先退出该供应商的所有窗口,其他供应商可继续运行。该选项不会撤销服务端 Token 或清理浏览器登录状态。
406
+
407
+ 正常退出会清除运行记录;强杀后可能在供应商目录的 `.akm-runs/` 留下记录,或留下短时 `.akm-settings.lock`。仅在确认该供应商相关 AKM/Codex 进程均已退出后清理这些记录;不要删除历史目录。
398
408
 
399
409
  更新检查结果(包括失败结果)缓存在 `~/.akm-update-check.json`,24 小时内不重复请求 npm。可通过 `CC_NO_UPDATE_CHECK=1` 禁用检查。
400
410
 
@@ -484,7 +494,7 @@ akm personal -q
484
494
  **切换原理:**
485
495
 
486
496
  - **Claude Code** — 通过环境变量注入启动子进程,不修改配置文件,切换只在当前会话生效
487
- - **Codex CLI** — 写入 `~/.codex/auth.json` 和 `config.toml`,切换后直接运行 `codex` 也能使用新配置
497
+ - **Codex CLI** — 按供应商设置独立 `CODEX_HOME`,认证和运行状态隔离,会话文件共享,支持多窗口并行
488
498
 
489
499
  **环境变量映射:**
490
500
 
@@ -534,14 +544,14 @@ Codex CLI:
534
544
 
535
545
  ### 切换 Codex 后提示 "Token data is not available"
536
546
 
537
- `~/.codex/auth.json` 格式不正确。重新切换即可:
547
+ 检查对应供应商独立目录中的 `auth.json`。退出该供应商的所有窗口后再启动;官方账号可使用 `akm <供应商> --relogin` 重新认证。若认证 JSON 已损坏,显式重新登录会先备份原始文件,再清理认证;普通启动不会覆盖损坏文件:
538
548
 
539
549
  ```bash
540
550
  akm my-codex
541
551
  ```
542
552
 
543
- akm 会把活跃认证切换为 `auth_mode = "apikey"`,并写入新的 `OPENAI_API_KEY`。
544
- 原 ChatGPT 登录态不会混入活跃认证文件,修改前内容会保存在 `~/.codex/akm-backups/`。
553
+ API Key 模式会在对应供应商目录写入 `auth_mode = "apikey"` 和 `OPENAI_API_KEY`。
554
+ 修改前内容保存在该供应商目录的 `akm-backups/` 中,不改动其他供应商认证。
545
555
  `auth.json` 与 `config.toml` 作为一组更新;任一文件写入失败时会自动恢复两者的原始内容。
546
556
 
547
557
  ### Claude Code 切换后环境变量不生效
@@ -588,6 +598,7 @@ MIT License
588
598
 
589
599
  ## 链接
590
600
 
601
+ - [修改记录](CHANGELOG.md)
591
602
  - [NPM](https://www.npmjs.com/package/@pikecode/api-key-manager)
592
603
  - [GitHub](https://github.com/pikecode/api-key-manager)
593
604
  - [Issues](https://github.com/pikecode/api-key-manager/issues)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pikecode/api-key-manager",
3
- "version": "2.2.1",
3
+ "version": "2.2.3",
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": {
@@ -152,7 +152,6 @@ class BaseCommand {
152
152
 
153
153
  const handler = this.escManager.register({
154
154
  once: options.once !== false,
155
- postDelay: typeof options.postDelay === 'number' ? options.postDelay : undefined,
156
155
  onTrigger: () => {
157
156
  this.cancelActivePrompt();
158
157
  this.clearScreen();
@@ -162,23 +161,17 @@ class BaseCommand {
162
161
  }
163
162
 
164
163
  if (typeof callback === 'function') {
165
- const delay = typeof options.callbackDelay === 'number' ? options.callbackDelay : 50;
166
- setTimeout(() => {
167
- try {
168
- const result = callback();
169
- if (result && typeof result.catch === 'function') {
170
- result.catch((error) => {
171
- if (!this.isEscCancelled(error)) {
172
- Logger.error(`ESC回退回调执行失败: ${error.message}`);
173
- }
174
- });
175
- }
176
- } catch (error) {
177
- if (!this.isEscCancelled(error)) {
178
- Logger.error(`ESC回退回调执行失败: ${error.message}`);
179
- }
164
+ // 同步执行通知,避免新菜单渲染后旧通知才写入终端。
165
+ try {
166
+ const result = callback();
167
+ if (result && typeof result.catch === 'function') {
168
+ result.catch((error) => {
169
+ if (!this.isEscCancelled(error)) Logger.error(`ESC回退回调执行失败: ${error.message}`);
170
+ });
180
171
  }
181
- }, delay);
172
+ } catch (error) {
173
+ if (!this.isEscCancelled(error)) Logger.error(`ESC回退回调执行失败: ${error.message}`);
174
+ }
182
175
  }
183
176
  }
184
177
  });
@@ -155,6 +155,7 @@ class BackupManager {
155
155
 
156
156
  let addedCount = 0;
157
157
  let skippedCount = 0;
158
+ const nextConfig = { ...this.configManager.config, providers: { ...this.configManager.config.providers } };
158
159
 
159
160
  for (const [name, provider] of Object.entries(importData.providers)) {
160
161
  const exists = this.configManager.getProvider(name);
@@ -166,7 +167,7 @@ class BackupManager {
166
167
  }
167
168
 
168
169
  // 添加或更新供应商
169
- this.configManager.config.providers[name] = {
170
+ nextConfig.providers[name] = {
170
171
  ...provider,
171
172
  name,
172
173
  importedAt: new Date().toISOString()
@@ -177,19 +178,19 @@ class BackupManager {
177
178
  // 如果设置了 currentProvider 且该供应商存在
178
179
  if (
179
180
  importData.currentProvider &&
180
- this.configManager.config.providers[importData.currentProvider]
181
+ nextConfig.providers[importData.currentProvider]
181
182
  ) {
182
- if (!this.configManager.config.currentProvider || options.overwrite) {
183
- this.configManager.config.currentProvider = importData.currentProvider;
183
+ if (!nextConfig.currentProvider || options.overwrite) {
184
+ nextConfig.currentProvider = importData.currentProvider;
184
185
  }
185
186
  }
186
187
 
187
- const activeProvider = this.configManager.config.currentProvider;
188
- for (const [name, provider] of Object.entries(this.configManager.config.providers)) {
189
- provider.current = name === activeProvider;
188
+ const activeProvider = nextConfig.currentProvider;
189
+ for (const [name, provider] of Object.entries(nextConfig.providers)) {
190
+ nextConfig.providers[name] = { ...provider, current: name === activeProvider };
190
191
  }
191
192
 
192
- await this.configManager.save();
193
+ await this.configManager.save(nextConfig);
193
194
 
194
195
  Logger.success('配置导入完成');
195
196
  console.log(chalk.gray(` 导入文件: ${absolutePath}`));
@@ -1,3 +1,6 @@
1
+ const { stripVTControlCharacters } = require('node:util');
2
+ const { compactTerminalText } = require('../../utils/terminal-format');
3
+
1
4
  class ProviderChoicesHelper {
2
5
  static buildProviderChoices(providers, options = {}) {
3
6
  const {
@@ -54,8 +57,11 @@ class ProviderChoicesHelper {
54
57
  ? chalk.green(' 🌐 官方登录')
55
58
  : '';
56
59
 
60
+ const label = `${icon} ${ideTag} ${UIHelper.formatProvider(provider)}${authModeLabel}${lastUsedLabel} ${statusLabel}`;
61
+ const plain = stripVTControlCharacters(label);
62
+ const compact = compactTerminalText(plain);
57
63
  return {
58
- name: `${icon} ${ideTag} ${UIHelper.formatProvider(provider)}${authModeLabel}${lastUsedLabel} ${statusLabel}`,
64
+ name: compact === plain ? label : compact,
59
65
  value: provider.name,
60
66
  short: provider.name
61
67
  };
@@ -7,10 +7,18 @@ async function launchProviderProcess(provider, selectedLaunchArgs, options = {})
7
7
  return;
8
8
  }
9
9
 
10
- await executeWithEnv(provider, selectedLaunchArgs);
10
+ await executeWithEnv(provider, selectedLaunchArgs, options);
11
11
  }
12
12
 
13
13
  async function markProviderAsCurrent(configManager, provider, lastUsedArgs = []) {
14
+ const latestProvider = await getLatestProvider(configManager, provider);
15
+ await configManager.activateProvider(latestProvider.name, lastUsedArgs);
16
+ return typeof configManager.getProvider === 'function'
17
+ ? configManager.getProvider(latestProvider.name)
18
+ : latestProvider;
19
+ }
20
+
21
+ async function getLatestProvider(configManager, provider) {
14
22
  if (typeof configManager.load === 'function') {
15
23
  await configManager.load(true);
16
24
  }
@@ -24,13 +32,11 @@ async function markProviderAsCurrent(configManager, provider, lastUsedArgs = [])
24
32
  throw new Error(`供应商 '${provider.name}' 不存在\n使用 'akm list' 查看所有已配置的供应商`);
25
33
  }
26
34
 
27
- await configManager.activateProvider(latestProvider.name, lastUsedArgs);
28
- return typeof configManager.getProvider === 'function'
29
- ? configManager.getProvider(latestProvider.name)
30
- : latestProvider;
35
+ return latestProvider;
31
36
  }
32
37
 
33
38
  module.exports = {
34
39
  launchProviderProcess,
35
- markProviderAsCurrent
40
+ markProviderAsCurrent,
41
+ getLatestProvider
36
42
  };
@@ -4,6 +4,7 @@
4
4
  */
5
5
 
6
6
  const chalk = require('chalk');
7
+ const { compactTerminalText } = require('../../utils/terminal-format');
7
8
 
8
9
  class StatusHelper {
9
10
  /**
@@ -48,7 +49,7 @@ class StatusHelper {
48
49
  const color = colorMap[availability.state] || chalk.gray;
49
50
  const label = availability.label || defaultLabelMap[availability.state] || '未知';
50
51
 
51
- return color(label);
52
+ return color(compactTerminalText(label, 24));
52
53
  }
53
54
 
54
55
  /**
@@ -16,8 +16,9 @@ const { StatusHelper } = require('./switch/status-helper');
16
16
  const { LaunchArgsHelper } = require('./switch/launch-args-helper');
17
17
  const { ProviderChoicesHelper } = require('./switch/provider-choices-helper');
18
18
  const { ensureClaudeSettingsCompatibility } = require('./switch/claude-settings-compatibility');
19
- const { launchProviderProcess, markProviderAsCurrent } = require('./switch/provider-launcher');
19
+ const { launchProviderProcess, markProviderAsCurrent, getLatestProvider } = require('./switch/provider-launcher');
20
20
  const { ProviderManager } = require('./switch/provider-manager');
21
+ const { listPageSize } = require('../utils/terminal-format');
21
22
 
22
23
  /**
23
24
  * 环境切换器类
@@ -65,9 +66,7 @@ class EnvSwitcher extends BaseCommand {
65
66
  }
66
67
 
67
68
  _getPageSize(itemCount) {
68
- const rows = process.stdout.rows || 24;
69
- const reserved = 8;
70
- return Math.min(itemCount, Math.max(5, rows - reserved));
69
+ return listPageSize(itemCount);
71
70
  }
72
71
 
73
72
  async validateProvider(providerName) {
@@ -184,13 +183,14 @@ class EnvSwitcher extends BaseCommand {
184
183
  const loadingInterval = UIHelper.createLoadingAnimation('正在设置环境...');
185
184
 
186
185
  try {
187
- const launchProvider = await markProviderAsCurrent(this.configManager, provider, selectedLaunchArgs);
186
+ const launchProvider = await getLatestProvider(this.configManager, provider);
188
187
  UIHelper.clearLoadingAnimation(loadingInterval);
189
188
 
190
189
  console.log(UIHelper.createCard('准备就绪', `环境配置完成,正在启动 🚀 ${ideDisplayName}...`, UIHelper.icons.success));
191
190
  console.log();
192
191
  await launchProviderProcess(launchProvider, selectedLaunchArgs, {
193
- forceRelogin: this.forceRelogin
192
+ forceRelogin: this.forceRelogin,
193
+ onStarted: () => markProviderAsCurrent(this.configManager, launchProvider, selectedLaunchArgs)
194
194
  });
195
195
 
196
196
  } catch (error) {
@@ -218,13 +218,14 @@ class EnvSwitcher extends BaseCommand {
218
218
  const retryLoadingInterval = UIHelper.createLoadingAnimation('正在重新启动(无历史恢复)...');
219
219
 
220
220
  try {
221
- const retryProvider = await markProviderAsCurrent(this.configManager, provider, retryArgs);
221
+ const retryProvider = await getLatestProvider(this.configManager, provider);
222
222
  UIHelper.clearLoadingAnimation(retryLoadingInterval);
223
223
 
224
224
  console.log(UIHelper.createCard('准备就绪', `环境配置完成,正在启动 🚀 ${ideDisplayName}(新会话)...`, UIHelper.icons.success));
225
225
  console.log();
226
226
  await launchProviderProcess(retryProvider, retryArgs, {
227
- forceRelogin: false
227
+ forceRelogin: false,
228
+ onStarted: () => markProviderAsCurrent(this.configManager, retryProvider, retryArgs)
228
229
  });
229
230
  return;
230
231
  } catch (retryError) {
@@ -244,13 +245,14 @@ class EnvSwitcher extends BaseCommand {
244
245
  const retryLoadingInterval = UIHelper.createLoadingAnimation('正在重新启动(新会话)...');
245
246
 
246
247
  try {
247
- const retryProvider = await markProviderAsCurrent(this.configManager, provider, retryArgs);
248
+ const retryProvider = await getLatestProvider(this.configManager, provider);
248
249
  UIHelper.clearLoadingAnimation(retryLoadingInterval);
249
250
 
250
251
  console.log(UIHelper.createCard('准备就绪', `环境配置完成,正在启动 🚀 ${ideDisplayName}(新会话)...`, UIHelper.icons.success));
251
252
  console.log();
252
253
  await launchProviderProcess(retryProvider, retryArgs, {
253
- forceRelogin: false
254
+ forceRelogin: false,
255
+ onStarted: () => markProviderAsCurrent(this.configManager, retryProvider, retryArgs)
254
256
  });
255
257
  return;
256
258
  } catch (retryError) {
@@ -751,7 +753,7 @@ class EnvSwitcher extends BaseCommand {
751
753
  providers = [...providers].sort((a, b) => {
752
754
  const stateA = statusMap[a.name]?.state || 'pending';
753
755
  const stateB = statusMap[b.name]?.state || 'pending';
754
- return (stateOrder[stateA] || 2) - (stateOrder[stateB] || 2);
756
+ return (stateOrder[stateA] ?? 2) - (stateOrder[stateB] ?? 2);
755
757
  });
756
758
 
757
759
  this._renderPage({
@@ -858,7 +860,7 @@ class EnvSwitcher extends BaseCommand {
858
860
  if (this.activeStatusRefresh !== refreshToken) {
859
861
  return;
860
862
  }
861
- Logger.error(`供应商状态检测失败: ${error.message}`);
863
+ // 检测失败通过提示行展示,避免在活动菜单中插入日志打乱光标。
862
864
  const fallback = this._buildErrorStatusMap(providers, error);
863
865
  Object.assign(latestMap, fallback);
864
866
  this.latestStatusMap = latestMap;
@@ -887,6 +889,10 @@ class EnvSwitcher extends BaseCommand {
887
889
  return;
888
890
  }
889
891
 
892
+ if (this._refreshTimer) {
893
+ clearTimeout(this._refreshTimer);
894
+ this._refreshTimer = null;
895
+ }
890
896
  this._refreshPromptChoices(activePrompt, providers, statusMap, { hasError: Boolean(error) });
891
897
  }
892
898
 
@@ -904,14 +910,12 @@ class EnvSwitcher extends BaseCommand {
904
910
  }
905
911
 
906
912
  // 节流:80ms 内的多次回调合并为一次 render,避免高频刷新导致 ANSI 光标错位
907
- if (this._refreshTimer) {
908
- clearTimeout(this._refreshTimer);
909
- }
913
+ if (this._refreshTimer) return;
910
914
  this._refreshTimer = setTimeout(() => {
911
915
  this._refreshTimer = null;
912
916
  if (this.activeStatusRefresh !== refreshToken) return;
913
917
  const activeP = this.activePrompt?.promise?.ui?.activePrompt;
914
- if (!activeP || activeP.status === 'answered') return;
918
+ if (!activeP || activeP !== activePrompt || activeP.status === 'answered') return;
915
919
  const providers = this.filteredProviders || this.configManager.listProviders();
916
920
  const statusMap = this.latestStatusMap || {};
917
921
  this._refreshPromptChoices(activeP, providers, statusMap);
@@ -921,18 +925,8 @@ class EnvSwitcher extends BaseCommand {
921
925
  _refreshPromptChoices(activePrompt, providers, statusMap, options = {}) {
922
926
  const includeActions = this.currentPromptContext === 'manage';
923
927
 
924
- let sortedProviders = providers;
925
- if (includeActions) {
926
- const stateOrder = { online: 0, degraded: 1, pending: 2, offline: 3 };
927
- sortedProviders = [...providers].sort((a, b) => {
928
- const stateA = statusMap[a.name]?.state || 'pending';
929
- const stateB = statusMap[b.name]?.state || 'pending';
930
- return (stateOrder[stateA] ?? 2) - (stateOrder[stateB] ?? 2);
931
- });
932
- this.filteredProviders = sortedProviders;
933
- }
934
-
935
- const updatedChoicesBase = this.createProviderChoices(sortedProviders, includeActions, statusMap);
928
+ // 只更新状态文字,不在用户操作过程中重排列表。
929
+ const updatedChoicesBase = this.createProviderChoices(providers, includeActions, statusMap);
936
930
  const updatedChoices = [...updatedChoicesBase];
937
931
 
938
932
  if (!includeActions) {
@@ -948,11 +942,18 @@ class EnvSwitcher extends BaseCommand {
948
942
  }
949
943
 
950
944
  const previousValue = this._getActivePromptPreviousValue(activePrompt);
945
+ const nextChoices = new Choices(updatedChoices, activePrompt.answers);
946
+ const message = this._buildStatusPromptMessage(providers.length, options.hasError);
947
+ const pageSize = this._getPageSize(updatedChoices.length);
948
+ const previousChoices = activePrompt.opt.choices.realChoices;
949
+ if (pageSize === activePrompt.opt.pageSize && message === activePrompt.opt.message && nextChoices.realChoices.length === previousChoices.length &&
950
+ nextChoices.realChoices.every((choice, index) => choice.name === previousChoices[index].name && choice.value === previousChoices[index].value)) return;
951
951
 
952
- activePrompt.opt.choices = new Choices(updatedChoices, activePrompt.answers);
952
+ activePrompt.opt.choices = nextChoices;
953
+ activePrompt.opt.pageSize = pageSize;
953
954
 
954
955
  this._restorePromptSelection(activePrompt, previousValue);
955
- activePrompt.opt.message = this._buildStatusPromptMessage(providers.length, options.hasError);
956
+ activePrompt.opt.message = message;
956
957
 
957
958
  activePrompt.render();
958
959
  }
package/src/config.js CHANGED
@@ -412,7 +412,7 @@ class ConfigManager {
412
412
  }
413
413
 
414
414
  // 使用不可变方式更新 config
415
- this.config = {
415
+ const nextConfig = {
416
416
  ...this.config,
417
417
  currentProvider: newCurrentProvider,
418
418
  providers: {
@@ -422,9 +422,11 @@ class ConfigManager {
422
422
  };
423
423
 
424
424
  // 保证 current 标记与 currentProvider 一致,避免出现多个 current 或丢失 current 的情况
425
- this._syncCurrentFlags();
425
+ for (const key of Object.keys(nextConfig.providers)) {
426
+ nextConfig.providers[key] = { ...nextConfig.providers[key], current: key === nextConfig.currentProvider };
427
+ }
426
428
 
427
- return await this.save();
429
+ return await this.save(nextConfig);
428
430
  }
429
431
 
430
432
  async removeProvider(name) {
@@ -487,8 +489,8 @@ class ConfigManager {
487
489
  }
488
490
  });
489
491
 
490
- this.config = { ...this.config, currentProvider: name, providers: updatedProviders };
491
- return await this.save();
492
+ const nextConfig = { ...this.config, currentProvider: name, providers: updatedProviders };
493
+ return await this.save(nextConfig);
492
494
  }
493
495
 
494
496
  async setCurrentProvider(name) {
@@ -511,13 +513,13 @@ class ConfigManager {
511
513
  });
512
514
 
513
515
  // 使用不可变方式更新 config
514
- this.config = {
516
+ const nextConfig = {
515
517
  ...this.config,
516
518
  currentProvider: name,
517
519
  providers: updatedProviders
518
520
  };
519
521
 
520
- return await this.save();
522
+ return await this.save(nextConfig);
521
523
  }
522
524
 
523
525
  /**
@@ -545,7 +547,7 @@ class ConfigManager {
545
547
  };
546
548
 
547
549
  // 使用不可变方式更新 config
548
- this.config = {
550
+ const nextConfig = {
549
551
  ...this.config,
550
552
  providers: {
551
553
  ...this.config.providers,
@@ -553,7 +555,7 @@ class ConfigManager {
553
555
  }
554
556
  };
555
557
 
556
- return await this.save();
558
+ return await this.save(nextConfig);
557
559
  }
558
560
 
559
561
  /**
@@ -599,7 +601,7 @@ class ConfigManager {
599
601
  };
600
602
 
601
603
  // 使用不可变方式更新 config
602
- this.config = {
604
+ const nextConfig = {
603
605
  ...this.config,
604
606
  providers: {
605
607
  ...this.config.providers,
@@ -607,7 +609,7 @@ class ConfigManager {
607
609
  }
608
610
  };
609
611
 
610
- return await this.save();
612
+ return await this.save(nextConfig);
611
613
  }
612
614
 
613
615
  /**
@@ -765,9 +767,8 @@ class ConfigManager {
765
767
  }
766
768
 
767
769
  async reset() {
768
- this.config = this.getDefaultConfig();
769
- this.isLoaded = true;
770
- return await this._performSave();
770
+ await this.ensureLoaded();
771
+ return await this.save(this.getDefaultConfig());
771
772
  }
772
773
  }
773
774
 
@@ -10,7 +10,7 @@ class EscNavigationManager {
10
10
  this.listenerBound = false;
11
11
  this.rawModeEnabled = false;
12
12
  this.previousRawMode = null;
13
- this.postCallbackDelay = typeof options.postCallbackDelay === 'number' ? options.postCallbackDelay : 50;
13
+ this.previousFlowing = null;
14
14
 
15
15
  this.supported = Boolean(
16
16
  this.input &&
@@ -34,8 +34,7 @@ class EscNavigationManager {
34
34
  const handler = {
35
35
  id: Symbol('esc-handler'),
36
36
  onTrigger: typeof options.onTrigger === 'function' ? options.onTrigger : null,
37
- once: options.once !== false,
38
- postDelay: typeof options.postDelay === 'number' ? options.postDelay : this.postCallbackDelay
37
+ once: options.once !== false
39
38
  };
40
39
 
41
40
  this.handlers.push(handler);
@@ -131,14 +130,12 @@ class EscNavigationManager {
131
130
  }
132
131
 
133
132
  if (handler.onTrigger) {
134
- setTimeout(() => {
135
- try {
136
- handler.onTrigger();
137
- } catch {
138
- // 在ESC回调中抛出的错误不应终止进程
139
- // 交由调用方自行处理记录
140
- }
141
- }, handler.postDelay);
133
+ // ESC 已经过组合键等待期,立即取消旧提示,避免回调落入下一个菜单。
134
+ try {
135
+ handler.onTrigger();
136
+ } catch {
137
+ // 交由调用方处理回调错误。
138
+ }
142
139
  }
143
140
  }
144
141
 
@@ -174,6 +171,7 @@ class EscNavigationManager {
174
171
 
175
172
  if (typeof this.input.resume === 'function') {
176
173
  try {
174
+ this.previousFlowing = this.input.readableFlowing;
177
175
  this.input.resume();
178
176
  } catch {
179
177
  // 某些输入流不支持 resume,忽略即可
@@ -193,6 +191,10 @@ class EscNavigationManager {
193
191
  if (this.listenerBound) {
194
192
  this.input.removeListener('data', this.handleData);
195
193
  this.listenerBound = false;
194
+ // 只恢复本管理器启动的输入流,避免退出后 stdin 仍阻止进程结束。
195
+ if (this.previousFlowing !== true && typeof this.input.pause === 'function') {
196
+ this.input.pause();
197
+ }
196
198
  }
197
199
 
198
200
  this.cancelPending();
@@ -611,7 +611,7 @@ async function clearCodexAkmConfig(options = {}) {
611
611
  buildSessionCacheAuthPath(codexHome)
612
612
  ])];
613
613
  const originals = await Promise.all(changedPaths.map(readFileSnapshot));
614
- await readExistingAuthJson(authJsonPath);
614
+ if (!forceRelogin) await readExistingAuthJson(authJsonPath);
615
615
  const existingToml = originals[1].exists ? originals[1].content.toString('utf8') : '';
616
616
  const cleanedToml = removeAkmModelProvider(removeTopLevelApiBaseUrl(existingToml));
617
617
  const cachedAuth = cachedAuthPath ? await fs.readFile(cachedAuthPath) : null;
@@ -628,7 +628,7 @@ async function clearCodexAkmConfig(options = {}) {
628
628
 
629
629
  // 指定账号时替换当前认证,未指定账号时保留现有官方认证。
630
630
  const shouldRemoveAuthJson = forceRelogin
631
- ? await shouldRemoveAuthJsonForRelogin(authJsonPath)
631
+ ? originals[0].exists
632
632
  : sessionKey
633
633
  ? await shouldRemoveAuthJsonForRelogin(authJsonPath)
634
634
  : await shouldRemoveAuthJsonForChatGptLogin(authJsonPath);
@@ -669,9 +669,8 @@ async function cacheCodexOfficialSession(options = {}) {
669
669
  }
670
670
 
671
671
  async function withCodexSessionRemoval(sessionKey, removeProvider) {
672
- const { acquireCodexLock } = require('./codex-lock');
673
- const release = await acquireCodexLock();
674
- try {
672
+ const { removeProviderRuntime } = require('./codex-runtime');
673
+ return removeProviderRuntime(sessionKey, async () => {
675
674
  const cachePath = buildSessionCacheAuthPath(resolveCodexHome(), sessionKey);
676
675
  const snapshot = await readFileSnapshot(cachePath);
677
676
  try {
@@ -685,14 +684,13 @@ async function withCodexSessionRemoval(sessionKey, removeProvider) {
685
684
  }
686
685
  throw error;
687
686
  }
688
- } finally {
689
- await release();
690
- }
687
+ });
691
688
  }
692
689
 
693
690
  module.exports = {
694
691
  resolveCodexHome,
695
692
  buildCodexPaths,
693
+ buildSessionCacheAuthPath,
696
694
  readCodexFiles,
697
695
  applyCodexConfig,
698
696
  clearCodexAkmConfig,
@@ -0,0 +1,130 @@
1
+ const fs = require('fs-extra');
2
+ const path = require('path');
3
+ const { BaseCommand } = require('../commands/BaseCommand');
4
+ const { compactTerminalText, escapeTerminalText, listPageSize } = require('./terminal-format');
5
+ const { resolveCodexHome } = require('./codex-files');
6
+
7
+ async function listCodexHistory(root = resolveCodexHome()) {
8
+ const history = [];
9
+ async function scan(directory) {
10
+ let entries;
11
+ try { entries = await fs.readdir(directory, { withFileTypes: true }); }
12
+ catch (error) { if (error.code === 'ENOENT') return; throw error; }
13
+ for (const entry of entries) {
14
+ const file = path.join(directory, entry.name);
15
+ if (entry.isDirectory()) await scan(file);
16
+ else if (entry.isFile() && entry.name.endsWith('.jsonl')) {
17
+ // 只读头部元数据,避免把完整对话加载进内存或显示在列表中。
18
+ let handle;
19
+ try {
20
+ try { handle = await fs.open(file, 'r'); }
21
+ catch (error) { if (error.code === 'ENOENT') continue; throw error; }
22
+ const chunks = [];
23
+ let offset = 0;
24
+ // 元数据可能包含长指令,分块读至首行结束,上限 4 MiB。
25
+ while (offset < 4 * 1024 * 1024) {
26
+ const buffer = Buffer.alloc(16384);
27
+ const { bytesRead } = await fs.read(handle, buffer, 0, buffer.length, offset);
28
+ if (!bytesRead) break;
29
+ chunks.push(buffer.subarray(0, bytesRead));
30
+ offset += bytesRead;
31
+ if (buffer.subarray(0, bytesRead).includes(10)) break;
32
+ }
33
+ const line = Buffer.concat(chunks).toString('utf8').split('\n')[0];
34
+ let meta;
35
+ try { meta = JSON.parse(line); } catch { continue; }
36
+ if (!meta || typeof meta !== 'object' || Array.isArray(meta)) continue;
37
+ const data = meta.payload;
38
+ if (meta.type !== 'session_meta' || !data || typeof data !== 'object' || Array.isArray(data) || typeof data.id !== 'string' || !/^[0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12}$/i.test(data.id)) continue;
39
+ const stat = await fs.fstat(handle);
40
+ history.push({ id: data.id, cwd: String(data.cwd || ''), timestamp: String(data.timestamp || meta.timestamp || ''), modifiedAt: stat.mtimeMs, provider: String(data.model_provider || '未知') });
41
+ } finally {
42
+ if (handle !== undefined) await fs.close(handle);
43
+ }
44
+ }
45
+ }
46
+ }
47
+ await scan(path.join(root, 'sessions'));
48
+ await scan(path.join(root, 'archived_sessions'));
49
+ const unique = new Map();
50
+ for (const item of history.sort((a, b) => b.modifiedAt - a.modifiedAt || a.id.localeCompare(b.id))) {
51
+ if (!unique.has(item.id)) unique.set(item.id, item);
52
+ }
53
+ return [...unique.values()];
54
+ }
55
+
56
+ async function normalizeDirectory(directory) {
57
+ if (!directory || !path.isAbsolute(directory)) return null;
58
+ let resolved = path.resolve(directory);
59
+ try { resolved = await fs.realpath(resolved); }
60
+ catch (error) { if (!['ENOENT', 'ENOTDIR'].includes(error.code)) throw error; }
61
+ return process.platform === 'win32' ? resolved.toLowerCase() : resolved;
62
+ }
63
+
64
+ async function selectCodexHistory(config, args) {
65
+ if (!args.includes('resume')) return args;
66
+ const history = await listCodexHistory();
67
+ if (!history.length) {
68
+ const error = new Error('没有可用的 Codex 历史对话');
69
+ error.code = 'SESSION_LOCKED';
70
+ throw error;
71
+ }
72
+ if (!process.stdin.isTTY || !process.stdout.isTTY) throw new Error('恢复历史需要交互终端,请交互选择历史或使用 --no-args 新建会话');
73
+ const currentDirectory = await normalizeDirectory(process.cwd());
74
+ const directories = new Map();
75
+ const local = [];
76
+ const other = [];
77
+ for (const item of history) {
78
+ if (!directories.has(item.cwd)) directories.set(item.cwd, await normalizeDirectory(item.cwd));
79
+ (directories.get(item.cwd) === currentDirectory ? local : other).push(item);
80
+ }
81
+ const navigation = new BaseCommand();
82
+ const limits = { local: 20, other: 20 };
83
+ let showOther = false;
84
+ let defaultId;
85
+ try {
86
+ let sessionId;
87
+ while (true) {
88
+ const group = showOther ? 'other' : 'local';
89
+ const items = showOther ? other : local;
90
+ const visible = items.slice(0, limits[group]);
91
+ const choices = visible.map(item => ({
92
+ name: compactTerminalText(`${item.id.slice(0, 8)} | ${new Date(item.modifiedAt).toLocaleString()} | ${path.basename(item.cwd) || '未知项目'} | ${item.provider}`),
93
+ value: item.id
94
+ }));
95
+ if (items.length > visible.length) choices.push({ name: `加载更多(已显示 ${visible.length}/${items.length})`, value: 'more' });
96
+ choices.push({ name: '新建会话(不恢复历史)', value: 'new' });
97
+ if (showOther) choices.push({ name: '返回当前文件夹', value: 'back' });
98
+ else if (other.length) choices.push({ name: '查看其他项目历史', value: 'other' });
99
+ choices.push({ name: '取消', value: null });
100
+ ({ sessionId } = await navigation.promptWithESCAndDefault({
101
+ type: 'list', name: 'sessionId', pageSize: listPageSize(choices.length),
102
+ message: showOther ? '选择其他项目历史(ESC 返回)' : local.length ? '选择当前文件夹的历史对话(创建新分支,ESC 取消)' : '当前文件夹没有历史对话,可新建会话或查看其他项目',
103
+ default: defaultId || visible[0]?.id || 'new', choices
104
+ }, '', null, { sessionId: showOther ? 'back' : null }));
105
+ defaultId = undefined;
106
+ if (sessionId === 'more') {
107
+ defaultId = items[limits[group]]?.id;
108
+ limits[group] += 20;
109
+ continue;
110
+ }
111
+ if (sessionId === 'other') { showOther = true; continue; }
112
+ if (sessionId === 'back') { showOther = false; continue; }
113
+ break;
114
+ }
115
+ if (sessionId === 'new') return args.filter(arg => arg !== 'resume');
116
+ if (!sessionId) return null;
117
+ const selected = history.find(item => item.id === sessionId);
118
+ const details = `ID: ${selected.id}\n目录: ${escapeTerminalText(selected.cwd)}\n原供应商: ${escapeTerminalText(selected.provider)}\n创建时间: ${escapeTerminalText(selected.timestamp)}\n最近使用: ${new Date(selected.modifiedAt).toLocaleString()}`;
119
+ const { confirmed } = await navigation.promptWithESCAndDefault({
120
+ type: 'confirm', name: 'confirmed', default: false,
121
+ message: `${details}\n将以供应商「${escapeTerminalText(config.displayName || config.name)}」处理所选历史上下文并创建新对话;若原供应商不同,历史内容会发送给新供应商。是否继续?`
122
+ }, '', null, { confirmed: false });
123
+ if (!confirmed) return null;
124
+ return ['fork', sessionId, ...args.filter(arg => arg !== 'resume')];
125
+ } finally {
126
+ navigation.destroy();
127
+ }
128
+ }
129
+
130
+ module.exports = { listCodexHistory, selectCodexHistory };
@@ -1,13 +1,10 @@
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');
7
+ const { trackProcessStart } = require('./process-start');
11
8
 
12
9
  /**
13
10
  * 构建 Codex CLI 环境变量
@@ -79,25 +76,20 @@ async function executeCodexWithEnv(config, launchArgs = [], launchOptions = {})
79
76
 
80
77
  // 在写入 Codex 配置文件前完成全部输入校验。
81
78
  const env = buildCodexEnvVariables(config);
82
- const releaseLock = await acquireCodexLock();
79
+ const selectedArgs = await selectCodexHistory(config, launchArgs);
80
+ if (!selectedArgs) return;
81
+ const runtime = await prepareCodexRuntime(config, launchOptions);
82
+ env.CODEX_HOME = runtime.home;
83
83
  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
84
  // 处理参数:子命令放前面,选项放后面
97
- const rawArgs = Array.isArray(launchArgs) ? [...launchArgs] : [];
85
+ const rawArgs = [...selectedArgs];
98
86
  const subcommands = rawArgs.filter(arg => !arg.startsWith('-'));
99
87
  const options = rawArgs.filter(arg => arg.startsWith('-'));
100
- const args = [...subcommands, ...options];
88
+ const args = [...subcommands, ...options,
89
+ '-c', 'cli_auth_credentials_store="file"',
90
+ '-c', `sqlite_home=${JSON.stringify(runtime.home)}`,
91
+ '-c', `model_provider="${authMode === 'chatgpt_login' || !config.baseUrl ? 'openai' : 'akm'}"`
92
+ ];
101
93
 
102
94
  clearTerminal();
103
95
 
@@ -113,6 +105,7 @@ async function executeCodexWithEnv(config, launchArgs = [], launchOptions = {})
113
105
  env,
114
106
  shell: false
115
107
  });
108
+ const waitForStart = trackProcessStart(child, launchOptions.onStarted);
116
109
 
117
110
  let stderrOutput = '';
118
111
  let spawnFailed = false;
@@ -135,14 +128,7 @@ async function executeCodexWithEnv(config, launchArgs = [], launchOptions = {})
135
128
  child.on('close', async (code, signal) => {
136
129
  cleanupSignals();
137
130
  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
- }
131
+ await waitForStart();
146
132
  if (code === 0 || code === 130 || signal === 'SIGINT') {
147
133
  resolve();
148
134
  } else {
@@ -153,13 +139,13 @@ async function executeCodexWithEnv(config, launchArgs = [], launchOptions = {})
153
139
  errorOutput.includes('failed to resume session') ||
154
140
  errorOutput.includes('thread already has an active');
155
141
 
156
- if (isSessionLockedError) {
142
+ if (isSessionLockedError && !rawArgs.includes('fork')) {
157
143
  const error = new Error('Codex 会话被锁定或无法恢复');
158
144
  error.code = 'SESSION_LOCKED';
159
145
  reject(error);
160
146
  } else {
161
147
  const error = new Error(`Codex CLI 异常退出,退出代码: ${code}${stderrOutput.trim() ? `\n${stderrOutput.trim()}` : ''}`);
162
- if (rawArgs.includes('resume') && code === 1) error.code = 'RESUME_FAILED';
148
+ if (launchArgs.includes('resume') && code === 1) error.code = 'RESUME_FAILED';
163
149
  reject(error);
164
150
  }
165
151
  }
@@ -176,7 +162,7 @@ async function executeCodexWithEnv(config, launchArgs = [], launchOptions = {})
176
162
  });
177
163
  });
178
164
  } finally {
179
- await releaseLock();
165
+ await runtime.release();
180
166
  }
181
167
  }
182
168
 
@@ -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 };
@@ -2,6 +2,7 @@ const spawn = require('cross-spawn');
2
2
  const { sanitizeEnvValue, clearTerminal } = require('./env-utils');
3
3
  const { assertSupportedLaunchArgs } = require('./launch-args');
4
4
  const { validator } = require('./validator');
5
+ const { trackProcessStart } = require('./process-start');
5
6
 
6
7
  function buildEnvVariables(config) {
7
8
  const env = { ...process.env };
@@ -48,7 +49,7 @@ function buildEnvVariables(config) {
48
49
  }
49
50
  }
50
51
 
51
- async function executeWithEnv(config, launchArgs = []) {
52
+ async function executeWithEnv(config, launchArgs = [], launchOptions = {}) {
52
53
  assertSupportedLaunchArgs('claude', launchArgs);
53
54
  const env = buildEnvVariables(config);
54
55
  const args = [...launchArgs];
@@ -63,6 +64,7 @@ async function executeWithEnv(config, launchArgs = []) {
63
64
  env,
64
65
  shell: false
65
66
  });
67
+ const waitForStart = trackProcessStart(child, launchOptions.onStarted);
66
68
 
67
69
  let stderrOutput = '';
68
70
 
@@ -73,7 +75,8 @@ async function executeWithEnv(config, launchArgs = []) {
73
75
  process.stderr.write(data);
74
76
  });
75
77
 
76
- child.on('close', (code, signal) => {
78
+ child.on('close', async (code, signal) => {
79
+ await waitForStart();
77
80
  if (code === 0 || code === 130 || signal === 'SIGINT') {
78
81
  resolve();
79
82
  } else {
@@ -6,7 +6,9 @@ async function acquireFileLock(lockPath, busyMessage) {
6
6
  handle = await fs.open(lockPath, 'wx', 0o600);
7
7
  } catch (error) {
8
8
  if (error.code !== 'EEXIST') throw error;
9
- throw new Error(`${busyMessage}\n若进程异常终止,请确认相关进程均已退出后手动删除锁文件:${lockPath}`);
9
+ const busy = new Error(`${busyMessage}\n若进程异常终止,请确认相关进程均已退出后手动删除锁文件:${lockPath}`);
10
+ busy.code = 'LOCK_BUSY';
11
+ throw busy;
10
12
  }
11
13
  try {
12
14
  await fs.write(handle, String(process.pid));
@@ -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
 
@@ -0,0 +1,15 @@
1
+ const { Logger } = require('./logger');
2
+
3
+ function trackProcessStart(child, onStarted) {
4
+ let task = Promise.resolve();
5
+ child.on('spawn', () => {
6
+ if (!onStarted) return;
7
+ task = Promise.resolve().then(onStarted).catch(error => {
8
+ // 统计保存失败不应中断已经启动的交互进程。
9
+ Logger.warning(`进程已启动,但记录供应商使用状态失败: ${error.message}`);
10
+ });
11
+ });
12
+ return () => task;
13
+ }
14
+
15
+ module.exports = { trackProcessStart };
@@ -52,8 +52,28 @@ function formatMessage(message, type = 'info') {
52
52
  return formatter(`${symbol} ${message}`);
53
53
  }
54
54
 
55
+ function listPageSize(count) {
56
+ return Math.max(1, Math.min(count, 15, (process.stdout.rows || 24) - 8));
57
+ }
58
+
59
+ function compactTerminalText(value, columns = (process.stdout.columns || 80) - 4) {
60
+ const text = escapeTerminalText(value);
61
+ let width = 0;
62
+ let result = '';
63
+ // 非 ASCII 字符保守按两列计算,避免中文和 emoji 在窄终端换行。
64
+ for (const character of text) {
65
+ const size = character.codePointAt(0) > 127 ? 2 : 1;
66
+ if (width + size > Math.max(0, columns - 2)) return result + '..';
67
+ width += size;
68
+ result += character;
69
+ }
70
+ return result;
71
+ }
72
+
55
73
  module.exports = {
56
74
  containsUnsafeTerminalCharacters,
57
75
  escapeTerminalText,
76
+ listPageSize,
77
+ compactTerminalText,
58
78
  formatMessage
59
79
  };
@@ -1,13 +0,0 @@
1
- const fs = require('fs-extra');
2
- const path = require('path');
3
- const { acquireFileLock } = require('./file-lock');
4
-
5
- async function acquireCodexLock() {
6
- const { resolveCodexHome } = require('./codex-files');
7
- const home = resolveCodexHome();
8
- await fs.ensureDir(home);
9
- const lockPath = path.join(home, '.akm-launch.lock');
10
- return acquireFileLock(lockPath, '此 Codex 目录已有 AKM 会话运行,请先退出该会话。');
11
- }
12
-
13
- module.exports = { acquireCodexLock };