codex-id 0.2.1 → 0.2.3

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,6 +11,9 @@
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
+
14
17
  `codex-id.json` 只保存最小结构。默认账号来自 Codex 登录态:
15
18
 
16
19
  ```json
@@ -195,7 +198,8 @@ cid use 6b17e1c8
195
198
  额度判定规则:
196
199
 
197
200
  - 付费账号比较 Next 剩余额度;只要 Total 剩余额度为 0,就视为冷却账号,不参与自动切换
198
- - 免费账号没有 Next 额度,只比较 Total 剩余额度
201
+ - 免费账号和只有总周期限额的账号没有 Next 额度,只比较 Total 剩余额度
202
+ - 只有 Next 额度、没有 Total 的付费账号,只比较 Next 剩余额度
199
203
  - 自动切换不比较当前账号和目标账号的具体百分比
200
204
 
201
205
  `use` 带账号时会把目标账号的 `auth.json` 覆盖到:
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "codex-id",
3
- "version": "0.2.1",
3
+ "version": "0.2.3",
4
4
  "description": "Codex account switching CLI",
5
5
  "license": "MIT",
6
6
  "type": "commonjs",
package/src/auth.js CHANGED
@@ -36,22 +36,14 @@ 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) : '';
45
41
  };
46
42
 
47
43
  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
- }
44
+ const token = auth && auth.personal_access_token;
45
+ if (typeof token !== 'string' || token.length < 8) return '';
46
+ return `pat-${token.slice(-8).replace(/^[-_]+/, '')}`;
55
47
  };
56
48
 
57
49
  // 优先展示邮箱;缺少邮箱时退回 account_id 或 personal_access_token 短标识。
@@ -65,6 +57,7 @@ const decodeAccountLabel = (homeDir) => {
65
57
  module.exports = {
66
58
  decodeAccountEmailFromAuth,
67
59
  decodeAccountLabel,
60
+ decodeBase64Url,
68
61
  decodePersonalAccessTokenLabelFromAuth,
69
62
  decodeShortAccountIdFromAuth,
70
63
  readAuth,
package/src/commands.js CHANGED
@@ -6,6 +6,7 @@ const {
6
6
  assertNotSymlink,
7
7
  ensureDir,
8
8
  ensureReadableFile,
9
+ getAccountsFile,
9
10
  getCodexHome,
10
11
  writeFileAtomically,
11
12
  } = require('./paths');
@@ -39,13 +40,18 @@ const runInitChecks = (env = process.env) => {
39
40
  };
40
41
 
41
42
  const syncCurrentAccount = (env = process.env, output = process.stdout) => {
42
- const codexHome = getCodexHome(env);
43
- const { account, overwritten } = upsertAccount(readAuth(codexHome), env);
43
+ const { account, overwritten } = upsertAccount(readAuth(getCodexHome(env)), env);
44
44
  if (overwritten) {
45
- output.write(`账号已存在:${displayAccount(account)},已更新:${path.join(codexHome, 'codex-id.json')}\n`);
45
+ output.write(`账号已存在:${displayAccount(account)},已更新:${getAccountsFile(env)}\n`);
46
46
  return;
47
47
  }
48
- output.write(`已同步当前 Codex 账号:${displayAccount(account)},已写入:${path.join(codexHome, 'codex-id.json')}\n`);
48
+ output.write(`已同步当前 Codex 账号:${displayAccount(account)},已写入:${getAccountsFile(env)}\n`);
49
+ };
50
+
51
+ const writeCurrentAuth = (auth, env = process.env) => {
52
+ const authPath = path.join(getCodexHome(env), 'auth.json');
53
+ writeFileAtomically(authPath, `${JSON.stringify(auth, null, 2)}\n`);
54
+ return authPath;
49
55
  };
50
56
 
51
57
  const initAccounts = (env = process.env, output = process.stdout) => {
@@ -68,10 +74,9 @@ const removeLoginTempDirs = (env = process.env) => {
68
74
  const useAccount = (selector, env = process.env, output = process.stdout) => {
69
75
  const account = resolveAccount(selector, env);
70
76
  if (!account) throw new Error(`账号不存在:${selector}`);
71
- const codexHome = getCodexHome(env);
72
- ensureDir(codexHome);
73
- writeFileAtomically(path.join(codexHome, 'auth.json'), `${JSON.stringify(account.auth, null, 2)}\n`);
74
- output.write(`已切换 Codex 账号:${displayAccount(account)},已更新:${path.join(codexHome, 'auth.json')};VS Code Codex 可能需要 Reload Window 或重启 VS Code 后生效。\n`);
77
+ ensureDir(getCodexHome(env));
78
+ const authPath = writeCurrentAuth(account.auth, env);
79
+ output.write(`已切换 Codex 账号:${displayAccount(account)},已更新:${authPath};VS Code Codex 可能需要 Reload Window 或重启 VS Code 后生效。\n`);
75
80
  };
76
81
 
77
82
  const removeAccountFromStore = (account, message, env = process.env, output = process.stdout) => {
@@ -88,7 +93,7 @@ const removeAccount = (selector, env = process.env, output = process.stdout) =>
88
93
  };
89
94
 
90
95
  const writeEmptyAccountsMessage = (env = process.env, output = process.stdout) => {
91
- output.write(`(${path.join(getCodexHome(env), 'codex-id.json')} 里还没有账号)\n`);
96
+ output.write(`(${getAccountsFile(env)} 里还没有账号)\n`);
92
97
  };
93
98
 
94
99
  const formatCodexLoginFailure = (codexBin, result) => {
@@ -247,12 +252,12 @@ const useDefaultAccount = async (env = process.env, output = process.stdout) =>
247
252
 
248
253
  const getUsageRowColor = ({ isOffline, planLabel, nextUsed, totalUsed, nextPercent, totalPercent }) => {
249
254
  if (isOffline) return 'lightRed';
250
- if (planLabel === 'Free') {
251
- if (totalUsed >= 100 || totalPercent === '0%') return 'lightGray';
255
+ if (planLabel === 'Free' || nextPercent === '-') {
256
+ if (totalUsed >= 100 || totalPercent === '0%') return 'gray';
252
257
  if (totalUsed >= 97) return 'lightYellow';
253
258
  return '';
254
259
  }
255
- if (nextUsed >= 100 || nextPercent === '0%' || totalPercent === '0%') return 'lightGray';
260
+ if (nextUsed >= 100 || nextPercent === '0%' || totalPercent === '0%') return 'gray';
256
261
  if (nextUsed >= 97) return 'lightYellow';
257
262
  return '';
258
263
  };
@@ -304,15 +309,13 @@ const getTotalResetMode = (resetAt) => {
304
309
 
305
310
  const buildUsageColumns = (item) => {
306
311
  const planLabel = term.formatPlanType(item.plan);
307
- const nextReset = item.next_reset ?? item.h5_reset;
308
- const totalReset = item.total_reset ?? item.d7_reset;
309
- const nextPercent = term.formatUsagePercent(item.next_used ?? item.h5_used);
310
- const totalPercent = term.formatUsagePercent(item.total_used ?? item.d7_used);
311
- const nextColumn = nextPercent !== '-' && nextReset
312
- ? `${nextPercent} (${term.formatResetTime(nextReset, 'time')})`
312
+ const nextPercent = term.formatUsagePercent(item.next_used);
313
+ const totalPercent = term.formatUsagePercent(item.total_used);
314
+ const nextColumn = nextPercent !== '-' && item.next_reset
315
+ ? `${nextPercent} (${term.formatResetTime(item.next_reset, 'time')})`
313
316
  : nextPercent;
314
- const totalColumn = totalPercent !== '-' && totalReset
315
- ? `${totalPercent} (${term.formatResetTime(totalReset, getTotalResetMode(totalReset))})`
317
+ const totalColumn = totalPercent !== '-' && item.total_reset
318
+ ? `${totalPercent} (${term.formatResetTime(item.total_reset, getTotalResetMode(item.total_reset))})`
316
319
  : totalPercent;
317
320
 
318
321
  return { nextColumn, nextPercent, planLabel, totalColumn, totalPercent };
@@ -323,10 +326,10 @@ const renderUsageRow = (row, item, accountWidth, output = process.stdout) => {
323
326
  const statusColor = getUsageRowColor({
324
327
  isOffline: row.isOffline,
325
328
  nextPercent,
326
- nextUsed: item.next_used ?? item.h5_used,
329
+ nextUsed: item.next_used,
327
330
  planLabel,
328
331
  totalPercent,
329
- totalUsed: item.total_used ?? item.d7_used,
332
+ totalUsed: item.total_used,
330
333
  });
331
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)}`;
332
335
  term.printRow(line, { isCurrent: row.isCurrent, color: statusColor }, output);
