codex-id 0.2.3 → 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
@@ -11,9 +11,6 @@
11
11
  └── codex-id.json # codex-id 账号库
12
12
  ```
13
13
 
14
- 从旧版 `codexs` 升级:不再读取 `~/.codex-accounts/` 和 `CODEX_ACCOUNTS_ROOT`,
15
- 旧账号需逐个 `codex login` 后运行 `cid init`,或用 `cid add` 重新添加。
16
-
17
14
  `codex-id.json` 只保存最小结构。默认账号来自 Codex 登录态:
18
15
 
19
16
  ```json
@@ -89,30 +86,30 @@ Node CLI 支持以下终端环境:
89
86
  运行要求:
90
87
 
91
88
  - Node.js 18+
92
- - 已安装或可定位 `codex`
89
+ - `cid add` 登录时需要已安装或可定位 `codex`
93
90
 
94
- ## 用法
91
+ ### 代理
95
92
 
96
- 初始化本机已有 Codex 登录态:
93
+ `cid` 优先使用环境变量 `HTTPS_PROXY`;未设置时,macOS 和 Windows
94
+ 读取系统 HTTPS 代理(不读系统例外列表),Linux 和 WSL 只认环境变量。
97
95
 
98
- ```bash
99
- cid init
100
- # 或
101
- cid i
102
- ```
96
+ 不支持 PAC 和 SOCKS(环境变量里写 SOCKS 地址会打印警告)。自动启用代理需要 Node 24.14+ 或 25.4+,更早的版本会打印警告。
103
97
 
104
- `init` 会先检查基础环境:
98
+ ## 用法
105
99
 
106
- - `codex` 可执行文件可找到
107
- - `~/.codex/auth.json` 存在、可读、不是符号链接
108
- - `~/.codex/` 可写,`~/.codex/codex-id.json` 不是符号链接
100
+ `cid list` 和 `cid use` 会先把当前 `~/.codex/auth.json` 的登录态同步进账号库:
109
101
 
110
- 检查通过后,CLI 会从当前 `~/.codex/auth.json` 解析邮箱;如果没有邮箱,
111
- 则改用 `account_id` 前 8 位,并同步到账号库:
112
-
113
- ```bash
114
- ~/.codex/codex-id.json
115
- ```
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`
116
113
 
117
114
  登录账号:
118
115
 
@@ -129,6 +126,7 @@ cid add at-...
129
126
  ~/.codex/codex-id.json
130
127
  ```
131
128
 
129
+ 访问令牌以 `at-` 开头,其他开头(含 `sk-` API Key)直接拒绝。
132
130
  `add` 带访问令牌时不会调用 `codex login`,会先用 Usage 额度接口验证令牌,
133
131
  并读取接口返回的邮箱、套餐等用户信息;验证通过后直接写入:
134
132
 
@@ -140,7 +138,7 @@ cid add at-...
140
138
  }
141
139
  ```
142
140
 
143
- 如果该邮箱已存在,`add` 会直接覆盖账号库里的对应 `auth`,
141
+ 如果账号库里已有同一账号(区分方式见上文),`add` 会直接覆盖它的 `auth`,
144
142
  不会额外保留一份新登录结果,也不会残留 `.login.*` 临时目录。
145
143
 
146
144
  查看账号列表:
@@ -156,22 +154,16 @@ cid l
156
154
  - 查询额度前会检查账号库里的 `access_token`,已过期或 1 天内到期时,
157
155
  自动用 `refresh_token` 续期并回写 `~/.codex/codex-id.json`
158
156
  - 如果续期的是当前生效账号,会同步更新 `~/.codex/auth.json`
159
- - 续期失败不会伪装成功;后续探活仍会按 Usage 接口结果显示离线或未知
157
+ - 续期失败不会伪装成功;该账号仍按本次额度查询结果显示
160
158
  - 优先显示套餐、Next 短周期额度、Total 总周期额度
161
159
  - 账号列直接显示完整邮箱;邮箱缺失时显示短 ID,不做截断
162
160
  - 账号显示顺序与 `cid use N`、`cid remove N` 的编号解析顺序一致
163
161
  - 当前账号会在编号后显示绿色 `*`,行颜色仍按账号状态显示
164
- - 额度检测失败的账号,会直接用 Usage 接口探活
165
162
  - limited 账号显示为浅黄色,cooling 账号显示为浅灰色
166
- - 明确 401 / 403 的 offline 账号会显示为浅红色
167
- - 网络异常等未知状态只标为未知
168
-
169
- 本地状态检查时:
170
-
171
- - `已登录`:账号库里有可用 `auth`
172
- - `未登录`:账号库存在账号条目,但没有可用 `auth`
173
- - `离线`:Usage 接口探活明确返回 401 / 403
174
- - `未知`:网络异常、服务异常或其他无法确认的探活失败
163
+ - API Key 账号不查询额度,显示 `API Key`
164
+ - 没拿到额度的账号直接按这次查询结果显示:
165
+ - `离线`:接口返回 401 / 403,或账号没有可用凭据(浅红色)
166
+ - `未知(原因)`:网络或服务异常,括号里是状态码或错误码
175
167
 
176
168
  切换账号:
177
169
 
@@ -191,6 +183,9 @@ cid use 6b17e1c8
191
183
 
192
184
  - 当前生效账号处于 available 时,不自动切换
193
185
  - 当前生效账号处于 limited、cooling 或 offline 时,才会尝试自动切换
186
+ - 当前账号额度为“未知”(网络或服务异常、接口没给额度数据)时不切换
187
+ - API Key 账号按量计费:当前是它时不自动切走,也不会自动切到它;
188
+ 需要时用 `cid use <账号>` 手动切换
194
189
  - 触发自动切换后,会切到第一个 available 账号
195
190
  - 如果列表里没有 available 账号,也不会强制切换
196
191
  - 如果额度接口不可用,或当前没有 available 账号,则报错或保持不切换
@@ -227,28 +222,8 @@ cid r 2
227
222
  ```
