codex-id 0.2.2 → 0.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/README.md CHANGED
@@ -86,30 +86,30 @@ Node CLI 支持以下终端环境:
86
86
  运行要求:
87
87
 
88
88
  - Node.js 18+
89
- - 已安装或可定位 `codex`
89
+ - `cid add` 登录时需要已安装或可定位 `codex`
90
90
 
91
- ## 用法
92
-
93
- 初始化本机已有 Codex 登录态:
91
+ ### 代理
94
92
 
95
- ```bash
96
- cid init
97
- # 或
98
- cid i
99
- ```
93
+ `cid` 优先使用环境变量 `HTTPS_PROXY`;未设置时,macOS 和 Windows
94
+ 读取系统 HTTPS 代理(不读系统例外列表),Linux 和 WSL 只认环境变量。
100
95
 
101
- `init` 会先检查基础环境:
96
+ 不支持 PAC 和 SOCKS(环境变量里写 SOCKS 地址会打印警告)。自动启用代理需要 Node 24.14+ 或 25.4+,更早的版本会打印警告。
102
97
 
103
- - `codex` 可执行文件可找到
104
- - `~/.codex/auth.json` 存在、可读、不是符号链接
105
- - `~/.codex/` 可写,`~/.codex/codex-id.json` 不是符号链接
98
+ ## 用法
106
99
 
107
- 检查通过后,CLI 会从当前 `~/.codex/auth.json` 解析邮箱;如果没有邮箱,
108
- 则改用 `account_id` 前 8 位,并同步到账号库:
100
+ `cid list` 和 `cid use` 会先把当前 `~/.codex/auth.json` 的登录态同步进账号库:
109
101
 
110
- ```bash
111
- ~/.codex/codex-id.json
112
- ```
102
+ - 账号库里没有时自动添加;邮箱缺失时用 `account_id` 前 8 位标识
103
+ - 已有时,只有当前登录态的 `last_refresh` 更新才覆盖
104
+ - 普通登录按“邮箱 + 工作空间 ID(`account_id`)”区分账号,访问令牌账号按令牌区分;
105
+ 同一邮箱的多个工作空间各存一份
106
+ - 同名账号在列表里附带短 ID(工作空间 ID 前 8 位、`pat-短标识` 或 `key-短标识`);
107
+ `use` / `remove` 用序号或短 ID 指定,只给邮箱且匹配多个时报错
108
+ - API Key 登录态(`OPENAI_API_KEY` 以 `sk-` 开头且没有登录令牌)同样会同步进账号库
109
+ (明文保存,权限与其他账号相同),用
110
+ `key-` 加末 8 位标识。只能这样同步入库,`cid add` 不接受 API Key
111
+ - 无法识别账号的登录态(含损坏的 `auth.json`)不会写入,并打印提示;此时 `use`
112
+ 不会覆盖它,需要先备份或删除 `auth.json`
113
113
 
114
114
  登录账号:
115
115
 
@@ -126,6 +126,7 @@ cid add at-...
126
126
  ~/.codex/codex-id.json
127
127
  ```
128
128
 
129
+ 访问令牌以 `at-` 开头,其他开头(含 `sk-` API Key)直接拒绝。
129
130
  `add` 带访问令牌时不会调用 `codex login`,会先用 Usage 额度接口验证令牌,
130
131
  并读取接口返回的邮箱、套餐等用户信息;验证通过后直接写入:
131
132
 
@@ -137,7 +138,7 @@ cid add at-...
137
138
  }
138
139
  ```
139
140
 
140
- 如果该邮箱已存在,`add` 会直接覆盖账号库里的对应 `auth`,
141
+ 如果账号库里已有同一账号(区分方式见上文),`add` 会直接覆盖它的 `auth`,
141
142
  不会额外保留一份新登录结果,也不会残留 `.login.*` 临时目录。
142
143
 
143
144
  查看账号列表:
@@ -153,22 +154,16 @@ cid l
153
154
  - 查询额度前会检查账号库里的 `access_token`,已过期或 1 天内到期时,