@@ -340,7 +343,7 @@ const renderStatusRow = (row, accountWidth, output = process.stdout) => {
340
343
  const refreshAccountForList = async (account, activeLabel, env, services, errOutput) => {
341
344
  if (!tokenExpiresSoon(account.auth)) return { account, refreshedCurrent: false, changed: false };
342
345
  try {
343
- const nextAuth = await refreshAuth(account.auth, env, services.refreshFetch);
346
+ const nextAuth = await refreshAuth(account.auth, services.refreshFetch);
344
347
  if (!nextAuth) return { account, refreshedCurrent: false, changed: false };
345
348
  const next = { ...account, auth: nextAuth };
346
349
  return {
@@ -365,10 +368,7 @@ const refreshAccountsForList = async (accounts, activeLabel, env = process.env,
365
368
  const refreshed = results.map((result) => result.account);
366
369
  writeAccounts(refreshed, env);
367
370
  const current = results.find((result) => result.refreshedCurrent);
368
- if (current) {
369
- const codexHome = getCodexHome(env);
370
- writeFileAtomically(path.join(codexHome, 'auth.json'), `${JSON.stringify(current.account.auth, null, 2)}\n`);
371
- }
371
+ if (current) writeCurrentAuth(current.account.auth, env);
372
372
  return refreshed;
373
373
  };
374
374
 
@@ -387,10 +387,7 @@ const syncPersonalAccessTokenEmails = (accounts, usageResults, activeLabel, env
387
387
  if (!changed) return accounts;
388
388
 
389
389
  writeAccounts(synced, env);
390
- if (activeAuth) {
391
- const codexHome = getCodexHome(env);
392
- writeFileAtomically(path.join(codexHome, 'auth.json'), `${JSON.stringify(activeAuth, null, 2)}\n`);
393
- }
390
+ if (activeAuth) writeCurrentAuth(activeAuth, env);
394
391
  return synced;
395
392
  };
396
393
 
package/src/refresh.js CHANGED
@@ -1,5 +1,7 @@
1
+ const { decodeBase64Url } = require('./auth');
2
+
1
3
  const CLIENT_ID = 'app_EMoamEEZ73f0CkXaXp7hrann';
2
- const DEFAULT_REFRESH_TOKEN_URL = 'https://auth.openai.com/oauth/token';
4
+ const REFRESH_TOKEN_URL = 'https://auth.openai.com/oauth/token';
3
5
  const REFRESH_GRACE_SECONDS = 24 * 60 * 60;
4
6
  const REQUEST_TIMEOUT_MS = 8000;
5
7
 
@@ -8,9 +10,7 @@ const decodeJwtPayload = (token) => {
8
10
  const [, payload] = token.split('.');
9
11
  if (!payload) return null;
10
12
  try {
11
- const normalized = payload.replace(/-/g, '+').replace(/_/g, '/');
12
- const padded = normalized.padEnd(Math.ceil(normalized.length / 4) * 4, '=');
13
- return JSON.parse(Buffer.from(padded, 'base64').toString('utf8'));
13
+ return JSON.parse(decodeBase64Url(payload));
14
14
  } catch (_) {
15
15
  return null;
16
16
  }
@@ -30,12 +30,11 @@ const buildRefreshBody = (refreshToken) => {
30
30
  return body;
31
31
  };
32
32
 
33
- const refreshAuth = async (auth, env = process.env, fetchImpl = fetch) => {
33
+ const refreshAuth = async (auth, fetchImpl = fetch) => {
34
34
  const tokens = auth && auth.tokens;
35
35
  if (!tokens || typeof tokens.refresh_token !== 'string') return null;
36
- if (typeof fetchImpl !== 'function' || typeof AbortSignal.timeout !== 'function') return null;
37
36
 
38
- const response = await fetchImpl(env.CODEX_REFRESH_TOKEN_URL_OVERRIDE || DEFAULT_REFRESH_TOKEN_URL, {
37
+ const response = await fetchImpl(REFRESH_TOKEN_URL, {
39
38
  method: 'POST',
40
39
  headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
41
40
  body: buildRefreshBody(tokens.refresh_token),
package/src/terminal.js CHANGED
@@ -15,7 +15,7 @@ const colorize = (value, color, env = process.env, stream = process.stdout) => {
15
15
  if (!stream.isTTY || env.NO_COLOR) return value;
16
16
  const colors = {
17
17
  green: 32,
18
- lightGray: '38;2;230;230;230',
18
+ gray: 90,
19
19
  lightRed: '38;2;255;160;160',
20
20
  lightYellow: '38;2;255;230;150',
21
21
  };
package/src/usage.js CHANGED
@@ -1,6 +1,3 @@
1
- const path = require('node:path');
2
- const { readAuth } = require('./auth');
3
-
4
1
  const USAGE_ENDPOINT = 'https://chatgpt.com/backend-api/wham/usage';
5
2
  const REQUEST_TIMEOUT_MS = 8000;
6
3
  const USAGE_5H_WINDOW_SECONDS = 18000;
@@ -13,28 +10,23 @@ const ACCOUNT_USAGE_STATES = Object.freeze({
13
10
  OFFLINE: 'offline',
14
11
  });
15
12
 
16
- // 从 auth.json 中提取调用 Usage 接口所需的最小凭据;
17
- // 复用 readAuth 的 symlink 防护,保证 list / probe 与 use / init 安全等级一致。
18
- const extractAuthFields = (homeDir) => {
19
- try {
20
- const auth = typeof homeDir === 'string' ? readAuth(homeDir) : homeDir && homeDir.auth;
21
- if (auth && typeof auth.personal_access_token === 'string') {
22
- return {
23
- accessToken: auth.personal_access_token,
24
- accountId: '',
25
- };
26
- }
27
- const tokens = auth && auth.tokens;
28
- if (!tokens || typeof tokens.access_token !== 'string' || typeof tokens.account_id !== 'string') {
29
- return null;
30
- }
13
+ // 从账号 auth 中提取调用 Usage 接口所需的最小凭据。
14
+ const extractAuthFields = (account) => {
15
+ const auth = account && account.auth;
16
+ if (auth && typeof auth.personal_access_token === 'string') {
31
17
  return {
32
- accessToken: tokens.access_token,
33
- accountId: tokens.account_id,
18
+ accessToken: auth.personal_access_token,
19
+ accountId: '',
34
20
  };
35
- } catch (_) {
21
+ }
22
+ const tokens = auth && auth.tokens;
23
+ if (!tokens || typeof tokens.access_token !== 'string' || typeof tokens.account_id !== 'string') {
36
24
  return null;
37
25
  }
26
+ return {
27
+ accessToken: tokens.access_token,
28
+ accountId: tokens.account_id,
29
+ };
38
30
  };
39
31
 
40
32
  const normalizePercent = (value) => {
@@ -52,8 +44,6 @@ const hasUsageFields = (item) => {
52
44
  item.plan
53
45
  || isValidPercent(item.next_used)
54
46
  || isValidPercent(item.total_used)
55
- || isValidPercent(item.h5_used)
56
- || isValidPercent(item.d7_used)
57
47
  ));
58
48
  };
59
49
 
@@ -64,12 +54,12 @@ const buildUsageHeaders = (token, accountId = '') => {
64
54
  };
65
55
 
66
56
  // 将账号条目转换成可并发查询 Usage 的请求条目。
67
- const buildUsageEntries = (accountDirs) => {
68
- return accountDirs.flatMap((account) => {
57
+ const buildUsageEntries = (accounts) => {
58
+ return accounts.flatMap((account) => {
69
59
  const fields = extractAuthFields(account);
70
60
  if (!fields) return [];
71
61
  return [{
72
- key: typeof account === 'string' ? path.basename(account) : account.id,
62
+ key: account.id,
73
63
  token: fields.accessToken,
74
64
  accountId: fields.accountId,
75
65
  }];
@@ -99,22 +89,14 @@ const fetchUsageOne = async (entry, fetchImpl = fetch) => {
99
89
  const windows = [rateLimit.primary_window, rateLimit.secondary_window].filter(Boolean);
100
90
  const next = findWindow(windows, USAGE_5H_WINDOW_SECONDS);
101
91
  const total = findTotalWindow(windows);
102
- const nextUsed = normalizePercent(next.used_percent);
103
- const totalUsed = normalizePercent(total.used_percent);
104
92
  return {
105
93
  key: entry.key,
106
94
  email: data.email || '',
107
95
  plan: data.plan_type || '',
108
- next_used: nextUsed,
96
+ next_used: normalizePercent(next.used_percent),
109
97
  next_reset: next.reset_at ?? null,
110
- next_seconds: next.limit_window_seconds ?? null,
111
- total_used: totalUsed,
98
+ total_used: normalizePercent(total.used_percent),
112
99
  total_reset: total.reset_at ?? null,
113
- total_seconds: total.limit_window_seconds ?? null,
114
- h5_used: nextUsed,
115
- h5_reset: next.reset_at ?? null,
116
- d7_used: totalUsed,
117
- d7_reset: total.reset_at ?? null,
118
100
  };
119
101
  } catch (error) {
120
102
  return { key: entry.key, error: error.message };
@@ -122,10 +104,9 @@ const fetchUsageOne = async (entry, fetchImpl = fetch) => {
122
104
  };
123
105
 
124
106
  // 用 Usage 接口探活账号,避免依赖本地 codex 命令或模型列表输出。
125
- const probeAccountStatus = async (homeDir, fetchImpl = fetch) => {
126
- const fields = extractAuthFields(homeDir);
107
+ const probeAccountStatus = async (account, fetchImpl = fetch) => {
108
+ const fields = extractAuthFields(account);
127
109
  if (!fields) return 'offline';
128
- if (typeof fetchImpl !== 'function' || typeof AbortSignal.timeout !== 'function') return 'unknown';
129
110
  try {
130
111
  const response = await fetchImpl(USAGE_ENDPOINT, {
131
112
  headers: buildUsageHeaders(fields.accessToken, fields.accountId),
@@ -140,9 +121,6 @@ const probeAccountStatus = async (homeDir, fetchImpl = fetch) => {
140
121
  };
141
122
 
142
123
  const fetchPersonalAccessTokenProfile = async (token, fetchImpl = fetch) => {
143
- if (typeof fetchImpl !== 'function' || typeof AbortSignal.timeout !== 'function') {
144
- throw new Error('当前 Node 运行时不支持访问令牌验证');
145
- }
146
124
  const response = await fetchImpl(USAGE_ENDPOINT, {
147
125
  headers: buildUsageHeaders(token),
148
126
  signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
@@ -155,9 +133,8 @@ const fetchPersonalAccessTokenProfile = async (token, fetchImpl = fetch) => {
155
133
  };
156
134
  };
157
135
 
158
- const loadUsage = async (accountDirs, fetchImpl = fetch) => {
159
- if (typeof fetchImpl !== 'function' || typeof AbortSignal.timeout !== 'function') return [];
160
- const entries = buildUsageEntries(accountDirs);
136
+ const loadUsage = async (accounts, fetchImpl = fetch) => {
137
+ const entries = buildUsageEntries(accounts);
161
138
  if (entries.length === 0) return [];
162
139
  return Promise.all(entries.map((entry) => fetchUsageOne(entry, fetchImpl)));
163
140
  };
@@ -186,13 +163,13 @@ const classifyPrimaryWindow = (usedPercent) => {
186
163
  // 统一账号额度状态,供自动切换和后续展示逻辑复用。
187
164
  const getAccountUsageState = (item) => {
188
165
  if (!hasUsageFields(item)) return ACCOUNT_USAGE_STATES.OFFLINE;
189
- const nextUsed = item.next_used ?? item.h5_used;
190
- const totalUsed = item.total_used ?? item.d7_used;
191
- if (item.plan === 'free') return classifyPrimaryWindow(totalUsed);
192
- if (!isValidPercent(totalUsed) || totalUsed >= QUOTA_COOLING_PERCENT) {
166
+ // 免费账号和只有总周期限额的账号没有 Next 窗口,只按 Total 判断。
167
+ if (item.plan === 'free' || !isValidPercent(item.next_used)) return classifyPrimaryWindow(item.total_used);
168
+ // 只有 Next 窗口的账号(如部分 team 访问令牌账号)只按 Next 判断。
169
+ if (isValidPercent(item.total_used) && item.total_used >= QUOTA_COOLING_PERCENT) {
193
170
  return ACCOUNT_USAGE_STATES.COOLING;
194
171
  }
195
- return classifyPrimaryWindow(nextUsed);
172
+ return classifyPrimaryWindow(item.next_used);
196
173
  };
197
174
 
198
175
  const accountShouldAutoSwitch = (results, key) => {