hi-ai-cli 0.1.0-beta.0 → 0.1.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 +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 +26 -13
- 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.0.** 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 may omit the year; HiAI handles timezone offsets, year rollover, and daylight-saving changes. Missing or changed output counts as a failed read.
|
|
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 may omit the year; HiAI handles timezone offsets, year rollover, and daylight-saving changes. Missing or changed output counts as a failed read. Both formats 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
|
|
|
@@ -72,8 +72,9 @@ function claudeReset(text, now, maximumDelay) {
|
|
|
72
72
|
}
|
|
73
73
|
|
|
74
74
|
function claudeWindow(line, now, maximumDelay) {
|
|
75
|
-
//
|
|
76
|
-
|
|
75
|
+
// An idle window is reported as unused with no reset time (captured live).
|
|
76
|
+
// A started window always names its reset, even at 0%.
|
|
77
|
+
if (line === '0% used') return { reset: null, used: 0 };
|
|
77
78
|
const match = /^(\d+(?:\.\d+)?)% used · resets (.+)$/.exec(line);
|
|
78
79
|
if (!match || Number(match[1]) > 100) throw new Error('Claude /usage window is unrecognized.');
|
|
79
80
|
const reset = claudeReset(match[2], now, maximumDelay);
|
|
@@ -96,11 +97,20 @@ export function normalizeClaudeUsage(raw, now = Date.now()) {
|
|
|
96
97
|
return normalize(primary, secondary, now, 'claude-cli-usage');
|
|
97
98
|
}
|
|
98
99
|
|
|
99
|
-
|
|
100
|
-
|
|
100
|
+
const CODEX_RECHECK_MS = 2000;
|
|
101
|
+
const codexLimits = raw => raw?.rateLimitsByLimitId?.codex || raw?.rateLimits;
|
|
102
|
+
const codexUnused = raw => codexLimits(raw)?.primary?.usedPercent === 0 && Number.isFinite(codexLimits(raw).primary.resetsAt);
|
|
103
|
+
|
|
104
|
+
// An idle Codex account reports an unused window whose reset is recomputed as
|
|
105
|
+
// one window length after each read (captured live). A started window keeps a
|
|
106
|
+
// fixed reset, so a later reading tells them apart without trusting the clock.
|
|
107
|
+
export function normalizeCodexUsage(raw, now = Date.now(), later) {
|
|
108
|
+
const limits = codexLimits(later || raw);
|
|
101
109
|
if (!limits || !Object.hasOwn(limits, 'primary')) throw new Error('Codex usage response has no primary window.');
|
|
102
110
|
const names = { used: 'usedPercent', reset: 'resetsAt', seconds: true };
|
|
103
|
-
|
|
111
|
+
const idle = later && codexUnused(raw) && codexUnused(later) && limits.primary.resetsAt > codexLimits(raw).primary.resetsAt;
|
|
112
|
+
const primary = idle ? { reset: null, used: 0 } : window(limits.primary, names, now);
|
|
113
|
+
return normalize(primary, limits.secondary == null ? null : window(limits.secondary, names, now), now, 'codex-app-server');
|
|
104
114
|
}
|
|
105
115
|
|
|
106
116
|
export async function readClaudeUsage(provider, { env = process.env, cwd, runner = execute } = {}) {
|
|
@@ -116,17 +126,17 @@ export async function readClaudeUsage(provider, { env = process.env, cwd, runner
|
|
|
116
126
|
export function readCodexUsage(provider, { env = process.env, cwd } = {}) {
|
|
117
127
|
return new Promise((resolve, reject) => {
|
|
118
128
|
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;
|
|
129
|
+
let buffer = ''; let bytes = 0; let done = false; let first; let recheck;
|
|
120
130
|
const finish = (error, result) => {
|
|
121
131
|
if (done) return;
|
|
122
|
-
done = true; clearTimeout(timer);
|
|
132
|
+
done = true; clearTimeout(timer); clearTimeout(recheck);
|
|
123
133
|
process.off('SIGINT', onInterrupt); process.off('SIGTERM', onTerminate);
|
|
124
134
|
child.stdin.destroy(); child.stdout.destroy();
|
|
125
135
|
try { process.kill(-child.pid, 'SIGKILL'); } catch { /* Already exited. */ }
|
|
126
136
|
if (error) reject(error); else resolve(result);
|
|
127
137
|
};
|
|
128
|
-
const onInterrupt = () =>
|
|
129
|
-
const onTerminate = () =>
|
|
138
|
+
const onInterrupt = () => finish(new Interrupted('SIGINT'));
|
|
139
|
+
const onTerminate = () => finish(new Interrupted('SIGTERM'));
|
|
130
140
|
const timer = setTimeout(() => finish(new Error('Codex usage check timed out.')), 20_000);
|
|
131
141
|
const send = message => child.stdin.write(`${JSON.stringify(message)}\n`);
|
|
132
142
|
process.once('SIGINT', onInterrupt); process.once('SIGTERM', onTerminate);
|
|
@@ -142,11 +152,14 @@ export function readCodexUsage(provider, { env = process.env, cwd } = {}) {
|
|
|
142
152
|
const line = buffer.slice(0, index); buffer = buffer.slice(index + 1);
|
|
143
153
|
let message;
|
|
144
154
|
try { message = JSON.parse(line); } catch { finish(new Error('Invalid Codex usage response.')); return; }
|
|
145
|
-
if (
|
|
155
|
+
if (![1, 2, 3].includes(message.id)) continue;
|
|
146
156
|
if (message.error) { finish(new Error('Codex usage unavailable. Check the subscription login.')); return; }
|
|
147
157
|
if (message.id === 1) { send({ method: 'initialized', params: {} }); send({ id: 2, method: 'account/rateLimits/read' }); }
|
|
148
|
-
else {
|
|
149
|
-
|
|
158
|
+
else if (message.id === 2 && codexUnused(message.result)) {
|
|
159
|
+
first = message.result;
|
|
160
|
+
recheck = setTimeout(() => send({ id: 3, method: 'account/rateLimits/read' }), CODEX_RECHECK_MS);
|
|
161
|
+
} else {
|
|
162
|
+
try { finish(null, first ? normalizeCodexUsage(first, Date.now(), message.result) : normalizeCodexUsage(message.result)); }
|
|
150
163
|
catch (error) { finish(error); }
|
|
151
164
|
}
|
|
152
165
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "hi-ai-cli",
|
|
3
|
-
"version": "0.1.0
|
|
3
|
+
"version": "0.1.0",
|
|
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",
|