agy-cli-usage 0.3.1 → 0.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,221 @@
1
+ // Fallback path: drive the real `agy` TUI in a pseudo-terminal, send `/usage`,
2
+ // reconstruct the rendered screen with a headless VT emulator, and parse the
3
+ // panel. Used only when the direct API path is unavailable (no readable
4
+ // keyring, or the internal API changed). Slower and more brittle than the API
5
+ // path, but uses agy's own auth so it works wherever agy itself works.
6
+ //
7
+ // Why a VT emulator: agy renders /usage in the alternate screen buffer using
8
+ // cursor addressing, so naive ANSI-stripping yields nothing. We feed the raw
9
+ // PTY bytes through @xterm/headless to get the final visible screen, then parse.
10
+ //
11
+ // Capture backend: python3 `pty` on POSIX (no native build), node-pty on
12
+ // Windows (ConPTY). agy shows a welcome screen first, so `/usage` is sent after
13
+ // a delay and the session is held open long enough to render.
14
+ import { spawn } from 'node:child_process';
15
+ import { writeFileSync, readFileSync, mkdtempSync, existsSync } from 'node:fs';
16
+ import { tmpdir, homedir } from 'node:os';
17
+ import { join, delimiter } from 'node:path';
18
+ // Resolve the agy binary: explicit AGY_BIN, then PATH, then common install dir.
19
+ function resolveAgy() {
20
+ const explicit = process.env.AGY_BIN;
21
+ if (explicit)
22
+ return explicit;
23
+ const exe = process.platform === 'win32' ? 'agy.exe' : 'agy';
24
+ for (const dir of (process.env.PATH || '').split(delimiter)) {
25
+ if (dir && existsSync(join(dir, exe)))
26
+ return join(dir, exe);
27
+ }
28
+ const local = join(homedir(), '.local', 'bin', exe);
29
+ if (existsSync(local))
30
+ return local;
31
+ return 'agy'; // last resort: let the OS resolve it
32
+ }
33
+ const AGY_BIN = resolveAgy();
34
+ const COLS = 120;
35
+ const ROWS = 60;
36
+ const USAGE_AT_MS = 10_000; // send /usage after the welcome screen settles
37
+ const TEARDOWN_MS = 23_000; // keep session open long enough to render
38
+ // --- capture: returns raw PTY bytes (Buffer) or null --------------------------
39
+ async function captureViaNodePty() {
40
+ // node-pty is an optional dependency; defeat static module resolution so the
41
+ // build doesn't require it (CI installs with --omit=optional).
42
+ const moduleName = 'node-pty';
43
+ let pty;
44
+ try {
45
+ pty = await import(moduleName);
46
+ }
47
+ catch {
48
+ return null;
49
+ }
50
+ return new Promise((resolve) => {
51
+ let term;
52
+ try {
53
+ term = pty.spawn(AGY_BIN, [], { name: 'xterm-256color', cols: COLS, rows: ROWS, cwd: process.cwd(), env: process.env });
54
+ }
55
+ catch {
56
+ resolve(null);
57
+ return;
58
+ }
59
+ const chunks = [];
60
+ term.onData((d) => chunks.push(Buffer.from(d, 'utf8')));
61
+ const t1 = setTimeout(() => { try {
62
+ term.write('/usage\r');
63
+ }
64
+ catch { /* ignore */ } }, USAGE_AT_MS);
65
+ const t2 = setTimeout(() => {
66
+ try {
67
+ term.write('\x03');
68
+ }
69
+ catch { /* ignore */ }
70
+ try {
71
+ term.kill();
72
+ }
73
+ catch { /* ignore */ }
74
+ resolve(Buffer.concat(chunks));
75
+ }, TEARDOWN_MS);
76
+ term.onExit(() => { clearTimeout(t1); clearTimeout(t2); resolve(Buffer.concat(chunks)); });
77
+ });
78
+ }
79
+ async function captureViaPython() {
80
+ if (process.platform === 'win32')
81
+ return null;
82
+ const dir = mkdtempSync(join(tmpdir(), 'agy-usage-'));
83
+ const helper = join(dir, 'drive.py');
84
+ const outFile = join(dir, 'out.bin');
85
+ writeFileSync(helper, `import os, pty, time, select, signal, struct, fcntl, termios
86
+ AGY = ${JSON.stringify(AGY_BIN)}
87
+ out = open(${JSON.stringify(outFile)}, "wb")
88
+ pid, fd = pty.fork()
89
+ if pid == 0:
90
+ os.execvpe(AGY, [AGY], os.environ)
91
+ os._exit(127)
92
+ fcntl.ioctl(fd, termios.TIOCSWINSZ, struct.pack("HHHH", ${ROWS}, ${COLS}, 0, 0))
93
+ start = time.time(); sent = False
94
+ while time.time() - start < ${TEARDOWN_MS / 1000}:
95
+ e = time.time() - start
96
+ r, _, _ = select.select([fd], [], [], 0.5)
97
+ if r:
98
+ try: d = os.read(fd, 8192)
99
+ except OSError: break
100
+ if not d: break
101
+ out.write(d); out.flush()
102
+ if not sent and e > ${USAGE_AT_MS / 1000}:
103
+ os.write(fd, b"/usage\\r"); sent = True
104
+ try: os.write(fd, b"\\x03")
105
+ except OSError: pass
106
+ try: os.kill(pid, signal.SIGTERM)
107
+ except Exception: pass
108
+ out.close()
109
+ `);
110
+ return new Promise((resolve) => {
111
+ const proc = spawn('python3', [helper], { stdio: 'ignore' });
112
+ proc.on('error', () => resolve(null));
113
+ proc.on('exit', () => {
114
+ try {
115
+ resolve(readFileSync(outFile));
116
+ }
117
+ catch {
118
+ resolve(null);
119
+ }
120
+ });
121
+ });
122
+ }
123
+ // --- VT reconstruction --------------------------------------------------------
124
+ async function reconstructScreen(raw) {
125
+ const { Terminal } = await import('@xterm/headless');
126
+ const term = new Terminal({ cols: COLS, rows: ROWS, allowProposedApi: true, scrollback: 200 });
127
+ await new Promise((res) => term.write(raw, res));
128
+ const buf = term.buffer.active;
129
+ const lines = [];
130
+ // include scrollback so a panel taller than the viewport is still captured
131
+ for (let i = 0; i < buf.length; i++) {
132
+ const line = buf.getLine(i);
133
+ if (line)
134
+ lines.push(line.translateToString(true).replace(/\s+$/, ''));
135
+ }
136
+ term.dispose();
137
+ return lines.join('\n');
138
+ }
139
+ // --- parse --------------------------------------------------------------------
140
+ function parseDuration(text) {
141
+ let seconds = 0;
142
+ const d = text.match(/(\d+)\s*day/i);
143
+ const h = text.match(/(\d+)\s*h(?:our)?/i);
144
+ const m = text.match(/(\d+)\s*m(?:in)?/i);
145
+ if (d)
146
+ seconds += +d[1] * 86400;
147
+ if (h)
148
+ seconds += +h[1] * 3600;
149
+ if (m)
150
+ seconds += +m[1] * 60;
151
+ return seconds || null;
152
+ }
153
+ /** Parse the reconstructed /usage screen text into { account, groups:[...] }. */
154
+ export function parsePanel(text) {
155
+ const lines = text.split(/\r?\n/);
156
+ const account = text.match(/Account:\s*(\S+)/)?.[1] ?? null;
157
+ const groups = [];
158
+ let group = null;
159
+ let bucket = null;
160
+ const pushBucket = () => { if (group && bucket)
161
+ group.buckets.push(bucket); bucket = null; };
162
+ const pushGroup = () => { pushBucket(); if (group)
163
+ groups.push(group); group = null; };
164
+ for (const line of lines) {
165
+ const t = line.trim();
166
+ if (!t)
167
+ continue;
168
+ if (/^[A-Z][A-Z0-9 &/]*MODELS$/.test(t)) {
169
+ pushGroup();
170
+ group = { name: t.replace(/\s+/g, ' '), models: '', buckets: [] };
171
+ continue;
172
+ }
173
+ const models = t.match(/^Models within this group:\s*(.+)$/i);
174
+ if (models && group) {
175
+ group.models = models[1].trim();
176
+ continue;
177
+ }
178
+ if (/^(Weekly Limit|Five Hour Limit|5[- ]?Hour Limit)$/i.test(t)) {
179
+ pushBucket();
180
+ const kind = /week/i.test(t) ? 'weekly' : '5h';
181
+ bucket = { kind, label: t, remainingFraction: null, resetsInSeconds: null, available: false, description: null };
182
+ continue;
183
+ }
184
+ if (bucket) {
185
+ const pct = t.match(/(\d+(?:\.\d+)?)\s*%/);
186
+ if (pct && bucket.remainingFraction == null)
187
+ bucket.remainingFraction = +pct[1] / 100;
188
+ if (/Quota available/i.test(t)) {
189
+ bucket.available = true;
190
+ bucket.remainingFraction = 1;
191
+ }
192
+ const refresh = t.match(/Refreshes in (.+)$/i);
193
+ if (refresh)
194
+ bucket.resetsInSeconds = parseDuration(refresh[1]);
195
+ }
196
+ }
197
+ pushGroup();
198
+ return { account, groups };
199
+ }
200
+ /** Run agy, capture /usage, reconstruct + parse the panel. */
201
+ export async function captureUsageViaPty() {
202
+ const order = process.platform === 'win32'
203
+ ? [captureViaNodePty, captureViaPython]
204
+ : [captureViaPython, captureViaNodePty];
205
+ let raw = null;
206
+ for (const fn of order) {
207
+ raw = await fn();
208
+ if (raw && raw.length)
209
+ break;
210
+ }
211
+ if (!raw || !raw.length) {
212
+ throw new Error('No PTY backend captured agy output (need python3 on POSIX, or node-pty on Windows)');
213
+ }
214
+ const screen = await reconstructScreen(raw);
215
+ const parsed = parsePanel(screen);
216
+ if (!parsed.groups.length) {
217
+ throw new Error('Could not parse /usage panel from agy output');
218
+ }
219
+ return parsed;
220
+ }
221
+ //# sourceMappingURL=pty-fallback.js.map
@@ -0,0 +1,7 @@
1
+ import type { FetchResult, ParsedPanel, Snapshot } from './types.js';
2
+ /** Build a normalized snapshot from the raw retrieveUserQuotaSummary response. */
3
+ export declare function fromApi({ raw, host, account, tier }: FetchResult, nowMs?: number): Snapshot;
4
+ /** Build a normalized snapshot from PTY-parsed groups (see pty-fallback.ts). */
5
+ export declare function fromPty(parsed: ParsedPanel, nowMs?: number): Snapshot;
6
+ /** Format a seconds duration like agy: "73h 53m" / "2h 7m" / "12m". */
7
+ export declare function formatDuration(seconds: number | null): string | null;
@@ -0,0 +1,81 @@
1
+ // Normalizes quota data from either source (direct API JSON or PTY-parsed text)
2
+ // into one shape consumed by the renderer / JSON output / HTTP endpoint.
3
+ function bucketKind(window, label) {
4
+ if (window === 'weekly' || /week/i.test(label))
5
+ return 'weekly';
6
+ if (window === '5h' || /5.?hour|five.?hour/i.test(label))
7
+ return '5h';
8
+ return window || label;
9
+ }
10
+ function secondsUntil(resetAt, now) {
11
+ if (!resetAt)
12
+ return null;
13
+ const ms = new Date(resetAt).getTime() - now;
14
+ return Number.isFinite(ms) ? Math.max(0, Math.round(ms / 1000)) : null;
15
+ }
16
+ /** Build a normalized snapshot from the raw retrieveUserQuotaSummary response. */
17
+ export function fromApi({ raw, host, account, tier }, nowMs = Date.now()) {
18
+ const groups = (raw.groups ?? []).map((g) => ({
19
+ name: g.displayName ?? 'Models',
20
+ models: (g.description ?? '').replace(/^Models within this group:\s*/i, '').trim(),
21
+ buckets: (g.buckets ?? []).map((b) => {
22
+ const remaining = typeof b.remainingFraction === 'number' ? b.remainingFraction : null;
23
+ return {
24
+ kind: bucketKind(b.window, b.displayName ?? ''),
25
+ label: b.displayName ?? b.window ?? '',
26
+ remainingFraction: remaining,
27
+ usedFraction: remaining == null ? null : 1 - remaining,
28
+ resetAt: b.resetTime ?? null,
29
+ resetsInSeconds: secondsUntil(b.resetTime, nowMs),
30
+ available: remaining === 1,
31
+ description: b.description ?? null,
32
+ };
33
+ }),
34
+ }));
35
+ return {
36
+ account: account ?? null,
37
+ tier: tier ?? null,
38
+ fetchedAt: new Date(nowMs).toISOString(),
39
+ source: 'api',
40
+ host: host ?? null,
41
+ note: raw.description ?? null,
42
+ groups,
43
+ };
44
+ }
45
+ /** Build a normalized snapshot from PTY-parsed groups (see pty-fallback.ts). */
46
+ export function fromPty(parsed, nowMs = Date.now()) {
47
+ const groups = (parsed.groups ?? []).map((g) => ({
48
+ name: g.name,
49
+ models: g.models ?? '',
50
+ buckets: (g.buckets ?? []).map((b) => ({
51
+ kind: b.kind,
52
+ label: b.label,
53
+ remainingFraction: b.remainingFraction ?? null,
54
+ usedFraction: b.remainingFraction == null ? null : 1 - b.remainingFraction,
55
+ resetAt: b.resetsInSeconds != null ? new Date(nowMs + b.resetsInSeconds * 1000).toISOString() : null,
56
+ resetsInSeconds: b.resetsInSeconds ?? null,
57
+ available: b.available ?? b.remainingFraction === 1,
58
+ description: b.description ?? null,
59
+ })),
60
+ }));
61
+ return {
62
+ account: parsed.account ?? null,
63
+ tier: null,
64
+ fetchedAt: new Date(nowMs).toISOString(),
65
+ source: 'pty',
66
+ host: null,
67
+ note: parsed.note ?? null,
68
+ groups,
69
+ };
70
+ }
71
+ /** Format a seconds duration like agy: "73h 53m" / "2h 7m" / "12m". */
72
+ export function formatDuration(seconds) {
73
+ if (seconds == null)
74
+ return null;
75
+ const h = Math.floor(seconds / 3600);
76
+ const m = Math.floor((seconds % 3600) / 60);
77
+ if (h > 0)
78
+ return `${h}h ${m}m`;
79
+ return `${m}m`;
80
+ }
81
+ //# sourceMappingURL=quota.js.map
@@ -0,0 +1,3 @@
1
+ import type { Snapshot } from './types.js';
2
+ /** Returns the full panel as a string. */
3
+ export declare function renderPanel(snap: Snapshot): string;
@@ -0,0 +1,82 @@
1
+ // Renders a normalized quota snapshot as a terminal panel, mirroring agy's
2
+ // `/usage` layout (progress bar + percent + reset time per bucket).
3
+ import { formatDuration } from './quota.js';
4
+ const BAR_WIDTH = 50;
5
+ const useColor = () => Boolean(process.stdout.isTTY) && !process.env.NO_COLOR;
6
+ const c = (code, s) => (useColor() ? `\x1b[${code}m${s}\x1b[0m` : s);
7
+ const dim = (s) => c('2', s);
8
+ const bold = (s) => c('1', s);
9
+ // remaining-based color: lots left = green, getting low = yellow/red.
10
+ function barColor(remaining) {
11
+ if (remaining == null)
12
+ return '37';
13
+ if (remaining > 0.5)
14
+ return '32'; // green
15
+ if (remaining > 0.2)
16
+ return '33'; // yellow
17
+ return '31'; // red
18
+ }
19
+ function bar(remainingFraction) {
20
+ const frac = remainingFraction == null ? 0 : Math.max(0, Math.min(1, remainingFraction));
21
+ const filled = Math.round(frac * BAR_WIDTH);
22
+ const body = '█'.repeat(filled) + '░'.repeat(BAR_WIDTH - filled);
23
+ return useColor() ? `\x1b[${barColor(remainingFraction)}m${body}\x1b[0m` : body;
24
+ }
25
+ function bucketLine(b) {
26
+ const lines = [];
27
+ lines.push(` ${bold(b.label)}`);
28
+ if (b.available) {
29
+ lines.push(` [${bar(1)}] ${c('32', 'Quota available')}`);
30
+ }
31
+ else {
32
+ const pct = b.remainingFraction == null ? '—' : `${(b.remainingFraction * 100).toFixed(2)}%`;
33
+ const remainPct = b.remainingFraction == null ? '' : `${Math.round(b.remainingFraction * 100)}% remaining`;
34
+ const dur = formatDuration(b.resetsInSeconds);
35
+ const reset = dur ? ` · ${dim(`Refreshes in ${dur}`)}` : '';
36
+ lines.push(` [${bar(b.remainingFraction)}] ${pct}`);
37
+ lines.push(` ${dim(remainPct)}${reset}`);
38
+ }
39
+ return lines.join('\n');
40
+ }
41
+ /** Returns the full panel as a string. */
42
+ export function renderPanel(snap) {
43
+ const out = [];
44
+ out.push('');
45
+ out.push(bold(' Models & Quota'));
46
+ if (snap.account)
47
+ out.push(` ${dim('Account:')} ${snap.account}`);
48
+ out.push(` ${dim(`source: ${snap.source}${snap.host ? ` · ${snap.host}` : ''} · ${snap.fetchedAt}`)}`);
49
+ out.push('');
50
+ for (const g of snap.groups) {
51
+ out.push(bold(` ${g.name.toUpperCase()}`));
52
+ if (g.models)
53
+ out.push(` ${dim(`Models within this group: ${g.models}`)}`);
54
+ out.push('');
55
+ for (const b of g.buckets) {
56
+ out.push(bucketLine(b));
57
+ out.push('');
58
+ }
59
+ }
60
+ if (snap.note) {
61
+ out.push(dim(wrap(snap.note, 76, ' │')));
62
+ }
63
+ return out.join('\n');
64
+ }
65
+ function wrap(text, width, prefix) {
66
+ const words = text.split(/\s+/);
67
+ const lines = [];
68
+ let cur = '';
69
+ for (const w of words) {
70
+ if ((cur + ' ' + w).trim().length > width) {
71
+ lines.push(prefix + cur);
72
+ cur = w;
73
+ }
74
+ else {
75
+ cur = (cur + ' ' + w).trim();
76
+ }
77
+ }
78
+ if (cur)
79
+ lines.push(prefix + cur);
80
+ return lines.join('\n');
81
+ }
82
+ //# sourceMappingURL=render.js.map
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
@@ -0,0 +1,43 @@
1
+ #!/usr/bin/env node
2
+ // Optional lightweight HTTP endpoint for dashboard integration.
3
+ // Serves the normalized quota snapshot as JSON, going through the same 5-minute
4
+ // cache as the CLI so polling clients never hammer the upstream API.
5
+ //
6
+ // PORT=3007 node dist/src/server.js
7
+ // GET /quota -> normalized snapshot JSON
8
+ // GET /healthz -> { ok: true }
9
+ import { createServer } from 'node:http';
10
+ import { getSnapshot } from './main.js';
11
+ const PORT = Number(process.env.PORT) || 3007;
12
+ const HOST = process.env.HOST || '127.0.0.1';
13
+ const server = createServer(async (req, res) => {
14
+ const url = new URL(req.url ?? '/', `http://${req.headers.host ?? 'localhost'}`);
15
+ if (url.pathname === '/healthz') {
16
+ res.writeHead(200, { 'Content-Type': 'application/json' });
17
+ res.end(JSON.stringify({ ok: true }));
18
+ return;
19
+ }
20
+ if (url.pathname === '/quota') {
21
+ try {
22
+ const noCache = url.searchParams.get('refresh') === '1';
23
+ const snap = await getSnapshot({ source: 'auto', channel: 'auto', cache: !noCache });
24
+ res.writeHead(200, {
25
+ 'Content-Type': 'application/json',
26
+ 'Access-Control-Allow-Origin': '*',
27
+ 'Cache-Control': 'public, max-age=300',
28
+ });
29
+ res.end(JSON.stringify(snap));
30
+ }
31
+ catch (err) {
32
+ res.writeHead(502, { 'Content-Type': 'application/json' });
33
+ res.end(JSON.stringify({ error: err instanceof Error ? err.message : String(err) }));
34
+ }
35
+ return;
36
+ }
37
+ res.writeHead(404, { 'Content-Type': 'application/json' });
38
+ res.end(JSON.stringify({ error: 'not found' }));
39
+ });
40
+ server.listen(PORT, HOST, () => {
41
+ process.stdout.write(`agy-usage server on http://${HOST}:${PORT} (GET /quota)\n`);
42
+ });
43
+ //# sourceMappingURL=server.js.map
@@ -0,0 +1,67 @@
1
+ export type BucketKind = 'weekly' | '5h' | string;
2
+ export interface RawBucket {
3
+ bucketId?: string;
4
+ displayName?: string;
5
+ window?: string;
6
+ resetTime?: string;
7
+ description?: string;
8
+ remainingFraction?: number;
9
+ }
10
+ export interface RawGroup {
11
+ displayName?: string;
12
+ description?: string;
13
+ buckets?: RawBucket[];
14
+ }
15
+ export interface RawQuotaResponse {
16
+ groups?: RawGroup[];
17
+ description?: string;
18
+ }
19
+ /** Result of api.fetchQuotaSummary. */
20
+ export interface FetchResult {
21
+ raw: RawQuotaResponse;
22
+ host: string | null;
23
+ account: string | null;
24
+ tier: string | null;
25
+ }
26
+ export interface ParsedBucket {
27
+ kind: BucketKind;
28
+ label: string;
29
+ remainingFraction: number | null;
30
+ resetsInSeconds: number | null;
31
+ available: boolean;
32
+ description: string | null;
33
+ }
34
+ export interface ParsedGroup {
35
+ name: string;
36
+ models: string;
37
+ buckets: ParsedBucket[];
38
+ }
39
+ export interface ParsedPanel {
40
+ account: string | null;
41
+ groups: ParsedGroup[];
42
+ note?: string | null;
43
+ }
44
+ export interface Bucket {
45
+ kind: BucketKind;
46
+ label: string;
47
+ remainingFraction: number | null;
48
+ usedFraction: number | null;
49
+ resetAt: string | null;
50
+ resetsInSeconds: number | null;
51
+ available: boolean;
52
+ description: string | null;
53
+ }
54
+ export interface Group {
55
+ name: string;
56
+ models: string;
57
+ buckets: Bucket[];
58
+ }
59
+ export interface Snapshot {
60
+ account: string | null;
61
+ tier: string | null;
62
+ fetchedAt: string;
63
+ source: 'api' | 'pty';
64
+ host: string | null;
65
+ note: string | null;
66
+ groups: Group[];
67
+ }
@@ -0,0 +1,3 @@
1
+ // Shared types for agy-cli-usage.
2
+ export {};
3
+ //# sourceMappingURL=types.js.map
@@ -0,0 +1,17 @@
1
+ /**
2
+ * Installed version, read from this package's package.json.
3
+ * NOTE: this module compiles to dist/src/update.js, so package.json (at the
4
+ * package root) is two levels up.
5
+ */
6
+ export declare function currentVersion(): string;
7
+ /**
8
+ * Compare two dotted versions numerically (prerelease tags ignored).
9
+ * Returns negative if a<b, 0 if equal, positive if a>b.
10
+ */
11
+ export declare function semverCompare(a: string, b: string): number;
12
+ /** Latest published version: prefer the user's configured registry (npm view), fall back to public. */
13
+ export declare function latestVersion(): Promise<string | null>;
14
+ /** Run the update flow. Returns the intended process exit code. */
15
+ export declare function runUpdate({ checkOnly }?: {
16
+ checkOnly?: boolean;
17
+ }): Promise<number>;
@@ -0,0 +1,87 @@
1
+ // Self-update + version helpers for the CLI.
2
+ //
3
+ // `agy-cli-usage update` check the registry and `npm install -g` if newer
4
+ // `agy-cli-usage update --check` report only, don't install
5
+ // `agy-cli-usage --version` print the installed version
6
+ import { execFileSync, spawnSync } from 'node:child_process';
7
+ import { readFileSync } from 'node:fs';
8
+ const PKG_NAME = 'agy-cli-usage';
9
+ /**
10
+ * Installed version, read from this package's package.json.
11
+ * NOTE: this module compiles to dist/src/update.js, so package.json (at the
12
+ * package root) is two levels up.
13
+ */
14
+ export function currentVersion() {
15
+ const pkg = JSON.parse(readFileSync(new URL('../../package.json', import.meta.url), 'utf8'));
16
+ return pkg.version;
17
+ }
18
+ /**
19
+ * Compare two dotted versions numerically (prerelease tags ignored).
20
+ * Returns negative if a<b, 0 if equal, positive if a>b.
21
+ */
22
+ export function semverCompare(a, b) {
23
+ const norm = (v) => String(v)
24
+ .replace(/^v/, '')
25
+ .split('-')[0]
26
+ .split('.')
27
+ .map((n) => parseInt(n, 10) || 0);
28
+ const pa = norm(a);
29
+ const pb = norm(b);
30
+ for (let i = 0; i < Math.max(pa.length, pb.length); i++) {
31
+ const d = (pa[i] || 0) - (pb[i] || 0);
32
+ if (d !== 0)
33
+ return d;
34
+ }
35
+ return 0;
36
+ }
37
+ /** Latest published version: prefer the user's configured registry (npm view), fall back to public. */
38
+ export async function latestVersion() {
39
+ try {
40
+ const out = execFileSync('npm', ['view', PKG_NAME, 'version'], {
41
+ encoding: 'utf8',
42
+ stdio: ['ignore', 'pipe', 'ignore'],
43
+ }).trim();
44
+ if (out)
45
+ return out;
46
+ }
47
+ catch {
48
+ // npm missing or offline — try the public registry directly
49
+ }
50
+ try {
51
+ const res = await fetch(`https://registry.npmjs.org/${PKG_NAME}/latest`);
52
+ if (res.ok)
53
+ return (await res.json()).version;
54
+ }
55
+ catch {
56
+ // offline
57
+ }
58
+ return null;
59
+ }
60
+ /** Run the update flow. Returns the intended process exit code. */
61
+ export async function runUpdate({ checkOnly = false } = {}) {
62
+ const current = currentVersion();
63
+ const latest = await latestVersion();
64
+ if (!latest) {
65
+ process.stderr.write('Could not determine the latest version (offline or npm unavailable).\n');
66
+ return 1;
67
+ }
68
+ if (semverCompare(latest, current) <= 0) {
69
+ process.stdout.write(`agy-cli-usage is up to date (${current}).\n`);
70
+ return 0;
71
+ }
72
+ process.stdout.write(`Update available: ${current} -> ${latest}\n`);
73
+ if (checkOnly) {
74
+ process.stdout.write('Run `agy-cli-usage update` to install it.\n');
75
+ return 0;
76
+ }
77
+ process.stdout.write(`Installing ${PKG_NAME}@${latest} globally…\n`);
78
+ const r = spawnSync('npm', ['install', '-g', `${PKG_NAME}@${latest}`], { stdio: 'inherit' });
79
+ if (r.error) {
80
+ process.stderr.write(`Failed to run npm: ${r.error.message}\nInstall manually: npm install -g ${PKG_NAME}@latest\n`);
81
+ return 1;
82
+ }
83
+ if (r.status === 0)
84
+ process.stdout.write(`Updated to ${latest}.\n`);
85
+ return r.status ?? 0;
86
+ }
87
+ //# sourceMappingURL=update.js.map
package/package.json CHANGED
@@ -1,24 +1,28 @@
1
1
  {
2
2
  "name": "agy-cli-usage",
3
- "version": "0.3.1",
3
+ "version": "0.4.1",
4
4
  "description": "Headless usage/quota monitor for the Antigravity CLI (agy) — reads Cloud Code quota directly, with a PTY fallback. No IDE required.",
5
5
  "type": "module",
6
+ "types": "dist/src/main.d.ts",
6
7
  "bin": {
7
- "agy-cli-usage": "src/main.js",
8
- "agy-usage": "src/main.js"
8
+ "agy-cli-usage": "dist/src/main.js",
9
+ "agy-usage": "dist/src/main.js"
9
10
  },
10
11
  "scripts": {
11
- "start": "node src/main.js",
12
- "serve": "node server.js",
13
- "test": "node --test",
14
- "check": "node --check src/main.js && node --check server.js"
12
+ "build": "tsc",
13
+ "check": "tsc --noEmit",
14
+ "pretest": "tsc",
15
+ "test": "node --test dist/test/unit.test.js",
16
+ "start": "tsc && node dist/src/main.js",
17
+ "serve": "tsc && node dist/src/server.js",
18
+ "prepack": "tsc"
15
19
  },
16
20
  "engines": {
17
21
  "node": ">=18"
18
22
  },
19
23
  "files": [
20
- "src/",
21
- "server.js",
24
+ "dist/src/**/*.js",
25
+ "dist/src/**/*.d.ts",
22
26
  "README.md",
23
27
  "CHANGELOG.md",
24
28
  "LICENSE"
@@ -49,5 +53,9 @@
49
53
  "optionalDependencies": {
50
54
  "node-pty": "^1.0.0"
51
55
  },
52
- "license": "MIT"
56
+ "license": "MIT",
57
+ "devDependencies": {
58
+ "@types/node": "^26.0.0",
59
+ "typescript": "^6.0.3"
60
+ }
53
61
  }