@pikecode/api-key-manager 2.2.2 → 2.2.4

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 CHANGED
@@ -2,7 +2,48 @@
2
2
 
3
3
  记录项目的功能、修复和兼容性变化。以下历史条目依据 Git 提交补录,不代表已核实 npm 发布状态。
4
4
 
5
- ## 未发布(当前目标版本 2.2.2)
5
+ ## 未发布(当前目标版本 2.2.4)
6
+
7
+ ### 修复
8
+
9
+ - 历史分支确认区分同一供应商配置、不同供应商配置和来源无法确认,避免每次重复显示固定的跨供应商提醒。
10
+ - 第三方新对话使用独立模型供应商标识记录来源,名称、端点或认证变化后视为不同配置;不修改原历史。旧 `akm` 历史及官方 `openai` 账号无法精确区分时明确提示未知,不猜测归属。
11
+ - 官方登录仍使用原生 `openai` 标识;所有历史分支保留确认,默认不继续。
12
+ - 历史列表和确认页将内部来源标识映射为可读供应商名称,无法匹配时明确标为来源未确认,不猜测官方账号。
13
+ - 确认页选择“否”返回原列表,保留项目分组、已加载批次和选中项;ESC 取消启动。
14
+
15
+ ### 验证
16
+
17
+ - 61 个测试套件、643 项测试、Lint 和覆盖率门槛通过,覆盖来源分支文案及独立模型供应商启动参数。原生 Codex 0.166.0 app-server 离线分支验证通过:目标标识写入新历史,原文件未变化。使用临时目录和模拟历史,未执行真实模型请求。
18
+
19
+ ## 2.2.3
20
+
21
+
22
+ ### 修复
23
+
24
+ - 配置添加、激活、切换、参数记忆、统计、重置和导入使用候选配置,保存成功后才更新内存,防止失败修改被后续操作写入。
25
+ - 显式 `--relogin` 可备份并清理损坏的认证文件;普通启动仍拒绝损坏认证,保留原内容。
26
+ - 历史列表跳过 `null`、数组、非对象和非法会话元数据,单条异常记录不再阻断全部正常历史。
27
+ - 子进程创建后才记录当前供应商、使用次数和启动参数;取消历史选择或未创建进程时不记录。状态保存失败单独提示,不中断已创建的进程。
28
+ - 历史按会话文件最近修改时间排序,并保留创建时间展示;重复 ID 优先使用最近修改的记录。
29
+ - 历史选择优先匹配当前工作目录,默认选中该目录最近使用的对话;无匹配时默认新建,其他项目历史需主动进入查看。使用规范化完整路径及真实路径匹配,避免同名目录误匹配,并兼容目录链接。
30
+
31
+ - 终端列表状态刷新保持顺序和选中项,连续回调合并刷新、相同内容跳过重绘,过期提示不再刷新;检测失败通过提示行展示。
32
+ - Codex 历史每批展示 20 条并支持加载更多,短条目按终端宽度截断,完整信息在确认页展示;统一 ESC 返回/取消,列表页大小按终端高度调整。首次仍扫描全部历史头部元数据。
33
+
34
+ - 移除 ESC 识别后的两层延迟回调,避免旧菜单通知或清屏落入新菜单;保留组合键识别等待,方向键不会直接触发返回。
35
+ - 供应商条目按终端宽度截断,状态文字限制长度并转义控制字符,避免长错误信息改变列表行数;修正管理列表将在线状态 `0` 当作空值的初始排序错误。
36
+
37
+ - ESC 监听结束时恢复输入流状态:原本未流动的 stdin 在清理时暂停,原本已流动的输入保持不变,修复交互终端运行测试后进程无法自然退出的问题。
38
+
39
+ ### 验证
40
+
41
+ - 60 个测试套件、632 项测试、Lint 和项目覆盖率门槛通过。
42
+ - 伪终端使用真实 Inquirer 验证 ESC 取消、下一菜单连续下移跨页及回车,返回预期条目;未覆盖所有终端模拟器与动态缩放。
43
+ - 交互终端普通测试可自然退出;`--detectOpenHandles` 模式仍可能列出 stdin 的 `TTYWRAP`,但修复后进程也能自行结束。新增输入流三种初始状态的清理回归测试。
44
+ - 版本元数据同步为 2.2.3;未执行发布。
45
+
46
+ ## 2.2.2(历史补录)
6
47
 
