hi-ai-cli 0.0.0-stage → 0.1.0-beta.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 anik-jha and HiAI contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,160 @@
1
- # Temporary Holding Version
1
+ # HiAI
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
+ **A little hi, right on reset.**
4
+
5
+ [Source](https://github.com/anik-jha/hi-ai) · [Issues](https://github.com/anik-jha/hi-ai/issues) · [MIT license](LICENSE)
6
+
7
+ A small, usage-aware utility for **Claude Code and Codex**, on macOS and Linux. Install it once, choose your providers, and let it follow their actual usage windows.
8
+
9
+ - **No active window:** send a minimal hello to start one.
10
+ - **An active window:** save the provider's reported reset time and send the next hello when that time arrives.
11
+ - **After a restart:** read usage again before deciding, rather than blindly starting another five-hour timer.
12
+ - **Usage unavailable:** retry first; after three consecutive failures, use a five-hour timer until usage reads recover.
13
+
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
+
16
+ **Release status: beta.** Usage readers, timing decisions, failure recovery, and native schedulers have tests. Live usage reads and background delivery have been verified on this Mac. The complete idle → hello → newly active window transition still needs to be observed on a real account. A hello consumes usage; the provider controls quota and billing.
17
+
18
+ ## Install
19
+
20
+ Requires **Node.js 22+** and the selected provider CLIs, signed into your subscriptions:
21
+
22
+ - [Claude Code](https://code.claude.com/docs/en/overview): `claude auth login`.
23
+ - [Standalone Codex CLI](https://learn.chatgpt.com/docs/cli): `codex login`. HiAI skips copies inside versioned IDE extension folders.
24
+ - On Linux: `crontab` and a running cron service. Debian/Ubuntu: `sudo apt install cron && sudo systemctl enable --now cron`.
25
+
26
+ ```sh
27
+ npm install -g hi-ai-cli@beta
28
+ hi-ai setup --providers claude,codex
29
+ ```
30
+
31
+ Setup detects CLI paths and installs a user schedule. The first automatic usage check normally runs within about a minute. It sends a hello only if the provider is idle; an existing window is allowed to reach its reported reset time first.
32
+
33
+ Use `--providers claude` or `--providers codex` for just one. Without `--providers`, setup offers the detected CLIs interactively.
34
+
35
+ To delay the first automatic check:
36
+
37
+ ```sh
38
+ hi-ai setup --time 06:00 --providers claude,codex
39
+ ```
40
+
41
+ `--time` means the next occurrence of that local time. Subsequent hellos follow provider resets.
42
+
43
+ ## Why use HiAI instead of a cron command?
44
+
45
+ Cron can launch a command. HiAI adds the account-state and recovery logic around that command, with one setup for both providers and the same management commands on macOS and Linux.
46
+
47
+ A cron expression such as `0 */5 * * *` runs at 00:00, 05:00, 10:00, 15:00, and 20:00, with only four hours between 20:00 and midnight. It also has no connection to a window you started manually at another time. HiAI reads that window and uses its reported reset instead.
48
+
49
+ | Task | HiAI handles it |
50
+ | --- | --- |
51
+ | Avoid an unnecessary startup hello | Check whether a usage window is already active. |
52
+ | Align with existing usage | Save the reset time returned by the provider. |
53
+ | Recover after restart | Refresh usage for the current boot before deciding. |
54
+ | Run both providers | Independent usage state, models, and deadlines. |
55
+ | Confirm delivery | Validate structured CLI responses before recording success. |
56
+ | Prevent overlapping calls | Share a lock across scheduled runs, manual runs, and settings changes. |
57
+ | Handle uncertainty | Apply timeouts, request backoff, and delivery cooldowns. |
58
+ | Manage the schedule | Preview, inspect status, pause, resume, and uninstall. |
59
+
60
+ You can implement this in your own script. HiAI packages it together, with tests and zero npm runtime dependencies.
61
+
62
+ ## Use
63
+
64
+ ```sh
65
+ hi-ai status # Usage state, next hello, and last scheduler check
66
+ hi-ai run --dry-run # Preview hello arguments without sending anything
67
+ hi-ai run # Explicitly send now, overriding the automatic usage decision
68
+ hi-ai pause # Remove the schedule; retain settings and state
69
+ hi-ai resume # Reinstall the schedule and refresh usage
70
+ hi-ai uninstall # Remove the schedule, settings, state, and logs
71
+ npm uninstall -g hi-ai-cli
72
+ ```
73
+
74
+ Change providers or models by rerunning setup:
75
+
76
+ ```sh
77
+ hi-ai setup --providers claude,codex \
78
+ --claude-model haiku --codex-model gpt-6-luna
79
+ ```
80
+
81
+ Model access depends on your account. There is no automatic fallback to a more expensive model. Recent CLIs are required for the flags used here; see the validation notes below.
82
+
83
+ ## How scheduling works
84
+
85
+ A user LaunchAgent on macOS, or a marked block in the user's crontab on Linux, checks due times once a minute. Model calls happen only when a hello is due. Reading usage does not run inference.
86
+
87
+ At the first check, after setup/resume, and after an OS reboot, HiAI reads current usage. If a window is active, its deadline is saved. A normal check at that deadline sends one hello; it does not keep chasing a newly advanced deadline. A reported exhausted weekly quota postpones the hello until that blocking window resets. Claude reset times have minute precision; HiAI waits until the displayed minute has fully elapsed to avoid sending early.
88
+
89
+ Usage readings are cached briefly. An active deadline can be followed without repeatedly querying the service. Failed usage checks retry no sooner than five minutes, honoring any longer retry deadline. After three consecutive failures (normally about ten minutes), that provider switches to a five-hour timer. With no previous hello or known reset, the third failed check can send the first hello. Existing reset deadlines and delivery cooldowns still apply. HiAI keeps trying usage reads and returns to provider reset times when they recover. `status` identifies timer fallback explicitly; failed reads are never labeled idle.
90
+
91
+ If a provider still reports an idle window after a successful hello, HiAI limits automatic sends to at most one per five hours. This prevents reporting lag, unmetered plans, or different quota pools from producing a hello on every check. A provider-reported reset takes precedence over this local safety interval.
92
+
93
+ Sleep and shutdown pause execution. The next available check handles an overdue deadline once; missed intervals do not create a burst of messages. HiAI does not wake the computer. macOS requires a logged-in user session; Linux requires cron to be running. Delivery can be about a minute after a deadline, plus OS and CLI delays.
94
+
95
+ Each provider has a two-minute hello timeout. HiAI records an attempt before calling the CLI. After interruption, timeout, or an unconfirmed response, a five-hour cooldown reduces duplicate sends when delivery is uncertain. This is not an exactly-once delivery guarantee. Known provider failures can retry after five minutes.
96
+
97
+ A saved provider failure is a completed scheduled check, so the scheduler process exits 0 and the provider error remains visible in `status`. Crashes, invalid state, and storage/configuration errors still exit nonzero. Explicit manual runs also exit nonzero on provider failure.
98
+
99
+ ## Usage access and privacy
100
+
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
+
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. The current active-window format has been captured live; a real idle-window capture remains pending.
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.
106
+
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
+
109
+ Hellos run in a temporary empty directory. Claude tools, MCP servers, and user hooks are disabled for the invocation. Codex ignores user config for the hello and uses its read-only sandbox. Sessions are ephemeral. Provider output is inspected in memory, not saved to the log.
110
+
111
+ Settings, sanitized quota observations, deadlines, the latest scheduler heartbeat, and the latest 100 result records live in `~/.hi-ai/`. Logs contain confirmation/process metadata, not provider output or credentials. `HI_AI_HOME` overrides this directory.
112
+
113
+ ## Runtime and status
114
+
115
+ For Homebrew Node, setup selects a stable executable link such as `/opt/homebrew/bin/node`, rather than a versioned Cellar path. Other installations retain their resolved installation path, avoiding fnm's per-shell links. Rerun setup after moving the package or changing installation managers.
116
+
117
+ `status` distinguishes a loaded job from an observed scheduled check, reports missing executables and named launchd exit codes such as `78: EX_CONFIG`, and flags a heartbeat older than ten minutes. A provider error is shown separately from a broken scheduler.
118
+
119
+ Setup, pause, resume, and uninstall refuse to change settings while a check or hello is running; retry when it finishes. Invalid JSON or timestamps stop sending until the saved state is repaired. An interrupted lock-recovery error names the lock to remove after confirming no HiAI process is running.
120
+
121
+ ## Test
122
+
123
+ From the repository:
124
+
125
+ ```sh
126
+ npm test
127
+ npm run test:docker
128
+ HI_AI_TEST_LAUNCHD=1 node --test test/macos-launchd.test.mjs
129
+ ```
130
+
131
+ The local suite covers idle/active usage, provider resets, reboot refresh, deadline latching, weekly blocks, malformed CLI output, timezone and year boundaries, daylight-saving gaps and folds, repeated-failure timer fallback and recovery, RPC requests without inference, and sanitized persisted observations. It also covers lifecycle commands, concurrency, interruption recovery, invalid state, Node upgrade links, fnm cleanup, named launchd exit codes, and provider versus scheduler failures.
132
+
133
+ The Docker test installs the actual npm archive on Node 22 with Debian cron. Real cron ticks send and repeat fake hellos using controlled usage fixtures, and lifecycle commands preserve unrelated jobs. Allow about two minutes. The macOS test uses a real timer: an active fixture receives no early hello, then both providers are invoked after its reset. It also simulates a Node-link upgrade and provider failure without labeling the schedule broken. No automated scheduler test reads real credentials or sends paid requests.
134
+
135
+ For explicit live checks:
136
+
137
+ ```sh
138
+ HI_AI_LIVE_TEST=1 npm run test:live
139
+ HI_AI_LIVE_TEST=1 npm run test:live:scheduled
140
+ ```
141
+
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
+
144
+ ## Beta validation
145
+
146
+ Verified on this Mac: 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. The complete idle → hello → newly active window transition still needs a real idle-window observation.
147
+
148
+ 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
+
150
+ HiAI delegates authentication to the unmodified Claude Code binary, following the boundary in Anthropic’s [authentication and credential-use rules](https://code.claude.com/docs/en/legal-and-compliance#authentication-and-credential-use). Anthropic also [documents scripted CLI usage](https://code.claude.com/docs/en/headless). Provider terms and plan rules apply.
151
+
152
+ ## Run from source
153
+
154
+ ```sh
155
+ git clone https://github.com/anik-jha/hi-ai.git
156
+ cd hi-ai
157
+ npm install -g .
158
+ ```
159
+
160
+ Maintained by [anik-jha](https://github.com/anik-jha).
package/bin/hi-ai.mjs ADDED
@@ -0,0 +1,136 @@
1
+ #!/usr/bin/env node
2
+ import * as fs from 'node:fs/promises';
3
+ import { parseArgs } from 'node:util';
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';
6
+ import * as scheduler from '../lib/scheduler.mjs';
7
+
8
+ const help = `hi-ai — a tiny scheduled hello for Claude Code and Codex
9
+
10
+ setup [--time HH:MM] [--providers claude,codex]
11
+ [--claude-model haiku] [--codex-model gpt-6-luna]
12
+ run [--dry-run] Send one hello now, or preview the CLI arguments
13
+ status Show the schedule and last results
14
+ pause Remove the schedule; keep settings
15
+ resume Reinstall the saved schedule
16
+ uninstall Remove the schedule, settings, and local logs
17
+
18
+ Checks provider usage on startup and after a system restart.
19
+ Sends hi if idle, or waits for the provider's reported reset time.
20
+ --time HH:MM delays the first automatic check (local time).
21
+ Requires Node.js 22+, a logged-in provider CLI, and cron on Linux.
22
+ Pings consume usage; they cannot force a quota reset.
23
+ `;
24
+
25
+ async function main() {
26
+ const { values, positionals } = parseArgs({
27
+ allowPositionals: true,
28
+ options: {
29
+ time: { type: 'string' }, providers: { type: 'string' },
30
+ 'claude-model': { type: 'string' }, 'codex-model': { type: 'string' },
31
+ 'dry-run': { type: 'boolean' }, scheduled: { type: 'boolean' },
32
+ help: { type: 'boolean', short: 'h' }, version: { type: 'boolean', short: 'v' },
33
+ },
34
+ });
35
+ if (values.version) { console.log(JSON.parse(await fs.readFile(new URL('../package.json', import.meta.url), 'utf8')).version); return; }
36
+ if (values.help || !positionals.length) { console.log(help); return; }
37
+ if (positionals.length !== 1) throw new Error('Expected one command. See hi-ai --help.');
38
+ const action = positionals[0];
39
+ const allowed = action === 'setup' ? ['time', 'providers', 'claude-model', 'codex-model']
40
+ : action === 'run' ? ['dry-run', 'scheduled'] : [];
41
+ for (const key of Object.keys(values)) if (!allowed.includes(key)) throw new Error(`--${key} is not valid for ${action}.`);
42
+
43
+ let unlock;
44
+ if (['setup', 'pause', 'resume', 'uninstall'].includes(action)) {
45
+ unlock = await acquireLock();
46
+ if (!unlock) throw new Error('A ping or settings change is running. Wait and retry this command.');
47
+ }
48
+ try {
49
+ if (action === 'setup') {
50
+ const previous = await readJSON('config.json');
51
+ const detected = [];
52
+ for (const name of Object.keys(defaults)) {
53
+ const executable = await findExecutable(name);
54
+ if (executable) detected.push({ name, executable });
55
+ }
56
+ let names = values.providers;
57
+ let time = values.time;
58
+ if (process.stdin.isTTY && (!values.providers || !values.time)) {
59
+ const reader = createInterface({ input: process.stdin, output: process.stdout });
60
+ try {
61
+ if (!names) names = (await reader.question(`Providers [${detected.map(p => p.name).join(',')}]: `)).trim();
62
+ if (!values.time) time = (await reader.question('First usage check at HH:MM [start now]: ')).trim() || undefined;
63
+ } finally { reader.close(); }
64
+ }
65
+ const firstAt = firstStart(time);
66
+ const selected = names === undefined || names === '' ? detected.map(p => p.name) : [...new Set(names.split(',').map(name => name.trim()))];
67
+ if (!selected.length) throw new Error('No provider CLIs found on PATH. Install Claude Code or Codex and log in first.');
68
+ const providers = selected.map(name => {
69
+ if (!Object.hasOwn(defaults, name)) throw new Error(`Unknown provider: ${name}. Choose claude,codex.`);
70
+ const executable = detected.find(p => p.name === name)?.executable;
71
+ if (!executable) throw new Error(`${name} is not on PATH. Install it and log in first.`);
72
+ const model = values[`${name}-model`] ?? previous?.providers.find(p => p.name === name)?.model ?? defaults[name];
73
+ if (!model.trim() || model.startsWith('-')) throw new Error(`Invalid ${name} model.`);
74
+ return { name, executable, model };
75
+ });
76
+ const runtime = await scheduler.runtime();
77
+ const authPaths = Object.fromEntries(['CODEX_HOME', 'CLAUDE_CONFIG_DIR'].filter(key => process.env[key]).map(key => [key, process.env[key]]));
78
+ const next = { firstAt, providers, path: process.env.PATH, authPaths, enabled: true, scheduler: { ...runtime, installedAt: new Date().toISOString() } };
79
+ await writeJSON('config.json', next);
80
+ try { await scheduler.install(undefined, runtime); }
81
+ catch (error) {
82
+ if (previous) await writeJSON('config.json', previous);
83
+ else await fs.rm(file('config.json'), { force: true });
84
+ throw error;
85
+ }
86
+ await fs.rm(file('heartbeat.json'), { force: true });
87
+ console.log(`Scheduled ${providers.map(p => `${p.name} (${p.model})`).join(', ')} using each provider's reported reset time.`);
88
+ console.log(`First usage check ${time ? `from ${new Date(firstAt).toLocaleString()}` : 'due now'}, within about a minute. Idle windows get hi; active windows wait until reset.`);
89
+ } else if (action === 'run') {
90
+ const success = await run({ scheduled: values.scheduled, dryRun: values['dry-run'] });
91
+ // A saved provider failure is a completed scheduler check. Actual runner
92
+ // errors still throw and exit nonzero through main's error handler.
93
+ if (!success && !values.scheduled) process.exitCode = 1;
94
+ } else if (action === 'status') {
95
+ const settings = await config();
96
+ const state = await readState();
97
+ const health = await scheduler.inspect(settings);
98
+ const heartbeat = await readJSON('heartbeat.json');
99
+ const since = Date.parse(heartbeat?.at || settings.scheduler?.installedAt);
100
+ const stale = Number.isFinite(since) && Date.now() - since > 10 * 60 * 1000;
101
+ const label = !settings.enabled ? 'Paused' : !health.registered ? 'Schedule missing' : health.issues.length ? 'Broken schedule' : stale ? 'Scheduler inactive' : !heartbeat ? 'Waiting for first scheduler check' : 'Scheduled';
102
+ console.log(`${label}: provider reset times; checked every minute.`);
103
+ console.log(`Last scheduled check: ${heartbeat ? `${heartbeat.at} (${heartbeat.phase}${heartbeat.ok === false ? ', provider failure' : ''})` : 'not observed yet'}.`);
104
+ for (const issue of health.issues) console.log(` ${issue}`);
105
+ if (stale && settings.enabled && health.registered) console.log(' No scheduler check observed in over ten minutes. Check the OS scheduler and rerun hi-ai setup.');
106
+ for (const provider of settings.providers) {
107
+ const last = state[provider.name];
108
+ console.log(`${provider.name} (${provider.model}): ${last?.pendingAt ? `delivery uncertain since ${last.pendingAt}` : last?.at ? `${last.ok ? 'sent' : 'failed'} at ${last.at}` : 'no pings yet'}`);
109
+ const due = nextDueAt(settings, last);
110
+ console.log(` Usage: ${last?.usage ? `${last.usage.state} (${last.usage.usedPercent}% used)` : 'awaiting first usage check'}.`);
111
+ if (last?.usageError) console.log(` ${last.usageError}`);
112
+ if (last?.usageFallback) console.log(` Automatic mode: five-hour timer fallback (${last.usageFailures} consecutive usage checks failed).`);
113
+ console.log(` Next hello: ${!last?.usage && !last?.lastSuccessAt ? 'after checking provider usage' : due <= Date.now() ? 'due now' : new Date(due).toLocaleString()}`);
114
+ }
115
+ console.log(`Settings and recent results: ${home()}`);
116
+ } else if (action === 'pause') {
117
+ const settings = await config();
118
+ await scheduler.remove();
119
+ await writeJSON('config.json', { ...settings, enabled: false });
120
+ console.log('Paused. Use hi-ai resume to restart.');
121
+ } else if (action === 'resume') {
122
+ const settings = await config();
123
+ const runtime = await scheduler.runtime();
124
+ await scheduler.install(undefined, runtime);
125
+ await writeJSON('config.json', { ...settings, enabled: true, scheduler: { ...runtime, installedAt: new Date().toISOString() } });
126
+ await fs.rm(file('heartbeat.json'), { force: true });
127
+ console.log('Resumed: provider reset times. Usage is checked before starting an idle window.');
128
+ } else if (action === 'uninstall') {
129
+ await scheduler.remove();
130
+ for (const name of ['config.json', 'state.json', 'runs.log', 'heartbeat.json']) await fs.rm(file(name), { force: true });
131
+ console.log('Schedule, settings, and logs removed. Remove the CLI with npm uninstall -g hi-ai-cli.');
132
+ } else throw new Error(`Unknown command: ${action}. See hi-ai --help.`);
133
+ } finally { if (unlock) await unlock(); }
134
+ }
135
+
136
+ main().catch(error => { console.error(`hi-ai: ${error.message}`); process.exitCode = 1; });
package/lib/core.mjs ADDED
@@ -0,0 +1,305 @@
1
+ import { constants } from 'node:fs';
2
+ import * as fs from 'node:fs/promises';
3
+ import os from 'node:os';
4
+ import path from 'node:path';
5
+ import { execute } from './process.mjs';
6
+ import { bootId, readUsage } from './usage.mjs';
7
+ export { execute } from './process.mjs';
8
+
9
+ export const defaults = { claude: 'haiku', codex: 'gpt-6-luna' };
10
+ export const FIVE_HOURS_MS = 5 * 60 * 60 * 1000;
11
+ export const RETRY_DELAY_MS = 5 * 60 * 1000;
12
+ export const USAGE_FAILURE_LIMIT = 3;
13
+ export const home = () => path.resolve(process.env.HI_AI_HOME || path.join(os.homedir(), '.hi-ai'));
14
+ export const file = name => path.join(home(), name);
15
+
16
+ export async function readJSON(name, fallback) {
17
+ try { return JSON.parse(await fs.readFile(file(name), 'utf8')); }
18
+ catch (error) { if (error.code === 'ENOENT') return fallback; throw error; }
19
+ }
20
+
21
+ export async function writeJSON(name, value) {
22
+ await fs.mkdir(home(), { recursive: true, mode: 0o700 });
23
+ const target = file(name);
24
+ const temporary = `${target}.${process.pid}.tmp`;
25
+ try {
26
+ await fs.writeFile(temporary, `${JSON.stringify(value, null, 2)}\n`, { mode: 0o600 });
27
+ await fs.rename(temporary, target);
28
+ } finally { await fs.rm(temporary, { force: true }); }
29
+ }
30
+
31
+ export async function config() {
32
+ const value = await readJSON('config.json');
33
+ if (!value) throw new Error('Run hi-ai setup first.');
34
+ if (!value || typeof value !== 'object' || typeof value.enabled !== 'boolean') throw new Error('Invalid configuration. Run hi-ai setup again.');
35
+ if (value.firstAt !== undefined && (typeof value.firstAt !== 'string' || !Number.isFinite(Date.parse(value.firstAt)))) throw new Error('Invalid start time. Run hi-ai setup again.');
36
+ if (!Array.isArray(value.providers) || !value.providers.length) throw new Error('No providers configured. Run setup again.');
37
+ for (const provider of value.providers) {
38
+ if (!provider || !Object.hasOwn(defaults, provider.name) || typeof provider.executable !== 'string' || !path.isAbsolute(provider.executable) || typeof provider.model !== 'string' || !provider.model.trim() || provider.model.startsWith('-')) {
39
+ throw new Error('Invalid provider configuration. Run setup again.');
40
+ }
41
+ }
42
+ if (new Set(value.providers.map(provider => provider.name)).size !== value.providers.length) throw new Error('Duplicate providers in configuration. Run hi-ai setup again.');
43
+ return value;
44
+ }
45
+
46
+ export async function readState() {
47
+ const state = await readJSON('state.json', {});
48
+ if (!state || typeof state !== 'object' || Array.isArray(state)) throw new Error('Invalid state.json; repair or restore it before sending more pings.');
49
+ for (const last of Object.values(state)) {
50
+ if (!last || typeof last !== 'object' || (last.ok !== undefined && typeof last.ok !== 'boolean')) throw new Error('Invalid provider state; repair state.json before sending more pings.');
51
+ for (const key of ['at', 'lastSuccessAt', 'pendingAt', 'resetAt', 'usageRetryAt']) {
52
+ if (last[key] !== undefined && (typeof last[key] !== 'string' || !Number.isFinite(Date.parse(last[key])))) throw new Error(`Invalid ${key} in state.json; repair it before sending more pings.`);
53
+ }
54
+ if (last.usageFailures !== undefined && (!Number.isSafeInteger(last.usageFailures) || last.usageFailures < 0)) throw new Error('Invalid usage failure count in state.json.');
55
+ }
56
+ return state;
57
+ }
58
+
59
+ export function validateTime(value) {
60
+ if (!/^([01]\d|2[0-3]):[0-5]\d$/.test(value)) throw new Error('Time must be HH:MM in 24-hour local time, for example 06:00.');
61
+ return value;
62
+ }
63
+
64
+ export async function findExecutable(name) {
65
+ for (const directory of (process.env.PATH || '').split(path.delimiter).filter(Boolean)) {
66
+ const candidate = path.resolve(directory, name);
67
+ if (name === 'codex' && /[/\\]openai\.chatgpt-[^/\\]+[/\\]/.test(candidate)) continue;
68
+ try {
69
+ await fs.access(candidate, constants.X_OK);
70
+ if ((await fs.stat(candidate)).isFile()) return candidate;
71
+ } catch { /* Try the next PATH entry. */ }
72
+ }
73
+ return null;
74
+ }
75
+
76
+ export function providerArgs(provider) {
77
+ const prompt = 'hi. Reply only: hi';
78
+ if (provider.name === 'claude') return [
79
+ '-p', prompt, '--model', provider.model, '--tools', '', '--strict-mcp-config',
80
+ '--mcp-config', '{"mcpServers":{}}', '--no-session-persistence',
81
+ '--setting-sources', '', '--settings', '{"disableAllHooks":true}',
82
+ '--system-prompt', 'Reply with hi.', '--output-format', 'json',
83
+ ];
84
+ return [
85
+ 'exec', '--model', provider.model, '--json', '--ephemeral', '--skip-git-repo-check',
86
+ '--ignore-user-config', '--sandbox', 'read-only', '--color', 'never',
87
+ '-c', 'model_provider="openai"', '-c', 'model_reasoning_effort="low"',
88
+ '-c', 'developer_instructions="Reply with hi. Do not use tools."', prompt,
89
+ ];
90
+ }
91
+
92
+ export function deliveryConfirmed(name, stdout) {
93
+ try {
94
+ if (name === 'claude') {
95
+ const result = JSON.parse(stdout);
96
+ return result.type === 'result' && result.subtype === 'success' && result.is_error === false && typeof result.result === 'string' && !!result.result.trim();
97
+ }
98
+ const events = stdout.trim().split('\n').map(line => JSON.parse(line));
99
+ return !events.some(event => ['error', 'turn.failed'].includes(event.type))
100
+ && events.some(event => event.type === 'turn.completed')
101
+ && events.some(event => event.type === 'item.completed' && event.item?.type === 'agent_message' && typeof event.item.text === 'string' && !!event.item.text.trim());
102
+ } catch { return false; }
103
+ }
104
+
105
+ export function firstStart(time, now = new Date()) {
106
+ if (time === undefined) return now.toISOString();
107
+ validateTime(time);
108
+ const [hour, minute] = time.split(':').map(Number);
109
+ const first = new Date(now);
110
+ first.setHours(hour, minute, 0, 0);
111
+ if (first <= now) first.setDate(first.getDate() + 1);
112
+ return first.toISOString();
113
+ }
114
+
115
+ export function nextDueAt(settings, last) {
116
+ const successAt = Date.parse(last?.lastSuccessAt);
117
+ const resetAt = Date.parse(last?.resetAt);
118
+ let due = Number.isFinite(resetAt) ? resetAt : Number.isFinite(successAt) ? successAt + FIVE_HOURS_MS : Date.parse(settings.firstAt || '1970-01-01T00:00:00Z');
119
+ const attemptAt = Date.parse(last?.at);
120
+ if (last?.ok === false && Number.isFinite(attemptAt)) due = Math.max(due, attemptAt + RETRY_DELAY_MS);
121
+ const pendingAt = Date.parse(last?.pendingAt);
122
+ if (Number.isFinite(pendingAt)) due = Math.max(due, pendingAt + FIVE_HOURS_MS);
123
+ const retryAt = Date.parse(last?.usageRetryAt);
124
+ if (Number.isFinite(retryAt)) due = Math.max(due, retryAt);
125
+ return due;
126
+ }
127
+
128
+ export async function prepareScheduled(provider, settings, last, { boot, now = Date.now(), usageReader = readUsage, env = process.env, cwd } = {}) {
129
+ const coolingDown = Math.max(
130
+ Date.parse(last.pendingAt) + FIVE_HOURS_MS || 0,
131
+ last.ok === false ? Date.parse(last.at) + RETRY_DELAY_MS || 0 : 0,
132
+ Date.parse(last.usageRetryAt) || 0,
133
+ );
134
+ if (now < coolingDown) return false;
135
+ if (!last.lastSuccessAt && !last.resetAt && now < Date.parse(settings.firstAt)) return false;
136
+ const deadline = Date.parse(last.resetAt);
137
+ const cachedAt = Date.parse(last.usage?.checkedAt);
138
+ const observationValid = observation => ['idle', 'active', 'blocked'].includes(observation?.state)
139
+ && Number.isFinite(Date.parse(observation.checkedAt))
140
+ && typeof observation.usedPercent === 'number' && Number.isFinite(observation.usedPercent)
141
+ && (observation.state === 'idle' ? observation.resetAt === null : Number.isFinite(Date.parse(observation.resetAt)));
142
+ const sameSession = observationValid(last.usage) && last.usage.boot === boot
143
+ && cachedAt >= (Date.parse(settings.scheduler?.installedAt) || 0);
144
+ // Latch a known deadline: re-reading a newly advanced quota window here could
145
+ // postpone the hello forever. A recorded reset produces one attempt.
146
+ if (Number.isFinite(deadline) && deadline <= now && sameSession) return true;
147
+ if (Number.isFinite(deadline) && deadline > now && sameSession) return false;
148
+ if (!sameSession || cachedAt > now || now - cachedAt >= RETRY_DELAY_MS) {
149
+ try {
150
+ const observation = await usageReader(provider, { env, cwd });
151
+ if (!observationValid(observation)) throw new Error('Provider usage response is invalid.');
152
+ last.usage = { ...observation, boot };
153
+ delete last.usageError; delete last.usageRetryAt; delete last.usageFailures; delete last.usageFallback;
154
+ } catch (error) {
155
+ last.usageError = `${provider.name} usage check unavailable: ${error.message || 'request failed'}`.slice(0, 200);
156
+ last.usageFailures = Math.min((last.usageFailures || 0) + 1, 1_000_000);
157
+ const delay = Number.isFinite(error.retryAfterMs) ? Math.max(RETRY_DELAY_MS, error.retryAfterMs) : RETRY_DELAY_MS;
158
+ last.usageRetryAt = new Date(now + Math.min(delay, 7 * 24 * 60 * 60 * 1000)).toISOString();
159
+ if (last.usageFailures < USAGE_FAILURE_LIMIT) return false;
160
+ last.usageFallback = true;
161
+ // Keep known reset deadlines and delivery cooldowns. A failed read never
162
+ // becomes an idle observation; this is explicitly the local timer mode.
163
+ return now >= nextDueAt(settings, { ...last, usageRetryAt: undefined });
164
+ }
165
+ }
166
+ const observedReset = Date.parse(last.usage.resetAt);
167
+ if (last.usage.state !== 'idle' && Number.isFinite(observedReset) && observedReset > now) {
168
+ last.resetAt = last.usage.resetAt;
169
+ return false;
170
+ }
171
+ delete last.resetAt;
172
+ if (Number.isFinite(deadline) && deadline <= now) return true;
173
+ // If a successful hi is followed by an idle reading (reporting lag, an
174
+ // unmetered plan, or a separate quota pool), do not send a hi on every tick.
175
+ return now >= nextDueAt(settings, last);
176
+ }
177
+
178
+ export async function acquireLock() {
179
+ await fs.mkdir(home(), { recursive: true, mode: 0o700 });
180
+ for (let attempt = 0; attempt < 2; attempt++) {
181
+ try {
182
+ const handle = await fs.open(file('run.lock'), 'wx', 0o600);
183
+ try { await handle.writeFile(String(process.pid)); }
184
+ catch (error) { await fs.rm(file('run.lock'), { force: true }); throw error; }
185
+ finally { await handle.close(); }
186
+ return () => fs.rm(file('run.lock'), { force: true });
187
+ } catch (error) {
188
+ if (error.code !== 'EEXIST') throw error;
189
+ // Only one process may reclaim a stale lock. Otherwise two reapers can
190
+ // accidentally unlink a new owner's live lock.
191
+ let recovery;
192
+ try { recovery = await fs.open(file('recovery.lock'), 'wx', 0o600); }
193
+ catch (failure) {
194
+ if (failure.code !== 'EEXIST') throw failure;
195
+ const owner = Number(await fs.readFile(file('recovery.lock'), 'utf8').catch(() => ''));
196
+ if (Number.isInteger(owner) && owner > 0) {
197
+ try { process.kill(owner, 0); }
198
+ catch (problem) {
199
+ if (problem.code === 'ESRCH') throw new Error(`Interrupted lock recovery. Confirm no HiAI process is running before removing ${file('recovery.lock')}.`);
200
+ }
201
+ } else {
202
+ const stat = await fs.stat(file('recovery.lock')).catch(() => null);
203
+ if (stat && Date.now() - stat.mtimeMs > RETRY_DELAY_MS) throw new Error(`Incomplete lock recovery. Confirm no HiAI process is running before removing ${file('recovery.lock')}.`);
204
+ }
205
+ return null;
206
+ }
207
+ try {
208
+ await recovery.writeFile(String(process.pid));
209
+ const pid = Number(await fs.readFile(file('run.lock'), 'utf8').catch(() => ''));
210
+ if (Number.isInteger(pid) && pid > 0) {
211
+ try { process.kill(pid, 0); return null; }
212
+ catch (failure) { if (failure.code !== 'ESRCH') return null; }
213
+ } else {
214
+ const stat = await fs.stat(file('run.lock')).catch(() => null);
215
+ if (stat && Date.now() - stat.mtimeMs < 300_000) return null;
216
+ }
217
+ await fs.rm(file('run.lock'), { force: true });
218
+ } finally {
219
+ await recovery.close();
220
+ await fs.rm(file('recovery.lock'), { force: true });
221
+ }
222
+ }
223
+ }
224
+ return null;
225
+ }
226
+
227
+ async function log(entry) {
228
+ const previous = await fs.readFile(file('runs.log'), 'utf8').catch(error => {
229
+ if (error.code === 'ENOENT') return ''; throw error;
230
+ });
231
+ const lines = [...previous.trim().split('\n').filter(Boolean), JSON.stringify(entry)].slice(-100);
232
+ await fs.writeFile(file('runs.log'), `${lines.join('\n')}\n`, { mode: 0o600 });
233
+ }
234
+
235
+ export async function run({ scheduled = false, dryRun = false, output = console.log, usageReader = readUsage, bootIdentifier } = {}) {
236
+ if (dryRun) {
237
+ const settings = await config();
238
+ for (const provider of settings.providers) output(JSON.stringify([provider.executable, ...providerArgs(provider)]));
239
+ return true;
240
+ }
241
+ const unlock = await acquireLock();
242
+ if (!unlock) { output('A ping is already running; skipped.'); return true; }
243
+ let workspace;
244
+ let scheduledCheck = false;
245
+ try {
246
+ const settings = await config();
247
+ if (scheduled && !settings.enabled) { output('Paused.'); return true; }
248
+ if (scheduled) {
249
+ await writeJSON('heartbeat.json', { at: new Date().toISOString(), phase: 'started' });
250
+ scheduledCheck = true;
251
+ }
252
+ const state = await readState();
253
+ const env = { ...process.env, PATH: settings.path || process.env.PATH };
254
+ for (const key of ['CODEX_HOME', 'CLAUDE_CONFIG_DIR']) if (settings.authPaths?.[key]) env[key] = settings.authPaths[key];
255
+ // Prefer the CLI's saved subscription login over inherited API keys.
256
+ for (const key of ['OPENAI_API_KEY', 'CODEX_API_KEY', 'ANTHROPIC_API_KEY', 'ANTHROPIC_AUTH_TOKEN']) delete env[key];
257
+ const boot = scheduled ? bootIdentifier || await bootId() : null;
258
+ let success = true;
259
+ for (const provider of settings.providers) {
260
+ state[provider.name] ||= {};
261
+ if (scheduled) {
262
+ workspace ||= await fs.mkdtemp(path.join(os.tmpdir(), 'hi-ai-'));
263
+ const ready = await prepareScheduled(provider, settings, state[provider.name], { boot, usageReader, env, cwd: workspace });
264
+ await writeJSON('state.json', state);
265
+ if (state[provider.name].usageFallback) output(`${provider.name}: five-hour timer fallback (${state[provider.name].usageFailures} consecutive usage checks failed).`);
266
+ if (!ready) {
267
+ output(state[provider.name].usageError || `${provider.name}: waiting for its usage window reset.`);
268
+ if (state[provider.name].usageError) success = false;
269
+ continue;
270
+ }
271
+ }
272
+ workspace ||= await fs.mkdtemp(path.join(os.tmpdir(), 'hi-ai-'));
273
+ state[provider.name] = { ...state[provider.name], pendingAt: new Date().toISOString() };
274
+ // If interrupted after delivery, the next run waits five hours rather
275
+ // than immediately repeating a message whose outcome is unknown.
276
+ await writeJSON('state.json', state);
277
+ let result;
278
+ try {
279
+ const { stdout, ...details } = await execute(provider.executable, providerArgs(provider), { cwd: workspace, env });
280
+ result = { ...details, confirmed: details.code === 0 && deliveryConfirmed(provider.name, stdout) };
281
+ } catch (error) {
282
+ result = { code: null, error: error.code || 'spawn failed' };
283
+ }
284
+ const ok = result.confirmed === true && !result.timedOut && !result.outputTooLarge;
285
+ const entry = { at: new Date().toISOString(), provider: provider.name, ok, ...result };
286
+ if (!ok && result.code === 0) entry.error = 'unconfirmed_response';
287
+ if (ok || (result.code !== 0 && !result.signal && !result.timedOut && !result.outputTooLarge)) delete state[provider.name].pendingAt;
288
+ state[provider.name] = { ...state[provider.name], ...entry, ...(ok ? { lastSuccessAt: entry.at } : {}) };
289
+ delete state[provider.name].resetAt;
290
+ // Persist each provider immediately: a later provider failure must not cause duplicate pings.
291
+ await writeJSON('state.json', state);
292
+ await log(entry);
293
+ output(ok ? `${provider.name}: hi sent.` : `${provider.name}: failed${result.timedOut ? ' (timed out)' : ''}. Check its CLI login, model access, and version.`);
294
+ if (!ok) success = false;
295
+ }
296
+ if (scheduledCheck) await writeJSON('heartbeat.json', { at: new Date().toISOString(), phase: 'finished', ok: success });
297
+ return success;
298
+ } catch (error) {
299
+ if (scheduledCheck) await writeJSON('heartbeat.json', { at: new Date().toISOString(), phase: 'failed' }).catch(() => {});
300
+ throw error;
301
+ } finally {
302
+ try { if (workspace) await fs.rm(workspace, { recursive: true, force: true }); }
303
+ finally { await unlock(); }
304
+ }
305
+ }
@@ -0,0 +1,35 @@
1
+ import { spawn } from 'node:child_process';
2
+
3
+ // No shell, no unbounded output, and terminate the whole process group on timeout.
4
+ export function execute(executable, args, { cwd, env = process.env, timeout = 120_000 } = {}) {
5
+ return new Promise((resolve, reject) => {
6
+ const child = spawn(executable, args, { cwd, env, detached: true, stdio: ['ignore', 'pipe', 'ignore'] });
7
+ let timedOut = false;
8
+ let outputTooLarge = false;
9
+ let size = 0;
10
+ const chunks = [];
11
+ const stop = () => { try { process.kill(-child.pid, 'SIGKILL'); } catch { /* Already exited. */ } };
12
+ const interrupt = signal => { stop(); cleanup(); process.kill(process.pid, signal); };
13
+ const onInterrupt = () => interrupt('SIGINT');
14
+ const onTerminate = () => interrupt('SIGTERM');
15
+ const cleanup = () => {
16
+ clearTimeout(timer);
17
+ process.off('SIGINT', onInterrupt); process.off('SIGTERM', onTerminate);
18
+ };
19
+ process.once('SIGINT', onInterrupt); process.once('SIGTERM', onTerminate);
20
+ child.stdout.on('data', chunk => {
21
+ size += chunk.length;
22
+ if (size > 262_144) { outputTooLarge = true; stop(); }
23
+ else chunks.push(chunk);
24
+ });
25
+ const timer = setTimeout(() => {
26
+ timedOut = true;
27
+ stop();
28
+ }, timeout);
29
+ child.on('error', error => { cleanup(); reject(error); });
30
+ child.on('close', (code, signal) => {
31
+ cleanup();
32
+ resolve({ code, signal, timedOut, outputTooLarge, stdout: Buffer.concat(chunks).toString('utf8') });
33
+ });
34
+ });
35
+ }
@@ -0,0 +1,177 @@
1
+ import * as fs from 'node:fs/promises';
2
+ import os from 'node:os';
3
+ import path from 'node:path';
4
+ import { fileURLToPath } from 'node:url';
5
+ import { spawnSync } from 'node:child_process';
6
+ import { home } from './core.mjs';
7
+ import { constants } from 'node:fs';
8
+
9
+ const label = 'io.hi-ai';
10
+ const start = '# hi-ai:begin';
11
+ const end = '# hi-ai:end';
12
+ const entry = fileURLToPath(new URL('../bin/hi-ai.mjs', import.meta.url));
13
+ const plistPath = () => path.join(os.homedir(), 'Library', 'LaunchAgents', `${label}.plist`);
14
+ const domain = () => `gui/${process.getuid()}`;
15
+
16
+ export async function nodeExecutable({ current = process.execPath, searchPath = process.env.PATH || '', aliases = ['/opt/homebrew/bin/node', '/usr/local/bin/node'] } = {}) {
17
+ const target = await fs.realpath(current);
18
+ // fnm's multishell links and other PATH shims can be temporary. Preserve the
19
+ // resolved installation path unless Homebrew's removable Cellar is involved.
20
+ const cellar = target.indexOf('/Cellar/');
21
+ if (cellar === -1) return target;
22
+ const prefix = target.slice(0, cellar);
23
+ const formula = target.slice(cellar + '/Cellar/'.length).split('/')[0];
24
+ const candidates = [
25
+ path.join(prefix, 'bin', 'node'), path.join(prefix, 'opt', formula, 'bin', 'node'),
26
+ ...aliases,
27
+ ...searchPath.split(path.delimiter).filter(Boolean).map(directory => path.resolve(directory, 'node')),
28
+ ].filter(candidate => !candidate.includes('/fnm_multishells/'));
29
+ const matches = [];
30
+ for (const candidate of new Set(candidates)) {
31
+ try {
32
+ await fs.access(candidate, constants.X_OK);
33
+ if (await fs.realpath(candidate) === target) matches.push(candidate);
34
+ } catch { /* Missing PATH entries are normal. */ }
35
+ }
36
+ // Keep an upgrade-stable alias instead of resolving it into Homebrew's Cellar.
37
+ return matches.find(candidate => !candidate.includes('/Cellar/')) || matches[0] || current;
38
+ }
39
+
40
+ export async function runtime() {
41
+ return { node: await nodeExecutable(), script: entry };
42
+ }
43
+
44
+ export function shellQuote(value) {
45
+ if (/[\r\n\0]/.test(value)) throw new Error('Scheduler paths cannot contain line breaks or NUL.');
46
+ return `'${value.replaceAll("'", "'\\''")}'`;
47
+ }
48
+
49
+ export function stripCron(value) {
50
+ const lines = value.split('\n');
51
+ const result = [];
52
+ let inside = false;
53
+ for (const line of lines) {
54
+ if (line === start) {
55
+ if (inside) throw new Error('Malformed hi-ai crontab block. Repair it with crontab -e.');
56
+ inside = true;
57
+ } else if (line === end) {
58
+ if (!inside) throw new Error('Malformed hi-ai crontab block. Repair it with crontab -e.');
59
+ inside = false;
60
+ } else if (!inside) result.push(line);
61
+ }
62
+ if (inside) throw new Error('Unclosed hi-ai crontab block. Repair it with crontab -e.');
63
+ return result.join('\n');
64
+ }
65
+
66
+ export function cronText(previous, { node, script = entry, directory = home(), searchPath = process.env.PATH || '' } = {}) {
67
+ if (!node) throw new Error('A Node executable is required to build the schedule.');
68
+ const args = ['env', `HI_AI_HOME=${directory}`, `PATH=${searchPath}`, node, script, 'run', '--scheduled'];
69
+ // cron treats percent specially even inside shell quotes.
70
+ const command = `${args.map(shellQuote).join(' ')} >/dev/null 2>&1`.replaceAll('%', '\\%');
71
+ const preserved = stripCron(previous).replace(/\n*$/, '');
72
+ return `${preserved ? `${preserved}\n` : ''}${start}\n* * * * * ${command}\n${end}\n`;
73
+ }
74
+
75
+ const xml = value => String(value).replaceAll('&', '&amp;').replaceAll('<', '&lt;').replaceAll('>', '&gt;').replaceAll('"', '&quot;').replaceAll("'", '&apos;');
76
+
77
+ export function plistText({ node, script = entry, directory = home(), searchPath = process.env.PATH || '' } = {}) {
78
+ if (!node) throw new Error('A Node executable is required to build the schedule.');
79
+ return `<?xml version="1.0" encoding="UTF-8"?>
80
+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
81
+ <plist version="1.0"><dict>
82
+ <key>Label</key><string>${label}</string>
83
+ <key>ProgramArguments</key><array>${[node, script, 'run', '--scheduled'].map(value => `<string>${xml(value)}</string>`).join('')}</array>
84
+ <key>EnvironmentVariables</key><dict><key>HI_AI_HOME</key><string>${xml(directory)}</string><key>PATH</key><string>${xml(searchPath)}</string></dict>
85
+ <key>StartInterval</key><integer>60</integer>
86
+ <key>ProcessType</key><string>Background</string>
87
+ </dict></plist>
88
+ `;
89
+ }
90
+
91
+ function command(executable, args, input) {
92
+ const result = spawnSync(executable, args, { input, encoding: 'utf8', timeout: 10_000 });
93
+ if (result.error) throw new Error(`${executable}: ${result.error.message}`);
94
+ return result;
95
+ }
96
+
97
+ function check(result, message) {
98
+ if (result.status !== 0) throw new Error(`${message}: ${result.stderr.trim() || `exit ${result.status}`}`);
99
+ }
100
+
101
+ function currentCron() {
102
+ const result = command('crontab', ['-l']);
103
+ if (result.status === 0) return result.stdout;
104
+ if (result.status === 1 && /no crontab/i.test(result.stderr)) return '';
105
+ check(result, 'Cannot read crontab (install cron and check user permissions)');
106
+ }
107
+
108
+ export async function registered(platform = process.platform) {
109
+ if (platform === 'darwin') return command('launchctl', ['print', `${domain()}/${label}`]).status === 0;
110
+ if (platform === 'linux') return currentCron().split('\n').includes(start);
111
+ throw new Error('Only macOS and Linux are supported.');
112
+ }
113
+
114
+ export async function install(platform = process.platform, options) {
115
+ options ||= await runtime();
116
+ if (platform === 'linux') {
117
+ check(command('crontab', ['-'], cronText(currentCron(), options)), 'Cannot install crontab');
118
+ } else if (platform === 'darwin') {
119
+ const target = plistPath();
120
+ await fs.mkdir(path.dirname(target), { recursive: true });
121
+ const previous = await fs.readFile(target, 'utf8').catch(error => {
122
+ if (error.code === 'ENOENT') return null; throw error;
123
+ });
124
+ const wasRegistered = await registered(platform);
125
+ if (wasRegistered) check(command('launchctl', ['bootout', `${domain()}/${label}`]), 'Cannot unload old schedule');
126
+ try {
127
+ await fs.writeFile(target, plistText(options), { mode: 0o600 });
128
+ check(command('launchctl', ['bootstrap', domain(), target]), 'Cannot load schedule');
129
+ } catch (error) {
130
+ if (previous !== null) {
131
+ await fs.writeFile(target, previous, { mode: 0o600 });
132
+ if (wasRegistered) check(command('launchctl', ['bootstrap', domain(), target]), 'Cannot restore previous schedule');
133
+ } else await fs.rm(target, { force: true });
134
+ throw error;
135
+ }
136
+ } else throw new Error('Only macOS and Linux are supported.');
137
+ }
138
+
139
+ export async function inspect(settings, platform = process.platform) {
140
+ const issues = [];
141
+ let active;
142
+ let actualNode;
143
+ let lastExitCode;
144
+ if (platform === 'darwin') {
145
+ const job = command('launchctl', ['print', `${domain()}/${label}`]);
146
+ active = job.status === 0;
147
+ if (active) {
148
+ actualNode = job.stdout.match(/^\s*program = (.+)$/m)?.[1]?.trim();
149
+ const code = job.stdout.match(/^[\t ]*last exit code = (\d+)(?:[\t ]*:[^\r\n]+)?[\t ]*$/m)?.[1];
150
+ if (code !== undefined) lastExitCode = Number(code);
151
+ }
152
+ } else active = await registered(platform);
153
+ const node = actualNode || settings.scheduler?.node;
154
+ const script = settings.scheduler?.script;
155
+ for (const [name, target, mode] of [['Node executable', node, constants.X_OK], ['HiAI script', script, constants.R_OK]]) {
156
+ if (!target) { issues.push(`${name} path is unknown; rerun hi-ai setup.`); continue; }
157
+ try { await fs.access(target, mode); }
158
+ catch { issues.push(`${name} is missing or inaccessible: ${target}. Rerun hi-ai setup.`); }
159
+ }
160
+ for (const provider of settings.providers) {
161
+ try { await fs.access(provider.executable, constants.X_OK); }
162
+ catch { issues.push(`${provider.name} executable is missing or inaccessible: ${provider.executable}.`); }
163
+ }
164
+ if (lastExitCode !== undefined && lastExitCode !== 0) issues.push(`launchd's last exit code was ${lastExitCode}.`);
165
+ return { registered: active, issues, lastExitCode };
166
+ }
167
+
168
+ export async function remove(platform = process.platform) {
169
+ if (platform === 'linux') {
170
+ const previous = currentCron();
171
+ const next = stripCron(previous);
172
+ if (next !== previous) check(command('crontab', ['-'], next), 'Cannot remove schedule');
173
+ } else if (platform === 'darwin') {
174
+ if (await registered(platform)) check(command('launchctl', ['bootout', `${domain()}/${label}`]), 'Cannot unload schedule');
175
+ await fs.rm(plistPath(), { force: true });
176
+ } else throw new Error('Only macOS and Linux are supported.');
177
+ }
package/lib/usage.mjs ADDED
@@ -0,0 +1,167 @@
1
+ import * as fs from 'node:fs/promises';
2
+ import { spawn } from 'node:child_process';
3
+ import { execute } from './process.mjs';
4
+
5
+ const packageVersion = JSON.parse(await fs.readFile(new URL('../package.json', import.meta.url), 'utf8')).version;
6
+
7
+ function window(value, names, now) {
8
+ if (value === null) return { reset: null, used: 0 };
9
+ if (!value || typeof value !== 'object' || Array.isArray(value)) throw new Error('Usage window is missing.');
10
+ if (!Object.hasOwn(value, names.used) || !Object.hasOwn(value, names.reset)) throw new Error('Usage window fields are missing.');
11
+ const used = value[names.used];
12
+ const raw = value[names.reset];
13
+ const reset = raw == null ? null : names.seconds ? Number(raw) * 1000 : Date.parse(raw);
14
+ if (reset !== null && (!Number.isFinite(reset) || reset <= 0)) throw new Error('Usage reset time is invalid.');
15
+ if (used == null && reset === null) return { reset: null, used: 0 };
16
+ if (typeof used !== 'number' || !Number.isFinite(used) || used < 0 || used > 100) throw new Error('Usage percentage is invalid.');
17
+ if (used > 0 && reset === null) throw new Error('Used quota has no reset time.');
18
+ return { reset: reset && reset > now ? reset : null, used };
19
+ }
20
+
21
+ function normalize(primary, secondary, now, source) {
22
+ const blocked = secondary?.used >= 100 && secondary.reset ? secondary.reset : null;
23
+ const reset = blocked ? Math.max(blocked, primary.reset || 0) : primary.reset;
24
+ return {
25
+ source, checkedAt: new Date(now).toISOString(),
26
+ state: reset ? blocked ? 'blocked' : 'active' : 'idle',
27
+ resetAt: reset ? new Date(reset).toISOString() : null,
28
+ usedPercent: primary.used,
29
+ };
30
+ }
31
+
32
+ const months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
33
+
34
+ function localParts(formatter, time) {
35
+ const parts = Object.fromEntries(formatter.formatToParts(time).map(part => [part.type, part.value]));
36
+ return ['year', 'month', 'day', 'hour', 'minute'].map(key => Number(parts[key]));
37
+ }
38
+
39
+ // Resolve a wall-clock time in the reported IANA timezone, independently of the
40
+ // host timezone. Reject DST gaps and choose the later occurrence of a fold.
41
+ function wallTime(formatter, parts) {
42
+ const [year, month, day, hour, minute] = parts;
43
+ const wall = Date.UTC(year, month - 1, day, hour, minute);
44
+ const candidates = new Set();
45
+ for (const shift of [-86400_000, 0, 86400_000]) {
46
+ const sample = wall + shift;
47
+ const local = localParts(formatter, sample);
48
+ const offset = Date.UTC(local[0], local[1] - 1, ...local.slice(2)) - sample;
49
+ const candidate = wall - offset;
50
+ if (localParts(formatter, candidate).every((value, index) => value === parts[index])) candidates.add(candidate);
51
+ }
52
+ return candidates.size ? Math.max(...candidates) : NaN;
53
+ }
54
+
55
+ function claudeReset(text, now, maximumDelay) {
56
+ const match = /^(?:(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) (\d{1,2}) at )?(\d{1,2})(?::(\d{2}))?\s*(am|pm) \(([^()]+)\)$/i.exec(text);
57
+ if (!match) throw new Error('Claude /usage reset format is unrecognized.');
58
+ const [, monthName, dayText, hourText, minuteText = '0', period, zone] = match;
59
+ const hour = Number(hourText); const minute = Number(minuteText);
60
+ if (hour < 1 || hour > 12 || minute > 59) throw new Error('Claude /usage reset time is invalid.');
61
+ let formatter;
62
+ 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
+ catch { throw new Error('Claude /usage timezone is invalid.'); }
64
+ const current = localParts(formatter, now);
65
+ const dates = monthName
66
+ ? [-1, 0, 1].map(offset => [current[0] + offset, months.findIndex(month => month.toLowerCase() === monthName.toLowerCase()) + 1, Number(dayText)])
67
+ : [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
+ const candidates = dates.map(date => wallTime(formatter, [...date, hour % 12 + (period.toLowerCase() === 'pm' ? 12 : 0), minute]) + 60_000)
69
+ .filter(time => Number.isFinite(time) && time >= now - 60_000 && time <= now + maximumDelay);
70
+ if (!candidates.length) throw new Error('Claude /usage reset date is invalid or out of range.');
71
+ return Math.min(...candidates);
72
+ }
73
+
74
+ function claudeWindow(line, now, maximumDelay) {
75
+ // Only explicit idle text is accepted; a missing line or bare 0% is unknown.
76
+ if (/^(?:not started|no active (?:session|usage window))\.?$/i.test(line)) return { reset: null, used: 0 };
77
+ const match = /^(\d+(?:\.\d+)?)% used · resets (.+)$/.exec(line);
78
+ if (!match || Number(match[1]) > 100) throw new Error('Claude /usage window is unrecognized.');
79
+ const reset = claudeReset(match[2], now, maximumDelay);
80
+ return { reset: reset > now ? reset : null, used: Number(match[1]) };
81
+ }
82
+
83
+ export function normalizeClaudeUsage(raw, now = Date.now()) {
84
+ if (raw?.type !== 'result' || raw.subtype !== 'success' || raw.is_error !== false || raw.local_command !== 'usage'
85
+ || raw.num_turns !== 0 || raw.total_cost_usd !== 0 || raw.duration_api_ms !== 0
86
+ || !raw.modelUsage || Object.keys(raw.modelUsage).length || typeof raw.result !== 'string') {
87
+ throw new Error('Claude did not return a local, zero-inference /usage result.');
88
+ }
89
+ const lines = raw.result.split(/\r?\n/);
90
+ const session = lines.filter(line => line.startsWith('Current session: '));
91
+ if (session.length !== 1) throw new Error('Claude /usage has no unique current-session line.');
92
+ const primary = claudeWindow(session[0].slice('Current session: '.length), now, 6 * 3600_000);
93
+ const weekly = lines.filter(line => line.startsWith('Current week (all models): '));
94
+ if (weekly.length > 1) throw new Error('Claude /usage has duplicate weekly windows.');
95
+ const secondary = weekly.length ? claudeWindow(weekly[0].slice('Current week (all models): '.length), now, 8 * 86400_000) : null;
96
+ return normalize(primary, secondary, now, 'claude-cli-usage');
97
+ }
98
+
99
+ export function normalizeCodexUsage(raw, now = Date.now()) {
100
+ const limits = raw?.rateLimitsByLimitId?.codex || raw?.rateLimits;
101
+ if (!limits || !Object.hasOwn(limits, 'primary')) throw new Error('Codex usage response has no primary window.');
102
+ const names = { used: 'usedPercent', reset: 'resetsAt', seconds: true };
103
+ return normalize(window(limits.primary, names, now), limits.secondary == null ? null : window(limits.secondary, names, now), now, 'codex-app-server');
104
+ }
105
+
106
+ export async function readClaudeUsage(provider, { env = process.env, cwd, runner = execute } = {}) {
107
+ // The unmodified CLI owns all authentication. An invalid model prevents an
108
+ // inference request if a future CLI stops recognizing /usage locally.
109
+ const result = await runner(provider.executable, ['-p', '/usage', '--safe-mode', '--no-session-persistence', '--output-format', 'json', '--model', 'hi-ai-usage-check-only-invalid-model'], { env, cwd, timeout: 30_000 });
110
+ if (result.code !== 0 || result.timedOut || result.outputTooLarge) throw new Error('Claude /usage command failed. Check the CLI login and version.');
111
+ let raw;
112
+ try { raw = JSON.parse(result.stdout); } catch { throw new Error('Claude /usage returned invalid JSON.'); }
113
+ return normalizeClaudeUsage(raw);
114
+ }
115
+
116
+ export function readCodexUsage(provider, { env = process.env, cwd } = {}) {
117
+ return new Promise((resolve, reject) => {
118
+ 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;
120
+ const finish = (error, result) => {
121
+ if (done) return;
122
+ done = true; clearTimeout(timer);
123
+ process.off('SIGINT', onInterrupt); process.off('SIGTERM', onTerminate);
124
+ child.stdin.destroy(); child.stdout.destroy();
125
+ try { process.kill(-child.pid, 'SIGKILL'); } catch { /* Already exited. */ }
126
+ if (error) reject(error); else resolve(result);
127
+ };
128
+ const onInterrupt = () => { finish(new Error('Usage check interrupted.')); process.kill(process.pid, 'SIGINT'); };
129
+ const onTerminate = () => { finish(new Error('Usage check interrupted.')); process.kill(process.pid, 'SIGTERM'); };
130
+ const timer = setTimeout(() => finish(new Error('Codex usage check timed out.')), 20_000);
131
+ const send = message => child.stdin.write(`${JSON.stringify(message)}\n`);
132
+ process.once('SIGINT', onInterrupt); process.once('SIGTERM', onTerminate);
133
+ child.stdin.on('error', () => finish(new Error('Codex usage connection failed.')));
134
+ child.on('error', () => finish(new Error('Cannot start Codex usage reader.')));
135
+ child.on('close', () => { if (!done) finish(new Error('Codex usage reader exited before returning limits.')); });
136
+ child.stdout.on('data', chunk => {
137
+ bytes += chunk.length;
138
+ if (bytes > 262_144) { finish(new Error('Codex usage response is too large.')); return; }
139
+ buffer += chunk.toString('utf8');
140
+ let index;
141
+ while (!done && (index = buffer.indexOf('\n')) !== -1) {
142
+ const line = buffer.slice(0, index); buffer = buffer.slice(index + 1);
143
+ let message;
144
+ try { message = JSON.parse(line); } catch { finish(new Error('Invalid Codex usage response.')); return; }
145
+ if (message.id !== 1 && message.id !== 2) continue;
146
+ if (message.error) { finish(new Error('Codex usage unavailable. Check the subscription login.')); return; }
147
+ if (message.id === 1) { send({ method: 'initialized', params: {} }); send({ id: 2, method: 'account/rateLimits/read' }); }
148
+ else {
149
+ try { finish(null, normalizeCodexUsage(message.result)); }
150
+ catch (error) { finish(error); }
151
+ }
152
+ }
153
+ });
154
+ send({ id: 1, method: 'initialize', params: { clientInfo: { name: 'hi_ai', title: 'HiAI', version: packageVersion } } });
155
+ });
156
+ }
157
+
158
+ export async function bootId() {
159
+ if (process.platform === 'linux') return (await fs.readFile('/proc/sys/kernel/random/boot_id', 'utf8')).trim();
160
+ const result = await execute('/usr/sbin/sysctl', ['-n', 'kern.boottime'], { timeout: 5000 });
161
+ if (result.code !== 0 || !result.stdout.trim()) throw new Error('Cannot determine system boot time.');
162
+ return result.stdout.trim();
163
+ }
164
+
165
+ export async function readUsage(provider, options) {
166
+ return provider.name === 'claude' ? readClaudeUsage(provider, options) : readCodexUsage(provider, options);
167
+ }
package/package.json CHANGED
@@ -1,6 +1,38 @@
1
1
  {
2
2
  "name": "hi-ai-cli",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0-beta.0",
4
+ "description": "A usage-aware hello at reset for Claude Code and Codex on macOS and Linux.",
5
+ "author": "anik-jha",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/anik-jha/hi-ai.git"
9
+ },
10
+ "homepage": "https://github.com/anik-jha/hi-ai#readme",
11
+ "bugs": {
12
+ "url": "https://github.com/anik-jha/hi-ai/issues"
13
+ },
14
+ "type": "module",
15
+ "bin": {
16
+ "hi-ai": "bin/hi-ai.mjs"
17
+ },
18
+ "engines": {
19
+ "node": ">=22"
20
+ },
21
+ "os": [
22
+ "darwin",
23
+ "linux"
24
+ ],
25
+ "files": [
26
+ "bin/",
27
+ "lib/",
28
+ "README.md",
29
+ "LICENSE"
30
+ ],
31
+ "scripts": {
32
+ "test": "node --test",
33
+ "test:live": "node scripts/live-smoke.mjs",
34
+ "test:live:scheduled": "node scripts/live-scheduled-smoke.mjs",
35
+ "test:docker": "docker build -f Dockerfile.test -t hi-ai-test . && docker run --rm hi-ai-test"
36
+ },
37
+ "license": "MIT"
38
+ }