hi-ai-cli 0.1.0-beta.0 → 0.1.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 +10 -6
- package/bin/hi-ai.mjs +8 -2
- package/lib/core.mjs +6 -3
- package/lib/process.mjs +10 -1
- package/lib/usage.mjs +35 -16
- package/package.json +6 -20
package/README.md
CHANGED
|
@@ -13,7 +13,7 @@ A small, usage-aware utility for **Claude Code and Codex**, on macOS and Linux.
|
|
|
13
13
|
|
|
14
14
|
HiAI uses lightweight models by default: Claude's `haiku` alias and Codex's `gpt-6-luna`. It has no npm runtime dependencies, GUI, or HiAI account.
|
|
15
15
|
|
|
16
|
-
**Release status:
|
|
16
|
+
**Release status: 0.1.1.** Usage readers, timing decisions, failure recovery, and native schedulers have tests. Live usage reads, background delivery, and the idle → hello → newly active window transition have been observed on real accounts on macOS; see [Validation](#validation) for what is and is not covered. A hello consumes usage; the provider controls quota and billing.
|
|
17
17
|
|
|
18
18
|
## Install
|
|
19
19
|
|
|
@@ -24,7 +24,7 @@ Requires **Node.js 22+** and the selected provider CLIs, signed into your subscr
|
|
|
24
24
|
- On Linux: `crontab` and a running cron service. Debian/Ubuntu: `sudo apt install cron && sudo systemctl enable --now cron`.
|
|
25
25
|
|
|
26
26
|
```sh
|
|
27
|
-
npm install -g hi-ai-cli
|
|
27
|
+
npm install -g hi-ai-cli
|
|
28
28
|
hi-ai setup --providers claude,codex
|
|
29
29
|
```
|
|
30
30
|
|
|
@@ -100,9 +100,9 @@ A saved provider failure is a completed scheduled check, so the scheduler proces
|
|
|
100
100
|
|
|
101
101
|
**Claude:** HiAI runs the installed, unmodified `claude -p /usage --safe-mode --no-session-persistence --output-format json` command. Claude Code owns login and credential refresh. HiAI does not read the Keychain, credential files, access tokens, or refresh tokens, and makes no direct Anthropic HTTP requests.
|
|
102
102
|
|
|
103
|
-
The command uses a deliberately invalid model name, so a CLI that stops recognizing `/usage` locally cannot silently turn the check into a normal model request. HiAI requires a local `usage` result with zero turns, zero API duration, zero cost, and no model usage before parsing the current-session and all-model weekly lines. The human-readable reset includes a timezone and
|
|
103
|
+
The command uses a deliberately invalid model name, so a CLI that stops recognizing `/usage` locally cannot silently turn the check into a normal model request. HiAI requires a local `usage` result with zero turns, zero API duration, zero cost, and no model usage before parsing the current-session and all-model weekly lines. The human-readable reset includes a timezone, and its wording follows the platform's date formatting: `Nov 13 at 5am` on macOS, `Nov 13, 5am` on Linux, with the year added when the reset falls in the next year. HiAI accepts both forms and handles timezone offsets, year rollover, and daylight-saving changes. Missing or changed output counts as a failed read. Both session states have been captured live: an active session names its reset time, and an idle session reads `0% used` with no reset time.
|
|
104
104
|
|
|
105
|
-
**Codex:** HiAI starts the installed CLI's app server and calls the documented [`account/rateLimits/read`](https://learn.chatgpt.com/docs/app-server) method. It creates no thread or inference turn and does not parse Codex credential files.
|
|
105
|
+
**Codex:** HiAI starts the installed CLI's app server and calls the documented [`account/rateLimits/read`](https://learn.chatgpt.com/docs/app-server) method. It creates no thread or inference turn and does not parse Codex credential files. An idle Codex account reports an unused window whose reset time moves forward with every read, while a started window keeps a fixed reset. When the window is unused, HiAI reads twice, two seconds apart, and treats a moving reset as idle.
|
|
106
106
|
|
|
107
107
|
Custom `CLAUDE_CONFIG_DIR` and `CODEX_HOME` paths are retained by setup. Inherited API-key variables are removed from subprocesses to prefer saved subscription logins; check that your CLIs use the intended account.
|
|
108
108
|
|
|
@@ -141,9 +141,13 @@ HI_AI_LIVE_TEST=1 npm run test:live:scheduled
|
|
|
141
141
|
|
|
142
142
|
`test:live` forces one real hello per provider and consumes usage. `test:live:scheduled` installs a temporary macOS schedule, reads actual usage, and either sends if idle or confirms the saved reset deadline. It then removes the temporary schedule and refuses to replace an existing HiAI LaunchAgent.
|
|
143
143
|
|
|
144
|
-
##
|
|
144
|
+
## Validation
|
|
145
145
|
|
|
146
|
-
Verified on
|
|
146
|
+
Verified on one Mac with Claude Code 2.1.311 and standalone Codex CLI 0.167.1: live background hello delivery and live usage reads for both providers. A real scheduled startup detected both active windows, saved their reported reset times, and sent no early hellos.
|
|
147
|
+
|
|
148
|
+
The idle → hello → newly active window transition was observed on real accounts on 2026-11-12. Codex was read as idle, received a hello, and then reported an active window with a fixed reset five hours later. Claude was followed through a reported reset: the reader showed the window as active until its reset time and as idle immediately afterwards, HiAI sent one hello at the saved deadline, and the next reading showed a new active window with a reported reset.
|
|
149
|
+
|
|
150
|
+
On Linux, the full suite and the Docker real-cron test have passed on Ubuntu 24.04 (aarch64) with Node 22, using stand-in provider CLIs.
|
|
147
151
|
|
|
148
152
|
Other remaining checks are a complete five-hour soak, a physical sleep/reboot cycle, live authenticated Linux CLIs, and a minimum supported CLI version range. Passing scheduler tests or a hello response does not prove that a provider replenishes quota.
|
|
149
153
|
|
package/bin/hi-ai.mjs
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
import * as fs from 'node:fs/promises';
|
|
3
3
|
import { parseArgs } from 'node:util';
|
|
4
4
|
import { createInterface } from 'node:readline/promises';
|
|
5
|
-
import { acquireLock, config, defaults, file, findExecutable, firstStart, home, nextDueAt, readJSON, readState, run, writeJSON } from '../lib/core.mjs';
|
|
5
|
+
import { acquireLock, config, defaults, file, findExecutable, firstStart, home, Interrupted, nextDueAt, readJSON, readState, run, writeJSON } from '../lib/core.mjs';
|
|
6
6
|
import * as scheduler from '../lib/scheduler.mjs';
|
|
7
7
|
|
|
8
8
|
const help = `hi-ai — a tiny scheduled hello for Claude Code and Codex
|
|
@@ -133,4 +133,10 @@ async function main() {
|
|
|
133
133
|
} finally { if (unlock) await unlock(); }
|
|
134
134
|
}
|
|
135
135
|
|
|
136
|
-
main().catch(error => {
|
|
136
|
+
main().catch(error => {
|
|
137
|
+
// Cleanup has finished and the handlers are gone, so this ends the process
|
|
138
|
+
// with the original signal status.
|
|
139
|
+
if (error instanceof Interrupted) { process.kill(process.pid, error.signal); return; }
|
|
140
|
+
console.error(`hi-ai: ${error.message}`);
|
|
141
|
+
process.exitCode = 1;
|
|
142
|
+
});
|
package/lib/core.mjs
CHANGED
|
@@ -2,9 +2,9 @@ import { constants } from 'node:fs';
|
|
|
2
2
|
import * as fs from 'node:fs/promises';
|
|
3
3
|
import os from 'node:os';
|
|
4
4
|
import path from 'node:path';
|
|
5
|
-
import { execute } from './process.mjs';
|
|
5
|
+
import { execute, Interrupted } from './process.mjs';
|
|
6
6
|
import { bootId, readUsage } from './usage.mjs';
|
|
7
|
-
export { execute } from './process.mjs';
|
|
7
|
+
export { execute, Interrupted } from './process.mjs';
|
|
8
8
|
|
|
9
9
|
export const defaults = { claude: 'haiku', codex: 'gpt-6-luna' };
|
|
10
10
|
export const FIVE_HOURS_MS = 5 * 60 * 60 * 1000;
|
|
@@ -152,6 +152,7 @@ export async function prepareScheduled(provider, settings, last, { boot, now = D
|
|
|
152
152
|
last.usage = { ...observation, boot };
|
|
153
153
|
delete last.usageError; delete last.usageRetryAt; delete last.usageFailures; delete last.usageFallback;
|
|
154
154
|
} catch (error) {
|
|
155
|
+
if (error instanceof Interrupted) throw error;
|
|
155
156
|
last.usageError = `${provider.name} usage check unavailable: ${error.message || 'request failed'}`.slice(0, 200);
|
|
156
157
|
last.usageFailures = Math.min((last.usageFailures || 0) + 1, 1_000_000);
|
|
157
158
|
const delay = Number.isFinite(error.retryAfterMs) ? Math.max(RETRY_DELAY_MS, error.retryAfterMs) : RETRY_DELAY_MS;
|
|
@@ -279,6 +280,8 @@ export async function run({ scheduled = false, dryRun = false, output = console.
|
|
|
279
280
|
const { stdout, ...details } = await execute(provider.executable, providerArgs(provider), { cwd: workspace, env });
|
|
280
281
|
result = { ...details, confirmed: details.code === 0 && deliveryConfirmed(provider.name, stdout) };
|
|
281
282
|
} catch (error) {
|
|
283
|
+
// Leave pendingAt in place: the hello may have been delivered.
|
|
284
|
+
if (error instanceof Interrupted) throw error;
|
|
282
285
|
result = { code: null, error: error.code || 'spawn failed' };
|
|
283
286
|
}
|
|
284
287
|
const ok = result.confirmed === true && !result.timedOut && !result.outputTooLarge;
|
|
@@ -296,7 +299,7 @@ export async function run({ scheduled = false, dryRun = false, output = console.
|
|
|
296
299
|
if (scheduledCheck) await writeJSON('heartbeat.json', { at: new Date().toISOString(), phase: 'finished', ok: success });
|
|
297
300
|
return success;
|
|
298
301
|
} catch (error) {
|
|
299
|
-
if (scheduledCheck) await writeJSON('heartbeat.json', { at: new Date().toISOString(), phase: 'failed' }).catch(() => {});
|
|
302
|
+
if (scheduledCheck && !(error instanceof Interrupted)) await writeJSON('heartbeat.json', { at: new Date().toISOString(), phase: 'failed' }).catch(() => {});
|
|
300
303
|
throw error;
|
|
301
304
|
} finally {
|
|
302
305
|
try { if (workspace) await fs.rm(workspace, { recursive: true, force: true }); }
|
package/lib/process.mjs
CHANGED
|
@@ -1,5 +1,14 @@
|
|
|
1
1
|
import { spawn } from 'node:child_process';
|
|
2
2
|
|
|
3
|
+
// Thrown instead of exiting, so callers release locks and temporary files
|
|
4
|
+
// before the entry point re-raises the signal.
|
|
5
|
+
export class Interrupted extends Error {
|
|
6
|
+
constructor(signal) {
|
|
7
|
+
super(`Interrupted by ${signal}.`);
|
|
8
|
+
this.signal = signal;
|
|
9
|
+
}
|
|
10
|
+
}
|
|
11
|
+
|
|
3
12
|
// No shell, no unbounded output, and terminate the whole process group on timeout.
|
|
4
13
|
export function execute(executable, args, { cwd, env = process.env, timeout = 120_000 } = {}) {
|
|
5
14
|
return new Promise((resolve, reject) => {
|
|
@@ -9,7 +18,7 @@ export function execute(executable, args, { cwd, env = process.env, timeout = 12
|
|
|
9
18
|
let size = 0;
|
|
10
19
|
const chunks = [];
|
|
11
20
|
const stop = () => { try { process.kill(-child.pid, 'SIGKILL'); } catch { /* Already exited. */ } };
|
|
12
|
-
const interrupt = signal => { stop(); cleanup();
|
|
21
|
+
const interrupt = signal => { stop(); cleanup(); reject(new Interrupted(signal)); };
|
|
13
22
|
const onInterrupt = () => interrupt('SIGINT');
|
|
14
23
|
const onTerminate = () => interrupt('SIGTERM');
|
|
15
24
|
const cleanup = () => {
|
package/lib/usage.mjs
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import * as fs from 'node:fs/promises';
|
|
2
2
|
import { spawn } from 'node:child_process';
|
|
3
|
-
import { execute } from './process.mjs';
|
|
3
|
+
import { execute, Interrupted } from './process.mjs';
|
|
4
4
|
|
|
5
5
|
const packageVersion = JSON.parse(await fs.readFile(new URL('../package.json', import.meta.url), 'utf8')).version;
|
|
6
6
|
|
|
@@ -52,18 +52,24 @@ function wallTime(formatter, parts) {
|
|
|
52
52
|
return candidates.size ? Math.max(...candidates) : NaN;
|
|
53
53
|
}
|
|
54
54
|
|
|
55
|
+
// Claude Code formats resets with its runtime's ICU data, which joins the date
|
|
56
|
+
// and time with " at " (macOS system ICU) or ", " (the ICU bundled on Linux),
|
|
57
|
+
// and adds the year only when the reset falls in a different year.
|
|
58
|
+
const CLAUDE_RESET = /^(?:(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s(\d{1,2})(?:,\s(\d{4}))?(?:\sat|,)\s)?(\d{1,2})(?::(\d{2}))?\s*(am|pm)\s\(([^()]+)\)$/i;
|
|
59
|
+
|
|
55
60
|
function claudeReset(text, now, maximumDelay) {
|
|
56
|
-
const match =
|
|
61
|
+
const match = CLAUDE_RESET.exec(text);
|
|
57
62
|
if (!match) throw new Error('Claude /usage reset format is unrecognized.');
|
|
58
|
-
const [, monthName, dayText, hourText, minuteText = '0', period, zone] = match;
|
|
63
|
+
const [, monthName, dayText, yearText, hourText, minuteText = '0', period, zone] = match;
|
|
59
64
|
const hour = Number(hourText); const minute = Number(minuteText);
|
|
60
65
|
if (hour < 1 || hour > 12 || minute > 59) throw new Error('Claude /usage reset time is invalid.');
|
|
61
66
|
let formatter;
|
|
62
67
|
try { formatter = new Intl.DateTimeFormat('en-US', { timeZone: zone, year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', hourCycle: 'h23' }); }
|
|
63
68
|
catch { throw new Error('Claude /usage timezone is invalid.'); }
|
|
64
69
|
const current = localParts(formatter, now);
|
|
70
|
+
const month = monthName && months.findIndex(name => name.toLowerCase() === monthName.toLowerCase()) + 1;
|
|
65
71
|
const dates = monthName
|
|
66
|
-
? [-1, 0, 1].map(offset =>
|
|
72
|
+
? (yearText ? [Number(yearText)] : [-1, 0, 1].map(offset => current[0] + offset)).map(year => [year, month, Number(dayText)])
|
|
67
73
|
: [0, 1].map(offset => { const date = new Date(Date.UTC(current[0], current[1] - 1, current[2] + offset)); return [date.getUTCFullYear(), date.getUTCMonth() + 1, date.getUTCDate()]; });
|
|
68
74
|
const candidates = dates.map(date => wallTime(formatter, [...date, hour % 12 + (period.toLowerCase() === 'pm' ? 12 : 0), minute]) + 60_000)
|
|
69
75
|
.filter(time => Number.isFinite(time) && time >= now - 60_000 && time <= now + maximumDelay);
|
|
@@ -72,8 +78,9 @@ function claudeReset(text, now, maximumDelay) {
|
|
|
72
78
|
}
|
|
73
79
|
|
|
74
80
|
function claudeWindow(line, now, maximumDelay) {
|
|
75
|
-
//
|
|
76
|
-
|
|
81
|
+
// An idle window is reported as unused with no reset time (captured live).
|
|
82
|
+
// A started window always names its reset, even at 0%.
|
|
83
|
+
if (line === '0% used') return { reset: null, used: 0 };
|
|
77
84
|
const match = /^(\d+(?:\.\d+)?)% used · resets (.+)$/.exec(line);
|
|
78
85
|
if (!match || Number(match[1]) > 100) throw new Error('Claude /usage window is unrecognized.');
|
|
79
86
|
const reset = claudeReset(match[2], now, maximumDelay);
|
|
@@ -96,11 +103,20 @@ export function normalizeClaudeUsage(raw, now = Date.now()) {
|
|
|
96
103
|
return normalize(primary, secondary, now, 'claude-cli-usage');
|
|
97
104
|
}
|
|
98
105
|
|
|
99
|
-
|
|
100
|
-
|
|
106
|
+
const CODEX_RECHECK_MS = 2000;
|
|
107
|
+
const codexLimits = raw => raw?.rateLimitsByLimitId?.codex || raw?.rateLimits;
|
|
108
|
+
const codexUnused = raw => codexLimits(raw)?.primary?.usedPercent === 0 && Number.isFinite(codexLimits(raw).primary.resetsAt);
|
|
109
|
+
|
|
110
|
+
// An idle Codex account reports an unused window whose reset is recomputed as
|
|
111
|
+
// one window length after each read (captured live). A started window keeps a
|
|
112
|
+
// fixed reset, so a later reading tells them apart without trusting the clock.
|
|
113
|
+
export function normalizeCodexUsage(raw, now = Date.now(), later) {
|
|
114
|
+
const limits = codexLimits(later || raw);
|
|
101
115
|
if (!limits || !Object.hasOwn(limits, 'primary')) throw new Error('Codex usage response has no primary window.');
|
|
102
116
|
const names = { used: 'usedPercent', reset: 'resetsAt', seconds: true };
|
|
103
|
-
|
|
117
|
+
const idle = later && codexUnused(raw) && codexUnused(later) && limits.primary.resetsAt > codexLimits(raw).primary.resetsAt;
|
|
118
|
+
const primary = idle ? { reset: null, used: 0 } : window(limits.primary, names, now);
|
|
119
|
+
return normalize(primary, limits.secondary == null ? null : window(limits.secondary, names, now), now, 'codex-app-server');
|
|
104
120
|
}
|
|
105
121
|
|
|
106
122
|
export async function readClaudeUsage(provider, { env = process.env, cwd, runner = execute } = {}) {
|
|
@@ -116,17 +132,17 @@ export async function readClaudeUsage(provider, { env = process.env, cwd, runner
|
|
|
116
132
|
export function readCodexUsage(provider, { env = process.env, cwd } = {}) {
|
|
117
133
|
return new Promise((resolve, reject) => {
|
|
118
134
|
const child = spawn(provider.executable, ['app-server', '--stdio'], { env, cwd, detached: true, stdio: ['pipe', 'pipe', 'ignore'] });
|
|
119
|
-
let buffer = ''; let bytes = 0; let done = false;
|
|
135
|
+
let buffer = ''; let bytes = 0; let done = false; let first; let recheck;
|
|
120
136
|
const finish = (error, result) => {
|
|
121
137
|
if (done) return;
|
|
122
|
-
done = true; clearTimeout(timer);
|
|
138
|
+
done = true; clearTimeout(timer); clearTimeout(recheck);
|
|
123
139
|
process.off('SIGINT', onInterrupt); process.off('SIGTERM', onTerminate);
|
|
124
140
|
child.stdin.destroy(); child.stdout.destroy();
|
|
125
141
|
try { process.kill(-child.pid, 'SIGKILL'); } catch { /* Already exited. */ }
|
|
126
142
|
if (error) reject(error); else resolve(result);
|
|
127
143
|
};
|
|
128
|
-
const onInterrupt = () =>
|
|
129
|
-
const onTerminate = () =>
|
|
144
|
+
const onInterrupt = () => finish(new Interrupted('SIGINT'));
|
|
145
|
+
const onTerminate = () => finish(new Interrupted('SIGTERM'));
|
|
130
146
|
const timer = setTimeout(() => finish(new Error('Codex usage check timed out.')), 20_000);
|
|
131
147
|
const send = message => child.stdin.write(`${JSON.stringify(message)}\n`);
|
|
132
148
|
process.once('SIGINT', onInterrupt); process.once('SIGTERM', onTerminate);
|
|
@@ -142,11 +158,14 @@ export function readCodexUsage(provider, { env = process.env, cwd } = {}) {
|
|
|
142
158
|
const line = buffer.slice(0, index); buffer = buffer.slice(index + 1);
|
|
143
159
|
let message;
|
|
144
160
|
try { message = JSON.parse(line); } catch { finish(new Error('Invalid Codex usage response.')); return; }
|
|
145
|
-
if (
|
|
161
|
+
if (![1, 2, 3].includes(message.id)) continue;
|
|
146
162
|
if (message.error) { finish(new Error('Codex usage unavailable. Check the subscription login.')); return; }
|
|
147
163
|
if (message.id === 1) { send({ method: 'initialized', params: {} }); send({ id: 2, method: 'account/rateLimits/read' }); }
|
|
148
|
-
else {
|
|
149
|
-
|
|
164
|
+
else if (message.id === 2 && codexUnused(message.result)) {
|
|
165
|
+
first = message.result;
|
|
166
|
+
recheck = setTimeout(() => send({ id: 3, method: 'account/rateLimits/read' }), CODEX_RECHECK_MS);
|
|
167
|
+
} else {
|
|
168
|
+
try { finish(null, first ? normalizeCodexUsage(first, Date.now(), message.result) : normalizeCodexUsage(message.result)); }
|
|
150
169
|
catch (error) { finish(error); }
|
|
151
170
|
}
|
|
152
171
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "hi-ai-cli",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.1",
|
|
4
4
|
"description": "A usage-aware hello at reset for Claude Code and Codex on macOS and Linux.",
|
|
5
5
|
"author": "anik-jha",
|
|
6
6
|
"repository": {
|
|
@@ -8,26 +8,12 @@
|
|
|
8
8
|
"url": "git+https://github.com/anik-jha/hi-ai.git"
|
|
9
9
|
},
|
|
10
10
|
"homepage": "https://github.com/anik-jha/hi-ai#readme",
|
|
11
|
-
"bugs": {
|
|
12
|
-
"url": "https://github.com/anik-jha/hi-ai/issues"
|
|
13
|
-
},
|
|
11
|
+
"bugs": { "url": "https://github.com/anik-jha/hi-ai/issues" },
|
|
14
12
|
"type": "module",
|
|
15
|
-
"bin": {
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
"
|
|
19
|
-
"node": ">=22"
|
|
20
|
-
},
|
|
21
|
-
"os": [
|
|
22
|
-
"darwin",
|
|
23
|
-
"linux"
|
|
24
|
-
],
|
|
25
|
-
"files": [
|
|
26
|
-
"bin/",
|
|
27
|
-
"lib/",
|
|
28
|
-
"README.md",
|
|
29
|
-
"LICENSE"
|
|
30
|
-
],
|
|
13
|
+
"bin": { "hi-ai": "bin/hi-ai.mjs" },
|
|
14
|
+
"engines": { "node": ">=22" },
|
|
15
|
+
"os": ["darwin", "linux"],
|
|
16
|
+
"files": ["bin/", "lib/", "README.md", "LICENSE"],
|
|
31
17
|
"scripts": {
|
|
32
18
|
"test": "node --test",
|
|
33
19
|
"test:live": "node scripts/live-smoke.mjs",
|