@pikecode/api-key-manager 2.2.0 → 2.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -207,6 +207,8 @@ akm remove my-provider
207
207
  3. 预览将要删除的供应商列表
208
208
  4. 最终确认后批量删除
209
209
 
210
+ 删除 Codex 官方网页登录供应商时,会同时清理该名称的本地 Session 缓存;以后添加同名供应商需要重新认证。若同一 Codex 目录仍有 AKM 会话运行,删除会被阻止,请先退出会话。删除失败会恢复缓存;该操作不会撤销服务端 Token,也不会清理历史备份或其他账号的缓存。
211
+
210
212
  ### 编辑供应商
211
213
 
212
214
  ```bash
@@ -396,6 +398,10 @@ Codex 的不同账号共享历史目录,但 AKM 会对同一 `CODEX_HOME`(
396
398
 
397
399
  更新检查结果(包括失败结果)缓存在 `~/.akm-update-check.json`,24 小时内不重复请求 npm。可通过 `CC_NO_UPDATE_CHECK=1` 禁用检查。
398
400
 
401
+ 选择更新并重启后,旧进程会等待新版命令结束,再以相同退出码退出,不重复执行原命令。重启失败时会提示手动重新运行。
402
+
403
+ 配置读写使用短时文件锁,多个终端同时修改时会提示重试,避免后保存的配置覆盖先前修改。异常强杀后若遗留 `~/.akm-config.json.lock`,须确认相关 AKM 进程已退出后再清理。
404
+
399
405
  ### 多账号配置
400
406
 
401
407
  ```bash
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.1",
4
4
  "description": "A CLI tool for managing and switching multiple API provider configurations",
5
5
  "main": "src/index.js",
6
6
  "bin": {
@@ -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,6 +668,28 @@ 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 { acquireCodexLock } = require('./codex-lock');
673
+ const release = await acquireCodexLock();
674
+ try {
675
+ const cachePath = buildSessionCacheAuthPath(resolveCodexHome(), sessionKey);
676
+ const snapshot = await readFileSnapshot(cachePath);
677
+ try {
678
+ await fs.remove(cachePath);
679
+ return await removeProvider();
680
+ } catch (error) {
681
+ try {
682
+ await restoreFileSnapshot(cachePath, snapshot);
683
+ } catch (rollbackError) {
684
+ throw new Error(`删除失败且 Session 缓存恢复失败: ${error.message}; ${rollbackError.message}`, { cause: error });
685
+ }
686
+ throw error;
687
+ }
688
+ } finally {
689
+ await release();
690
+ }
691
+ }
692
+
671
693
  module.exports = {
672
694
  resolveCodexHome,
673
695
  buildCodexPaths,
@@ -675,6 +697,7 @@ module.exports = {
675
697
  applyCodexConfig,
676
698
  clearCodexAkmConfig,
677
699
  cacheCodexOfficialSession,
700
+ withCodexSessionRemoval,
678
701
  backupCodexFiles,
679
702
  removeTopLevelApiBaseUrl,
680
703
  removeAkmModelProvider,
@@ -1,28 +1,13 @@
1
1
  const fs = require('fs-extra');
2
2
  const path = require('path');
3
- const { resolveCodexHome } = require('./codex-files');
3
+ const { acquireFileLock } = require('./file-lock');
4
4
 
5
5
  async function acquireCodexLock() {
6
+ const { resolveCodexHome } = require('./codex-files');
6
7
  const home = resolveCodexHome();
7
8
  await fs.ensureDir(home);
8
9
  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);
10
+ return acquireFileLock(lockPath, '此 Codex 目录已有 AKM 会话运行,请先退出该会话。');
26
11
  }
27
12
 
28
13
  module.exports = { acquireCodexLock };
@@ -0,0 +1,23 @@
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
+ throw new Error(`${busyMessage}\n若进程异常终止,请确认相关进程均已退出后手动删除锁文件:${lockPath}`);
10
+ }
11
+ try {
12
+ await fs.write(handle, String(process.pid));
13
+ } catch (error) {
14
+ await fs.close(handle);
15
+ await fs.remove(lockPath);
16
+ throw error;
17
+ }
18
+ await fs.close(handle);
19
+ // shortcut: 强杀后的锁须人工确认进程退出后清理,避免误删仍被使用的锁。
20
+ return () => fs.remove(lockPath);
21
+ }
22
+
23
+ module.exports = { acquireFileLock };
@@ -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 {