@pikecode/api-key-manager 2.2.1 → 2.2.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +45 -0
- package/README.md +16 -9
- package/package.json +2 -1
- package/src/utils/codex-files.js +4 -6
- package/src/utils/codex-history.js +74 -0
- package/src/utils/codex-launcher.js +15 -32
- package/src/utils/codex-runtime.js +118 -0
- package/src/utils/file-lock.js +3 -1
- package/src/utils/launch-args.js +7 -7
- package/src/utils/codex-lock.js +0 -13
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
# 修改记录
|
|
2
|
+
|
|
3
|
+
记录项目的功能、修复和兼容性变化。以下历史条目依据 Git 提交补录,不代表已核实 npm 发布状态。
|
|
4
|
+
|
|
5
|
+
## 未发布(当前目标版本 2.2.2)
|
|
6
|
+
|
|
7
|
+
### 功能与行为调整
|
|
8
|
+
|
|
9
|
+
- 支持同一 Codex 供应商多窗口运行,以及不同供应商同时运行。
|
|
10
|
+
- 按供应商隔离认证、配置和 SQLite 运行状态,不再覆盖根目录认证或使用全局单窗口锁。
|
|
11
|
+
- 共享会话文件,支持从不同供应商的历史创建新分支;恢复前确认目标供应商,保留原始对话。
|
|
12
|
+
- 迁移同名官方 Session 缓存;重新认证、修改认证和删除账号只受该供应商的运行窗口约束。
|
|
13
|
+
- 更新 README,说明目录布局、历史分叉及异常退出记录的处理。
|
|
14
|
+
|
|
15
|
+
### 兼容性说明
|
|
16
|
+
|
|
17
|
+
- 从历史继续需要 Codex CLI 支持 `fork`,已用 0.166.0 的原生接口做离线验证。
|
|
18
|
+
- 直接运行原生 `codex` 仍使用原配置;使用 AKM 隔离配置需通过 `akm <供应商>` 启动。
|
|
19
|
+
- 首次复制到供应商目录的配置不会自动跟随根配置更新;共享历史、技能和插件目录保留在原位置。
|
|
20
|
+
|
|
21
|
+
### 维护
|
|
22
|
+
|
|
23
|
+
- 新增项目维护约定:每次修改同步记录变更,按影响评估版本升级。
|
|
24
|
+
- 保留用户指定的 2.2.2 目标版本,同步锁文件版本元数据。
|
|
25
|
+
- 将修改记录加入 npm 包文件清单,并在 README 中提供入口。
|
|
26
|
+
- 多窗口功能验证:58 个测试套件、591 项测试及项目完整检查通过。
|
|
27
|
+
|
|
28
|
+
## 2.2.1(历史补录)
|
|
29
|
+
|
|
30
|
+
- 更新包版本至 2.2.1;对应版本提交未包含其他代码变更。
|
|
31
|
+
|
|
32
|
+
## 2.2.0(历史补录)
|
|
33
|
+
|
|
34
|
+
- 加固 Codex Session 保存与认证切换回滚,修复自动重试时重复清理认证。
|
|
35
|
+
- 未知历史恢复错误保留实际原因,交互确认后才新开会话。
|
|
36
|
+
- 修复测试写入真实用户配置的问题,减少逐层重复报错。
|
|
37
|
+
- 更新检查缓存 24 小时;更新重启后等待新版进程结束,避免重复执行命令。
|
|
38
|
+
- 配置读写使用短时锁和内容冲突检查,降低并发覆盖风险。
|
|
39
|
+
- 删除官方供应商时清理对应 Session 缓存,失败时恢复。
|
|
40
|
+
- 增加真实命令入口、并发保存和删除回滚测试,以及三平台 CI 矩阵。
|
|
41
|
+
- 此版本曾采用 Codex 目录单窗口锁;当前目标版本已改为供应商隔离和多窗口运行。
|
|
42
|
+
|
|
43
|
+
## 2.1.9(历史补录)
|
|
44
|
+
|
|
45
|
+
- 增加 Claude Code 继续历史失败时的回退处理;后续版本收窄自动重试条件,避免把未知错误误判为无历史。
|
package/README.md
CHANGED
|
@@ -207,7 +207,7 @@ akm remove my-provider
|
|
|
207
207
|
3. 预览将要删除的供应商列表
|
|
208
208
|
4. 最终确认后批量删除
|
|
209
209
|
|
|
210
|
-
删除 Codex
|
|
210
|
+
删除 Codex 官方网页登录供应商时,会同时清理该名称的旧 Session 缓存和独立目录中的认证;以后添加同名供应商需要重新认证。只有该供应商仍有窗口运行时才阻止删除,其他供应商不受影响。删除失败会恢复认证;该操作不会撤销服务端 Token,也不会清理共享历史、历史备份或其他账号的缓存。
|
|
211
211
|
|
|
212
212
|
### 编辑供应商
|
|
213
213
|
|
|
@@ -388,13 +388,19 @@ akm switch openai-work --relogin
|
|
|
388
388
|
|
|
389
389
|
### 会话恢复与运行保护
|
|
390
390
|
|
|
391
|
-
|
|
391
|
+
同一供应商可以打开多个窗口,不同供应商也可以同时运行。一个窗口退出当前 Codex 会话后,可以再启动任意供应商,不影响其他窗口。
|
|
392
392
|
|
|
393
|
-
|
|
393
|
+
AKM 使用 `<CODEX_HOME>/akm-providers/<供应商标识>/` 保存各供应商独立的 `auth.json`、`config.toml` 和 SQLite 运行状态,根目录默认为 `~/.codex`。不再覆盖根目录认证,也不再使用旧的 `.akm-launch.lock` 限制窗口数量。直接运行原生 `codex` 仍使用其原有配置;请通过 `akm <供应商>` 使用隔离配置。
|
|
394
394
|
|
|
395
|
-
|
|
395
|
+
首次启动会复制根目录的配置与 `AGENTS.md`,并迁移同名官方 Session 缓存;不会继承其他账号的认证。后续 Codex 刷新的 Token 直接保存在该供应商目录,不再在窗口退出时覆盖回共享认证文件。根目录后续配置修改不会自动覆盖已创建的独立配置。
|
|
396
396
|
|
|
397
|
-
|
|
397
|
+
`sessions` 和 `archived_sessions` 通过目录链接共享,历史文件无需搬迁;SQLite 数据库与认证保持隔离。已有的 `skills`、`rules`、`plugins` 目录也会链接到原位置。Windows 使用目录联接(junction)。
|
|
398
|
+
|
|
399
|
+
选择“从历史继续”后,AKM 列出共享历史(包含其他供应商和项目),显示时间、目录、原模型供应商和对话 ID。确认目标供应商后使用 `codex fork <ID>` 创建新对话,原历史保持不变,多个窗口可以从同一历史分叉。跨供应商继续会向新供应商发送恢复所需的上下文,因此默认不确认;非交互终端不会自动选择历史。此功能需要支持 `codex fork` 的 Codex CLI,已使用 0.166.0 的原生接口验证。分叉失败会显示原因,不静默丢弃历史。
|
|
400
|
+
|
|
401
|
+
同一供应商的首次网页登录未完成时,先完成该窗口认证,再打开更多窗口。`--relogin`、修改密钥或认证配置、删除官方账号需要先退出该供应商的所有窗口,其他供应商可继续运行。该选项不会撤销服务端 Token 或清理浏览器登录状态。
|
|
402
|
+
|
|
403
|
+
正常退出会清除运行记录;强杀后可能在供应商目录的 `.akm-runs/` 留下记录,或留下短时 `.akm-settings.lock`。仅在确认该供应商相关 AKM/Codex 进程均已退出后清理这些记录;不要删除历史目录。
|
|
398
404
|
|
|
399
405
|
更新检查结果(包括失败结果)缓存在 `~/.akm-update-check.json`,24 小时内不重复请求 npm。可通过 `CC_NO_UPDATE_CHECK=1` 禁用检查。
|
|
400
406
|
|
|
@@ -484,7 +490,7 @@ akm personal -q
|
|
|
484
490
|
**切换原理:**
|
|
485
491
|
|
|
486
492
|
- **Claude Code** — 通过环境变量注入启动子进程,不修改配置文件,切换只在当前会话生效
|
|
487
|
-
- **Codex CLI** —
|
|
493
|
+
- **Codex CLI** — 按供应商设置独立 `CODEX_HOME`,认证和运行状态隔离,会话文件共享,支持多窗口并行
|
|
488
494
|
|
|
489
495
|
**环境变量映射:**
|
|
490
496
|
|
|
@@ -534,14 +540,14 @@ Codex CLI:
|
|
|
534
540
|
|
|
535
541
|
### 切换 Codex 后提示 "Token data is not available"
|
|
536
542
|
|
|
537
|
-
|
|
543
|
+
检查对应供应商独立目录中的 `auth.json`。退出该供应商的所有窗口后再启动;官方账号可使用 `--relogin` 重新认证:
|
|
538
544
|
|
|
539
545
|
```bash
|
|
540
546
|
akm my-codex
|
|
541
547
|
```
|
|
542
548
|
|
|
543
|
-
|
|
544
|
-
|
|
549
|
+
API Key 模式会在对应供应商目录写入 `auth_mode = "apikey"` 和 `OPENAI_API_KEY`。
|
|
550
|
+
修改前内容保存在该供应商目录的 `akm-backups/` 中,不改动其他供应商认证。
|
|
545
551
|
`auth.json` 与 `config.toml` 作为一组更新;任一文件写入失败时会自动恢复两者的原始内容。
|
|
546
552
|
|
|
547
553
|
### Claude Code 切换后环境变量不生效
|
|
@@ -588,6 +594,7 @@ MIT License
|
|
|
588
594
|
|
|
589
595
|
## 链接
|
|
590
596
|
|
|
597
|
+
- [修改记录](CHANGELOG.md)
|
|
591
598
|
- [NPM](https://www.npmjs.com/package/@pikecode/api-key-manager)
|
|
592
599
|
- [GitHub](https://github.com/pikecode/api-key-manager)
|
|
593
600
|
- [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.
|
|
3
|
+
"version": "2.2.2",
|
|
4
4
|
"description": "A CLI tool for managing and switching multiple API provider configurations",
|
|
5
5
|
"main": "src/index.js",
|
|
6
6
|
"bin": {
|
|
@@ -10,6 +10,7 @@
|
|
|
10
10
|
"bin/",
|
|
11
11
|
"src/",
|
|
12
12
|
"README.md",
|
|
13
|
+
"CHANGELOG.md",
|
|
13
14
|
"LICENSE"
|
|
14
15
|
],
|
|
15
16
|
"scripts": {
|
package/src/utils/codex-files.js
CHANGED
|
@@ -669,9 +669,8 @@ async function cacheCodexOfficialSession(options = {}) {
|
|
|
669
669
|
}
|
|
670
670
|
|
|
671
671
|
async function withCodexSessionRemoval(sessionKey, removeProvider) {
|
|
672
|
-
const {
|
|
673
|
-
|
|
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
|
-
}
|
|
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,74 @@
|
|
|
1
|
+
const fs = require('fs-extra');
|
|
2
|
+
const path = require('path');
|
|
3
|
+
const inquirer = require('inquirer');
|
|
4
|
+
const { resolveCodexHome } = require('./codex-files');
|
|
5
|
+
|
|
6
|
+
async function listCodexHistory(root = resolveCodexHome()) {
|
|
7
|
+
const history = [];
|
|
8
|
+
async function scan(directory) {
|
|
9
|
+
let entries;
|
|
10
|
+
try { entries = await fs.readdir(directory, { withFileTypes: true }); }
|
|
11
|
+
catch (error) { if (error.code === 'ENOENT') return; throw error; }
|
|
12
|
+
for (const entry of entries) {
|
|
13
|
+
const file = path.join(directory, entry.name);
|
|
14
|
+
if (entry.isDirectory()) await scan(file);
|
|
15
|
+
else if (entry.isFile() && entry.name.endsWith('.jsonl')) {
|
|
16
|
+
// 只读头部元数据,避免把完整对话加载进内存或显示在列表中。
|
|
17
|
+
let handle;
|
|
18
|
+
try {
|
|
19
|
+
try { handle = await fs.open(file, 'r'); }
|
|
20
|
+
catch (error) { if (error.code === 'ENOENT') continue; throw error; }
|
|
21
|
+
const chunks = [];
|
|
22
|
+
let offset = 0;
|
|
23
|
+
// 元数据可能包含长指令,分块读至首行结束,上限 4 MiB。
|
|
24
|
+
while (offset < 4 * 1024 * 1024) {
|
|
25
|
+
const buffer = Buffer.alloc(16384);
|
|
26
|
+
const { bytesRead } = await fs.read(handle, buffer, 0, buffer.length, offset);
|
|
27
|
+
if (!bytesRead) break;
|
|
28
|
+
chunks.push(buffer.subarray(0, bytesRead));
|
|
29
|
+
offset += bytesRead;
|
|
30
|
+
if (buffer.subarray(0, bytesRead).includes(10)) break;
|
|
31
|
+
}
|
|
32
|
+
const line = Buffer.concat(chunks).toString('utf8').split('\n')[0];
|
|
33
|
+
let meta;
|
|
34
|
+
try { meta = JSON.parse(line); } catch { continue; }
|
|
35
|
+
const data = meta.payload;
|
|
36
|
+
if (meta.type !== 'session_meta' || !/^[0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12}$/i.test(data?.id)) continue;
|
|
37
|
+
history.push({ id: data.id, cwd: String(data.cwd || ''), timestamp: String(data.timestamp || meta.timestamp || ''), provider: String(data.model_provider || '未知') });
|
|
38
|
+
} finally {
|
|
39
|
+
if (handle !== undefined) await fs.close(handle);
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
await scan(path.join(root, 'sessions'));
|
|
45
|
+
await scan(path.join(root, 'archived_sessions'));
|
|
46
|
+
return [...new Map(history.sort((a, b) => b.timestamp.localeCompare(a.timestamp)).map(item => [item.id, item])).values()];
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
async function selectCodexHistory(config, args) {
|
|
50
|
+
if (!args.includes('resume')) return args;
|
|
51
|
+
const history = await listCodexHistory();
|
|
52
|
+
if (!history.length) {
|
|
53
|
+
const error = new Error('没有可用的 Codex 历史对话');
|
|
54
|
+
error.code = 'SESSION_LOCKED';
|
|
55
|
+
throw error;
|
|
56
|
+
}
|
|
57
|
+
if (!process.stdin.isTTY || !process.stdout.isTTY) throw new Error('恢复历史需要交互终端,请交互选择历史或使用 --no-args 新建会话');
|
|
58
|
+
const { sessionId } = await inquirer.prompt({
|
|
59
|
+
type: 'list', name: 'sessionId', message: '选择历史对话(创建新分支,原记录保留)', pageSize: 15,
|
|
60
|
+
choices: [
|
|
61
|
+
{ name: '取消', value: null },
|
|
62
|
+
...history.map(item => ({ name: `${item.timestamp} | ${item.cwd} | ${item.provider} | ${item.id}`, value: item.id }))
|
|
63
|
+
]
|
|
64
|
+
});
|
|
65
|
+
if (!sessionId) return null;
|
|
66
|
+
const { confirmed } = await inquirer.prompt({
|
|
67
|
+
type: 'confirm', name: 'confirmed', default: false,
|
|
68
|
+
message: `将以供应商「${config.displayName || config.name}」处理所选历史上下文并创建新对话;若原供应商不同,历史内容会发送给新供应商。是否继续?`
|
|
69
|
+
});
|
|
70
|
+
if (!confirmed) return null;
|
|
71
|
+
return ['fork', sessionId, ...args.filter(arg => arg !== 'resume')];
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
module.exports = { listCodexHistory, selectCodexHistory };
|
|
@@ -1,13 +1,9 @@
|
|
|
1
1
|
const spawn = require('cross-spawn');
|
|
2
2
|
const { sanitizeEnvValue, clearTerminal } = require('./env-utils');
|
|
3
|
-
const {
|
|
4
|
-
|
|
5
|
-
clearCodexAkmConfig,
|
|
6
|
-
cacheCodexOfficialSession
|
|
7
|
-
} = require('./codex-files');
|
|
3
|
+
const { prepareCodexRuntime } = require('./codex-runtime');
|
|
4
|
+
const { selectCodexHistory } = require('./codex-history');
|
|
8
5
|
const { assertSupportedLaunchArgs } = require('./launch-args');
|
|
9
6
|
const { validator } = require('./validator');
|
|
10
|
-
const { acquireCodexLock } = require('./codex-lock');
|
|
11
7
|
|
|
12
8
|
/**
|
|
13
9
|
* 构建 Codex CLI 环境变量
|
|
@@ -79,25 +75,20 @@ async function executeCodexWithEnv(config, launchArgs = [], launchOptions = {})
|
|
|
79
75
|
|
|
80
76
|
// 在写入 Codex 配置文件前完成全部输入校验。
|
|
81
77
|
const env = buildCodexEnvVariables(config);
|
|
82
|
-
const
|
|
78
|
+
const selectedArgs = await selectCodexHistory(config, launchArgs);
|
|
79
|
+
if (!selectedArgs) return;
|
|
80
|
+
const runtime = await prepareCodexRuntime(config, launchOptions);
|
|
81
|
+
env.CODEX_HOME = runtime.home;
|
|
83
82
|
try {
|
|
84
|
-
// 根据认证模式处理配置文件
|
|
85
|
-
if (authMode === 'api_key') {
|
|
86
|
-
// 写入 ~/.codex/config.toml 和 ~/.codex/auth.json。
|
|
87
|
-
await applyCodexConfig(config);
|
|
88
|
-
} else if (authMode === 'chatgpt_login') {
|
|
89
|
-
// 清理 AKM 的配置,让 Codex 使用官方登录。
|
|
90
|
-
await clearCodexAkmConfig({
|
|
91
|
-
sessionKey: config.name,
|
|
92
|
-
forceRelogin: launchOptions.forceRelogin === true
|
|
93
|
-
});
|
|
94
|
-
}
|
|
95
|
-
|
|
96
83
|
// 处理参数:子命令放前面,选项放后面
|
|
97
|
-
const rawArgs =
|
|
84
|
+
const rawArgs = [...selectedArgs];
|
|
98
85
|
const subcommands = rawArgs.filter(arg => !arg.startsWith('-'));
|
|
99
86
|
const options = rawArgs.filter(arg => arg.startsWith('-'));
|
|
100
|
-
const args = [...subcommands, ...options
|
|
87
|
+
const args = [...subcommands, ...options,
|
|
88
|
+
'-c', 'cli_auth_credentials_store="file"',
|
|
89
|
+
'-c', `sqlite_home=${JSON.stringify(runtime.home)}`,
|
|
90
|
+
'-c', `model_provider="${authMode === 'chatgpt_login' || !config.baseUrl ? 'openai' : 'akm'}"`
|
|
91
|
+
];
|
|
101
92
|
|
|
102
93
|
clearTerminal();
|
|
103
94
|
|
|
@@ -135,14 +126,6 @@ async function executeCodexWithEnv(config, launchArgs = [], launchOptions = {})
|
|
|
135
126
|
child.on('close', async (code, signal) => {
|
|
136
127
|
cleanupSignals();
|
|
137
128
|
if (spawnFailed) return;
|
|
138
|
-
try {
|
|
139
|
-
if (authMode === 'chatgpt_login') {
|
|
140
|
-
await cacheCodexOfficialSession({ sessionKey: config.name });
|
|
141
|
-
}
|
|
142
|
-
} catch (error) {
|
|
143
|
-
reject(new Error(`保存 Codex 官方登录 Session 失败: ${error.message}`));
|
|
144
|
-
return;
|
|
145
|
-
}
|
|
146
129
|
if (code === 0 || code === 130 || signal === 'SIGINT') {
|
|
147
130
|
resolve();
|
|
148
131
|
} else {
|
|
@@ -153,13 +136,13 @@ async function executeCodexWithEnv(config, launchArgs = [], launchOptions = {})
|
|
|
153
136
|
errorOutput.includes('failed to resume session') ||
|
|
154
137
|
errorOutput.includes('thread already has an active');
|
|
155
138
|
|
|
156
|
-
if (isSessionLockedError) {
|
|
139
|
+
if (isSessionLockedError && !rawArgs.includes('fork')) {
|
|
157
140
|
const error = new Error('Codex 会话被锁定或无法恢复');
|
|
158
141
|
error.code = 'SESSION_LOCKED';
|
|
159
142
|
reject(error);
|
|
160
143
|
} else {
|
|
161
144
|
const error = new Error(`Codex CLI 异常退出,退出代码: ${code}${stderrOutput.trim() ? `\n${stderrOutput.trim()}` : ''}`);
|
|
162
|
-
if (
|
|
145
|
+
if (launchArgs.includes('resume') && code === 1) error.code = 'RESUME_FAILED';
|
|
163
146
|
reject(error);
|
|
164
147
|
}
|
|
165
148
|
}
|
|
@@ -176,7 +159,7 @@ async function executeCodexWithEnv(config, launchArgs = [], launchOptions = {})
|
|
|
176
159
|
});
|
|
177
160
|
});
|
|
178
161
|
} finally {
|
|
179
|
-
await
|
|
162
|
+
await runtime.release();
|
|
180
163
|
}
|
|
181
164
|
}
|
|
182
165
|
|
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
const fs = require('fs-extra');
|
|
2
|
+
const path = require('path');
|
|
3
|
+
const crypto = require('crypto');
|
|
4
|
+
const { acquireFileLock } = require('./file-lock');
|
|
5
|
+
const { writeJsonAtomic, writeFileAtomic } = require('./atomic-file');
|
|
6
|
+
const {
|
|
7
|
+
resolveCodexHome, buildSessionCacheAuthPath, applyCodexConfig, clearCodexAkmConfig
|
|
8
|
+
} = require('./codex-files');
|
|
9
|
+
|
|
10
|
+
function providerHome(name, root = resolveCodexHome()) {
|
|
11
|
+
if (typeof name !== 'string' || !name.trim()) throw new Error('Codex 供应商名称不能为空');
|
|
12
|
+
const key = path.basename(buildSessionCacheAuthPath(root, name), '.auth.json');
|
|
13
|
+
return path.join(root, 'akm-providers', key);
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
async function lockProvider(name, root = resolveCodexHome()) {
|
|
17
|
+
const home = providerHome(name, root);
|
|
18
|
+
await fs.ensureDir(home, { mode: 0o700 });
|
|
19
|
+
for (let attempt = 0; ; attempt++) {
|
|
20
|
+
try {
|
|
21
|
+
const release = await acquireFileLock(path.join(home, '.akm-settings.lock'), '该供应商正在初始化或修改认证,请稍后重试。');
|
|
22
|
+
return { home, release };
|
|
23
|
+
} catch (error) {
|
|
24
|
+
if (error.code !== 'LOCK_BUSY' || attempt >= 40) throw error;
|
|
25
|
+
await new Promise(resolve => setTimeout(resolve, 50));
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
async function activeRuns(home) {
|
|
31
|
+
const directory = path.join(home, '.akm-runs');
|
|
32
|
+
await fs.ensureDir(directory, { mode: 0o700 });
|
|
33
|
+
// 不自动删除强杀后留下的记录,父进程退出不代表 Codex 子进程已退出。
|
|
34
|
+
return (await fs.readdir(directory)).length;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
async function shareDirectory(root, home, name) {
|
|
38
|
+
const source = path.join(root, name);
|
|
39
|
+
const target = path.join(home, name);
|
|
40
|
+
await fs.ensureDir(source);
|
|
41
|
+
try {
|
|
42
|
+
await fs.symlink(path.resolve(source), target, process.platform === 'win32' ? 'junction' : 'dir');
|
|
43
|
+
} catch (error) {
|
|
44
|
+
if (error.code !== 'EEXIST') throw error;
|
|
45
|
+
if (await fs.realpath(target) !== await fs.realpath(source)) {
|
|
46
|
+
throw new Error(`历史或资源目录已存在且指向其他位置,请先检查:${target}`);
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
async function prepareCodexRuntime(config, { forceRelogin = false } = {}) {
|
|
52
|
+
const root = resolveCodexHome();
|
|
53
|
+
const { home, release } = await lockProvider(config.name, root);
|
|
54
|
+
try {
|
|
55
|
+
const markerPath = path.join(home, '.akm-config.json');
|
|
56
|
+
const authPath = path.join(home, 'auth.json');
|
|
57
|
+
const authMode = config.authMode || 'api_key';
|
|
58
|
+
const fingerprint = crypto.createHash('sha256').update(JSON.stringify([
|
|
59
|
+
authMode, config.authToken || null, config.baseUrl || null, config.models || null
|
|
60
|
+
])).digest('hex');
|
|
61
|
+
const marker = await fs.pathExists(markerPath) ? await fs.readJson(markerPath) : null;
|
|
62
|
+
const running = await activeRuns(home);
|
|
63
|
+
const changed = marker?.fingerprint !== fingerprint;
|
|
64
|
+
if (running && (changed || forceRelogin || !(await fs.pathExists(authPath)))) {
|
|
65
|
+
throw new Error(`该供应商仍有窗口运行或首次认证尚未完成,不能更改认证。请退出该供应商的窗口后重试;异常退出记录位于 ${path.join(home, '.akm-runs')}`);
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
for (const name of ['sessions', 'archived_sessions']) await shareDirectory(root, home, name);
|
|
69
|
+
for (const name of ['skills', 'rules', 'plugins']) {
|
|
70
|
+
if (await fs.pathExists(path.join(root, name))) await shareDirectory(root, home, name);
|
|
71
|
+
}
|
|
72
|
+
if (!marker) {
|
|
73
|
+
for (const name of ['config.toml', 'AGENTS.md']) {
|
|
74
|
+
if (await fs.pathExists(path.join(root, name))) {
|
|
75
|
+
await writeFileAtomic(path.join(home, name), await fs.readFile(path.join(root, name)));
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
// 仅迁移同名旧缓存,绝不继承根目录里其他账号的活跃认证。
|
|
79
|
+
const legacy = buildSessionCacheAuthPath(root, config.name);
|
|
80
|
+
if (authMode === 'chatgpt_login' && !forceRelogin && await fs.pathExists(legacy)) {
|
|
81
|
+
await writeFileAtomic(authPath, await fs.readFile(legacy));
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
if (changed || forceRelogin || (authMode === 'api_key' && !(await fs.pathExists(authPath)))) {
|
|
85
|
+
if (authMode === 'chatgpt_login') {
|
|
86
|
+
await clearCodexAkmConfig({ codexHome: home, forceRelogin: forceRelogin || Boolean(marker && changed) });
|
|
87
|
+
} else {
|
|
88
|
+
await applyCodexConfig(config, { codexHome: home });
|
|
89
|
+
}
|
|
90
|
+
await writeJsonAtomic(markerPath, { fingerprint });
|
|
91
|
+
}
|
|
92
|
+
const lease = path.join(home, '.akm-runs', `${process.pid}-${crypto.randomUUID()}.json`);
|
|
93
|
+
await writeJsonAtomic(lease, { pid: process.pid, startedAt: new Date().toISOString() });
|
|
94
|
+
return { home, release: () => fs.remove(lease) };
|
|
95
|
+
} finally {
|
|
96
|
+
await release();
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
async function removeProviderRuntime(name, operation) {
|
|
101
|
+
const { home, release } = await lockProvider(name);
|
|
102
|
+
try {
|
|
103
|
+
if (await activeRuns(home)) throw new Error('该供应商仍有窗口运行,请先退出后再删除');
|
|
104
|
+
const authPath = path.join(home, 'auth.json');
|
|
105
|
+
const snapshot = await fs.pathExists(authPath) ? await fs.readFile(authPath) : null;
|
|
106
|
+
await fs.remove(authPath);
|
|
107
|
+
try {
|
|
108
|
+
return await operation();
|
|
109
|
+
} catch (error) {
|
|
110
|
+
if (snapshot !== null) await writeFileAtomic(authPath, snapshot);
|
|
111
|
+
throw error;
|
|
112
|
+
}
|
|
113
|
+
} finally {
|
|
114
|
+
await release();
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
module.exports = { providerHome, prepareCodexRuntime, removeProviderRuntime };
|
package/src/utils/file-lock.js
CHANGED
|
@@ -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
|
-
|
|
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));
|
package/src/utils/launch-args.js
CHANGED
|
@@ -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
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
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
|
|
package/src/utils/codex-lock.js
DELETED
|
@@ -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 };
|