@alanwalk/codex-until 0.2.0 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,49 +1,38 @@
1
- # @alanwalk/codex-until
1
+ # codex-until
2
2
 
3
- Windows Codex 额度监控命令行工具。零 npm 依赖,Node.js 18 或以上。
3
+ 监控 Codex 剩余额度,发现额度重置时结束本机所有 Codex 会话。
4
4
 
5
- 菜单第一项为“刷新间隔”,左右键切换 `10s / 30s / 1m / 5m`,默认 `1m`;后两项为“转入后台”和“停止监控并退出”。
5
+ 支持 Windows、macOS、Linux。需要 Node.js 18+,以及已登录 ChatGPT 账号的官方 Codex CLI 或桌面应用。
6
6
 
7
- 使用官方轻量轮询参数 `excludeResetCreditDetails: true`,跳过不需要的重置次数详情查询。查询失败自动退避:若 App Server 错误数据或文本中包含有效的 `Retry-After`,至少等待服务端要求的时间;否则依次等待 1、2、4、8、16、30 分钟,之后保持最多每 30 分钟重试。等待不会短于所选刷新间隔,成功后恢复所选间隔。退避期间修改刷新间隔不能提前结束服务端等待。
7
+ ## 使用
8
8
 
9
- App Server 当前并不保证透传 HTTP 响应头,因此不能保证总能获取 `Retry-After`;无法获得时使用上述退避。面板显示退避倒计时,保留上次成功数据和额度比较基线。
10
-
11
- 终端面板展示剩余额度、下次额度重置时间(按本地时区显示),并逐秒更新距下次查询的预计倒计时。后台默认每 60 秒查询额度,可在菜单中上下选中“刷新间隔”,再用左右键切换 `10s / 30s / 1m / 5m`。修改即时应用到同一后台进程,转入后台后保持所选间隔;重新启动恢复默认 `1m`。后台按所选间隔查询额度,查询期间显示“正在查询”。查询失败时保留上次成功数据并提示错误;详细记录通过 logs 命令查看。
12
-
13
- 需要已安装并通过 ChatGPT 账号登录的官方 Codex CLI / 桌面应用。工具复用本地登录状态,不打印 token。默认使用桌面应用 CLI,找不到时使用 PATH 中的 `codex.exe`;可通过 `CODEX_QUOTA_CLI` 指定完整可执行文件路径。
14
-
15
- 无需预先执行 `npm install`,直接运行:
16
-
17
- ```powershell
18
- npx @alanwalk/codex-until
19
- npx --yes @alanwalk/codex-until status
20
- npx --yes @alanwalk/codex-until stop
21
- npx --yes @alanwalk/codex-until quota
22
- npx --yes @alanwalk/codex-until logs
9
+ ```sh
10
+ npx @alanwalk/codex-until # 打开交互面板
11
+ npx @alanwalk/codex-until -b # 后台运行
12
+ npx @alanwalk/codex-until status # 查看状态
13
+ npx @alanwalk/codex-until stop # 停止监控
14
+ npx @alanwalk/codex-until quota # 查询一次额度
15
+ npx @alanwalk/codex-until logs # 查看日志
23
16
  ```
24
17
 
25
- 不带参数会立即开启监控:在交互终端中显示彩色状态面板、剩余额度进度条、查询倒计时和下次重置时间。使用方向键选择操作并回车确认,也可直接按 `b` 转入后台、按 `q` 停止监控并退出,`Ctrl+C` 同样停止监控。转入后台只是退出控制台,监控进程及本次比较基线保持不变。输入流关闭时也会退出控制台并保留后台监控。
18
+ 面板显示剩余额度、下次重置时间和查询倒计时。上下键选择操作,左右键切换刷新间隔:`10s / 30s / 1m / 5m`,默认 `1m`。
26
19
 
27
- `start` 与无参数执行相同,在交互终端默认显示状态面板和操作菜单;使用 `-b / --background` 直接进入后台:
20
+ - **转入后台**:关闭面板,继续监控。也可按 `b`。
21
+ - **停止并退出**:停止监控,保留 Codex 会话。也可按 `q` 或 `Ctrl+C`。
28
22
 
29
- ```powershell
30
- npx @alanwalk/codex-until # 显示状态面板和菜单
31
- npx @alanwalk/codex-until start # 同上
32
- npx @alanwalk/codex-until -b # 直接后台运行
33
- npx @alanwalk/codex-until start --background # 同上,可简写 -b
34
- ```
23
+ ## 工作方式
35
24
 
36
- 通过自动化工具等非交互环境无参数执行时,默认后台启动,不等待输入。重复启动不会产生多个监控,前台模式可连接已有监控。`stop` 只停止监控,不停止 Codex。`status` 输出 JSON;表示后台监控进程可响应,不代表最近的额度请求一定成功,请结合 `logs` 查看查询结果。`--help` 显示帮助;添加 `--yes`(例如 `npx --yes @alanwalk/codex-until`)可跳过 npx 首次下载确认。
25
+ 通过官方 App Server 轻量查询额度,不发送模型请求。查询失败会自动退避;能取得 `Retry-After` 时遵守服务端等待时间。
37
26
 
38
- ## 重置判断
27
+ 同一账号、同一额度窗口的剩余百分比上升,或重置时间推迟且已用比例未增加,就视为重置。首次查询只建立基线,重启监控会重新建立基线。
39
28
 
40
- 首次成功查询只建立内存基线。后续对比上次成功查询,在账号、窗口名称和窗口时长相同的前提下,任一窗口满足以下条件即触发:
29
+ **检测到重置后会强制结束本机全部 Codex 进程及其子进程,正在执行的任务会中断。** 服务器修正额度也可能触发。
41
30
 
42
- - 已用百分比下降,即剩余额度上升,哪怕只上升 1%。
43
- - 重置时间推迟,且已用百分比没有增加。
31
+ ## 路径
44
32
 
45
- 查询失败记录日志并重试,不清空上一次成功结果。停止再启动重新建立基线,不比较监控停机期间的变化。服务端额度修正也可能满足上述规则。轮询存在约一分钟延迟,另加网络请求耗时。
33
+ 默认查找 Codex 桌面应用内的 CLI,找不到则使用 PATH 中的 `codex`。可用 `CODEX_QUOTA_CLI` 指定可执行文件完整路径。
46
34
 
47
- **触发后执行 `taskkill /F /T /IM codex.exe`,强制结束本机所有 Codex 进程及其子进程,包括其他账号的本地会话,正在执行的任务会被中断。远程主机不受影响。** 成功后监控退出;停止失败会记录错误,后续继续尝试。没有自动消费额度重置次数的功能。
35
+ 日志位置:
48
36
 
49
- 日志保存在 `%LOCALAPPDATA%\codex-quota-guard\monitor.log`,不写入 npx 缓存中的包目录。日志不包含凭据。后台监控没有开机自启功能。
37
+ - Windows:`%LOCALAPPDATA%\codex-quota-guard\monitor.log`
38
+ - macOS / Linux:`~/.codex-until/monitor.log`
package/bin/cli.cjs CHANGED
@@ -1,14 +1,12 @@
1
1
  #!/usr/bin/env node
2
2
  const net = require('node:net');
3
- const os = require('node:os');
4
3
  const path = require('node:path');
5
4
  const fs = require('node:fs');
6
- const crypto = require('node:crypto');
5
+ const { runtimePaths } = require('../platform.cjs');
7
6
  const { consoleMode } = require('./terminal.cjs');
8
7
  const { spawn } = require('node:child_process');
9
8
  const watch = require('../watch-codex-quota.cjs');
10
- const userKey = crypto.createHash('sha256').update(os.homedir()).digest('hex').slice(0, 16);
11
- const pipe = `\\\\.\\pipe\\codex-quota-guard-${userKey}`;
9
+ const { address: pipe, windows } = runtimePaths();
12
10
 
13
11
  function request(action) {
14
12
  return new Promise((resolve, reject) => {
@@ -33,6 +31,8 @@ async function status() {
33
31
  }
34
32
 
35
33
  async function daemon() {
34
+ let ownsSocket = false;
35
+ let staleSocketRetried = false;
36
36
  const server = net.createServer(socket => {
37
37
  socket.setTimeout(2000, () => socket.destroy());
38
38
  socket.on('error', () => {});
@@ -48,16 +48,33 @@ async function daemon() {
48
48
  });
49
49
  });
50
50
  });
51
- server.on('error', error => {
51
+ server.on('error', async error => {
52
+ if (!windows && error.code === 'EADDRINUSE' && !staleSocketRetried) {
53
+ try {
54
+ const existing = await status();
55
+ if (existing.running) { process.exit(0); return; }
56
+ fs.unlinkSync(pipe);
57
+ staleSocketRetried = true;
58
+ server.listen(pipe);
59
+ return;
60
+ } catch (failure) { console.error(failure.message); process.exit(1); return; }
61
+ }
52
62
  if (error.code !== 'EADDRINUSE') console.error(error.message);
53
63
  process.exit(error.code === 'EADDRINUSE' ? 0 : 1);
54
64
  });
55
- server.listen(pipe, () => {
65
+ process.once('exit', () => {
66
+ if (ownsSocket && !windows) { try { fs.unlinkSync(pipe); } catch {} }
67
+ });
68
+ process.once('SIGTERM', () => process.exit(0));
69
+ server.on('listening', () => {
70
+ ownsSocket = true;
71
+ if (!windows) fs.chmodSync(pipe, 0o600);
56
72
  watch.main().then(() => process.exit(process.exitCode || 0)).catch(error => {
57
73
  console.error(error.message);
58
74
  process.exit(1);
59
75
  });
60
76
  });
77
+ server.listen(pipe);
61
78
  }
62
79
 
63
80
  function parseOptions(args, interactive) {
@@ -77,7 +94,7 @@ function parseOptions(args, interactive) {
77
94
  async function main() {
78
95
  const { action, foreground } = parseOptions(process.argv.slice(2), Boolean(process.stdin.isTTY && process.stdout.isTTY));
79
96
  if (['help', '--help', '-h'].includes(action)) {
80
- console.log(`Codex Until (Windows, Node >=18)
97
+ console.log(`Codex Until (Windows / macOS / Linux, Node >=18)
81
98
  Usage: codex-until [start|stop|status|quota|logs]
82
99
  No command defaults to start. Without -b, show b/q controls in a terminal.
83
100
  Non-interactive invocations run in the background.
@@ -87,11 +104,10 @@ Non-interactive invocations run in the background.
87
104
  status Print monitor status as JSON.
88
105
  quota Query quota once without enabling monitoring.
89
106
  logs Print the last 50 log lines.
90
- Reset detection stops ALL local codex.exe processes and their children.
107
+ Reset detection stops ALL local Codex processes and their children.
91
108
  Restarting the monitor establishes a fresh baseline. No baseline is persisted.`);
