@alanwalk/codex-until 0.0.0-stage → 0.2.0

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,3 +1,49 @@
1
- # Temporary Holding Version
1
+ # @alanwalk/codex-until
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Windows Codex 额度监控命令行工具。零 npm 依赖,Node.js 18 或以上。
4
+
5
+ 菜单第一项为“刷新间隔”,左右键切换 `10s / 30s / 1m / 5m`,默认 `1m`;后两项为“转入后台”和“停止监控并退出”。
6
+
7
+ 使用官方轻量轮询参数 `excludeResetCreditDetails: true`,跳过不需要的重置次数详情查询。查询失败自动退避:若 App Server 错误数据或文本中包含有效的 `Retry-After`,至少等待服务端要求的时间;否则依次等待 1、2、4、8、16、30 分钟,之后保持最多每 30 分钟重试。等待不会短于所选刷新间隔,成功后恢复所选间隔。退避期间修改刷新间隔不能提前结束服务端等待。
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
23
+ ```
24
+
25
+ 不带参数会立即开启监控:在交互终端中显示彩色状态面板、剩余额度进度条、查询倒计时和下次重置时间。使用方向键选择操作并回车确认,也可直接按 `b` 转入后台、按 `q` 停止监控并退出,`Ctrl+C` 同样停止监控。转入后台只是退出控制台,监控进程及本次比较基线保持不变。输入流关闭时也会退出控制台并保留后台监控。
26
+
27
+ `start` 与无参数执行相同,在交互终端默认显示状态面板和操作菜单;使用 `-b / --background` 直接进入后台:
28
+
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
+ ```
35
+
36
+ 通过自动化工具等非交互环境无参数执行时,默认后台启动,不等待输入。重复启动不会产生多个监控,前台模式可连接已有监控。`stop` 只停止监控,不停止 Codex。`status` 输出 JSON;表示后台监控进程可响应,不代表最近的额度请求一定成功,请结合 `logs` 查看查询结果。`--help` 显示帮助;添加 `--yes`(例如 `npx --yes @alanwalk/codex-until`)可跳过 npx 首次下载确认。
37
+
38
+ ## 重置判断
39
+
40
+ 首次成功查询只建立内存基线。后续对比上次成功查询,在账号、窗口名称和窗口时长相同的前提下,任一窗口满足以下条件即触发:
41
+
42
+ - 已用百分比下降,即剩余额度上升,哪怕只上升 1%。
43
+ - 重置时间推迟,且已用百分比没有增加。
44
+
45
+ 查询失败记录日志并重试,不清空上一次成功结果。停止再启动重新建立基线,不比较监控停机期间的变化。服务端额度修正也可能满足上述规则。轮询存在约一分钟延迟,另加网络请求耗时。
46
+
47
+ **触发后执行 `taskkill /F /T /IM codex.exe`,强制结束本机所有 Codex 进程及其子进程,包括其他账号的本地会话,正在执行的任务会被中断。远程主机不受影响。** 成功后监控退出;停止失败会记录错误,后续继续尝试。没有自动消费额度重置次数的功能。
48
+
49
+ 日志保存在 `%LOCALAPPDATA%\codex-quota-guard\monitor.log`,不写入 npx 缓存中的包目录。日志不包含凭据。后台监控没有开机自启功能。
package/bin/cli.cjs ADDED
@@ -0,0 +1,135 @@
1
+ #!/usr/bin/env node
2
+ const net = require('node:net');
3
+ const os = require('node:os');
4
+ const path = require('node:path');
5
+ const fs = require('node:fs');
6
+ const crypto = require('node:crypto');
7
+ const { consoleMode } = require('./terminal.cjs');
8
+ const { spawn } = require('node:child_process');
9
+ 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}`;
12
+
13
+ function request(action) {
14
+ return new Promise((resolve, reject) => {
15
+ const socket = net.connect(pipe);
16
+ let response = '';
17
+ socket.setTimeout(2000, () => socket.destroy(new Error('Monitor response timed out')));
18
+ socket.on('connect', () => socket.write(action + '\n'));
19
+ socket.on('data', chunk => { response += chunk; });
20
+ socket.on('end', () => {
21
+ try { resolve(JSON.parse(response)); } catch { reject(new Error('Invalid monitor response')); }
22
+ });
23
+ socket.on('error', reject);
24
+ });
25
+ }
26
+
27
+ async function status() {
28
+ try { return await request('status'); }
29
+ catch (error) {
30
+ if (['ENOENT', 'ECONNREFUSED'].includes(error.code)) return { running: false, logPath: watch.logPath };
31
+ throw error;
32
+ }
33
+ }
34
+
35
+ async function daemon() {
36
+ const server = net.createServer(socket => {
37
+ socket.setTimeout(2000, () => socket.destroy());
38
+ socket.on('error', () => {});
39
+ socket.once('data', data => {
40
+ const action = data.toString().trim();
41
+ if (action.startsWith('interval:')) {
42
+ try { watch.setIntervalMs(Number(action.slice('interval:'.length))); }
43
+ catch (error) { socket.end(JSON.stringify({ error: error.message }) + '\n'); return; }
44
+ }
45
+ const result = { running: action !== 'stop', pid: process.pid, logPath: watch.logPath, ...watch.polling };
46
+ socket.end(JSON.stringify(result) + '\n', () => {
47
+ if (action === 'stop') process.exit(0);
48
+ });
49
+ });
50
+ });
51
+ server.on('error', error => {
52
+ if (error.code !== 'EADDRINUSE') console.error(error.message);
53
+ process.exit(error.code === 'EADDRINUSE' ? 0 : 1);
54
+ });
55
+ server.listen(pipe, () => {
56
+ watch.main().then(() => process.exit(process.exitCode || 0)).catch(error => {
57
+ console.error(error.message);
58
+ process.exit(1);
59
+ });
60
+ });
61
+ }
62
+
63
+ function parseOptions(args, interactive) {
64
+ if (args.length === 1 && args[0] === '--daemon') return { action: '--daemon', foreground: false };
65
+ const hasCommand = args.length > 0 && !args[0].startsWith('-');
66
+ const action = hasCommand ? args[0] : 'start';
67
+ if (['--help', '-h'].includes(args[0])) return { action: 'help', foreground: false };
68
+ const flags = hasCommand ? args.slice(1) : args;
69
+ if (flags.some(flag => !['--background', '-b'].includes(flag))) {
70
+ throw new Error('Unknown option. Use --help.');
71
+ }
72
+ const background = flags.some(flag => ['--background', '-b'].includes(flag));
73
+ if (flags.length && action !== 'start') throw new Error('Mode options are only supported by start.');
74
+ return { action, foreground: action === 'start' && interactive && !background };
75
+ }
76
+
77
+ async function main() {
78
+ const { action, foreground } = parseOptions(process.argv.slice(2), Boolean(process.stdin.isTTY && process.stdout.isTTY));
79
+ if (['help', '--help', '-h'].includes(action)) {
80
+ console.log(`Codex Until (Windows, Node >=18)
81
+ Usage: codex-until [start|stop|status|quota|logs]
82
+ No command defaults to start. Without -b, show b/q controls in a terminal.
83
+ Non-interactive invocations run in the background.
84
+ start Start polling every 60 seconds; repeated calls are safe.
85
+ --background / -b: start directly in the background.
86
+ stop Stop monitoring only. Codex sessions remain running.
87
+ status Print monitor status as JSON.
88
+ quota Query quota once without enabling monitoring.
89
+ logs Print the last 50 log lines.
90
+ Reset detection stops ALL local codex.exe processes and their children.
91
+ Restarting the monitor establishes a fresh baseline. No baseline is persisted.`);
92
+ return;
93
+ }
94
+ if (process.platform !== 'win32') throw new Error('This version supports Windows only.');
95
+ if (action === '--daemon') return daemon();
96
+ if (action === 'quota') return watch.main(true);
97
+ if (action === 'logs') {
98
+ if (!fs.existsSync(watch.logPath)) return console.log('No logs yet.');
99
+ return console.log(fs.readFileSync(watch.logPath, 'utf8').trimEnd().split('\n').slice(-50).join('\n'));
100
+ }
101
+ if (!['start', 'stop', 'status'].includes(action)) throw new Error(`Unknown command: ${action}. Use --help.`);
102
+ const before = await status();
103
+ if (action === 'status') return console.log(JSON.stringify(before));
104
+ if (action === 'stop') {
105
+ const result = before.running ? await request('stop') : before;
106
+ console.log(JSON.stringify({ ...result, changed: before.running }));
107
+ return;
108
+ }
109
+ if (before.running) {
110
+ if (foreground) await consoleMode({ status, request, logPath: watch.logPath });
111
+ else console.log(JSON.stringify({ ...before, changed: false }));
112
+ return;
113
+ }
114
+ fs.mkdirSync(path.dirname(watch.logPath), { recursive: true });
115
+ const output = fs.openSync(watch.logPath, 'a');
116
+ const child = spawn(process.execPath, [__filename, '--daemon'], {
117
+ detached: true, windowsHide: true, stdio: ['ignore', 'ignore', output],
118
+ });
119
+ fs.closeSync(output);
120
+ child.on('error', error => { console.error(error.message); process.exitCode = 1; });
121
+ child.unref();
122
+ for (let attempt = 0; attempt < 50; attempt++) {
123
+ await new Promise(resolve => setTimeout(resolve, 100));
124
+ const result = await status();
125
+ if (result.running) {
126
+ if (foreground) await consoleMode({ status, request, logPath: watch.logPath });
127
+ else console.log(JSON.stringify({ ...result, changed: true }));
128
+ return;
129
+ }
130
+ }
131
+ throw new Error(`Monitor failed to start. See ${watch.logPath}`);
132
+ }
133
+
134
+ module.exports = { parseOptions };
135
+ if (require.main === module) main().catch(error => { console.error(error.message); process.exitCode = 1; });
@@ -0,0 +1,145 @@
1
+ const fs = require('node:fs');
2
+ const readline = require('node:readline');
3
+
4
+ const intervals = [10000, 30000, 60000, 300000];
5
+ const intervalLabels = ['10s', '30s', '1m', '5m'];
6
+
7
+ function renderPanel({ running, pid, lines, selected = 0, columns = 80, color = true,
8
+ now = Date.now(), intervalMs = 60000, nextQueryAt, querying, cooldownUntil }) {
9
+ const paint = (code, text) => color ? `\x1b[${code}m${text}\x1b[0m` : text;
10
+ const clean = text => text.replace(/\x1b\[[0-?]*[ -/]*[@-~]/g, '').replace(/[\x00-\x1f\x7f]/g, '');
11
+ const records = lines.map(clean);
12
+ const quota = [...records].reverse().find(line => /remaining [\d.]+%/.test(line));
13
+ const match = quota?.match(/^(\S+).*?remaining ([\d.]+)%, reset (\S+)/);
14
+ const width = Math.max(8, Math.min(28, columns - 20));
15
+ const latestRecord = records.at(-1) || '';
16
+ const lastAttempt = Date.parse(latestRecord.split(' ')[0]);
17
+ const deadline = nextQueryAt ?? lastAttempt + intervalMs;
18
+ const secondsUntilQuery = Math.max(0, Math.ceil((deadline - now) / 1000));
19
+ let queryStatus = '正在查询…';
20
+ if (!querying && Number.isFinite(deadline) && secondsUntilQuery > 0) {
21
+ queryStatus = `${secondsUntilQuery} 秒后查询`;
22
+ }
23
+ if (cooldownUntil > now) queryStatus = `退避等待 · ${Math.ceil((cooldownUntil - now) / 1000)} 秒后重试`;
24
+ const output = [
25
+ '', paint('36', ' ╭───────────────────────╮'),
26
+ paint('36', ' │') + paint('1;36', ' CODEX UNTIL ') + paint('36', '│'),
27
+ paint('36', ' ╰───────────────────────╯'), '',
28
+ ` ${paint(running ? '32' : '33', running ? '● 正在监控' : '○ 监控已退出')} ${paint('90', `PID ${pid ?? '—'}`)}`,
29
+ ` ${paint('36', queryStatus)}`,
30
+ ];
31
+ if (match) {
32
+ const remaining = Math.max(0, Math.min(100, Number(match[2])));
33
+ const filled = Math.round(width * remaining / 100);
34
+ output.push('', ` 剩余额度 ${paint('1;36', `${remaining}%`)}`,
35
+ ` ${paint('36', '━'.repeat(filled))}${paint('90', '─'.repeat(width - filled))}`,
36
+ ` 下次重置 ${new Date(match[3]).toLocaleString('zh-CN', { hour12: false })}`);
37
+ } else output.push('', ' 剩余额度 —', ' 下次重置 —',
38
+ paint('90', ' 正在等待首次额度查询…'));
39
+ if (records.at(-1)?.includes('ERROR')) {
40
+ output.push(paint('33', ' 刷新失败,以上为上次成功数据。'));
41
+ }
42
+ output.push('', paint('90', ' 额度重置后,结束本机全部 Codex 会话。'), '');
43
+ const choices = intervalLabels.map((label, index) => intervals[index] === intervalMs ? `[${label}]` : label).join(' ');
44
+ for (const [index, label] of [`刷新间隔 ‹ ${choices} ›`, '转入后台,继续监控', '停止监控并退出'].entries()) {
45
+ output.push(index === selected ? paint('1;36', ` ❯ ${label}`) : paint('90', ` ${label}`));
46
+ }
47
+ output.push('');
48
+ return output.join('\n');
49
+ }
50
+
51
+ async function consoleMode({ status, request, logPath }) {
52
+ const input = process.stdin;
53
+ const output = process.stdout;
54
+ let selected = 0;
55
+ let busy = false;
56
+ let closing = false;
57
+ let changingInterval = false;
58
+ let current = { running: true };
59
+ let lines = [];
60
+ let lastPanel = '';
61
+ const wasRaw = input.isRaw;
62
+ readline.emitKeypressEvents(input);
63
+ input.setRawMode(true);
64
+ input.resume();
65
+ output.write('\x1b[?1049h\x1b[?25l');
66
+ return new Promise(resolve => {
67
+ const draw = () => {
68
+ if (closing) return;
69
+ const panel = renderPanel({ ...current, lines, selected,
70
+ columns: output.columns || 80, color: !process.env.NO_COLOR });
71
+ if (panel === lastPanel) return;
72
+ lastPanel = panel;
73
+ output.write('\x1b[H\x1b[2J' + panel);
74
+ };
75
+ const finish = async (stop, message) => {
76
+ if (closing) return;
77
+ closing = true;
78
+ clearInterval(timer);
79
+ input.removeListener('keypress', onKey);
80
+ input.removeListener('end', onEnd);
81
+ output.removeListener('resize', draw);
82
+ process.removeListener('SIGINT', onInterrupt);
83
+ let resultMessage = message;
84
+ try {
85
+ if (stop) {
86
+ if ((await status()).running) await request('stop');
87
+ resultMessage = '监控已停止,Codex 会话继续运行。';
88
+ }
89
+ } catch (error) { resultMessage = `停止失败:${error.message}`; process.exitCode = 1; }
90
+ finally {
91
+ input.setRawMode(Boolean(wasRaw));
92
+ input.pause();
93
+ output.write('\x1b[?25h\x1b[?1049l');
94
+ }
95
+ console.log(resultMessage || '已转入后台,监控继续运行。');
96
+ resolve();
97
+ };
98
+ const changeInterval = async direction => {
99
+ if (changingInterval || closing) return;
100
+ changingInterval = true;
101
+ try {
102
+ const currentIndex = intervals.indexOf(current.intervalMs ?? 60000);
103
+ const nextIndex = (currentIndex + direction + intervals.length) % intervals.length;
104
+ const result = await request(`interval:${intervals[nextIndex]}`);
105
+ if (result.error) throw new Error(result.error);
106
+ if (!Number.isFinite(result.intervalMs)) throw new Error('当前后台版本不支持切换间隔,请停止后重新启动监控。');
107
+ current = result;
108
+ draw();
109
+ } catch (error) { lines = [...lines, `ERROR: ${error.message}`]; draw(); }
110
+ finally { changingInterval = false; }
111
+ };
112
+ const onKey = (text, key = {}) => {
113
+ if (key.name === 'up') { selected = (selected + 2) % 3; draw(); }
114
+ else if (key.name === 'down') { selected = (selected + 1) % 3; draw(); }
115
+ else if (selected === 0 && key.name === 'left') void changeInterval(-1);
116
+ else if (selected === 0 && key.name === 'right') void changeInterval(1);
117
+ else if (key.name === 'return' && selected !== 0) void finish(selected === 2);
118
+ else if (text === 'b') void finish(false);
119
+ else if (text === 'q' || (key.ctrl && key.name === 'c')) void finish(true);
120
+ };
121
+ const onEnd = () => { void finish(false); };
122
+ const onInterrupt = () => { void finish(true); };
123
+ const refresh = async () => {
124
+ if (busy || closing) return;
125
+ busy = true;
126
+ try {
127
+ if (fs.existsSync(logPath)) lines = fs.readFileSync(logPath, 'utf8').trimEnd().split('\n').slice(-150);
128
+ current = await status();
129
+ if (closing) return;
130
+ draw();
131
+ if (!current.running) await finish(false, '后台监控已退出,请用 logs 查看原因。');
132
+ } catch (error) { lines = [...lines, `ERROR: ${error.message}`]; draw(); }
133
+ finally { busy = false; }
134
+ };
135
+ const timer = setInterval(refresh, 1000);
136
+ input.on('keypress', onKey);
137
+ input.on('end', onEnd);
138
+ output.on('resize', draw);
139
+ process.on('SIGINT', onInterrupt);
140
+ draw();
141
+ void refresh();
142
+ });
143
+ }
144
+
145
+ module.exports = { consoleMode, renderPanel };
package/package.json CHANGED
@@ -1,6 +1,24 @@
1
1
  {
2
2
  "name": "@alanwalk/codex-until",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.2.0",
4
+ "description": "Stop local Codex sessions when quota resets during monitoring.",
5
+ "homepage": "https://github.com/alanwalk/codex-until#readme",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/alanwalk/codex-until.git"
9
+ },
10
+ "bugs": { "url": "https://github.com/alanwalk/codex-until/issues" },
11
+ "license": "UNLICENSED",
12
+ "publishConfig": { "access": "public" },
13
+ "bin": { "codex-until": "bin/cli.cjs" },
14
+ "main": "watch-codex-quota.cjs",
15
+ "files": ["bin/", "watch-codex-quota.cjs", "README.md"],
16
+ "engines": { "node": ">=18" },
17
+ "os": ["win32"],
18
+ "scripts": {
19
+ "check": "node --check bin/cli.cjs && node --check bin/terminal.cjs && node --check watch-codex-quota.cjs && node bin/cli.cjs --help",
20
+ "test": "node watch-codex-quota.test.cjs",
21
+ "prepublishOnly": "npm run check && npm test"
22
+ },
23
+ "keywords": ["codex", "quota", "cli", "monitor"]
24
+ }
@@ -0,0 +1,202 @@
1
+ const { spawn, spawnSync } = require('node:child_process');
2
+ const readline = require('node:readline');
3
+ const fs = require('node:fs');
4
+ const path = require('node:path');
5
+ const os = require('node:os');
6
+
7
+ const logPath = path.join(process.env.LOCALAPPDATA || os.homedir(), 'codex-quota-guard', 'monitor.log');
8
+ const polling = { intervalMs: 60000, nextQueryAt: null, querying: false, cooldownUntil: null, failureCount: 0 };
9
+ const quotaParams = { excludeResetCreditDetails: true };
10
+ function quotaError(error) {
11
+ const result = new Error(error.message || 'Quota query failed');
12
+ result.data = error.data;
13
+ return result;
14
+ }
15
+
16
+ function retryAfterMs(error, now = Date.now()) {
17
+ const data = error.data;
18
+ const headers = data?.headers ?? data?.response?.headers;
19
+ let value = headers?.['retry-after'] ?? headers?.['Retry-After'] ?? data?.retryAfter ?? data?.retry_after;
20
+ if (value == null) {
21
+ const match = error.message.match(/retry-after["']?\s*[=:]\s*["']?([^\r\n"'}]+)/i);
22
+ if (match) value = match[1].trim();
23
+ }
24
+ if (value == null || String(value).trim() === '') return null;
25
+ const seconds = Number(value);
26
+ if (Number.isFinite(seconds) && seconds >= 0) return seconds * 1000;
27
+ const date = Date.parse(String(value));
28
+ return Number.isFinite(date) ? Math.max(0, date - now) : null;
29
+ }
30
+
31
+ function recordFailure(error, now = Date.now()) {
32
+ polling.failureCount += 1;
33
+ const requestedWait = retryAfterMs(error, now);
34
+ const backoff = Math.min(1800000, 60000 * 2 ** Math.min(5, polling.failureCount - 1));
35
+ const delay = Math.max(polling.intervalMs, requestedWait ?? backoff);
36
+ polling.cooldownUntil = now + delay;
37
+ return delay;
38
+ }
39
+
40
+ function recordSuccess() {
41
+ polling.failureCount = 0;
42
+ polling.cooldownUntil = null;
43
+ }
44
+
45
+ function queryDeadline(requested) {
46
+ return Math.max(requested, polling.cooldownUntil || 0);
47
+ }
48
+ let reschedule = null;
49
+ function setIntervalMs(intervalMs) {
50
+ if (![10000, 30000, 60000, 300000].includes(intervalMs)) throw new Error('Unsupported polling interval');
51
+ polling.intervalMs = intervalMs;
52
+ if (reschedule) reschedule(Date.now() + intervalMs);
53
+ }
54
+
55
+ function waitForNextQuery(started) {
56
+ return new Promise(resolve => {
57
+ let timer;
58
+ reschedule = nextQueryAt => {
59
+ clearTimeout(timer);
60
+ polling.nextQueryAt = queryDeadline(nextQueryAt);
61
+ const remaining = Math.max(0, polling.nextQueryAt - Date.now());
62
+ // Long Retry-After values must not overflow Node's timer and cause an immediate retry.
63
+ timer = setTimeout(() => {
64
+ if (Date.now() < polling.nextQueryAt) { reschedule(polling.nextQueryAt); return; }
65
+ reschedule = null;
66
+ resolve();
67
+ }, Math.min(remaining, 2147483647));
68
+ };
69
+ reschedule(started + polling.intervalMs);
70
+ });
71
+ }
72
+ function log(message) {
73
+ fs.mkdirSync(path.dirname(logPath), { recursive: true });
74
+ const line = `${new Date().toISOString()} ${message}`;
75
+ fs.appendFileSync(logPath, line + '\n');
76
+ console.log(line);
77
+ }
78
+
79
+ function readQuota() {
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');
83
+ const child = spawn(cli, ['app-server', '--stdio'], {
84
+ windowsHide: true, stdio: ['pipe', 'pipe', 'pipe'],
85
+ });
86
+ const send = message => child.stdin.write(JSON.stringify(message) + '\n');
87
+ const cleanup = () => child.kill();
88
+ process.once('exit', cleanup);
89
+ let settled = false;
90
+ const finish = (error, result) => {
91
+ if (settled) return;
92
+ settled = true;
93
+ process.removeListener('exit', cleanup);
94
+ clearTimeout(timeout);
95
+ child.kill();
96
+ if (error) reject(error);
97
+ else resolve(result);
98
+ };
99
+ const timeout = setTimeout(() => finish(new Error('Quota query timed out')), 30000);
100
+ child.stderr.resume();
101
+ child.on('error', error => finish(error));
102
+ child.stdin.on('error', error => finish(error));
103
+ child.on('exit', () => finish(new Error('Quota query process exited')));
104
+ readline.createInterface({ input: child.stdout }).on('line', line => {
105
+ let message;
106
+ try { message = JSON.parse(line); } catch { return; }
107
+ if (message.id !== 1 && message.id !== 2) return;
108
+ if (message.error) return finish(quotaError(message.error));
109
+ if (message.id === 1) {
110
+ send({ method: 'initialized', params: {} });
111
+ send({ id: 2, method: 'account/rateLimits/read', params: quotaParams });
112
+ } else {
113
+ finish(null, message.result);
114
+ }
115
+ });
116
+ send({ id: 1, method: 'initialize', params: {
117
+ clientInfo: { name: 'quota_watch', version: '1.0.0' },
118
+ } });
119
+ });
120
+ }
121
+
122
+ function getSnapshot(result) {
123
+ const limits = result.rateLimitsByLimitId?.codex ?? result.rateLimits;
124
+ if (!result.accountId || !limits || limits.limitId !== 'codex') {
125
+ throw new Error('Missing Codex account or quota');
126
+ }
127
+ const windows = {};
128
+ for (const name of ['primary', 'secondary']) {
129
+ const window = limits[name];
130
+ if (!window) continue;
131
+ if (!Number.isFinite(window.usedPercent) || window.usedPercent < 0 ||
132
+ window.usedPercent > 100 || !Number.isFinite(window.resetsAt) ||
133
+ !Number.isFinite(window.windowDurationMins)) {
134
+ throw new Error('Invalid quota window');
135
+ }
136
+ windows[name] = window;
137
+ }
138
+ if (!Object.keys(windows).length) throw new Error('No quota windows returned');
139
+ return { accountId: result.accountId, windows };
140
+ }
141
+
142
+ function resetReason(previous, current) {
143
+ if (!previous || previous.accountId !== current.accountId) return null;
144
+ for (const [name, window] of Object.entries(current.windows)) {
145
+ const before = previous.windows[name];
146
+ if (!before || before.windowDurationMins !== window.windowDurationMins) continue;
147
+ if (window.usedPercent < before.usedPercent) {
148
+ return `${name}: used ${before.usedPercent}% -> ${window.usedPercent}%`;
149
+ }
150
+ if (window.resetsAt > before.resetsAt && window.usedPercent <= before.usedPercent) {
151
+ return `${name}: reset time advanced`;
152
+ }
153
+ }
154
+ return null;
155
+ }
156
+
157
+ function stopCodex() {
158
+ // /T also stops tasks spawned by each Codex process.
159
+ const result = spawnSync('taskkill.exe', ['/F', '/T', '/IM', 'codex.exe'], {
160
+ windowsHide: true, encoding: 'utf8',
161
+ });
162
+ if (result.error || result.status !== 0) {
163
+ throw new Error(`Failed to stop Codex: ${result.error?.message ?? result.stderr.trim()}`);
164
+ }
165
+ log('All local codex.exe processes and their child processes stopped.');
166
+ }
167
+
168
+ async function main(queryOnly = process.argv.includes('--once')) {
169
+ let previous = null;
170
+ log('Started. Polling every 60 seconds. Ctrl+C stops this monitor.');
171
+ for (;;) {
172
+ const started = Date.now();
173
+ polling.querying = true;
174
+ polling.nextQueryAt = null;
175
+ try {
176
+ const current = getSnapshot(await readQuota());
177
+ recordSuccess();
178
+ log(Object.entries(current.windows).map(([name, window]) =>
179
+ `${name}: remaining ${100 - window.usedPercent}%, reset ${new Date(window.resetsAt * 1000).toISOString()}`
180
+ ).join('; '));
181
+ if (queryOnly) return;
182
+ const reason = resetReason(previous, current);
183
+ if (reason) {
184
+ log(`RESET DETECTED: ${reason}. Stopping all local Codex sessions.`);
185
+ stopCodex();
186
+ return;
187
+ }
188
+ previous = current;
189
+ } catch (error) {
190
+ log(`ERROR: ${error.message}`);
191
+ if (queryOnly) { process.exitCode = 1; return; }
192
+ const delay = recordFailure(error);
193
+ log(`BACKOFF: retry no earlier than ${new Date(polling.cooldownUntil).toISOString()} (${Math.ceil(delay / 1000)}s)`);
194
+ }
195
+ polling.querying = false;
196
+ await waitForNextQuery(started);
197
+ }
198
+ }
199
+
200
+ module.exports = { getSnapshot, resetReason, main, logPath, polling, setIntervalMs, waitForNextQuery,
201
+ quotaParams, quotaError, retryAfterMs, recordFailure, recordSuccess, queryDeadline };
202
+ if (require.main === module) main().catch(error => { console.error(error); process.exitCode = 1; });