228
223
 
229
224
  `remove` 会删除账号库里的目标账号,并同步清理所有 `.login.*`
230
- 临时登录目录;不会修改当前生效账号:
231
-
232
- ```bash
233
- ~/.codex/auth.json
234
- ```
235
-
236
- 删除离线账号:
237
-
238
- ```bash
239
- cid remove
240
- # 或
241
- cid r
242
- ```
243
-
244
- 无参 `remove` 会通过 Usage 接口探活所有已登录账号,并只提示是否删除
245
- 明确离线(401 / 403)的账号;网络异常、服务异常等未知状态会跳过。
246
- 账号库里没有可用 `auth` 的账号也会提示删除。确认选项:
247
-
248
- ```text
249
- 1:确定
250
- 2:取消
251
- ```
225
+ 临时登录目录。当前生效账号不能删除(否则下次 `list` / `use` 又会同步回来),
226
+ 需要先切换到其他账号。
252
227
 
253
228
  ## 环境变量
254
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.3",
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) => {
@@ -40,10 +40,20 @@ const decodeShortAccountIdFromAuth = (auth) => {
40
40
  return typeof accountId === 'string' && accountId.length >= 8 ? accountId.slice(0, 8) : '';
41
41
  };
42
42
 
43
+ const secretLabel = (prefix, secret) => {
44
+ if (typeof secret !== 'string' || secret.length < 8) return '';
45
+ return `${prefix}-${secret.slice(-8).replace(/^[-_]+/, '')}`;
46
+ };
47
+
43
48
  const decodePersonalAccessTokenLabelFromAuth = (auth) => {
44
- const token = auth && auth.personal_access_token;
45
- if (typeof token !== 'string' || token.length < 8) return '';
46
- return `pat-${token.slice(-8).replace(/^[-_]+/, '')}`;
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 : '';
47
57
  };
48
58
 
49
59
  // 优先展示邮箱;缺少邮箱时退回 account_id 或 personal_access_token 短标识。
@@ -60,5 +70,7 @@ module.exports = {
60
70
  decodeBase64Url,
61
71
  decodePersonalAccessTokenLabelFromAuth,
62
72
  decodeShortAccountIdFromAuth,
73
+ readApiKey,
63
74
  readAuth,
75
+ secretLabel,
64
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
  };
package/src/commands.js CHANGED
@@ -3,17 +3,16 @@ const path = require('node:path');
3
3
  const { spawnSync } = require('node:child_process');
4
4
  const { findCodexBin } = require('./codex');
5
5
  const {
6
- assertNotSymlink,
7
6
  ensureDir,
8
- ensureReadableFile,
9
7
  getAccountsFile,
10
8
  getCodexHome,
11
9
  writeFileAtomically,
12
10
  } = require('./paths');
13
11
  const {
12
+ accountLabel,
14
13
  currentAccount,
15
- currentSlotLabel,
16
14
  displayAccount,
15
+ findLogin,
17
16
  normalizeAccount,
18
17
  readAccounts,
19
18
  removeAccountEntry,
@@ -29,35 +28,39 @@ const term = require('./terminal');
29
28
  const TOTAL_RESET_TIME_THRESHOLD_SECONDS = 24 * 60 * 60;
30
29
  const PERSONAL_TOKEN_PREFIX = /^Bearer\s+/i;
31
30
 
32
- // init 先做环境预检,失败时暴露真实缺失项而不是继续写账号库。
33
- const runInitChecks = (env = process.env) => {
34
- findCodexBin(env);
35
- const codexHome = getCodexHome(env);
36
- const authPath = path.join(codexHome, 'auth.json');
37
- if (!fs.existsSync(codexHome)) throw new Error(`Codex 目录不存在:${codexHome}`);
38
- assertNotSymlink(codexHome, '拒绝读取符号链接目录');
39
- ensureReadableFile(authPath);
40
- };
41
-
42
- const syncCurrentAccount = (env = process.env, output = process.stdout) => {
43
- const { account, overwritten } = upsertAccount(readAuth(getCodexHome(env)), env);
44
- if (overwritten) {
45
- output.write(`账号已存在:${displayAccount(account)},已更新:${getAccountsFile(env)}\n`);
46
- return;
47
- }
48
- output.write(`已同步当前 Codex 账号:${displayAccount(account)},已写入:${getAccountsFile(env)}\n`);
49
- };
50
-
51
31
  const writeCurrentAuth = (auth, env = process.env) => {
52
32
  const authPath = path.join(getCodexHome(env), 'auth.json');
53
33
  writeFileAtomically(authPath, `${JSON.stringify(auth, null, 2)}\n`);
54
34
  return authPath;
55
35
  };
56
36
 
57
- const initAccounts = (env = process.env, output = process.stdout) => {
58
- runInitChecks(env);
59
- output.write('环境检查通过,');
60
- syncCurrentAccount(env, output);
37
+ const refreshedAt = (auth) => Date.parse(auth.last_refresh) || 0;
38
+
39
+ // list / use 前把 Codex 当前登录态收进账号库,避免切走时丢掉它续期得到的新令牌。
40
+ // 登录态存在但读不懂时返回 false。
41
+ const syncCurrentAccount = (env = process.env, output = process.stdout, errOutput = process.stderr) => {
42
+ let current;
43
+ try {
44
+ const auth = readAuth(getCodexHome(env));
45
+ if (!auth) return true;
46
+ current = normalizeAccount(auth);
47
+ } catch (error) {
48
+ errOutput.write(`当前登录态未同步:${error.message}\n`);
49
+ return false;
50
+ }
51
+ const stored = findLogin(readAccounts(env), current);
52
+ // 只用更新的登录态覆盖,避免冲掉刚用 add 写入账号库的新令牌。
53
+ if (stored && refreshedAt(current.auth) <= refreshedAt(stored.auth)) return true;
54
+ const { account } = upsertAccount(current.auth, env);
55
+ if (!stored) output.write(`已同步当前 Codex 账号:${accountLabel(account, readAccounts(env))}\n`);
56
+ return true;
57
+ };
58
+
59
+ // 切换会覆盖 auth.json,没能入库的登录态一旦覆盖就找不回来。
60
+ const syncBeforeSwitch = (env, output) => {
61
+ if (syncCurrentAccount(env, output)) return;
62
+ const authPath = path.join(getCodexHome(env), 'auth.json');
63
+ throw new Error(`为避免丢失当前登录态,未切换账号;请先备份或删除 ${authPath}`);
61
64
  };
62
65
 
63
66
  // 清理登录中断遗留的临时目录,只处理 `.login.*` 且跳过符号链接。
@@ -71,25 +74,34 @@ const removeLoginTempDirs = (env = process.env) => {
71
74
  }
72
75
  };
73
76
 
74
- const useAccount = (selector, env = process.env, output = process.stdout) => {
75
- const account = resolveAccount(selector, env);
76
- if (!account) throw new Error(`账号不存在:${selector}`);
77
+ const activateAccount = (account, env = process.env, output = process.stdout) => {
77
78
  ensureDir(getCodexHome(env));
78
79
  const authPath = writeCurrentAuth(account.auth, env);
79
- output.write(`已切换 Codex 账号:${displayAccount(account)},已更新:${authPath};VS Code Codex 可能需要 Reload Window 或重启 VS Code 后生效。\n`);
80
+ output.write(`已切换 Codex 账号:${accountLabel(account, readAccounts(env))},已更新:${authPath};VS Code Codex 可能需要 Reload Window 或重启 VS Code 后生效。\n`);
80
81
  };
81
82
 
82
- const removeAccountFromStore = (account, message, env = process.env, output = process.stdout) => {
83
- const accountLabel = displayAccount(account);
84
- removeAccountEntry(account, env);
85
- removeLoginTempDirs(env);
86
- output.write(`${message}:${accountLabel}\n`);
83
+ const useAccount = (selector, env = process.env, output = process.stdout) => {
84
+ // 先按同步前的列表解析序号,与用户上次看到的编号一致。
85
+ const selected = resolveAccount(selector, env);
86
+ syncBeforeSwitch(env, output);
87
+ const account = selected
88
+ ? findLogin(readAccounts(env), selected)
89
+ : resolveAccount(selector, env);
90
+ if (!account) throw new Error(`账号不存在:${selector}`);
91
+ activateAccount(account, env, output);
87
92
  };
88
93
 
89
94
  const removeAccount = (selector, env = process.env, output = process.stdout) => {
90
95
  const account = resolveAccount(selector, env);
91
96
  if (!account) throw new Error(`账号不存在:${selector}`);
92
- removeAccountFromStore(account, '已删除账号', env, output);
97
+ const current = currentAccount(env);
98
+ const label = accountLabel(account, readAccounts(env));
99
+ if (current && current.key === account.key) {
100
+ throw new Error(`不能删除当前生效账号:${label},请先用 cid use 切换到其他账号`);
101
+ }
102
+ removeAccountEntry(account, env);
103
+ removeLoginTempDirs(env);
104
+ output.write(`已删除账号:${label}\n`);
93
105
  };
94
106
 
95
107
  const writeEmptyAccountsMessage = (env = process.env, output = process.stdout) => {
@@ -108,54 +120,6 @@ const formatCodexLoginFailure = (codexBin, result) => {
108
120
  return details.join('\n');
109
121
  };
110
122
 
111
- // 批量删除只处理探活确认离线的账号,每个账号仍逐个交互确认。
112
- const removeOfflineAccounts = async (
113
- env = process.env,
114
- output = process.stdout,
115
- input = process.stdin,
116
- errOutput = process.stderr,
117
- ) => {
118
- ensureDir(getCodexHome(env));
119
- removeLoginTempDirs(env);
120
- const accounts = readAccounts(env);
121
- if (accounts.length === 0) {
122
- writeEmptyAccountsMessage(env, output);
123
- return;
124
- }
125
-
126
- let removed = 0;
127
- let abortedReason = '';
128
- for (const [index, account] of accounts.entries()) {
129
- const accountLabel = displayAccount(account);
130
- const status = await term.withProgress(
131
- `正在检测账号 ${index + 1}/${accounts.length}:${accountLabel}`,
132
- () => usage.probeAccountStatus(account),
133
- env,
134
- );
135
- if (status === 'unknown') {
136
- errOutput.write(`无法确认账号在线状态,已跳过:${accountLabel}\n`);
137
- continue;
138
- }
139
- if (status !== 'offline') continue;
140
- let confirmed = false;
141
- try {
142
- confirmed = await term.confirmRemoval(accountLabel, input, output);
143
- } catch (error) {
144
- abortedReason = error && error.message ? error.message : String(error);
145
- break;
146
- }
147
- if (!confirmed) continue;
148
- removeAccountFromStore(account, '已删除离线账号', env, output);
149
- removed += 1;
150
- }
151
- if (removed > 0) output.write(`本次共删除离线账号:${removed}\n`);
152
- else if (!abortedReason) output.write('没有离线账号可删除\n');
153
- if (abortedReason) {
154
- // 已删账号摘要先写到 stdout,再抛错让 main 设非零退出码。
155
- throw new Error(`${abortedReason}(已删除 ${removed} 个,剩余离线账号未处理)`);
156
- }
157
- };
158
-
159
123
  // Windows 下 `.cmd/.bat` 不能直接 spawn,需要走 cmd.exe 包装。
160
124
  const runCodexLogin = (codexBin, env) => {
161
125
  const childEnv = { ...env, CODEX_HOME: env.CODEX_HOME };
@@ -204,6 +168,12 @@ const addAccount = async (env = process.env, output = process.stdout) => {
204
168
  const normalizePersonalAccessToken = (token) => {
205
169
  const value = String(token || '').trim().replace(PERSONAL_TOKEN_PREFIX, '').trim();
206
170
  if (!value) throw new Error('缺少访问令牌');
171
+ // 必须在发请求前拦下:非法请求头的报错会带出完整令牌。
172
+ if (!/^[\x21-\x7e]+$/.test(value)) throw new Error('访问令牌含空白或非法字符');
173
+ if (value.startsWith('sk-')) {
174
+ throw new Error('cid add 不接受 API Key;请用 Codex 以 Key 登录后运行 cid list 同步');
175
+ }
176
+ if (!value.startsWith('at-')) throw new Error('访问令牌应以 at- 开头');
207
177
  return value;
208
178
  };
209
179
 
@@ -221,18 +191,28 @@ const addPersonalAccessToken = async (token, env = process.env, output = process
221
191
  };
222
192
 
223
193
  // 当前账号进入 limited/cooling/offline 后,才尝试切到第一个 available 账号。
194
+ // API Key 账号按量计费且没有额度数据:既不自动切走,也不会被自动选中。
224
195
  const useDefaultAccount = async (env = process.env, output = process.stdout) => {
196
+ syncBeforeSwitch(env, output);
225
197
  const accounts = readAccounts(env);
226
198
  if (accounts.length === 0) {
227
199
  writeEmptyAccountsMessage(env, output);
228
200
  return;
229
201
  }
202
+ const activeAccount = currentAccount(env);
203
+ if (activeAccount && activeAccount.isApiKey) {
204
+ output.write(`当前是 API Key 账号,不自动切换:${displayAccount(activeAccount)},未切换账号。\n`);
205
+ return;
206
+ }
230
207
  const usageResults = await term.withProgress('正在查询账号额度...', () => usage.loadUsage(accounts), env);
231
208
  if (!usage.hasUsageData(usageResults)) throw new Error('无法查询账号额度,未切换账号');
232
- const activeAccount = currentAccount(env);
233
- const currentKey = activeAccount ? activeAccount.id : '';
209
+ const currentKey = activeAccount ? activeAccount.key : '';
234
210
  if (activeAccount && !usage.accountShouldAutoSwitch(usageResults, currentKey)) {
235
- output.write(`当前 Codex 账号状态无需自动切换:${displayAccount(activeAccount)},未切换账号。\n`);
211
+ const item = usage.usageFor(usageResults, currentKey);
212
+ const reason = usage.getAccountUsageState(item) === usage.ACCOUNT_USAGE_STATES.UNKNOWN
213
+ ? `额度${describeFailure(item).text}`
214
+ : '状态无需自动切换';
215
+ output.write(`当前 Codex 账号${reason}:${displayAccount(activeAccount)},未切换账号。\n`);
236
216
  return;
237
217
  }
238
218
  const next = await term.withProgress(
@@ -247,11 +227,10 @@ const useDefaultAccount = async (env = process.env, output = process.stdout) =>
247
227
  }
248
228
  throw new Error('没有找到 available 账号,未切换账号');
249
229
  }
250
- useAccount(next.id, env, output);
230
+ activateAccount(next, env, output);
251
231
  };
252
232
 
253
- const getUsageRowColor = ({ isOffline, planLabel, nextUsed, totalUsed, nextPercent, totalPercent }) => {
254
- if (isOffline) return 'lightRed';
233
+ const getUsageRowColor = ({ planLabel, nextUsed, totalUsed, nextPercent, totalPercent }) => {
255
234
  if (planLabel === 'Free' || nextPercent === '-') {
256
235
  if (totalUsed >= 100 || totalPercent === '0%') return 'gray';
257
236
  if (totalUsed >= 97) return 'lightYellow';
@@ -264,44 +243,11 @@ const getUsageRowColor = ({ isOffline, planLabel, nextUsed, totalUsed, nextPerce
264
243
 
265
244
  const findFirstAvailableAccount = (accounts, usageResults, currentKey = '') => {
266
245
  return accounts.find((account) => {
267
- if (account.id === currentKey) return false;
268
- return usage.accountIsAvailableForAutoSwitch(usageResults, account.id);
246
+ if (account.key === currentKey) return false;
247
+ return usage.accountIsAvailableForAutoSwitch(usageResults, account.key);
269
248
  });
270
249
  };
271
250
 
272
- const lightStatusLabel = (account) => {
273
- return account && account.auth ? '已登录' : '未登录';
274
- };
275
-
276
- // 组装列表行数据;已有 Usage 数据时不再额外探活。
277
- const buildAccountRow = async (account, index, total, activeLabel, usageResults, env) => {
278
- const localLabel = displayAccount(account);
279
- const item = usage.usageFor(usageResults, account.id) || {};
280
- const accountLabel = item.email || localLabel;
281
- const key = account.id;
282
- let status = lightStatusLabel(account);
283
- let isOffline = false;
284
- const isCurrent = Boolean(activeLabel && localLabel === activeLabel);
285
-
286
- if (status === '已登录' && !usage.usageAvailableForAccount(usageResults, key)) {
287
- const probeStatus = await term.withProgress(`正在探活账号 ${index}/${total}:${accountLabel}`, () => usage.probeAccountStatus(account), env);
288
- if (probeStatus === 'offline') {
289
- status = '离线';
290
- isOffline = true;
291
- } else if (probeStatus === 'unknown') {
292
- status = '未知';
293
- }
294
- }
295
-
296
- return { account: accountLabel, isCurrent, isOffline, key, status, indexDisplay: term.formatListIndex(index, isCurrent) };
297
- };
298
-
299
- const loadAccountRows = async (accounts, activeLabel, usageResults, env = process.env) => {
300
- return Promise.all(accounts.map((account, index) => {
301
- return buildAccountRow(account, index + 1, accounts.length, activeLabel, usageResults, env);
302
- }));
303
- };
304
-
305
251
  const getTotalResetMode = (resetAt) => {
306
252
  const now = Math.floor(Date.now() / 1000);
307
253
  return resetAt - now <= TOTAL_RESET_TIME_THRESHOLD_SECONDS ? 'time' : 'date';
@@ -321,26 +267,36 @@ const buildUsageColumns = (item) => {
321
267
  return { nextColumn, nextPercent, planLabel, totalColumn, totalPercent };
322
268
  };
323
269
 
324
- const renderUsageRow = (row, item, accountWidth, output = process.stdout) => {
270
+ // 没拿到额度时直接根据这次查询结果说明状态,不再重复请求。
271
+ const describeFailure = (item) => {
272
+ if (usage.getAccountUsageState(item) === usage.ACCOUNT_USAGE_STATES.OFFLINE) return { text: '离线', isOffline: true };
273
+ return { text: item.error ? `未知(${item.error})` : '未知(无额度数据)', isOffline: false };
274
+ };
275
+
276
+ const renderRow = (name, index, isCurrent, item, accountWidth, output = process.stdout) => {
277
+ const prefix = `${term.pad(term.formatListIndex(index, isCurrent), term.INDEX_WIDTH)} ${term.pad(name, accountWidth)}`;
278
+ if (item && item.isApiKey) {
279
+ term.printRow(`${prefix} API Key`, { isCurrent, color: '' }, output);
280
+ return;
281
+ }
282
+ if (!usage.hasUsageFields(item)) {
283
+ const { text, isOffline } = describeFailure(item);
284
+ term.printRow(`${prefix} ${text}`, { isCurrent, color: isOffline ? 'lightRed' : '' }, output);
285
+ return;
286
+ }
325
287
  const { nextColumn, nextPercent, planLabel, totalColumn, totalPercent } = buildUsageColumns(item);
326
- const statusColor = getUsageRowColor({
327
- isOffline: row.isOffline,
288
+ const color = getUsageRowColor({
328
289
  nextPercent,
329
290
  nextUsed: item.next_used,
330
291
  planLabel,
331
292
  totalPercent,
332
293
  totalUsed: item.total_used,
333
294
  });
334
- const line = `${term.pad(row.indexDisplay, term.INDEX_WIDTH)} ${term.pad(row.account, accountWidth)} ${term.pad(planLabel, term.PLAN_WIDTH)} ${term.pad(nextColumn, term.USAGE_WIDTH)} ${term.pad(totalColumn, term.USAGE_WIDTH)}`;
335
- term.printRow(line, { isCurrent: row.isCurrent, color: statusColor }, output);
336
- };
337
-
338
- const renderStatusRow = (row, accountWidth, output = process.stdout) => {
339
- const line = `${term.pad(row.indexDisplay, term.INDEX_WIDTH)} ${term.pad(row.account, accountWidth)} ${term.pad(row.status, term.STATUS_WIDTH)}`;
340
- term.printRow(line, { isCurrent: row.isCurrent, color: row.isOffline ? 'lightRed' : '' }, output);
295
+ const line = `${prefix} ${term.pad(planLabel, term.PLAN_WIDTH)} ${term.pad(nextColumn, term.USAGE_WIDTH)} ${term.pad(totalColumn, term.USAGE_WIDTH)}`;
296
+ term.printRow(line, { isCurrent, color }, output);
341
297
  };
342
298
 
343
- const refreshAccountForList = async (account, activeLabel, env, services, errOutput) => {
299
+ const refreshAccountForList = async (account, activeKey, env, services, errOutput) => {
344
300
  if (!tokenExpiresSoon(account.auth)) return { account, refreshedCurrent: false, changed: false };
345
301
  try {
346
302
  const nextAuth = await refreshAuth(account.auth, services.refreshFetch);
@@ -349,7 +305,7 @@ const refreshAccountForList = async (account, activeLabel, env, services, errOut
349
305
  return {
350
306
  account: next,
351
307
  changed: true,
352
- refreshedCurrent: displayAccount(account) === activeLabel,
308
+ refreshedCurrent: account.key === activeKey,
353
309
  };
354
310
  } catch (error) {
355
311
  const message = error && error.message ? error.message : String(error);
@@ -358,10 +314,10 @@ const refreshAccountForList = async (account, activeLabel, env, services, errOut
358
314
  }
359
315
  };
360
316
 
361
- const refreshAccountsForList = async (accounts, activeLabel, env = process.env, services = {}) => {
317
+ const refreshAccountsForList = async (accounts, activeKey, env = process.env, services = {}) => {
362
318
  const errOutput = services.errOutput || process.stderr;
363
319
  const results = await Promise.all(accounts.map((account) => {
364
- return refreshAccountForList(account, activeLabel, env, services, errOutput);
320
+ return refreshAccountForList(account, activeKey, env, services, errOutput);
365
321
  }));
366
322
  if (!results.some((result) => result.changed)) return accounts;
367
323
 
@@ -372,60 +328,57 @@ const refreshAccountsForList = async (accounts, activeLabel, env = process.env,
372
328
  return refreshed;
373
329
  };
374
330
 
375
- const syncPersonalAccessTokenEmails = (accounts, usageResults, activeLabel, env = process.env) => {
331
+ const syncPersonalAccessTokenEmails = (accounts, usageResults, activeKey, env = process.env) => {
376
332
  let activeAuth = null;
377
333
  let changed = false;
378
334
  const synced = accounts.map((account) => {
379
- const item = usage.usageFor(usageResults, account.id);
335
+ const item = usage.usageFor(usageResults, account.key);
380
336
  if (!item || !item.email || account.email || !account.auth.personal_access_token) return account;
381
337
  const next = normalizeAccount({ ...account.auth, email: item.email });
382
- item.key = next.id;
383
338
  changed = true;
384
- if (displayAccount(account) === activeLabel) activeAuth = next.auth;
339
+ if (account.key === activeKey) activeAuth = next.auth;
385
340
  return next;
386
341
  });
387
342
  if (!changed) return accounts;
388
343
 
389
344
  writeAccounts(synced, env);
390
345
  if (activeAuth) writeCurrentAuth(activeAuth, env);
391
- return synced;
346
+ // 账号库写入时会重新排序,按落盘顺序显示,保证编号与 use / remove 一致。
347
+ return readAccounts(env);
392
348
  };
393
349
 
394
350
  const listAccounts = async (env = process.env, output = process.stdout, services = {}) => {
395
351
  ensureDir(getCodexHome(env));
396
- const activeLabel = currentSlotLabel(env);
352
+ // 必须先同步再续期:Codex 可能已经轮换过 refresh_token。
353
+ syncCurrentAccount(env, output, services.errOutput || process.stderr);
354
+ const activeKey = currentAccount(env)?.key;
397
355
  const accounts = await term.withProgress('正在刷新登录态...', () => {
398
- return refreshAccountsForList(readAccounts(env), activeLabel, env, services);
356
+ return refreshAccountsForList(readAccounts(env), activeKey, env, services);
399
357
  }, env);
400
358
  const usageResults = await term.withProgress('正在查询账号额度...', () => {
401
359
  return usage.loadUsage(accounts, services.usageFetch);
402
360
  }, env);
403
- const syncedAccounts = syncPersonalAccessTokenEmails(accounts, usageResults, activeLabel, env);
404
- const hasUsage = usage.hasUsageData(usageResults);
405
- const rows = await loadAccountRows(syncedAccounts, activeLabel, usageResults, env);
406
- const accountWidth = Math.max('Account'.length, ...rows.map((r) => r.account.length));
407
-
408
- const header = hasUsage
409
- ? `${term.pad('No.', term.INDEX_WIDTH)} ${term.pad('Account', accountWidth)} ${term.pad('Plan', term.PLAN_WIDTH)} ${term.pad('Next', term.USAGE_WIDTH)} ${term.pad('Total', term.USAGE_WIDTH)}`
410
- : `${term.pad('No.', term.INDEX_WIDTH)} ${term.pad('Account', accountWidth)} ${term.pad('Status', term.STATUS_WIDTH)}`;
361
+ const syncedAccounts = syncPersonalAccessTokenEmails(accounts, usageResults, activeKey, env);
362
+ const names = syncedAccounts.map((account) => accountLabel(account, syncedAccounts));
363
+ const accountWidth = Math.max('Account'.length, ...names.map((name) => name.length));
364
+
365
+ const header = `${term.pad('No.', term.INDEX_WIDTH)} ${term.pad('Account', accountWidth)} ${term.pad('Plan', term.PLAN_WIDTH)} ${term.pad('Next', term.USAGE_WIDTH)} ${term.pad('Total', term.USAGE_WIDTH)}`;
411
366
  output.write(`${term.bold(header, env, output)}\n`);
412
367
 
413
- for (const row of rows) {
414
- const item = usage.usageFor(usageResults, row.key) || {};
415
- if (hasUsage) renderUsageRow(row, item, accountWidth, output);
416
- else renderStatusRow(row, accountWidth, output);
417
- }
418
- if (rows.length === 0) writeEmptyAccountsMessage(env, output);
368
+ const currentKey = currentAccount(env)?.key;
369
+ syncedAccounts.forEach((account, i) => {
370
+ const item = account.isApiKey ? account : usage.usageFor(usageResults, account.key);
371
+ renderRow(names[i], i + 1, account.key === currentKey, item, accountWidth, output);
372
+ });
373
+ if (syncedAccounts.length === 0) writeEmptyAccountsMessage(env, output);
419
374
  };
420
375
 
421
376
  module.exports = {
422
377
  addAccount,
423
378
  addPersonalAccessToken,
424
379
  getUsageRowColor,
425
- initAccounts,
426
380
  listAccounts,
427
381
  removeAccount,
428
- removeOfflineAccounts,
429
382
  useAccount,
430
383
  useDefaultAccount,
431
384
  };
package/src/paths.js CHANGED
@@ -38,20 +38,22 @@ const assertNotSymlink = (targetPath, message) => {
38
38
  }
39
39
  };
40
40
 
41
- const ensureReadableFile = (filePath) => {
42
- if (!fs.existsSync(filePath) || !fs.statSync(filePath).isFile()) {
43
- throw new Error(`文件不存在:${filePath}`);
44
- }
45
- assertNotSymlink(filePath, '拒绝读取符号链接文件');
46
- fs.accessSync(filePath, fs.constants.R_OK);
47
- };
48
-
49
41
  const ensureDir = (dirPath) => {
50
42
  fs.mkdirSync(dirPath, { recursive: true, mode: 0o700 });
51
43
  assertNotSymlink(dirPath, '拒绝写入符号链接目录');
52
44
  try { fs.chmodSync(dirPath, 0o700); } catch (_) {}
53
45
  };
54
46
 
47
+ // 不透传解析错误:其中带文件原文,可能含令牌。
48
+ const readJsonFile = (filePath) => {
49
+ const text = fs.readFileSync(filePath, 'utf8');
50
+ try {
51
+ return JSON.parse(text);
52
+ } catch (_) {
53
+ throw new Error(`${filePath} 不是有效的 JSON`);
54
+ }
55
+ };
56
+
55
57
  // 先写唯一临时文件再 rename,避免 auth.json 出现半写入状态或并发冲突。
56
58
  const writeFileAtomically = (targetPath, data) => {
57
59
  const targetDir = path.dirname(targetPath);
@@ -88,9 +90,9 @@ const writeFileAtomically = (targetPath, data) => {
88
90
  module.exports = {
89
91
  assertNotSymlink,
90
92
  ensureDir,
91
- ensureReadableFile,
92
93
  getAccountsFile,
93
94
  getCodexHome,
94
95
  getHomeDir,
96
+ readJsonFile,
95
97
  writeFileAtomically,
96
98
  };
package/src/proxy.js ADDED
@@ -0,0 +1,66 @@
1
+ const { execFileSync } = require('node:child_process');
2
+ const http = require('node:http');
3
+ const path = require('node:path');
4
+
5
+ // cid 只访问 HTTPS 地址,系统代理只需取 HTTPS 一项。
6
+ const parseScutil = (text) => {
7
+ const read = (key) => (text.match(new RegExp(`^ ${key} : (.*)$`, 'm')) || [])[1];
8
+ const server = read('HTTPSEnable') === '1' && read('HTTPSProxy') ? `${read('HTTPSProxy')}:${read('HTTPSPort')}` : '';
9
+ return { server, unsupported: read('SOCKSEnable') === '1' || read('ProxyAutoConfigEnable') === '1' };
10
+ };
11
+
12
+ // ProxyServer 可能是 `host:port` 或 `http=..;https=..;socks=..`。
13
+ const parseRegistry = (text) => {
14
+ const read = (key) => (text.match(new RegExp(`^\\s+${key}\\s+REG_\\w+\\s+(\\S+)`, 'm')) || [])[1] || '';
15
+ const value = read('ProxyEnable') === '0x1' ? read('ProxyServer') : '';
16
+ const server = value.includes('=') ? (value.match(/(?:^|;)https=([^;]+)/) || [])[1] || '' : value;
17
+ return { server, unsupported: Boolean(read('AutoConfigURL')) || value.includes('socks=') };
18
+ };
19
+
20
+ // 环境变量优先;否则 macOS / Windows 读系统代理,Linux / WSL 只认环境变量。
21
+ const resolveProxy = (env = process.env, platform = process.platform, run = execFileSync) => {
22
+ const fromEnv = env.https_proxy || env.HTTPS_PROXY;
23
+ // Node 遇到 SOCKS 地址会静默直连,必须自己提示。
24
+ if (/^socks/i.test(fromEnv || '')) return { warning: '代理环境变量是 SOCKS,暂不支持' };
25
+ if (fromEnv) return { proxyEnv: env };
26
+ const options = { encoding: 'utf8', timeout: 2000, stdio: ['ignore', 'pipe', 'ignore'] };
27
+ let system = { server: '' };
28
+ try {
29
+ if (platform === 'darwin') {
30
+ system = parseScutil(run('/usr/sbin/scutil', ['--proxy'], options));
31
+ } else if (platform === 'win32') {
32
+ // 用绝对路径,避免执行到当前目录里的同名程序。
33
+ const reg = path.win32.join(env.SystemRoot || 'C:\\Windows', 'System32', 'reg.exe');
34
+ const key = 'HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings';
35
+ system = parseRegistry(run(reg, ['query', key], options));
36
+ }
37
+ } catch (_) {
38
+ return { warning: '读取系统代理失败' };
39
+ }
40
+ const { server, unsupported } = system;
41
+ if (server) return { proxyEnv: { HTTPS_PROXY: server.includes('://') ? server : `http://${server}` } };
42
+ return unsupported ? { warning: '系统代理是 PAC 或 SOCKS,暂不支持' } : {};
43
+ };
44
+
45
+ // Node 的 fetch 默认不读代理配置,需显式启用。
46
+ const setupProxy = (env = process.env, errOutput = process.stderr) => {
47
+ const warn = (reason) => errOutput.write(`警告:${reason},本次未启用代理(见 README「代理」)\n`);
48
+ const { proxyEnv, warning } = resolveProxy(env);
49
+ if (warning) warn(warning);
50
+ if (!proxyEnv) return;
51
+ if (!http.setGlobalProxyFromEnv) {
52
+ errOutput.write('警告:自动启用代理需要 Node 24.14+ 或 25.4+\n');
53
+ return;
54
+ }
55
+ try {
56
+ http.setGlobalProxyFromEnv(proxyEnv);
57
+ } catch (_) {
58
+ // 不回显代理地址,其中可能带账号密码。
59
+ warn('代理地址无效(需以 http:// 或 https:// 开头)');
60
+ }
61
+ };
62
+
63
+ module.exports = {
64
+ resolveProxy,
65
+ setupProxy,
66
+ };
package/src/terminal.js CHANGED
@@ -1,9 +1,6 @@
1
- const readline = require('node:readline/promises');
2
-
3
1
  const INDEX_WIDTH = 4;
4
2
  const PLAN_WIDTH = 8;
5
3
  const USAGE_WIDTH = 14;
6
- const STATUS_WIDTH = 10;
7
4
  const PROGRESS_INTERVAL_MS = 120;
8
5
  const PROGRESS_FRAMES = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'];
9
6
 
@@ -61,26 +58,6 @@ const formatListIndex = (index, isCurrent) => {
61
58
  return isCurrent ? `${index}*` : String(index);
62
59
  };
63
60
 
64
- // 删除离线账号必须由交互终端确认,避免脚本环境误删。
65
- const confirmRemoval = async (
66
- account,
67
- input = process.stdin,
68
- output = process.stdout,
69
- ) => {
70
- if (!input.isTTY) throw new Error('删除离线账号需要交互式终端确认');
71
- output.write(`检测到离线账号:${account}\n`);
72
- const rl = readline.createInterface({ input, output });
73
- const answer = await rl.question('是否删除?1:确定 2:取消\n');
74
- rl.close();
75
- if (answer === '1') return true;
76
- if (answer === '2') {
77
- output.write(`已取消删除离线账号:${account}\n`);
78
- } else {
79
- output.write(`输入无效,已取消删除离线账号:${account}\n`);
80
- }
81
- return false;
82
- };
83
-
84
61
  const printRow = (
85
62
  row,
86
63
  { isCurrent = false, color = '' } = {},
@@ -141,11 +118,9 @@ const withProgress = async (
141
118
  module.exports = {
142
119
  INDEX_WIDTH,
143
120
  PLAN_WIDTH,
144
- STATUS_WIDTH,
145
121
  USAGE_WIDTH,
146
122
  bold,
147
123
  colorize,
148
- confirmRemoval,
149
124
  formatListIndex,
150
125
  formatPlanType,
151
126
  formatResetTime,
package/src/usage.js CHANGED
@@ -8,6 +8,7 @@ const ACCOUNT_USAGE_STATES = Object.freeze({
8
8
  LIMITED: 'limited',
9
9
  COOLING: 'cooling',
10
10
  OFFLINE: 'offline',
11
+ UNKNOWN: 'unknown',
11
12
  });
12
13
 
13
14
  // 从账号 auth 中提取调用 Usage 接口所需的最小凭据。
@@ -59,7 +60,7 @@ const buildUsageEntries = (accounts) => {
59
60
  const fields = extractAuthFields(account);
60
61
  if (!fields) return [];
61
62
  return [{
62
- key: account.id,
63
+ key: account.key,
63
64
  token: fields.accessToken,
64
65
  accountId: fields.accountId,
65
66
  }];
@@ -99,24 +100,7 @@ const fetchUsageOne = async (entry, fetchImpl = fetch) => {
99
100
  total_reset: total.reset_at ?? null,
100
101
  };
101
102
  } catch (error) {
102
- return { key: entry.key, error: error.message };
103
- }
104
- };
105
-
106
- // 用 Usage 接口探活账号,避免依赖本地 codex 命令或模型列表输出。
107
- const probeAccountStatus = async (account, fetchImpl = fetch) => {
108
- const fields = extractAuthFields(account);
109
- if (!fields) return 'offline';
110
- try {
111
- const response = await fetchImpl(USAGE_ENDPOINT, {
112
- headers: buildUsageHeaders(fields.accessToken, fields.accountId),
113
- signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
114
- });
115
- if (response.ok) return 'online';
116
- if (response.status === 401 || response.status === 403) return 'offline';
117
- return 'unknown';
118
- } catch (_) {
119
- return 'unknown';
103
+ return { key: entry.key, error: (error.cause && error.cause.code) || error.name };
120
104
  }
121
105
  };
122
106
 
@@ -147,10 +131,6 @@ const usageFor = (results, key) => {
147
131
  return results.find((item) => item.key === key) || null;
148
132
  };
149
133
 
150
- const usageAvailableForAccount = (results, key) => {
151
- return hasUsageFields(usageFor(results, key));
152
- };
153
-
154
134
  const classifyPrimaryWindow = (usedPercent) => {
155
135
  if (!isValidPercent(usedPercent)) return ACCOUNT_USAGE_STATES.COOLING;
156
136
  if (usedPercent >= QUOTA_COOLING_PERCENT) return ACCOUNT_USAGE_STATES.COOLING;
@@ -162,7 +142,11 @@ const classifyPrimaryWindow = (usedPercent) => {
162
142
 
163
143
  // 统一账号额度状态,供自动切换和后续展示逻辑复用。
164
144
  const getAccountUsageState = (item) => {
165
- if (!hasUsageFields(item)) return ACCOUNT_USAGE_STATES.OFFLINE;
145
+ if (!item || (!isValidPercent(item.next_used) && !isValidPercent(item.total_used))) {
146
+ // 只有凭据缺失或被拒才算离线;网络、服务异常和缺额度数据不能当作账号不可用。
147
+ const rejected = !item || item.error === 401 || item.error === 403;
148
+ return rejected ? ACCOUNT_USAGE_STATES.OFFLINE : ACCOUNT_USAGE_STATES.UNKNOWN;
149
+ }
166
150
  // 免费账号和只有总周期限额的账号没有 Next 窗口,只按 Total 判断。
167
151
  if (item.plan === 'free' || !isValidPercent(item.next_used)) return classifyPrimaryWindow(item.total_used);
168
152
  // 只有 Next 窗口的账号(如部分 team 访问令牌账号)只按 Next 判断。
@@ -191,8 +175,7 @@ module.exports = {
191
175
  fetchPersonalAccessTokenProfile,
192
176
  getAccountUsageState,
193
177
  hasUsageData,
178
+ hasUsageFields,
194
179
  loadUsage,
195
- probeAccountStatus,
196
- usageAvailableForAccount,
197
180
  usageFor,
198
181
  };