7
48
  ### 功能与行为调整
8
49
 
package/README.md CHANGED
@@ -396,7 +396,11 @@ AKM 使用 `<CODEX_HOME>/akm-providers/<供应商标识>/` 保存各供应商独
396
396
 
397
397
  `sessions` 和 `archived_sessions` 通过目录链接共享,历史文件无需搬迁;SQLite 数据库与认证保持隔离。已有的 `skills`、`rules`、`plugins` 目录也会链接到原位置。Windows 使用目录联接(junction)。
398
398
 
399
- 选择“从历史继续”后,AKM 列出共享历史(包含其他供应商和项目),显示时间、目录、原模型供应商和对话 ID。确认目标供应商后使用 `codex fork <ID>` 创建新对话,原历史保持不变,多个窗口可以从同一历史分叉。跨供应商继续会向新供应商发送恢复所需的上下文,因此默认不确认;非交互终端不会自动选择历史。此功能需要支持 `codex fork` 的 Codex CLI,已使用 0.166.0 的原生接口验证。分叉失败会显示原因,不静默丢弃历史。
399
+ 选择“从历史继续”后,AKM 优先列出当前工作目录的历史(包括不同供应商),按会话文件最近修改时间排序,默认选中最近的一条;只有一条时默认选中该条。目录按规范化完整路径与真实路径匹配,不按文件夹名称匹配。当前目录没有历史时,默认选择新建会话;需要跨项目继续时,可主动选择“查看其他项目历史”,也可返回当前目录列表。列表每批展示 20 条,可选择“加载更多”,默认定位到新增批次第一条。列表使用短 ID、最近使用时间、项目名和原供应商,按终端宽度截断;确认页展示完整 ID、路径及创建时间。在其他项目列表按 ESC 返回当前目录,在当前目录列表或确认页按 ESC 取消。列表页大小按显示时的终端高度调整,最多 15 行。分批展示只减少菜单条目,首次仍扫描共享历史文件的头部元数据。单条非法元数据会被跳过。确认目标供应商后使用 `codex fork <ID>` 创建新对话,原历史保持不变,多个窗口可以从同一历史分叉。跨供应商继续会向新供应商发送恢复所需的上下文,因此默认不确认;非交互终端不会自动选择历史。此功能需要支持 `codex fork` 的 Codex CLI,已使用 0.166.0 的原生接口验证。分叉失败会显示原因,不静默丢弃历史。
400
+
401
+ 供应商列表异步检测状态时保持顺序和选中项不变,合并连续刷新并跳过相同内容;状态检测失败显示在提示行,避免日志插入活动菜单。供应商条目按终端宽度截断,状态文字限制长度;截断仅影响显示,选择仍使用完整供应商名称。ESC 识别后立即取消当前提示并执行返回通知,不再延迟写入下一菜单。
402
+
403
+ 取消历史选择不会改变当前供应商或使用统计。AKM 在操作系统确认子进程创建后记录使用状态;这表示进程已创建,不代表模型认证或请求已经成功。
400
404
 
401
405
  同一供应商的首次网页登录未完成时,先完成该窗口认证,再打开更多窗口。`--relogin`、修改密钥或认证配置、删除官方账号需要先退出该供应商的所有窗口,其他供应商可继续运行。该选项不会撤销服务端 Token 或清理浏览器登录状态。
402
406
 
@@ -540,7 +544,7 @@ Codex CLI:
540
544
 
541
545
  ### 切换 Codex 后提示 "Token data is not available"
542
546
 
543
- 检查对应供应商独立目录中的 `auth.json`。退出该供应商的所有窗口后再启动;官方账号可使用 `--relogin` 重新认证:
547
+ 检查对应供应商独立目录中的 `auth.json`。退出该供应商的所有窗口后再启动;官方账号可使用 `akm <供应商> --relogin` 重新认证。若认证 JSON 已损坏,显式重新登录会先备份原始文件,再清理认证;普通启动不会覆盖损坏文件:
544
548
 
