hi-ai-cli 0.1.1 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +31 -27
- package/bin/hi-ai.mjs +17 -11
- package/lib/core.mjs +51 -9
- package/lib/usage.mjs +113 -3
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -4,16 +4,16 @@
|
|
|
4
4
|
|
|
5
5
|
[Source](https://github.com/anik-jha/hi-ai) · [Issues](https://github.com/anik-jha/hi-ai/issues) · [MIT license](LICENSE)
|
|
6
6
|
|
|
7
|
-
A small, usage-aware utility for **Claude Code and
|
|
7
|
+
A small, usage-aware utility for **Claude Code, Codex, and Antigravity**, on macOS and Linux. Install it once, choose your providers, and let it follow their actual usage windows.
|
|
8
8
|
|
|
9
9
|
- **No active window:** send a minimal hello to start one.
|
|
10
10
|
- **An active window:** save the provider's reported reset time and send the next hello when that time arrives.
|
|
11
11
|
- **After a restart:** read usage again before deciding, rather than blindly starting another five-hour timer.
|
|
12
12
|
- **Usage unavailable:** retry first; after three consecutive failures, use a five-hour timer until usage reads recover.
|
|
13
13
|
|
|
14
|
-
HiAI uses lightweight models by default: Claude's `haiku` alias
|
|
14
|
+
HiAI uses lightweight models by default: Claude's `haiku` alias, Codex's `gpt-6-luna`, and Antigravity's `gemini-4-hydrogen-low`. It has no npm runtime dependencies, GUI, or HiAI account.
|
|
15
15
|
|
|
16
|
-
**Release status: 0.
|
|
16
|
+
**Release status: 0.2.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
|
|
|
@@ -21,28 +21,29 @@ Requires **Node.js 22+** and the selected provider CLIs, signed into your subscr
|
|
|
21
21
|
|
|
22
22
|
- [Claude Code](https://code.claude.com/docs/en/overview): `claude auth login`.
|
|
23
23
|
- [Standalone Codex CLI](https://learn.chatgpt.com/docs/cli): `codex login`. HiAI skips copies inside versioned IDE extension folders.
|
|
24
|
+
- [Google Antigravity CLI](https://antigravity.google/docs/getting-started): sign in once with `agy`. HiAI searches `PATH` first and falls back to `~/.gemini/bin/agy` and `~/.local/bin/agy`. On Linux, `agy` uses the OS keyring on desktop sessions and file-based token storage over SSH (which `hi-ai setup` preserves for `cron` via `AGY_CLI_FORCE_FILE_TOKEN_STORAGE=1`).
|
|
24
25
|
- On Linux: `crontab` and a running cron service. Debian/Ubuntu: `sudo apt install cron && sudo systemctl enable --now cron`.
|
|
25
26
|
|
|
26
27
|
```sh
|
|
27
28
|
npm install -g hi-ai-cli
|
|
28
|
-
hi-ai setup --providers claude,codex
|
|
29
|
+
hi-ai setup --providers claude,codex,antigravity
|
|
29
30
|
```
|
|
30
31
|
|
|
31
32
|
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
|
|
|
33
|
-
Use `--providers claude
|
|
34
|
+
Use `--providers claude`, `--providers codex`, or `--providers antigravity` (`agy` is accepted as an alias) for any subset. Without `--providers`, setup offers the detected CLIs interactively.
|
|
34
35
|
|
|
35
36
|
To delay the first automatic check:
|
|
36
37
|
|
|
37
38
|
```sh
|
|
38
|
-
hi-ai setup --time 06:00 --providers claude,codex
|
|
39
|
+
hi-ai setup --time 06:00 --providers claude,codex,antigravity
|
|
39
40
|
```
|
|
40
41
|
|
|
41
42
|
`--time` means the next occurrence of that local time. Subsequent hellos follow provider resets.
|
|
42
43
|
|
|
43
44
|
## Why use HiAI instead of a cron command?
|
|
44
45
|
|
|
45
|
-
Cron can launch a command. HiAI adds the account-state and recovery logic around that command, with one setup for
|
|
46
|
+
Cron can launch a command. HiAI adds the account-state and recovery logic around that command, with one setup for all three providers and the same management commands on macOS and Linux.
|
|
46
47
|
|
|
47
48
|
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
|
|
|
@@ -51,7 +52,7 @@ A cron expression such as `0 */5 * * *` runs at 00:00, 05:00, 10:00, 15:00, and
|
|
|
51
52
|
| Avoid an unnecessary startup hello | Check whether a usage window is already active. |
|
|
52
53
|
| Align with existing usage | Save the reset time returned by the provider. |
|
|
53
54
|
| Recover after restart | Refresh usage for the current boot before deciding. |
|
|
54
|
-
| Run
|
|
55
|
+
| Run multiple providers | Independent usage state, models, and deadlines. |
|
|
55
56
|
| Confirm delivery | Validate structured CLI responses before recording success. |
|
|
56
57
|
| Prevent overlapping calls | Share a lock across scheduled runs, manual runs, and settings changes. |
|
|
57
58
|
| Handle uncertainty | Apply timeouts, request backoff, and delivery cooldowns. |
|
|
@@ -74,8 +75,9 @@ npm uninstall -g hi-ai-cli
|
|
|
74
75
|
Change providers or models by rerunning setup:
|
|
75
76
|
|
|
76
77
|
```sh
|
|
77
|
-
hi-ai setup --providers claude,codex \
|
|
78
|
-
--claude-model haiku --codex-model gpt-6-luna
|
|
78
|
+
hi-ai setup --providers claude,codex,antigravity \
|
|
79
|
+
--claude-model haiku --codex-model gpt-6-luna \
|
|
80
|
+
--antigravity-model gemini-4-hydrogen-low
|
|
79
81
|
```
|
|
80
82
|
|
|
81
83
|
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.
|
|
@@ -104,9 +106,11 @@ The command uses a deliberately invalid model name, so a CLI that stops recogniz
|
|
|
104
106
|
|
|
105
107
|
**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
108
|
|
|
107
|
-
|
|
109
|
+
**Antigravity:** HiAI runs the installed, unmodified `agy -p /usage --output-format json` command with session-only settings (`--settings`) and requires a local `usage` command response with zero turns and zero tokens. Unlike Claude Code, `agy` rejects unknown `--model` names before running local slash commands, so an invalid-model guard cannot be used; if a future CLI ever turns `/usage` into a model request (`num_turns > 0` or any nonzero token count), HiAI rejects the reading and pauses scheduled Antigravity usage checks and hellos for seven days rather than retrying every five minutes. A reply that only changes format, with zero turns and zero tokens, counts as an ordinary failed read. Antigravity owns sign-in and credential refresh; HiAI does not read keyring entries or credential files. Antigravity groups quota into `Gemini Models` and `Claude and GPT models`, each with five-hour and weekly buckets; HiAI selects the quota group matching `--antigravity-model` (falling back to the weekly bucket on weekly-only plans). Like Codex, an unused Antigravity bucket reports `remaining_fraction: 1` with a reset time that advances on each read, so HiAI rechecks two seconds later when `remaining_fraction` is `1`. An unused bucket can instead report the zero timestamp (`1970-01-01T00:00:00Z`) as its reset, which HiAI reads as idle without a recheck.
|
|
108
110
|
|
|
109
|
-
|
|
111
|
+
Custom `CLAUDE_CONFIG_DIR`, `CODEX_HOME`, Linux D-Bus/runtime (`XDG_RUNTIME_DIR`, `DBUS_SESSION_BUS_ADDRESS`), and Antigravity auth/storage (`AGY_ADC_AUTH`, `AGY_CLI_FORCE_FILE_TOKEN_STORAGE`, `GOOGLE_APPLICATION_CREDENTIALS`, `CLOUDSDK_CONFIG`) variables are retained by setup when present. Linux SSH setups automatically record `AGY_CLI_FORCE_FILE_TOKEN_STORAGE=1` so `cron` reads the same file-based token store as SSH sign-in; if you signed in on a Linux desktop (keyring) and later run `setup` over SSH, prefix `AGY_CLI_FORCE_FILE_TOKEN_STORAGE=0` to keep keyring mode. Inherited API-key variables (`OPENAI_API_KEY`, `CODEX_API_KEY`, `ANTHROPIC_API_KEY`, `ANTHROPIC_AUTH_TOKEN`, `GEMINI_API_KEY`, `GOOGLE_API_KEY`) are removed from subprocesses to prefer saved subscription logins; check that your CLIs use the intended account.
|
|
112
|
+
|
|
113
|
+
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. Antigravity disables slash commands, enables its sandbox, enforces `strict` tool permissions (which headless print mode soft-denies without executing), and disables paid AI credit overages (`useG1Credits: false`) for the invocation. Provider output is inspected in memory, not saved to the log.
|
|
110
114
|
|
|
111
115
|
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
116
|
|
|
@@ -123,33 +127,33 @@ Setup, pause, resume, and uninstall refuse to change settings while a check or h
|
|
|
123
127
|
From the repository:
|
|
124
128
|
|
|
125
129
|
```sh
|
|
126
|
-
npm test
|
|
127
|
-
npm run test:docker
|
|
128
|
-
HI_AI_TEST_LAUNCHD=1 node --test test/macos-launchd.test.mjs
|
|
130
|
+
npm test # unit suite
|
|
131
|
+
npm run test:docker # npm archive + real cron in Debian, about two minutes
|
|
132
|
+
HI_AI_TEST_LAUNCHD=1 node --test test/macos-launchd.test.mjs # real launchd timer, macOS only
|
|
129
133
|
```
|
|
130
134
|
|
|
131
|
-
|
|
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:
|
|
135
|
+
These use stand-in provider CLIs, so they read no real credentials and send no paid requests. Live checks use your real accounts and consume usage:
|
|
136
136
|
|
|
137
137
|
```sh
|
|
138
|
-
HI_AI_LIVE_TEST=1 npm run test:live
|
|
139
|
-
HI_AI_LIVE_TEST=1 npm run test:live:scheduled
|
|
138
|
+
HI_AI_LIVE_TEST=1 npm run test:live # one real hello per provider
|
|
139
|
+
HI_AI_LIVE_TEST=1 npm run test:live:scheduled # macOS: temporary schedule with a real usage read
|
|
140
140
|
```
|
|
141
141
|
|
|
142
|
-
`test:live
|
|
142
|
+
`test:live:scheduled` removes its temporary schedule afterwards and refuses to replace an existing HiAI LaunchAgent.
|
|
143
143
|
|
|
144
144
|
## Validation
|
|
145
145
|
|
|
146
|
-
|
|
146
|
+
Tested on live accounts, one machine per platform:
|
|
147
147
|
|
|
148
|
-
|
|
148
|
+
| | macOS (`launchd`) | Linux (`cron`) |
|
|
149
|
+
|---|---|---|
|
|
150
|
+
| Claude Code | Usage reads, scheduled hellos, full reset cycle | Usage reads, scheduled hellos, full reset cycle |
|
|
151
|
+
| Codex | Usage reads, scheduled hellos, full reset cycle | Usage reads, scheduled hello at reset |
|
|
152
|
+
| Antigravity | Usage reads, manual hello | Usage reads, token renewal, manual hello |
|
|
149
153
|
|
|
150
|
-
|
|
154
|
+
macOS used Claude Code 2.1.311, Codex CLI 0.167.1, and Antigravity CLI 1.5.16. Linux (Ubuntu 24.04, aarch64, signed in over SSH) used Claude Code 2.1.322, Codex CLI 0.166.0, and Antigravity CLI 1.5.17.
|
|
151
155
|
|
|
152
|
-
|
|
156
|
+
Not yet tested: an Antigravity hello sent by the scheduler on either platform, and Antigravity on a Linux desktop that keeps its sign-in in the keyring. A confirmed hello does not prove that a provider replenishes quota.
|
|
153
157
|
|
|
154
158
|
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.
|
|
155
159
|
|
package/bin/hi-ai.mjs
CHANGED
|
@@ -2,13 +2,14 @@
|
|
|
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, Interrupted, nextDueAt, readJSON, readState, run, writeJSON } from '../lib/core.mjs';
|
|
5
|
+
import { acquireLock, captureAuthPaths, 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
|
-
const help = `hi-ai — a tiny scheduled hello for Claude Code and
|
|
8
|
+
const help = `hi-ai — a tiny scheduled hello for Claude Code, Codex, and Antigravity
|
|
9
9
|
|
|
10
|
-
setup [--time HH:MM] [--providers claude,codex]
|
|
10
|
+
setup [--time HH:MM] [--providers claude,codex,antigravity]
|
|
11
11
|
[--claude-model haiku] [--codex-model gpt-6-luna]
|
|
12
|
+
[--antigravity-model gemini-4-hydrogen-low]
|
|
12
13
|
run [--dry-run] Send one hello now, or preview the CLI arguments
|
|
13
14
|
status Show the schedule and last results
|
|
14
15
|
pause Remove the schedule; keep settings
|
|
@@ -22,12 +23,14 @@ Requires Node.js 22+, a logged-in provider CLI, and cron on Linux.
|
|
|
22
23
|
Pings consume usage; they cannot force a quota reset.
|
|
23
24
|
`;
|
|
24
25
|
|
|
26
|
+
const providerAlias = name => name === 'agy' ? 'antigravity' : name;
|
|
27
|
+
|
|
25
28
|
async function main() {
|
|
26
29
|
const { values, positionals } = parseArgs({
|
|
27
30
|
allowPositionals: true,
|
|
28
31
|
options: {
|
|
29
32
|
time: { type: 'string' }, providers: { type: 'string' },
|
|
30
|
-
'claude-model': { type: 'string' }, 'codex-model': { type: 'string' },
|
|
33
|
+
'claude-model': { type: 'string' }, 'codex-model': { type: 'string' }, 'antigravity-model': { type: 'string' },
|
|
31
34
|
'dry-run': { type: 'boolean' }, scheduled: { type: 'boolean' },
|
|
32
35
|
help: { type: 'boolean', short: 'h' }, version: { type: 'boolean', short: 'v' },
|
|
33
36
|
},
|
|
@@ -36,7 +39,7 @@ async function main() {
|
|
|
36
39
|
if (values.help || !positionals.length) { console.log(help); return; }
|
|
37
40
|
if (positionals.length !== 1) throw new Error('Expected one command. See hi-ai --help.');
|
|
38
41
|
const action = positionals[0];
|
|
39
|
-
const allowed = action === 'setup' ? ['time', 'providers', 'claude-model', 'codex-model']
|
|
42
|
+
const allowed = action === 'setup' ? ['time', 'providers', 'claude-model', 'codex-model', 'antigravity-model']
|
|
40
43
|
: action === 'run' ? ['dry-run', 'scheduled'] : [];
|
|
41
44
|
for (const key of Object.keys(values)) if (!allowed.includes(key)) throw new Error(`--${key} is not valid for ${action}.`);
|
|
42
45
|
|
|
@@ -63,18 +66,18 @@ async function main() {
|
|
|
63
66
|
} finally { reader.close(); }
|
|
64
67
|
}
|
|
65
68
|
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
|
|
69
|
+
const selected = names === undefined || names === '' ? detected.map(p => p.name) : [...new Set(names.split(',').map(name => providerAlias(name.trim())))];
|
|
70
|
+
if (!selected.length) throw new Error('No provider CLIs found on PATH. Install Claude Code, Codex, or Antigravity CLI and log in first.');
|
|
68
71
|
const providers = selected.map(name => {
|
|
69
|
-
if (!Object.hasOwn(defaults, name)) throw new Error(`Unknown provider: ${name}. Choose claude,codex.`);
|
|
72
|
+
if (!Object.hasOwn(defaults, name)) throw new Error(`Unknown provider: ${name}. Choose claude,codex,antigravity.`);
|
|
70
73
|
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.`);
|
|
74
|
+
if (!executable) throw new Error(`${name === 'antigravity' ? 'antigravity (agy)' : name} is not on PATH. Install it and log in first.`);
|
|
72
75
|
const model = values[`${name}-model`] ?? previous?.providers.find(p => p.name === name)?.model ?? defaults[name];
|
|
73
76
|
if (!model.trim() || model.startsWith('-')) throw new Error(`Invalid ${name} model.`);
|
|
74
77
|
return { name, executable, model };
|
|
75
78
|
});
|
|
76
79
|
const runtime = await scheduler.runtime();
|
|
77
|
-
const authPaths =
|
|
80
|
+
const authPaths = captureAuthPaths(providers);
|
|
78
81
|
const next = { firstAt, providers, path: process.env.PATH, authPaths, enabled: true, scheduler: { ...runtime, installedAt: new Date().toISOString() } };
|
|
79
82
|
await writeJSON('config.json', next);
|
|
80
83
|
try { await scheduler.install(undefined, runtime); }
|
|
@@ -110,7 +113,10 @@ async function main() {
|
|
|
110
113
|
console.log(` Usage: ${last?.usage ? `${last.usage.state} (${last.usage.usedPercent}% used)` : 'awaiting first usage check'}.`);
|
|
111
114
|
if (last?.usageError) console.log(` ${last.usageError}`);
|
|
112
115
|
if (last?.usageFallback) console.log(` Automatic mode: five-hour timer fallback (${last.usageFailures} consecutive usage checks failed).`);
|
|
113
|
-
|
|
116
|
+
const nextLabel = !last?.usage && !last?.lastSuccessAt
|
|
117
|
+
? (Date.parse(last?.usageRetryAt) > Date.now() ? `after usage check retry (${new Date(due).toLocaleString()})` : 'after checking provider usage')
|
|
118
|
+
: due <= Date.now() ? 'due now' : new Date(due).toLocaleString();
|
|
119
|
+
console.log(` Next hello: ${nextLabel}`);
|
|
114
120
|
}
|
|
115
121
|
console.log(`Settings and recent results: ${home()}`);
|
|
116
122
|
} else if (action === 'pause') {
|
package/lib/core.mjs
CHANGED
|
@@ -3,10 +3,31 @@ import * as fs from 'node:fs/promises';
|
|
|
3
3
|
import os from 'node:os';
|
|
4
4
|
import path from 'node:path';
|
|
5
5
|
import { execute, Interrupted } from './process.mjs';
|
|
6
|
-
import { bootId, readUsage } from './usage.mjs';
|
|
6
|
+
import { ANTIGRAVITY_SETTINGS, bootId, readUsage } from './usage.mjs';
|
|
7
7
|
export { execute, Interrupted } from './process.mjs';
|
|
8
8
|
|
|
9
|
-
export const defaults = { claude: 'haiku', codex: 'gpt-6-luna' };
|
|
9
|
+
export const defaults = { claude: 'haiku', codex: 'gpt-6-luna', antigravity: 'gemini-4-hydrogen-low' };
|
|
10
|
+
export const SESSION_ENV_KEYS = ['XDG_RUNTIME_DIR', 'DBUS_SESSION_BUS_ADDRESS'];
|
|
11
|
+
export const SSH_ENV_KEYS = ['SSH_CONNECTION', 'SSH_CLIENT', 'SSH_TTY'];
|
|
12
|
+
export const AUTH_ENV_KEYS = [
|
|
13
|
+
'CODEX_HOME', 'CLAUDE_CONFIG_DIR',
|
|
14
|
+
...SESSION_ENV_KEYS,
|
|
15
|
+
'AGY_ADC_AUTH', 'AGY_CLI_FORCE_FILE_TOKEN_STORAGE',
|
|
16
|
+
'GOOGLE_APPLICATION_CREDENTIALS', 'CLOUDSDK_CONFIG',
|
|
17
|
+
];
|
|
18
|
+
export const STRIPPED_API_KEYS = ['OPENAI_API_KEY', 'CODEX_API_KEY', 'ANTHROPIC_API_KEY', 'ANTHROPIC_AUTH_TOKEN', 'GEMINI_API_KEY', 'GOOGLE_API_KEY'];
|
|
19
|
+
|
|
20
|
+
export function captureAuthPaths(providers, env = process.env, platform = process.platform) {
|
|
21
|
+
const authPaths = Object.fromEntries(AUTH_ENV_KEYS.filter(key => env[key]).map(key => [key, env[key]]));
|
|
22
|
+
// Over SSH, agy stores OAuth tokens in a local file instead of the OS keyring.
|
|
23
|
+
// Cron lacks SSH_* variables, so persist file-storage mode for Linux SSH setups.
|
|
24
|
+
if (platform === 'linux' && !authPaths.AGY_CLI_FORCE_FILE_TOKEN_STORAGE
|
|
25
|
+
&& providers.some(provider => provider.name === 'antigravity')
|
|
26
|
+
&& SSH_ENV_KEYS.some(key => env[key])) {
|
|
27
|
+
authPaths.AGY_CLI_FORCE_FILE_TOKEN_STORAGE = '1';
|
|
28
|
+
}
|
|
29
|
+
return authPaths;
|
|
30
|
+
}
|
|
10
31
|
export const FIVE_HOURS_MS = 5 * 60 * 60 * 1000;
|
|
11
32
|
export const RETRY_DELAY_MS = 5 * 60 * 1000;
|
|
12
33
|
export const USAGE_FAILURE_LIMIT = 3;
|
|
@@ -62,13 +83,19 @@ export function validateTime(value) {
|
|
|
62
83
|
}
|
|
63
84
|
|
|
64
85
|
export async function findExecutable(name) {
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
86
|
+
const binary = name === 'antigravity' ? 'agy' : name;
|
|
87
|
+
const userHome = process.env.HOME || os.homedir();
|
|
88
|
+
const directories = [
|
|
89
|
+
...(process.env.PATH || '').split(path.delimiter).filter(Boolean),
|
|
90
|
+
...(binary === 'agy' ? [path.join(userHome, '.gemini', 'bin'), path.join(userHome, '.local', 'bin')] : []),
|
|
91
|
+
];
|
|
92
|
+
for (const directory of directories) {
|
|
93
|
+
const candidate = path.resolve(directory, binary);
|
|
94
|
+
if (binary === 'codex' && /[/\\]openai\.chatgpt-[^/\\]+[/\\]/.test(candidate)) continue;
|
|
68
95
|
try {
|
|
69
96
|
await fs.access(candidate, constants.X_OK);
|
|
70
97
|
if ((await fs.stat(candidate)).isFile()) return candidate;
|
|
71
|
-
} catch { /* Try the next
|
|
98
|
+
} catch { /* Try the next directory. */ }
|
|
72
99
|
}
|
|
73
100
|
return null;
|
|
74
101
|
}
|
|
@@ -81,6 +108,11 @@ export function providerArgs(provider) {
|
|
|
81
108
|
'--setting-sources', '', '--settings', '{"disableAllHooks":true}',
|
|
82
109
|
'--system-prompt', 'Reply with hi.', '--output-format', 'json',
|
|
83
110
|
];
|
|
111
|
+
if (provider.name === 'antigravity') return [
|
|
112
|
+
'-p', prompt, '--model', provider.model, '--output-format', 'json',
|
|
113
|
+
'--disable-slash-commands', '--sandbox', '--print-timeout', '90s',
|
|
114
|
+
'--settings', ANTIGRAVITY_SETTINGS,
|
|
115
|
+
];
|
|
84
116
|
return [
|
|
85
117
|
'exec', '--model', provider.model, '--json', '--ephemeral', '--skip-git-repo-check',
|
|
86
118
|
'--ignore-user-config', '--sandbox', 'read-only', '--color', 'never',
|
|
@@ -95,6 +127,10 @@ export function deliveryConfirmed(name, stdout) {
|
|
|
95
127
|
const result = JSON.parse(stdout);
|
|
96
128
|
return result.type === 'result' && result.subtype === 'success' && result.is_error === false && typeof result.result === 'string' && !!result.result.trim();
|
|
97
129
|
}
|
|
130
|
+
if (name === 'antigravity') {
|
|
131
|
+
const result = JSON.parse(stdout);
|
|
132
|
+
return result.status === 'SUCCESS' && !result.error && typeof result.response === 'string' && !!result.response.trim();
|
|
133
|
+
}
|
|
98
134
|
const events = stdout.trim().split('\n').map(line => JSON.parse(line));
|
|
99
135
|
return !events.some(event => ['error', 'turn.failed'].includes(event.type))
|
|
100
136
|
&& events.some(event => event.type === 'turn.completed')
|
|
@@ -154,9 +190,13 @@ export async function prepareScheduled(provider, settings, last, { boot, now = D
|
|
|
154
190
|
} catch (error) {
|
|
155
191
|
if (error instanceof Interrupted) throw error;
|
|
156
192
|
last.usageError = `${provider.name} usage check unavailable: ${error.message || 'request failed'}`.slice(0, 200);
|
|
157
|
-
last.usageFailures = Math.min((last.usageFailures || 0) + 1, 1_000_000);
|
|
158
193
|
const delay = Number.isFinite(error.retryAfterMs) ? Math.max(RETRY_DELAY_MS, error.retryAfterMs) : RETRY_DELAY_MS;
|
|
159
194
|
last.usageRetryAt = new Date(now + Math.min(delay, 7 * 24 * 60 * 60 * 1000)).toISOString();
|
|
195
|
+
if (error.pauseFallback) {
|
|
196
|
+
delete last.usageFallback;
|
|
197
|
+
return false;
|
|
198
|
+
}
|
|
199
|
+
last.usageFailures = Math.min((last.usageFailures || 0) + 1, 1_000_000);
|
|
160
200
|
if (last.usageFailures < USAGE_FAILURE_LIMIT) return false;
|
|
161
201
|
last.usageFallback = true;
|
|
162
202
|
// Keep known reset deadlines and delivery cooldowns. A failed read never
|
|
@@ -252,9 +292,11 @@ export async function run({ scheduled = false, dryRun = false, output = console.
|
|
|
252
292
|
}
|
|
253
293
|
const state = await readState();
|
|
254
294
|
const env = { ...process.env, PATH: settings.path || process.env.PATH };
|
|
255
|
-
for (const key of
|
|
295
|
+
for (const key of AUTH_ENV_KEYS) {
|
|
296
|
+
if (settings.authPaths?.[key] && (!SESSION_ENV_KEYS.includes(key) || !env[key])) env[key] = settings.authPaths[key];
|
|
297
|
+
}
|
|
256
298
|
// Prefer the CLI's saved subscription login over inherited API keys.
|
|
257
|
-
for (const key of
|
|
299
|
+
for (const key of STRIPPED_API_KEYS) delete env[key];
|
|
258
300
|
const boot = scheduled ? bootIdentifier || await bootId() : null;
|
|
259
301
|
let success = true;
|
|
260
302
|
for (const provider of settings.providers) {
|
package/lib/usage.mjs
CHANGED
|
@@ -104,6 +104,23 @@ export function normalizeClaudeUsage(raw, now = Date.now()) {
|
|
|
104
104
|
}
|
|
105
105
|
|
|
106
106
|
const CODEX_RECHECK_MS = 2000;
|
|
107
|
+
const ANTIGRAVITY_RECHECK_MS = 2000;
|
|
108
|
+
export const ANTIGRAVITY_SETTINGS = JSON.stringify({
|
|
109
|
+
agentMode: '', modelProvider: '', toolPermission: 'strict',
|
|
110
|
+
allowNonWorkspaceAccess: false, useG1Credits: false, notifications: false,
|
|
111
|
+
});
|
|
112
|
+
|
|
113
|
+
function waitInterruptible(ms) {
|
|
114
|
+
return new Promise((resolve, reject) => {
|
|
115
|
+
const stop = signal => { cleanup(); reject(new Interrupted(signal)); };
|
|
116
|
+
const onInterrupt = () => stop('SIGINT');
|
|
117
|
+
const onTerminate = () => stop('SIGTERM');
|
|
118
|
+
const cleanup = () => { clearTimeout(timer); process.off('SIGINT', onInterrupt); process.off('SIGTERM', onTerminate); };
|
|
119
|
+
const timer = setTimeout(() => { cleanup(); resolve(); }, ms);
|
|
120
|
+
process.once('SIGINT', onInterrupt); process.once('SIGTERM', onTerminate);
|
|
121
|
+
});
|
|
122
|
+
}
|
|
123
|
+
|
|
107
124
|
const codexLimits = raw => raw?.rateLimitsByLimitId?.codex || raw?.rateLimits;
|
|
108
125
|
const codexUnused = raw => codexLimits(raw)?.primary?.usedPercent === 0 && Number.isFinite(codexLimits(raw).primary.resetsAt);
|
|
109
126
|
|
|
@@ -119,14 +136,105 @@ export function normalizeCodexUsage(raw, now = Date.now(), later) {
|
|
|
119
136
|
return normalize(primary, limits.secondary == null ? null : window(limits.secondary, names, now), now, 'codex-app-server');
|
|
120
137
|
}
|
|
121
138
|
|
|
122
|
-
|
|
139
|
+
// Only a model turn or spent tokens prove that /usage reached a model. A
|
|
140
|
+
// renamed or missing command field alone is a format change, so it takes the
|
|
141
|
+
// normal failed-read path instead of the seven-day pause.
|
|
142
|
+
const antigravityRanInference = raw => raw.num_turns > 0
|
|
143
|
+
|| (!!raw.usage && typeof raw.usage === 'object' && Object.values(raw.usage).some(count => count > 0));
|
|
144
|
+
|
|
145
|
+
function antigravityGroup(raw, model = '') {
|
|
146
|
+
if (raw && typeof raw === 'object' && antigravityRanInference(raw)) {
|
|
147
|
+
const error = new Error('Antigravity /usage ran inference instead of a local command; pausing checks.');
|
|
148
|
+
error.retryAfterMs = 7 * 24 * 60 * 60 * 1000;
|
|
149
|
+
error.pauseFallback = true;
|
|
150
|
+
throw error;
|
|
151
|
+
}
|
|
152
|
+
if (raw?.status !== 'SUCCESS' || raw.error || raw.command?.name !== 'usage'
|
|
153
|
+
|| raw.num_turns !== 0 || !raw.usage
|
|
154
|
+
|| raw.usage.input_tokens !== 0 || raw.usage.output_tokens !== 0 || raw.usage.total_tokens !== 0
|
|
155
|
+
|| !Array.isArray(raw.command.data?.groups) || !raw.command.data.groups.length) {
|
|
156
|
+
throw new Error('Antigravity did not return a local, zero-inference /usage result.');
|
|
157
|
+
}
|
|
158
|
+
const thirdParty = /^(?:claude|gpt)(?:$|[^a-z0-9])/i.test(model.trim());
|
|
159
|
+
const matches = raw.command.data.groups.filter(group => Array.isArray(group?.buckets) && (
|
|
160
|
+
thirdParty
|
|
161
|
+
? group.buckets.some(bucket => /^3p-/i.test(bucket?.id || '')) || /\b(?:claude|gpt)\b/i.test(group.name || '')
|
|
162
|
+
: group.buckets.some(bucket => /^gemini-/i.test(bucket?.id || '')) || /\bgemini\b/i.test(group.name || '')
|
|
163
|
+
));
|
|
164
|
+
if (matches.length !== 1) throw new Error('Antigravity /usage has no unique quota group for the configured model.');
|
|
165
|
+
const buckets = matches[0].buckets;
|
|
166
|
+
const fiveHour = buckets.filter(bucket => bucket?.window === '5h');
|
|
167
|
+
const weekly = buckets.filter(bucket => bucket?.window === 'weekly');
|
|
168
|
+
if (fiveHour.length > 1 || weekly.length > 1 || (!fiveHour.length && !weekly.length)) {
|
|
169
|
+
throw new Error('Antigravity /usage quota buckets are unrecognized.');
|
|
170
|
+
}
|
|
171
|
+
return fiveHour.length
|
|
172
|
+
? { primary: fiveHour[0], secondary: weekly[0] || null }
|
|
173
|
+
: { primary: weekly[0], secondary: null };
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
function antigravityWindow(bucket, now) {
|
|
177
|
+
if (bucket === null) return null;
|
|
178
|
+
if (!bucket || typeof bucket !== 'object' || !Object.hasOwn(bucket, 'remaining_fraction')) {
|
|
179
|
+
throw new Error('Antigravity usage bucket fields are missing.');
|
|
180
|
+
}
|
|
181
|
+
const remaining = bucket.remaining_fraction;
|
|
182
|
+
if (typeof remaining !== 'number' || !Number.isFinite(remaining) || remaining < 0 || remaining > 1) {
|
|
183
|
+
throw new Error('Antigravity remaining quota fraction is invalid.');
|
|
184
|
+
}
|
|
185
|
+
const rawReset = bucket.reset_time;
|
|
186
|
+
// An unstarted window may report the zero timestamp instead of a reset (captured live).
|
|
187
|
+
const parsed = rawReset == null ? null : Date.parse(rawReset);
|
|
188
|
+
const reset = parsed === 0 ? null : parsed;
|
|
189
|
+
if (reset !== null && (typeof rawReset !== 'string' || !Number.isFinite(reset) || reset <= 0)) {
|
|
190
|
+
throw new Error('Antigravity usage reset time is invalid.');
|
|
191
|
+
}
|
|
192
|
+
const used = remaining === 1 ? 0 : remaining === 0 ? 100 : Math.min(99.9, Math.max(0.1, Math.round((1 - remaining) * 1000) / 10));
|
|
193
|
+
if (used > 0 && reset === null) throw new Error('Used quota has no reset time.');
|
|
194
|
+
return { reset: reset && reset > now ? reset : null, used };
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
function antigravityUnused(raw, model) {
|
|
198
|
+
try {
|
|
199
|
+
const { primary } = antigravityGroup(raw, model);
|
|
200
|
+
return primary?.remaining_fraction === 1 && typeof primary.reset_time === 'string' && Date.parse(primary.reset_time) > 0;
|
|
201
|
+
} catch { return false; }
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
// Like Codex, an unused Antigravity bucket reports remaining_fraction === 1
|
|
205
|
+
// with a reset_time recomputed one window length ahead on every read (captured
|
|
206
|
+
// live), while an active window keeps a fixed reset_time.
|
|
207
|
+
export function normalizeAntigravityUsage(raw, now = Date.now(), later, model = '') {
|
|
208
|
+
const first = antigravityGroup(raw, model);
|
|
209
|
+
const current = later ? antigravityGroup(later, model) : first;
|
|
210
|
+
const idle = later && antigravityUnused(raw, model) && antigravityUnused(later, model)
|
|
211
|
+
&& Date.parse(current.primary.reset_time) > Date.parse(first.primary.reset_time);
|
|
212
|
+
const primary = idle ? { reset: null, used: 0 } : antigravityWindow(current.primary, now);
|
|
213
|
+
return normalize(primary, antigravityWindow(current.secondary, now), now, 'antigravity-cli-usage');
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
export async function readClaudeUsage(provider, { env = process.env, cwd, runner = execute, now } = {}) {
|
|
123
217
|
// The unmodified CLI owns all authentication. An invalid model prevents an
|
|
124
218
|
// inference request if a future CLI stops recognizing /usage locally.
|
|
125
219
|
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 });
|
|
126
220
|
if (result.code !== 0 || result.timedOut || result.outputTooLarge) throw new Error('Claude /usage command failed. Check the CLI login and version.');
|
|
127
221
|
let raw;
|
|
128
222
|
try { raw = JSON.parse(result.stdout); } catch { throw new Error('Claude /usage returned invalid JSON.'); }
|
|
129
|
-
return normalizeClaudeUsage(raw);
|
|
223
|
+
return normalizeClaudeUsage(raw, now);
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
export async function readAntigravityUsage(provider, { env = process.env, cwd, runner = execute, wait = waitInterruptible, now } = {}) {
|
|
227
|
+
const args = ['-p', '/usage', '--output-format', 'json', '--print-timeout', '25s', '--settings', ANTIGRAVITY_SETTINGS];
|
|
228
|
+
const readOnce = async () => {
|
|
229
|
+
const result = await runner(provider.executable, args, { env, cwd, timeout: 30_000 });
|
|
230
|
+
if (result.code !== 0 || result.timedOut || result.outputTooLarge) throw new Error('Antigravity /usage command failed. Check the CLI login and version.');
|
|
231
|
+
try { return JSON.parse(result.stdout); } catch { throw new Error('Antigravity /usage returned invalid JSON.'); }
|
|
232
|
+
};
|
|
233
|
+
const first = await readOnce();
|
|
234
|
+
if (!antigravityUnused(first, provider.model)) return normalizeAntigravityUsage(first, now, undefined, provider.model);
|
|
235
|
+
await wait(ANTIGRAVITY_RECHECK_MS);
|
|
236
|
+
const second = await readOnce();
|
|
237
|
+
return normalizeAntigravityUsage(first, now, second, provider.model);
|
|
130
238
|
}
|
|
131
239
|
|
|
132
240
|
export function readCodexUsage(provider, { env = process.env, cwd } = {}) {
|
|
@@ -182,5 +290,7 @@ export async function bootId() {
|
|
|
182
290
|
}
|
|
183
291
|
|
|
184
292
|
export async function readUsage(provider, options) {
|
|
185
|
-
|
|
293
|
+
if (provider.name === 'claude') return readClaudeUsage(provider, options);
|
|
294
|
+
if (provider.name === 'antigravity') return readAntigravityUsage(provider, options);
|
|
295
|
+
return readCodexUsage(provider, options);
|
|
186
296
|
}
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "hi-ai-cli",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"description": "A usage-aware hello at reset for Claude Code and
|
|
3
|
+
"version": "0.2.0",
|
|
4
|
+
"description": "A usage-aware hello at reset for Claude Code, Codex, and Antigravity on macOS and Linux.",
|
|
5
5
|
"author": "anik-jha",
|
|
6
6
|
"repository": {
|
|
7
7
|
"type": "git",
|