154
155
  自动用 `refresh_token` 续期并回写 `~/.codex/codex-id.json`
155
156
  - 如果续期的是当前生效账号,会同步更新 `~/.codex/auth.json`
156
- - 续期失败不会伪装成功;后续探活仍会按 Usage 接口结果显示离线或未知
157
+ - 续期失败不会伪装成功;该账号仍按本次额度查询结果显示
157
158
  - 优先显示套餐、Next 短周期额度、Total 总周期额度
158
159
  - 账号列直接显示完整邮箱;邮箱缺失时显示短 ID,不做截断
159
160
  - 账号显示顺序与 `cid use N`、`cid remove N` 的编号解析顺序一致
160
161
  - 当前账号会在编号后显示绿色 `*`,行颜色仍按账号状态显示
161
- - 额度检测失败的账号,会直接用 Usage 接口探活
162
162
  - limited 账号显示为浅黄色,cooling 账号显示为浅灰色
163
- - 明确 401 / 403 的 offline 账号会显示为浅红色
164
- - 网络异常等未知状态只标为未知
165
-
166
- 本地状态检查时:
167
-
168
- - `已登录`:账号库里有可用 `auth`
169
- - `未登录`:账号库存在账号条目,但没有可用 `auth`
170
- - `离线`:Usage 接口探活明确返回 401 / 403
171
- - `未知`:网络异常、服务异常或其他无法确认的探活失败
163
+ - API Key 账号不查询额度,显示 `API Key`
164
+ - 没拿到额度的账号直接按这次查询结果显示:
165
+ - `离线`:接口返回 401 / 403,或账号没有可用凭据(浅红色)
166
+ - `未知(原因)`:网络或服务异常,括号里是状态码或错误码
172
167
 
173
168
  切换账号:
174
169
 
@@ -188,6 +183,9 @@ cid use 6b17e1c8
188
183
 
189
184
  - 当前生效账号处于 available 时,不自动切换
190
185
  - 当前生效账号处于 limited、cooling 或 offline 时,才会尝试自动切换
186
+ - 当前账号额度为“未知”(网络或服务异常、接口没给额度数据)时不切换
187
+ - API Key 账号按量计费:当前是它时不自动切走,也不会自动切到它;
188
+ 需要时用 `cid use <账号>` 手动切换
191
189
  - 触发自动切换后,会切到第一个 available 账号
192
190
  - 如果列表里没有 available 账号,也不会强制切换
193
191
  - 如果额度接口不可用,或当前没有 available 账号,则报错或保持不切换
@@ -195,7 +193,8 @@ cid use 6b17e1c8
195
193
  额度判定规则:
196
194
 
197
195
  - 付费账号比较 Next 剩余额度;只要 Total 剩余额度为 0,就视为冷却账号,不参与自动切换
198
- - 免费账号没有 Next 额度,只比较 Total 剩余额度
196
+ - 免费账号和只有总周期限额的账号没有 Next 额度,只比较 Total 剩余额度
197
+ - 只有 Next 额度、没有 Total 的付费账号,只比较 Next 剩余额度
199
198
  - 自动切换不比较当前账号和目标账号的具体百分比
200
199
 
201
200
  `use` 带账号时会把目标账号的 `auth.json` 覆盖到:
@@ -223,28 +222,8 @@ cid r 2
223
222
  ```
224
223
 
225
224
  `remove` 会删除账号库里的目标账号,并同步清理所有 `.login.*`
226
- 临时登录目录;不会修改当前生效账号:
227
-
228
- ```bash
229
- ~/.codex/auth.json
230
- ```
231
-
232
- 删除离线账号:
233
-
234
- ```bash
235
- cid remove
236
- # 或
237
- cid r
238
- ```
239
-
240
- 无参 `remove` 会通过 Usage 接口探活所有已登录账号,并只提示是否删除
241
- 明确离线(401 / 403)的账号;网络异常、服务异常等未知状态会跳过。
242
- 账号库里没有可用 `auth` 的账号也会提示删除。确认选项:
243
-
244
- ```text
245
- 1:确定
246
- 2:取消
247
- ```
225
+ 临时登录目录。当前生效账号不能删除(否则下次 `list` / `use` 又会同步回来),
226
+ 需要先切换到其他账号。
248
227
 
249
228
  ## 环境变量
250
229
 
package/bin/cid CHANGED
@@ -1,25 +1,24 @@
1
1
  #!/usr/bin/env node
2
2
 
3
3
  const commands = require('../src/commands');
4
+ const { setupProxy } = require('../src/proxy');
4
5
 
5
6
  function usage(output = process.stdout) {
6
7
  output.write(`cid - Codex 账号切换助手