92
109
  return;
93
110
  }
94
- if (process.platform !== 'win32') throw new Error('This version supports Windows only.');
95
111
  if (action === '--daemon') return daemon();
96
112
  if (action === 'quota') return watch.main(true);
97
113
  if (action === 'logs') {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@alanwalk/codex-until",
3
- "version": "0.2.0",
3
+ "version": "0.2.1",
4
4
  "description": "Stop local Codex sessions when quota resets during monitoring.",
5
5
  "homepage": "https://github.com/alanwalk/codex-until#readme",
6
6
  "repository": {
@@ -12,11 +12,10 @@
12
12
  "publishConfig": { "access": "public" },
13
13
  "bin": { "codex-until": "bin/cli.cjs" },
14
14
  "main": "watch-codex-quota.cjs",
15
- "files": ["bin/", "watch-codex-quota.cjs", "README.md"],
15
+ "files": ["bin/", "platform.cjs", "watch-codex-quota.cjs", "README.md"],
16
16
  "engines": { "node": ">=18" },
17
- "os": ["win32"],
18
17
  "scripts": {
19
- "check": "node --check bin/cli.cjs && node --check bin/terminal.cjs && node --check watch-codex-quota.cjs && node bin/cli.cjs --help",
18
+ "check": "node --check bin/cli.cjs && node --check bin/terminal.cjs && node --check platform.cjs && node --check watch-codex-quota.cjs && node bin/cli.cjs --help",
20
19
  "test": "node watch-codex-quota.test.cjs",
21
20
  "prepublishOnly": "npm run check && npm test"
22
21
  },
package/platform.cjs ADDED
@@ -0,0 +1,45 @@
1
+ const fs = require('node:fs');
2
+ const os = require('node:os');
3
+ const path = require('node:path');
4
+ const crypto = require('node:crypto');
5
+
6
+ function runtimePaths(platform = process.platform, env = process.env, home = os.homedir()) {
7
+ const windows = platform === 'win32';
8
+ const key = crypto.createHash('sha256').update(home).digest('hex').slice(0, 16);
9
+ const desktopCli = windows
10
+ ? path.join(env.LOCALAPPDATA || '', 'Programs/OpenAI/Codex/bin/codex.exe')
11
+ : '/Applications/Codex.app/Contents/Resources/codex';
12
+ const logDirectory = windows ? path.join(env.LOCALAPPDATA || home, 'codex-quota-guard')
13
+ : path.join(home, '.codex-until');
14
+ let cli = env.CODEX_QUOTA_CLI;
15
+ if (!cli) {
16
+ if (fs.existsSync(desktopCli)) cli = desktopCli;
17
+ else if (windows) cli = 'codex.exe';
18
+ else cli = 'codex';
19
+ }
20
+ return {
21
+ windows,
22
+ address: windows ? `\\\\.\\pipe\\codex-quota-guard-${key}` : path.join(os.tmpdir(), `codex-until-${key}.sock`),
23
+ logPath: path.join(logDirectory, 'monitor.log'),
24
+ cli,
25
+ };
26
+ }
27
+
28
+ function codexProcessIds(processList, ownPid = process.pid) {
29
+ const processes = processList.split('\n').flatMap(line => {
30
+ const match = line.trim().match(/^(\d+)\s+(\d+)\s+(.+)$/);
31
+ if (!match) return [];
32
+ return [{ pid: Number(match[1]), parent: Number(match[2]), name: path.posix.basename(match[3]) }];
33
+ });
34
+ const targets = new Set(processes.filter(item => /^(codex|codex-(aarch64|x86_64)-.+)$/i.test(item.name)).map(item => item.pid));
35
+ let added = true;
36
+ while (added) {
37
+ added = false;
38
+ for (const item of processes) {
39
+ if (targets.has(item.parent) && !targets.has(item.pid)) { targets.add(item.pid); added = true; }
40
+ }
41
+ }
42
+ return [...targets].reverse().filter(pid => pid !== ownPid && pid > 1);
43
+ }
44
+
45
+ module.exports = { runtimePaths, codexProcessIds };
@@ -2,9 +2,9 @@ const { spawn, spawnSync } = require('node:child_process');
2
2
  const readline = require('node:readline');
3
3
  const fs = require('node:fs');
4
4
  const path = require('node:path');
5
- const os = require('node:os');
5
+ const { runtimePaths, codexProcessIds } = require('./platform.cjs');
6
6
 
7
- const logPath = path.join(process.env.LOCALAPPDATA || os.homedir(), 'codex-quota-guard', 'monitor.log');
7
+ const { logPath } = runtimePaths();
8
8
  const polling = { intervalMs: 60000, nextQueryAt: null, querying: false, cooldownUntil: null, failureCount: 0 };
9
9
  const quotaParams = { excludeResetCreditDetails: true };
10
10
  function quotaError(error) {
@@ -78,8 +78,7 @@ function log(message) {
78
78
 
79
79
  function readQuota() {
80
80
  return new Promise((resolve, reject) => {
81
- const desktopCli = path.join(process.env.LOCALAPPDATA || '', 'Programs/OpenAI/Codex/bin/codex.exe');
82
- const cli = process.env.CODEX_QUOTA_CLI || (fs.existsSync(desktopCli) ? desktopCli : 'codex.exe');
81
+ const { cli } = runtimePaths();
83
82
  const child = spawn(cli, ['app-server', '--stdio'], {
84
83
  windowsHide: true, stdio: ['pipe', 'pipe', 'pipe'],
85
84
  });
@@ -155,6 +154,18 @@ function resetReason(previous, current) {
155
154
  }
156
155
 
157
156
  function stopCodex() {
157
+ if (process.platform !== 'win32') {
158
+ const result = spawnSync('ps', ['-A', '-o', 'pid=,ppid=,comm='], { encoding: 'utf8' });
159
+ if (result.error || result.status !== 0) throw new Error('Failed to enumerate Codex processes');
160
+ const failures = [];
161
+ for (const pid of codexProcessIds(result.stdout)) {
162
+ try { process.kill(pid, 'SIGKILL'); }
163
+ catch (error) { if (error.code !== 'ESRCH') failures.push(`${pid}: ${error.code}`); }
164
+ }
165
+ if (failures.length) throw new Error(`Failed to stop Codex: ${failures.join(', ')}`);
166
+ log('All local Codex processes and their child processes stopped.');
167
+ return;
168
+ }
158
169
  // /T also stops tasks spawned by each Codex process.
159
170
  const result = spawnSync('taskkill.exe', ['/F', '/T', '/IM', 'codex.exe'], {
160
171
  windowsHide: true, encoding: 'utf8',