545
549
  ```bash
546
550
  akm my-codex
@@ -598,3 +602,5 @@ MIT License
598
602
  - [NPM](https://www.npmjs.com/package/@pikecode/api-key-manager)
599
603
  - [GitHub](https://github.com/pikecode/api-key-manager)
600
604
  - [Issues](https://github.com/pikecode/api-key-manager/issues)
605
+
606
+ 历史恢复的确认文案会区分来源:同一第三方配置只提示创建新分支;不同配置提示上下文将发送给当前供应商;无法确定来源时明确提示未知。新建第三方对话会记录独立的模型供应商标识,旧历史不会被改写。多个官方账号仍共享原生 `openai` 标识,因此无法仅凭历史元数据判断账号是否相同。供应商名称、端点或认证改变后视为不同配置。所有情况仍需确认创建分支,默认选择“否”:返回历史列表并保留分组、已加载批次和选中项;确认页按 ESC 取消启动。历史来源可匹配现有配置时显示供应商名称,旧第三方、官方账号及已变更或删除的配置显示相应的来源未确认说明,不直接展示内部摘要标识。
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pikecode/api-key-manager",
3
- "version": "2.2.2",
3
+ "version": "2.2.4",
4
4
  "description": "A CLI tool for managing and switching multiple API provider configurations",
5
5
  "main": "src/index.js",
6
6
  "bin": {
@@ -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);
@@ -1,7 +1,10 @@
1
1
  const fs = require('fs-extra');
2
+ const { codexProviderIdentity, historyConfirmation } = require('./codex-provider-identity');
2
3
  const path = require('path');
3
- const inquirer = require('inquirer');
4
+ const { BaseCommand } = require('../commands/BaseCommand');
5
+ const { compactTerminalText, escapeTerminalText, listPageSize } = require('./terminal-format');
4
6
  const { resolveCodexHome } = require('./codex-files');
7
+ const { configManager } = require('../config');
5
8
 
6
9
  async function listCodexHistory(root = resolveCodexHome()) {
7
10
  const history = [];
@@ -32,9 +35,11 @@ async function listCodexHistory(root = resolveCodexHome()) {
32
35
  const line = Buffer.concat(chunks).toString('utf8').split('\n')[0];
33
36
  let meta;
34
37
  try { meta = JSON.parse(line); } catch { continue; }
38
+ if (!meta || typeof meta !== 'object' || Array.isArray(meta)) continue;
35
39
  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 || '未知') });
40
+ 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;
41
+ const stat = await fs.fstat(handle);
42
+ history.push({ id: data.id, cwd: String(data.cwd || ''), timestamp: String(data.timestamp || meta.timestamp || ''), modifiedAt: stat.mtimeMs, provider: String(data.model_provider || '未知') });
38
43
  } finally {
39
44
  if (handle !== undefined) await fs.close(handle);
40
45
  }
@@ -43,7 +48,19 @@ async function listCodexHistory(root = resolveCodexHome()) {
43
48
  }
44
49
  await scan(path.join(root, 'sessions'));
45
50
  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()];
51
+ const unique = new Map();
52
+ for (const item of history.sort((a, b) => b.modifiedAt - a.modifiedAt || a.id.localeCompare(b.id))) {
53
+ if (!unique.has(item.id)) unique.set(item.id, item);
54
+ }
55
+ return [...unique.values()];
56
+ }
57
+
58
+ async function normalizeDirectory(directory) {
59
+ if (!directory || !path.isAbsolute(directory)) return null;
60
+ let resolved = path.resolve(directory);
61
+ try { resolved = await fs.realpath(resolved); }
62
+ catch (error) { if (!['ENOENT', 'ENOTDIR'].includes(error.code)) throw error; }
63
+ return process.platform === 'win32' ? resolved.toLowerCase() : resolved;
47
64
  }
48
65
 
49
66
  async function selectCodexHistory(config, args) {
@@ -55,20 +72,73 @@ async function selectCodexHistory(config, args) {
55
72
  throw error;
56
73
  }
57
74
  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')];
75
+ await configManager.ensureLoaded();
76
+ const providerNames = new Map();
77
+ for (const provider of [...configManager.listProviders().filter(item => item.ideName === 'codex'), config]) {
78
+ const identity = codexProviderIdentity(provider);
79
+ // openai 标识无法区分账号,不能映射为某一个官方配置名称。
80
+ if (identity !== 'openai') providerNames.set(identity, provider.displayName || provider.name);
81
+ }
82
+ const providerLabel = identity => providerNames.get(identity) ||
83
+ (identity === 'openai' ? 'OpenAI(账号未确认)' : identity === 'akm' ? '第三方(来源未确认)' : '未知来源');
84
+ const currentDirectory = await normalizeDirectory(process.cwd());
85
+ const directories = new Map();
86
+ const local = [];
87
+ const other = [];
88
+ for (const item of history) {
89
+ if (!directories.has(item.cwd)) directories.set(item.cwd, await normalizeDirectory(item.cwd));
90
+ (directories.get(item.cwd) === currentDirectory ? local : other).push(item);
91
+ }
92
+ const navigation = new BaseCommand();
93
+ const limits = { local: 20, other: 20 };
94
+ let showOther = false;
95
+ let defaultId;
96
+ try {
97
+ let sessionId;
98
+ while (true) {
99
+ const group = showOther ? 'other' : 'local';
100
+ const items = showOther ? other : local;
101
+ const visible = items.slice(0, limits[group]);
102
+ const choices = visible.map(item => ({
103
+ name: compactTerminalText(`${item.id.slice(0, 8)} | ${new Date(item.modifiedAt).toLocaleString()} | ${path.basename(item.cwd) || '未知项目'} | ${providerLabel(item.provider)}`),
104
+ value: item.id
105
+ }));
106
+ if (items.length > visible.length) choices.push({ name: `加载更多(已显示 ${visible.length}/${items.length})`, value: 'more' });
107
+ choices.push({ name: '新建会话(不恢复历史)', value: 'new' });
108
+ if (showOther) choices.push({ name: '返回当前文件夹', value: 'back' });
109
+ else if (other.length) choices.push({ name: '查看其他项目历史', value: 'other' });
110
+ choices.push({ name: '取消', value: null });
111
+ ({ sessionId } = await navigation.promptWithESCAndDefault({
112
+ type: 'list', name: 'sessionId', pageSize: listPageSize(choices.length),
113
+ message: showOther ? '选择其他项目历史(ESC 返回)' : local.length ? '选择当前文件夹的历史对话(创建新分支,ESC 取消)' : '当前文件夹没有历史对话,可新建会话或查看其他项目',
114
+ default: defaultId || visible[0]?.id || 'new', choices
115
+ }, '', null, { sessionId: showOther ? 'back' : null }));
116
+ defaultId = undefined;
117
+ if (sessionId === 'more') {
118
+ defaultId = items[limits[group]]?.id;
119
+ limits[group] += 20;
120
+ continue;
121
+ }
122
+ if (sessionId === 'other') { showOther = true; continue; }
123
+ if (sessionId === 'back') { showOther = false; continue; }
124
+ if (sessionId === 'new') return args.filter(arg => arg !== 'resume');
125
+ if (!sessionId) return null;
126
+ const selected = history.find(item => item.id === sessionId);
127
+ const details = `ID: ${selected.id}\n目录: ${escapeTerminalText(selected.cwd)}\n原供应商: ${escapeTerminalText(providerLabel(selected.provider))}\n创建时间: ${escapeTerminalText(selected.timestamp)}\n最近使用: ${new Date(selected.modifiedAt).toLocaleString()}`;
128
+ const { confirmed } = await navigation.promptWithESCAndDefault({
129
+ type: 'confirm', name: 'confirmed', default: false,
130
+ message: `${details}\n当前供应商:「${escapeTerminalText(config.displayName || config.name)}」。${historyConfirmation(selected.provider, config)}(否:返回列表;ESC:取消启动)`
131
+ }, '', null, { confirmed: null });
132
+ if (confirmed === null) return null;
133
+ if (!confirmed) {
134
+ defaultId = sessionId;
135
+ continue;
136
+ }
137
+ return ['fork', sessionId, ...args.filter(arg => arg !== 'resume')];
138
+ }
139
+ } finally {
140
+ navigation.destroy();
141
+ }
72
142
  }
73
143
 
74
144
  module.exports = { listCodexHistory, selectCodexHistory };
@@ -1,9 +1,11 @@
1
1
  const spawn = require('cross-spawn');
2
+ const { codexProviderIdentity } = require('./codex-provider-identity');
2
3
  const { sanitizeEnvValue, clearTerminal } = require('./env-utils');
3
4
  const { prepareCodexRuntime } = require('./codex-runtime');
4
5
  const { selectCodexHistory } = require('./codex-history');
5
6
  const { assertSupportedLaunchArgs } = require('./launch-args');
6
7
  const { validator } = require('./validator');
8
+ const { trackProcessStart } = require('./process-start');
7
9
 
8
10
  /**
9
11
  * 构建 Codex CLI 环境变量
@@ -87,9 +89,17 @@ async function executeCodexWithEnv(config, launchArgs = [], launchOptions = {})
87
89
  const args = [...subcommands, ...options,
88
90
  '-c', 'cli_auth_credentials_store="file"',
89
91
  '-c', `sqlite_home=${JSON.stringify(runtime.home)}`,
90
- '-c', `model_provider="${authMode === 'chatgpt_login' || !config.baseUrl ? 'openai' : 'akm'}"`
92
+ '-c', `model_provider="${codexProviderIdentity(config)}"`
91
93
  ];
92
94
 
95
+ const providerKey = codexProviderIdentity(config);
96
+ if (providerKey !== 'openai') {
97
+ // 独立标识写入原生会话元数据,多窗口无需猜测历史文件的归属。
98
+ for (const [field, value] of Object.entries({ name: providerKey, base_url: config.baseUrl, wire_api: 'responses', requires_openai_auth: true })) {
99
+ args.push('-c', `model_providers.${providerKey}.${field}=${JSON.stringify(value)}`);
100
+ }
101
+ }
102
+
93
103
  clearTerminal();
94
104
 
95
105
  if (authMode === 'chatgpt_login') {
@@ -104,6 +114,7 @@ async function executeCodexWithEnv(config, launchArgs = [], launchOptions = {})
104
114
  env,
105
115
  shell: false
106
116
  });
117
+ const waitForStart = trackProcessStart(child, launchOptions.onStarted);
107
118
 
108
119
  let stderrOutput = '';
109
120
  let spawnFailed = false;
@@ -126,6 +137,7 @@ async function executeCodexWithEnv(config, launchArgs = [], launchOptions = {})
126
137
  child.on('close', async (code, signal) => {
127
138
  cleanupSignals();
128
139
  if (spawnFailed) return;
140
+ await waitForStart();
129
141
  if (code === 0 || code === 130 || signal === 'SIGINT') {
130
142
  resolve();
131
143
  } else {
@@ -0,0 +1,25 @@
1
+ const crypto = require('crypto');
2
+
3
+ function codexProviderIdentity(config) {
4
+ if (config.authMode === 'chatgpt_login' || !config.baseUrl) return 'openai';
5
+ // 认证或端点变化后视为不同来源,不保存明文密钥。
6
+ const digest = crypto.createHash('sha256').update(JSON.stringify([
7
+ config.name, config.baseUrl, config.authMode || 'api_key', config.authToken || ''
8
+ ])).digest('hex');
9
+ return `akm_${digest}`;
10
+ }
11
+
12
+ function historyConfirmation(provider, config) {
13
+ const target = codexProviderIdentity(config);
14
+ if (/^akm_[a-f0-9]{64}$/.test(provider) && provider === target) {
15
+ return '所选历史来自当前供应商配置,将创建新对话分支,原对话保留。是否继续?';
16
+ }
17
+ if ((/^akm_[a-f0-9]{64}$/.test(provider) && provider !== target) ||
18
+ (provider === 'akm' && target === 'openai') ||
19
+ (provider === 'openai' && target !== 'openai')) {
20
+ return '所选历史来自其他供应商配置,恢复所需的历史内容将发送给当前供应商,并创建新对话分支。是否继续?';
21
+ }
22
+ return '无法确认所选历史是否来自当前供应商或账号。继续后,恢复所需的历史内容将由当前供应商处理,并创建新对话分支。是否继续?';
23
+ }
24
+
25
+ module.exports = { codexProviderIdentity, historyConfirmation };
@@ -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 {
@@ -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
  };