7
8
 
8
9
  命令:
9
- cid init|i
10
10
  cid add|a [personal_access_token]
11
11
  cid list|l
12
12
  cid use|u [account]
13
- cid remove|r [account]
13
+ cid remove|r <account>
14
14
  cid help
15
15
 
16
16
  说明:
17
- account 可以是序号、邮箱、短 ID 或 pat-短标识;use 不带 account 时自动选择有额度账号。
17
+ account 可以是序号、邮箱、短 ID、pat-短标识或 key-短标识;use 不带 account 时自动选择有额度账号。
18
18
  ~/.codex/codex-id.json 存账号库。
19
19
  ~/.codex/auth.json 是当前生效槽位。
20
20
  cid add 不带参数时登录 Codex;带访问令牌时直接添加令牌账号。
21
- cid remove 不带账号时删除离线账号。
22
- cid init 会检查基础环境,并同步当前登录态。
21
+ cid list / use 会自动把当前 Codex 登录态同步进账号库。
23
22
 
24
23
  环境变量:
25
24
  CODEX_BIN 指定 codex 可执行文件路径
@@ -32,18 +31,14 @@ function assertNoExtra(args, command) {
32
31
 
33
32
  async function main(argv = process.argv.slice(2), io = {}) {
34
33
  const output = io.output || process.stdout;
35
- const input = io.input || process.stdin;
36
34
  const errOutput = io.errOutput || process.stderr;
37
35
  const env = io.env || process.env;
38
- const ALIAS = { i: 'init', l: 'list', a: 'add', u: 'use', r: 'remove', '-h': 'help', '--help': 'help' };
36
+ const ALIAS = { l: 'list', a: 'add', u: 'use', r: 'remove', '-h': 'help', '--help': 'help' };
39
37
  const [raw = 'help', ...args] = argv;
40
38
  const command = ALIAS[raw] || raw;
39
+ setupProxy(env, errOutput);
41
40
 
42
41
  switch (command) {
43
- case 'init':
44
- assertNoExtra(args, 'init');
45
- commands.initAccounts(env, output);
46
- break;
47
42
  case 'list':
48
43
  assertNoExtra(args, 'list');
49
44
  await commands.listAccounts(env, output);
@@ -61,9 +56,8 @@ async function main(argv = process.argv.slice(2), io = {}) {
61
56
  else throw new Error('用法:cid use [account]');
62
57
  break;
63
58
  case 'remove':
64
- if (args.length === 0) await commands.removeOfflineAccounts(env, output, input, errOutput);
65
- else if (args.length === 1) commands.removeAccount(args[0], env, output);
66
- else throw new Error('用法:cid remove [account]');
59
+ if (args.length !== 1) throw new Error('用法:cid remove <account>');
60
+ commands.removeAccount(args[0], env, output);
67
61
  break;
68
62
  case 'help':
69
63
  usage(output);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "codex-id",
3
- "version": "0.2.2",
3
+ "version": "0.2.4",
4
4
  "description": "Codex account switching CLI",
5
5
  "license": "MIT",
6
6
  "type": "commonjs",
package/src/accounts.js CHANGED
@@ -3,18 +3,21 @@ const {
3
3
  assertNotSymlink,
4
4
  getAccountsFile,
5
5
  getCodexHome,
6
+ readJsonFile,
6
7
  writeFileAtomically,
7
8
  } = require('./paths');
8
9
  const {
9
10
  decodeAccountEmailFromAuth,
10
- decodeAccountLabel,
11
11
  decodePersonalAccessTokenLabelFromAuth,
12
12
  decodeShortAccountIdFromAuth,
13
+ readApiKey,
14
+ readAuth,
15
+ secretLabel,
13
16
  } = require('./auth');
14
17
 
15
18
  const STORE_VERSION = 1;
16
19
  const SHORT_ACCOUNT_ID = /^[a-f0-9]{8}$/i;
17
- const PERSONAL_TOKEN_ID = /^pat-[A-Za-z0-9_-]{4,}$/;
20
+ const SECRET_ID = /^(pat|key)-[A-Za-z0-9_-]{4,}$/;
18
21
 
19
22
  // 校验外部传入的账号标识,避免路径穿越和隐藏目录误用。
20
23
  const validateName = (name) => {
@@ -23,8 +26,8 @@ const validateName = (name) => {
23
26
  throw new Error('账号名不能是 .、..、以 . 开头,且不能包含 /');
24
27
  }
25
28
  const email = /^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+$/;
26
- if (!email.test(name) && !SHORT_ACCOUNT_ID.test(name) && !PERSONAL_TOKEN_ID.test(name)) {
27
- throw new Error('账号只能是邮箱、短 ID 或个人访问令牌短标识');
29
+ if (!email.test(name) && !SHORT_ACCOUNT_ID.test(name) && !SECRET_ID.test(name)) {
30
+ throw new Error('账号只能是邮箱、短 ID、pat-短标识或 key-短标识');
28
31
  }
29
32
  };
30
33
 
@@ -32,13 +35,24 @@ const displayAccount = (account) => {
32
35
  return account.email || account.shortId || account.tokenId || account.id;
33
36
  };
34
37
 
38
+ // 同名账号(同一邮箱的多个工作空间或多个令牌)附带短 ID 区分。
39
+ const accountLabel = (account, accounts) => {
40
+ const name = displayAccount(account);
41
+ const shared = accounts.filter((item) => displayAccount(item) === name).length > 1;
42
+ const suffix = account.tokenId || account.shortId;
43
+ return shared && suffix ? `${name} (${suffix})` : name;
44
+ };
45
+
35
46
  const normalizeAccount = (auth) => {
36
47
  const email = decodeAccountEmailFromAuth(auth);
37
48
  const shortId = decodeShortAccountIdFromAuth(auth);
38
- const tokenId = decodePersonalAccessTokenLabelFromAuth(auth);
49
+ const apiKey = readApiKey(auth);
50
+ const tokenId = decodePersonalAccessTokenLabelFromAuth(auth) || secretLabel('key', apiKey);
39
51
  const id = email || shortId || tokenId;
40
- if (!id) throw new Error('未能从 auth.json 解析出邮箱、短 ID 或个人访问令牌短标识');
41
- return { auth, email, id, shortId, tokenId };
52
+ if (!id) throw new Error('未能从 auth.json 解析出邮箱、短 ID、访问令牌或 API Key');
53
+ // key 是账号唯一标识:一份登录只对应一个工作空间,访问令牌和 API Key 按自身区分。含密钥,不可打印。
54
+ const key = auth.personal_access_token || apiKey || `${email}|${(auth.tokens && auth.tokens.account_id) || ''}`;
55
+ return { auth, email, id, isApiKey: Boolean(apiKey), key, shortId, tokenId };
42
56
  };
43
57
 
44
58
  const accountMatches = (account, selector) => {
@@ -51,7 +65,7 @@ const readAccounts = (env = process.env) => {
51
65
  if (!fs.existsSync(filePath)) return [];
52
66
  assertNotSymlink(codexHome, '拒绝读取符号链接目录');
53
67
  assertNotSymlink(filePath, '拒绝读取符号链接账号库');
54
- const data = JSON.parse(fs.readFileSync(filePath, 'utf8'));
68
+ const data = readJsonFile(filePath);
55
69
  if (!data || data.version !== STORE_VERSION || !Array.isArray(data.accounts)) {
56
70
  throw new Error(`账号库格式无效:${filePath}`);
57
71
  }
@@ -64,7 +78,10 @@ const writeAccounts = (accounts, env = process.env) => {
64
78
  if (!fs.existsSync(codexHome)) fs.mkdirSync(codexHome, { recursive: true, mode: 0o700 });
65
79
  assertNotSymlink(codexHome, '拒绝写入符号链接目录');
66
80
  assertNotSymlink(filePath, '拒绝覆盖符号链接账号库');
67
- const sorted = [...accounts].sort((a, b) => displayAccount(a).localeCompare(displayAccount(b), 'en'));
81
+ // 同名时再按 key 排序,避免覆盖写入后编号漂移。
82
+ const sorted = [...accounts].sort((a, b) => {
83
+ return displayAccount(a).localeCompare(displayAccount(b), 'en') || a.key.localeCompare(b.key, 'en');
84
+ });
68
85
  const payload = {
69
86
  version: STORE_VERSION,
70
87
  accounts: sorted.map(({ auth }) => auth),
@@ -75,14 +92,13 @@ const writeAccounts = (accounts, env = process.env) => {
75
92
  const upsertAccount = (auth, env = process.env) => {
76
93
  const next = normalizeAccount(auth);
77
94
  const current = readAccounts(env);
78
- const overwritten = current.some((account) => account.id === next.id);
79
- const accounts = current.filter((account) => account.id !== next.id);
95
+ const accounts = current.filter((account) => account.key !== next.key);
80
96
  writeAccounts([...accounts, next], env);
81
- return { account: next, overwritten };
97
+ return { account: next, overwritten: accounts.length < current.length };
82
98
  };
83
99
 
84
100
  const removeAccountEntry = (account, env = process.env) => {
85
- writeAccounts(readAccounts(env).filter((item) => item.id !== account.id), env);
101
+ writeAccounts(readAccounts(env).filter((item) => item.key !== account.key), env);
86
102
  };
87
103
 
88
104
  const resolveAccount = (selector, env = process.env) => {
@@ -94,22 +110,36 @@ const resolveAccount = (selector, env = process.env) => {
94
110
  return accounts[index - 1];
95
111
  }
96
112
  validateName(selector);
97
- return accounts.find((account) => accountMatches(account, selector)) || null;
113
+ const matches = accounts.filter((account) => accountMatches(account, selector));
114
+ if (matches.length > 1) {
115
+ const choices = matches.map((account) => `${accounts.indexOf(account) + 1} ${accountLabel(account, accounts)}`);
116
+ throw new Error(`"${selector}" 匹配到多个账号,请用序号指定:${choices.join('、')}`);
117
+ }
118
+ return matches[0] || null;
98
119
  };
99
120
 
100
- const currentSlotLabel = (env = process.env) => {
101
- return decodeAccountLabel(getCodexHome(env));
121
+ const findLogin = (accounts, login) => {
122
+ return accounts.find((account) => account.key === login.key) || null;
102
123
  };
103
124
 
125
+ // 当前生效账号;没有登录态或无法识别时返回 null。
104
126
  const currentAccount = (env = process.env) => {
105
- const current = currentSlotLabel(env);
106
- return readAccounts(env).find((account) => displayAccount(account) === current) || null;
127
+ const auth = readAuth(getCodexHome(env));
128
+ if (!auth) return null;
129
+ let login;
130
+ try {
131
+ login = normalizeAccount(auth);
132
+ } catch (_) {
133
+ return null;
134
+ }
135
+ return findLogin(readAccounts(env), login);
107
136
  };
108
137
 
109
138
  module.exports = {
139
+ accountLabel,
110
140
  currentAccount,
111
- currentSlotLabel,
112
141
  displayAccount,
142
+ findLogin,
113
143
  normalizeAccount,
114
144
  readAccounts,
115
145
  removeAccountEntry,
package/src/auth.js CHANGED
@@ -1,6 +1,6 @@
1
1
  const fs = require('node:fs');
2
2
  const path = require('node:path');
3
- const { assertNotSymlink } = require('./paths');
3
+ const { assertNotSymlink, readJsonFile } = require('./paths');
4
4
 
5
5
  const decodeBase64Url = (value) => {
6
6
  const normalized = value.replace(/-/g, '+').replace(/_/g, '/');
@@ -14,7 +14,7 @@ const readAuth = (homeDir) => {
14
14
  if (!fs.existsSync(authPath)) return null;
15
15
  assertNotSymlink(homeDir, '拒绝读取符号链接目录');
16
16
  assertNotSymlink(authPath, '拒绝读取符号链接文件');
17
- return JSON.parse(fs.readFileSync(authPath, 'utf8'));
17
+ return readJsonFile(authPath);
18
18
  };
19
19
 
20
20
  const readIdTokenPayloadFromAuth = (auth) => {
@@ -36,22 +36,24 @@ const decodeAccountEmailFromAuth = (auth) => {
36
36
  };
37
37
 
38
38
  const decodeShortAccountIdFromAuth = (auth) => {
39
- try {
40
- const accountId = auth && auth.tokens && auth.tokens.account_id;
41
- return typeof accountId === 'string' && accountId.length >= 8 ? accountId.slice(0, 8) : '';
42
- } catch (_) {
43
- return '';
44
- }
39
+ const accountId = auth && auth.tokens && auth.tokens.account_id;
40
+ return typeof accountId === 'string' && accountId.length >= 8 ? accountId.slice(0, 8) : '';
41
+ };
42
+
43
+ const secretLabel = (prefix, secret) => {
44
+ if (typeof secret !== 'string' || secret.length < 8) return '';
45
+ return `${prefix}-${secret.slice(-8).replace(/^[-_]+/, '')}`;
45
46
  };
46
47
 
47
48
  const decodePersonalAccessTokenLabelFromAuth = (auth) => {
48
- try {
49
- const token = auth && auth.personal_access_token;
50
- if (typeof token !== 'string' || token.length < 8) return '';
51
- return `pat-${token.slice(-8).replace(/^[-_]+/, '')}`;
52
- } catch (_) {
53
- return '';
54
- }
49
+ return secretLabel('pat', auth && auth.personal_access_token);
50
+ };
51
+
52
+ // 普通登录的 auth.json 也可能带 OPENAI_API_KEY,没有登录令牌和访问令牌才算 API Key 账号。
53
+ const readApiKey = (auth) => {
54
+ if (!auth || auth.personal_access_token || (auth.tokens && auth.tokens.access_token)) return '';
55
+ const key = auth.OPENAI_API_KEY;
56
+ return typeof key === 'string' && key.startsWith('sk-') ? key : '';
55
57
  };
56
58
 
57
59
  // 优先展示邮箱;缺少邮箱时退回 account_id 或 personal_access_token 短标识。
@@ -65,7 +67,10 @@ const decodeAccountLabel = (homeDir) => {
65
67
  module.exports = {
66
68
  decodeAccountEmailFromAuth,
67
69
  decodeAccountLabel,
70
+ decodeBase64Url,
68
71
  decodePersonalAccessTokenLabelFromAuth,
69
72
  decodeShortAccountIdFromAuth,
73
+ readApiKey,
70
74
  readAuth,
75
+ secretLabel,
71
76
  };
package/src/codex.js CHANGED
@@ -20,51 +20,6 @@ const isExecutable = (filePath) => {
20
20
  }
21
21
  };
22
22
 
23
- const archAliases = (arch = process.arch) => {
24
- const aliases = {
25
- arm64: ['arm64', 'aarch64'],
26
- ia32: ['ia32', 'x86'],
27
- x64: ['x64', 'x86_64'],
28
- };
29
- return aliases[arch] || [arch];
30
- };
31
-
32
- const platformAliases = (platform = process.platform) => {
33
- const aliases = {
34
- darwin: ['darwin', 'macos'],
35
- linux: ['linux'],
36
- win32: ['win32', 'windows'],
37
- };
38
- return aliases[platform] || [platform];
39
- };
40
-
41
- const compatibleVscodePlatformNames = (
42
- platform = process.platform,
43
- arch = process.arch,
44
- ) => {
45
- return platformAliases(platform).flatMap((platformName) => {
46
- return archAliases(arch).map((archName) => `${platformName}-${archName}`);
47
- });
48
- };
49
-
50
- const platformNameFromExtension = (extensionName) => {
51
- const match = extensionName.match(/^openai\.chatgpt-.+?-(.+-.+)$/);
52
- return match ? match[1] : '';
53
- };
54
-
55
- const orderedVscodePlatformNames = (
56
- extensionName,
57
- platform = process.platform,
58
- arch = process.arch,
59
- ) => {
60
- const compatibleNames = compatibleVscodePlatformNames(platform, arch);
61
- const parsedName = platformNameFromExtension(extensionName);
62
- return [
63
- compatibleNames.includes(parsedName) ? parsedName : '',
64
- ...compatibleNames,
65
- ].filter(Boolean);
66
- };
67
-
68
23
  // 按 PATH 顺序查找命令,找到第一个可执行文件即返回。
69
24
  const findOnPath = (command, env = process.env) => {
70
25
  const pathValue = env.PATH || '';
@@ -77,23 +32,20 @@ const findOnPath = (command, env = process.env) => {
77
32
  return '';
78
33
  };
79
34
 
80
- // VS Code 插件内也可能自带 codex 二进制,作为 PATH 之外的兜底来源。
81
- const findVscodeCodex = (env = process.env) => {
35
+ // VS Code 插件内也带 codex,作为 PATH 之外的兜底来源。
36
+ const findVscodeCodex = (env = process.env, platform = process.platform) => {
82
37
  const extensionsDir = path.join(getHomeDir(env), '.vscode', 'extensions');
83
38
  if (!fs.existsSync(extensionsDir)) return '';
84
- const extensionNames = fs.readdirSync(extensionsDir).filter((name) => {
85
- return name.startsWith('openai.chatgpt-');
86
- });
39
+ // 插件里可能带其他系统的程序(如 Windows 版带 WSL 用的 Linux 版),按目录名前缀过滤。
40
+ const ownDir = { darwin: /^(darwin|macos)-/, win32: /^(win32|windows)-/ }[platform] || new RegExp(`^${platform}-`);
41
+ const names = platform === 'win32' ? ['codex.cmd', 'codex.exe'] : ['codex'];
87
42
 
88
- for (const extensionName of extensionNames.reverse()) {
43
+ for (const extensionName of fs.readdirSync(extensionsDir).sort().reverse()) {
89
44
  const binDir = path.join(extensionsDir, extensionName, 'bin');
90
- if (!fs.existsSync(binDir)) continue;
91
- const candidates = new Set(orderedVscodePlatformNames(extensionName));
92
- const found = [...candidates]
93
- .filter((platformName) => fs.existsSync(path.join(binDir, platformName)))
94
- .flatMap((platformName) =>
95
- executableNames('codex').map((name) => path.join(binDir, platformName, name)),
96
- )
45
+ if (!extensionName.startsWith('openai.chatgpt-') || !fs.existsSync(binDir)) continue;
46
+ const found = fs.readdirSync(binDir)
47
+ .filter((dir) => ownDir.test(dir))
48
+ .flatMap((dir) => names.map((name) => path.join(binDir, dir, name)))
97
49
  .find(isExecutable);
98
50
  if (found) return found;
99
51
  }
@@ -114,10 +66,6 @@ const findCodexBin = (env = process.env) => {
114
66
  };
115
67
 
116
68
  module.exports = {
117
- __test: {
118
- compatibleVscodePlatformNames,
119
- orderedVscodePlatformNames,
120
- platformNameFromExtension,
121
- },
122
69
  findCodexBin,
70
+ findVscodeCodex,
123
71
  };