@pikecode/api-key-manager 2.1.9 → 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 +18 -0
- package/bin/akm.js +2 -1
- package/package.json +1 -1
- package/src/commands/BaseCommand.js +4 -1
- package/src/commands/batch.js +1 -1
- package/src/commands/remove.js +2 -2
- package/src/commands/switch/provider-manager.js +1 -1
- package/src/commands/switch.js +13 -2
- package/src/config.js +30 -7
- package/src/utils/codex-files.js +47 -11
- package/src/utils/codex-launcher.js +81 -63
- package/src/utils/codex-lock.js +13 -0
- package/src/utils/env-launcher.js +4 -3
- package/src/utils/file-lock.js +23 -0
- package/src/utils/update-checker.js +39 -20
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
|
|
@@ -384,6 +386,22 @@ akm openai-work --relogin
|
|
|
384
386
|
akm switch openai-work --relogin
|
|
385
387
|
```
|
|
386
388
|
|
|
389
|
+
### 会话恢复与运行保护
|
|
390
|
+
|
|
391
|
+
Codex 的不同账号共享历史目录,但 AKM 会对同一 `CODEX_HOME`(默认 `~/.codex`)限制同时运行一个 Codex 会话,防止认证信息互相覆盖。退出当前会话后再切换账号。该保护仅覆盖通过 AKM 启动的进程,请勿同时用原生 `codex` 命令切换同一目录的认证。
|
|
392
|
+
|
|
393
|
+
正常退出会释放目录锁;强制杀死 AKM 后可能留下 `.akm-launch.lock`。只有确认该目录相关的 AKM 和 Codex 进程都已退出,才可手动删除此锁文件后重试。
|
|
394
|
+
|
|
395
|
+
`--relogin` 只在首次启动时清理本地认证;历史恢复失败后的自动重试会保留新登录态。该选项不会撤销服务端 Token 或清理浏览器登录状态。
|
|
396
|
+
|
|
397
|
+
恢复历史时,明确的历史缺失或锁定错误会自动改为新会话;其他退出码为 1 的错误会保留原因,在交互终端询问是否新开会话,默认不重试。非交互环境直接返回错误。
|
|
398
|
+
|
|
399
|
+
更新检查结果(包括失败结果)缓存在 `~/.akm-update-check.json`,24 小时内不重复请求 npm。可通过 `CC_NO_UPDATE_CHECK=1` 禁用检查。
|
|
400
|
+
|
|
401
|
+
选择更新并重启后,旧进程会等待新版命令结束,再以相同退出码退出,不重复执行原命令。重启失败时会提示手动重新运行。
|
|
402
|
+
|
|
403
|
+
配置读写使用短时文件锁,多个终端同时修改时会提示重试,避免后保存的配置覆盖先前修改。异常强杀后若遗留 `~/.akm-config.json.lock`,须确认相关 AKM 进程已退出后再清理。
|
|
404
|
+
|
|
387
405
|
### 多账号配置
|
|
388
406
|
|
|
389
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
|
@@ -211,7 +211,10 @@ class BaseCommand {
|
|
|
211
211
|
if (this.isEscCancelled(error)) {
|
|
212
212
|
return;
|
|
213
213
|
}
|
|
214
|
-
|
|
214
|
+
if (!error.commandContext) {
|
|
215
|
+
error.commandContext = context;
|
|
216
|
+
error.message = `${context}失败: ${error.message}`;
|
|
217
|
+
}
|
|
215
218
|
throw error;
|
|
216
219
|
}
|
|
217
220
|
|
package/src/commands/batch.js
CHANGED
|
@@ -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" 以确认';
|
package/src/commands/remove.js
CHANGED
|
@@ -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/commands/switch.js
CHANGED
|
@@ -195,6 +195,17 @@ class EnvSwitcher extends BaseCommand {
|
|
|
195
195
|
|
|
196
196
|
} catch (error) {
|
|
197
197
|
UIHelper.clearLoadingAnimation(loadingInterval);
|
|
198
|
+
if (error.code === 'RESUME_FAILED') {
|
|
199
|
+
if (!process.stdin.isTTY || !process.stdout.isTTY) throw error;
|
|
200
|
+
const { startNew } = await this.prompt({
|
|
201
|
+
type: 'confirm',
|
|
202
|
+
name: 'startNew',
|
|
203
|
+
message: `${error.message}\n是否不恢复历史,改为启动新会话?`,
|
|
204
|
+
default: false
|
|
205
|
+
});
|
|
206
|
+
if (!startNew) throw error;
|
|
207
|
+
error.code = isCodex ? 'SESSION_LOCKED' : 'NO_CONVERSATION_FOUND';
|
|
208
|
+
}
|
|
198
209
|
|
|
199
210
|
// Claude Code: 如果是"没有可恢复的会话"错误,自动移除 --continue 参数并重试
|
|
200
211
|
if (!isCodex &&
|
|
@@ -213,7 +224,7 @@ class EnvSwitcher extends BaseCommand {
|
|
|
213
224
|
console.log(UIHelper.createCard('准备就绪', `环境配置完成,正在启动 🚀 ${ideDisplayName}(新会话)...`, UIHelper.icons.success));
|
|
214
225
|
console.log();
|
|
215
226
|
await launchProviderProcess(retryProvider, retryArgs, {
|
|
216
|
-
forceRelogin:
|
|
227
|
+
forceRelogin: false
|
|
217
228
|
});
|
|
218
229
|
return;
|
|
219
230
|
} catch (retryError) {
|
|
@@ -239,7 +250,7 @@ class EnvSwitcher extends BaseCommand {
|
|
|
239
250
|
console.log(UIHelper.createCard('准备就绪', `环境配置完成,正在启动 🚀 ${ideDisplayName}(新会话)...`, UIHelper.icons.success));
|
|
240
251
|
console.log();
|
|
241
252
|
await launchProviderProcess(retryProvider, retryArgs, {
|
|
242
|
-
forceRelogin:
|
|
253
|
+
forceRelogin: false
|
|
243
254
|
});
|
|
244
255
|
return;
|
|
245
256
|
} catch (retryError) {
|
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
|
-
|
|
448
|
+
const nextConfig = {
|
|
435
449
|
...this.config,
|
|
436
450
|
currentProvider: newCurrentProvider,
|
|
437
451
|
providers: remainingProviders
|
|
438
452
|
};
|
|
439
453
|
|
|
440
|
-
|
|
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 = []) {
|
package/src/utils/codex-files.js
CHANGED
|
@@ -598,22 +598,35 @@ async function applyCodexConfig(config, options = {}) {
|
|
|
598
598
|
* @returns {Promise<{codexHome: string}>}
|
|
599
599
|
*/
|
|
600
600
|
async function clearCodexAkmConfig(options = {}) {
|
|
601
|
+
let snapshots;
|
|
601
602
|
try {
|
|
602
603
|
const codexHome = await ensureCodexHome(options.codexHome);
|
|
603
604
|
const { configTomlPath, authJsonPath } = buildCodexPaths(codexHome);
|
|
604
605
|
const sessionKey = normalizeSessionKey(options.sessionKey);
|
|
605
606
|
const forceRelogin = options.forceRelogin === true;
|
|
606
607
|
const cachedAuthPath = forceRelogin ? null : await findChatGptLoginAuthSource(codexHome, sessionKey);
|
|
608
|
+
const changedPaths = [...new Set([
|
|
609
|
+
authJsonPath, configTomlPath,
|
|
610
|
+
buildSessionCacheAuthPath(codexHome, sessionKey),
|
|
611
|
+
buildSessionCacheAuthPath(codexHome)
|
|
612
|
+
])];
|
|
613
|
+
const originals = await Promise.all(changedPaths.map(readFileSnapshot));
|
|
614
|
+
await readExistingAuthJson(authJsonPath);
|
|
615
|
+
const existingToml = originals[1].exists ? originals[1].content.toString('utf8') : '';
|
|
616
|
+
const cleanedToml = removeAkmModelProvider(removeTopLevelApiBaseUrl(existingToml));
|
|
617
|
+
const cachedAuth = cachedAuthPath ? await fs.readFile(cachedAuthPath) : null;
|
|
618
|
+
const writeFile = options.writeFile || writeFileAtomic;
|
|
607
619
|
|
|
608
620
|
// 备份当前配置
|
|
609
621
|
await backupCodexFiles(codexHome);
|
|
622
|
+
snapshots = changedPaths.map((filePath, index) => [filePath, originals[index]]);
|
|
610
623
|
if (forceRelogin) {
|
|
611
624
|
await clearCachedChatGptLoginAuth(codexHome, sessionKey);
|
|
612
625
|
} else if (!sessionKey) {
|
|
613
626
|
await cacheCurrentChatGptLoginAuth(codexHome, authJsonPath, sessionKey);
|
|
614
627
|
}
|
|
615
628
|
|
|
616
|
-
//
|
|
629
|
+
// 指定账号时替换当前认证,未指定账号时保留现有官方认证。
|
|
617
630
|
const shouldRemoveAuthJson = forceRelogin
|
|
618
631
|
? await shouldRemoveAuthJsonForRelogin(authJsonPath)
|
|
619
632
|
: sessionKey
|
|
@@ -624,8 +637,7 @@ async function clearCodexAkmConfig(options = {}) {
|
|
|
624
637
|
|
|
625
638
|
if (shouldRemoveAuthJson || shouldRestoreCachedAuth) {
|
|
626
639
|
if (shouldRestoreCachedAuth) {
|
|
627
|
-
await
|
|
628
|
-
await setSecurePermissions(authJsonPath);
|
|
640
|
+
await writeFile(authJsonPath, cachedAuth, { mode: 0o600 });
|
|
629
641
|
await cacheCurrentChatGptLoginAuth(codexHome, authJsonPath, sessionKey);
|
|
630
642
|
} else {
|
|
631
643
|
await fs.remove(authJsonPath);
|
|
@@ -633,18 +645,19 @@ async function clearCodexAkmConfig(options = {}) {
|
|
|
633
645
|
}
|
|
634
646
|
|
|
635
647
|
// 清理 config.toml 中的 AKM 配置
|
|
636
|
-
if (
|
|
637
|
-
|
|
638
|
-
const cleanedToml = removeAkmModelProvider(removeTopLevelApiBaseUrl(existingToml));
|
|
639
|
-
|
|
640
|
-
if (cleanedToml !== existingToml) {
|
|
641
|
-
await writeFileAtomic(configTomlPath, cleanedToml, { encoding: 'utf8', mode: 0o600 });
|
|
642
|
-
await setSecurePermissions(configTomlPath);
|
|
643
|
-
}
|
|
648
|
+
if (cleanedToml !== existingToml) {
|
|
649
|
+
await writeFile(configTomlPath, cleanedToml, { encoding: 'utf8', mode: 0o600 });
|
|
644
650
|
}
|
|
645
651
|
|
|
646
652
|
return { codexHome };
|
|
647
653
|
} catch (error) {
|
|
654
|
+
if (snapshots) {
|
|
655
|
+
try {
|
|
656
|
+
await Promise.all(snapshots.map(([filePath, snapshot]) => restoreFileSnapshot(filePath, snapshot)));
|
|
657
|
+
} catch (rollbackError) {
|
|
658
|
+
throw new Error(`清理 Codex AKM 配置失败且回滚失败: ${error.message}; ${rollbackError.message}`, { cause: error });
|
|
659
|
+
}
|
|
660
|
+
}
|
|
648
661
|
throw new Error(`清理 Codex AKM 配置失败: ${error.message}`, { cause: error });
|
|
649
662
|
}
|
|
650
663
|
}
|
|
@@ -655,6 +668,28 @@ async function cacheCodexOfficialSession(options = {}) {
|
|
|
655
668
|
return await cacheCurrentChatGptLoginAuth(codexHome, authJsonPath, options.sessionKey);
|
|
656
669
|
}
|
|
657
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
|
+
|
|
658
693
|
module.exports = {
|
|
659
694
|
resolveCodexHome,
|
|
660
695
|
buildCodexPaths,
|
|
@@ -662,6 +697,7 @@ module.exports = {
|
|
|
662
697
|
applyCodexConfig,
|
|
663
698
|
clearCodexAkmConfig,
|
|
664
699
|
cacheCodexOfficialSession,
|
|
700
|
+
withCodexSessionRemoval,
|
|
665
701
|
backupCodexFiles,
|
|
666
702
|
removeTopLevelApiBaseUrl,
|
|
667
703
|
removeAkmModelProvider,
|
|
@@ -7,6 +7,7 @@ const {
|
|
|
7
7
|
} = require('./codex-files');
|
|
8
8
|
const { assertSupportedLaunchArgs } = require('./launch-args');
|
|
9
9
|
const { validator } = require('./validator');
|
|
10
|
+
const { acquireCodexLock } = require('./codex-lock');
|
|
10
11
|
|
|
11
12
|
/**
|
|
12
13
|
* 构建 Codex CLI 环境变量
|
|
@@ -78,52 +79,62 @@ async function executeCodexWithEnv(config, launchArgs = [], launchOptions = {})
|
|
|
78
79
|
|
|
79
80
|
// 在写入 Codex 配置文件前完成全部输入校验。
|
|
80
81
|
const env = buildCodexEnvVariables(config);
|
|
82
|
+
const releaseLock = await acquireCodexLock();
|
|
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
|
+
}
|
|
81
95
|
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
} else if (authMode === 'chatgpt_login') {
|
|
88
|
-
// chatgpt_login 模式:清理 AKM 的配置,让 Codex 使用官方登录
|
|
89
|
-
await clearCodexAkmConfig({
|
|
90
|
-
sessionKey: config.name,
|
|
91
|
-
forceRelogin: launchOptions.forceRelogin === true
|
|
92
|
-
});
|
|
93
|
-
}
|
|
94
|
-
|
|
95
|
-
// 处理参数:子命令放前面,选项放后面
|
|
96
|
-
const rawArgs = Array.isArray(launchArgs) ? [...launchArgs] : [];
|
|
97
|
-
const subcommands = rawArgs.filter(arg => !arg.startsWith('-'));
|
|
98
|
-
const options = rawArgs.filter(arg => arg.startsWith('-'));
|
|
99
|
-
const args = [...subcommands, ...options];
|
|
100
|
-
|
|
101
|
-
clearTerminal();
|
|
102
|
-
|
|
103
|
-
if (authMode === 'chatgpt_login') {
|
|
104
|
-
console.log('\n启动 Codex CLI (官方网页登录)...\n');
|
|
105
|
-
} else {
|
|
106
|
-
console.log('\n启动 Codex CLI...\n');
|
|
107
|
-
}
|
|
108
|
-
|
|
109
|
-
return new Promise((resolve, reject) => {
|
|
110
|
-
const child = spawn('codex', args, {
|
|
111
|
-
stdio: ['inherit', 'inherit', 'pipe'],
|
|
112
|
-
env,
|
|
113
|
-
shell: false
|
|
114
|
-
});
|
|
96
|
+
// 处理参数:子命令放前面,选项放后面
|
|
97
|
+
const rawArgs = Array.isArray(launchArgs) ? [...launchArgs] : [];
|
|
98
|
+
const subcommands = rawArgs.filter(arg => !arg.startsWith('-'));
|
|
99
|
+
const options = rawArgs.filter(arg => arg.startsWith('-'));
|
|
100
|
+
const args = [...subcommands, ...options];
|
|
115
101
|
|
|
116
|
-
|
|
102
|
+
clearTerminal();
|
|
117
103
|
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
});
|
|
104
|
+
if (authMode === 'chatgpt_login') {
|
|
105
|
+
console.log('\n启动 Codex CLI (官方网页登录)...\n');
|
|
106
|
+
} else {
|
|
107
|
+
console.log('\n启动 Codex CLI...\n');
|
|
108
|
+
}
|
|
124
109
|
|
|
125
|
-
|
|
126
|
-
|
|
110
|
+
return await new Promise((resolve, reject) => {
|
|
111
|
+
const child = spawn('codex', args, {
|
|
112
|
+
stdio: ['inherit', 'inherit', 'pipe'],
|
|
113
|
+
env,
|
|
114
|
+
shell: false
|
|
115
|
+
});
|
|
116
|
+
|
|
117
|
+
let stderrOutput = '';
|
|
118
|
+
let spawnFailed = false;
|
|
119
|
+
const forwardInterrupt = () => child.kill('SIGINT');
|
|
120
|
+
const forwardTerminate = () => child.kill('SIGTERM');
|
|
121
|
+
process.on('SIGINT', forwardInterrupt);
|
|
122
|
+
process.on('SIGTERM', forwardTerminate);
|
|
123
|
+
const cleanupSignals = () => {
|
|
124
|
+
process.removeListener('SIGINT', forwardInterrupt);
|
|
125
|
+
process.removeListener('SIGTERM', forwardTerminate);
|
|
126
|
+
};
|
|
127
|
+
|
|
128
|
+
// 捕获 stderr 用于检查错误信息
|
|
129
|
+
child.stderr.on('data', (data) => {
|
|
130
|
+
const output = data.toString();
|
|
131
|
+
stderrOutput += output;
|
|
132
|
+
process.stderr.write(data);
|
|
133
|
+
});
|
|
134
|
+
|
|
135
|
+
child.on('close', async (code, signal) => {
|
|
136
|
+
cleanupSignals();
|
|
137
|
+
if (spawnFailed) return;
|
|
127
138
|
try {
|
|
128
139
|
if (authMode === 'chatgpt_login') {
|
|
129
140
|
await cacheCodexOfficialSession({ sessionKey: config.name });
|
|
@@ -132,34 +143,41 @@ async function executeCodexWithEnv(config, launchArgs = [], launchOptions = {})
|
|
|
132
143
|
reject(new Error(`保存 Codex 官方登录 Session 失败: ${error.message}`));
|
|
133
144
|
return;
|
|
134
145
|
}
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
146
|
+
if (code === 0 || code === 130 || signal === 'SIGINT') {
|
|
147
|
+
resolve();
|
|
148
|
+
} else {
|
|
149
|
+
// 只对明确的历史错误自动回退,未知错误交给用户决定。
|
|
150
|
+
const errorOutput = stderrOutput.toLowerCase();
|
|
151
|
+
const isSessionLockedError =
|
|
141
152
|
errorOutput.includes('already has an active writer') ||
|
|
142
153
|
errorOutput.includes('failed to resume session') ||
|
|
143
154
|
errorOutput.includes('thread already has an active');
|
|
144
155
|
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
156
|
+
if (isSessionLockedError) {
|
|
157
|
+
const error = new Error('Codex 会话被锁定或无法恢复');
|
|
158
|
+
error.code = 'SESSION_LOCKED';
|
|
159
|
+
reject(error);
|
|
160
|
+
} else {
|
|
161
|
+
const error = new Error(`Codex CLI 异常退出,退出代码: ${code}${stderrOutput.trim() ? `\n${stderrOutput.trim()}` : ''}`);
|
|
162
|
+
if (rawArgs.includes('resume') && code === 1) error.code = 'RESUME_FAILED';
|
|
163
|
+
reject(error);
|
|
164
|
+
}
|
|
151
165
|
}
|
|
152
|
-
}
|
|
153
|
-
});
|
|
166
|
+
});
|
|
154
167
|
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
168
|
+
child.on('error', (error) => {
|
|
169
|
+
spawnFailed = true;
|
|
170
|
+
cleanupSignals();
|
|
171
|
+
if (error.code === 'ENOENT') {
|
|
172
|
+
reject(new Error('找不到 codex 命令\n请先安装 Codex CLI: npm i -g @openai/codex 或 brew install --cask codex'));
|
|
173
|
+
} else {
|
|
174
|
+
reject(new Error(`启动 Codex CLI 失败: ${error.message}`));
|
|
175
|
+
}
|
|
176
|
+
});
|
|
161
177
|
});
|
|
162
|
-
}
|
|
178
|
+
} finally {
|
|
179
|
+
await releaseLock();
|
|
180
|
+
}
|
|
163
181
|
}
|
|
164
182
|
|
|
165
183
|
module.exports = { executeCodexWithEnv, buildCodexEnvVariables };
|
|
@@ -0,0 +1,13 @@
|
|
|
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 };
|
|
@@ -80,18 +80,19 @@ async function executeWithEnv(config, launchArgs = []) {
|
|
|
80
80
|
// 检查是否是"没有可恢复会话"的错误
|
|
81
81
|
// 检查 stderr 中是否包含各种格式的错误消息
|
|
82
82
|
const errorOutput = stderrOutput.toLowerCase();
|
|
83
|
-
const isContinueLaunch = args.includes('--continue');
|
|
84
83
|
const isNoConversationError =
|
|
85
84
|
errorOutput.includes('no conversation found') ||
|
|
86
85
|
errorOutput.includes('no recoverable session') ||
|
|
87
86
|
errorOutput.includes('no deferred tool marker');
|
|
88
87
|
|
|
89
|
-
if (isNoConversationError
|
|
88
|
+
if (isNoConversationError) {
|
|
90
89
|
const error = new Error('没有可恢复的会话\n提示: 请选择不带 --continue 参数重新开始');
|
|
91
90
|
error.code = 'NO_CONVERSATION_FOUND';
|
|
92
91
|
reject(error);
|
|
93
92
|
} else {
|
|
94
|
-
|
|
93
|
+
const error = new Error(`Claude Code 异常退出,退出代码: ${code}${stderrOutput.trim() ? `\n${stderrOutput.trim()}` : ''}`);
|
|
94
|
+
if (args.includes('--continue') && code === 1) error.code = 'RESUME_FAILED';
|
|
95
|
+
reject(error);
|
|
95
96
|
}
|
|
96
97
|
}
|
|
97
98
|
});
|
|
@@ -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 };
|
|
@@ -7,6 +7,10 @@
|
|
|
7
7
|
const chalk = require('chalk');
|
|
8
8
|
const inquirer = require('inquirer');
|
|
9
9
|
const spawn = require('cross-spawn');
|
|
10
|
+
const fs = require('fs-extra');
|
|
11
|
+
const os = require('os');
|
|
12
|
+
const path = require('path');
|
|
13
|
+
const { writeJsonAtomic } = require('./atomic-file');
|
|
10
14
|
|
|
11
15
|
/**
|
|
12
16
|
* 比较两个版本号
|
|
@@ -91,7 +95,20 @@ async function checkForUpdates({ packageName, currentVersion }) {
|
|
|
91
95
|
return;
|
|
92
96
|
}
|
|
93
97
|
|
|
94
|
-
const
|
|
98
|
+
const cachePath = path.join(os.homedir(), '.akm-update-check.json');
|
|
99
|
+
let cache;
|
|
100
|
+
try {
|
|
101
|
+
cache = await fs.readJson(cachePath);
|
|
102
|
+
} catch {
|
|
103
|
+
// 缓存缺失或损坏时重新检查。
|
|
104
|
+
}
|
|
105
|
+
const age = Date.now() - cache?.checkedAt;
|
|
106
|
+
const cached = cache?.packageName === packageName && Number.isFinite(age) && age >= 0 && age < 86400000;
|
|
107
|
+
const latest = cached ? cache.latest : await getLatestVersion(packageName);
|
|
108
|
+
if (!cached) {
|
|
109
|
+
// 失败也记录检查时间,离线时不重复阻塞每次启动。
|
|
110
|
+
await writeJsonAtomic(cachePath, { packageName, checkedAt: Date.now(), latest }).catch(() => {});
|
|
111
|
+
}
|
|
95
112
|
if (!latest) return;
|
|
96
113
|
|
|
97
114
|
if (compareVersions(latest, currentVersion) > 0) {
|
|
@@ -115,31 +132,33 @@ async function checkForUpdates({ packageName, currentVersion }) {
|
|
|
115
132
|
if (!doUpdate) return;
|
|
116
133
|
|
|
117
134
|
console.log(chalk.yellow('开始更新,请稍候...'));
|
|
118
|
-
await new Promise((resolve) => {
|
|
135
|
+
const installed = await new Promise((resolve) => {
|
|
119
136
|
const child = spawn('npm', ['i', '-g', `${packageName}@latest`], {
|
|
120
137
|
shell: false,
|
|
121
138
|
stdio: 'inherit'
|
|
122
139
|
});
|
|
123
140
|
child.on('close', (code) => resolve(code === 0));
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
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);
|
|
135
153
|
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
child.on('close', (code) =>
|
|
141
|
-
|
|
142
|
-
});
|
|
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;
|
|
143
162
|
});
|
|
144
163
|
}
|
|
145
164
|
} catch {
|