Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

add Antigravity + Grok usage adapters via headless TUI /usage scrape

[._.]/ Adam Eivy74ecece70b56
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 02834bbede..80edeceea0 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -59,3 +59,4 @@
- **[issue-2533] Extract JIRA-ticket claim assembly out of the route into `buildJiraTicketTask` (next to `buildClaimWorkTask`).** `POST /api/cos/tasks/jira-ticket` (the sprint-board per-card play button) inlined its reviewer-CSV resolution (`resolveClaimReviewersCsv`), the target-ticket constraint block (`buildTargetTicketBlock`), and the `claim-issue-jira` prompt assembly directly in `server/routes/cosTaskRoutes.js`. That logic now lives in `server/services/cosTaskGenerator.js` as an exported `buildJiraTicketTask(app, ticketKey)` that returns `{ ticketKey, prompt, taskMetadata }` — beside `buildClaimWorkTask`, sharing the same reviewer/isolation conventions. The route stays thin: validate → JIRA-enabled gate → assemble → queue. Pure refactor — the queued task's context, description, and `useWorktree/openPR` posture are byte-for-byte unchanged; new unit tests cover the extracted assembly.
- **[issue-2539] Serialize `createCachedStore` and `backup.saveState` writes; bound the rate-limit state maps.** `createCachedStore` now runs every write through an internal single-tail `createFileWriteQueue` and exposes a `mutate(fn)` primitive that serializes the whole `load → modify → persist` cycle, so two concurrent read-modify-write paths can no longer clobber each other; the feeds, social-accounts, platform-accounts, agent-personalities, and automation-scheduler services were migrated off the racy `load()` + `save()` pair onto `mutate()`. `backup.saveState` gained the same promise-tail so a run completing while the scheduler stamps a status can't lose fields. The moltbook/moltworld rate-limiters, which kept one in-memory state entry per API key / agent id forever, now store it in a new bounded `createBoundedStateMap({ maxSize, ttlMs })` helper (`server/lib/boundedStateMap.js`) that lazily evicts idle (TTL) and least-recently-used (LRU) entries. (The idle pipeline `writeQueues` pruning called for by the issue already shipped via `createKeyedFileWriteQueue`/`createKeyCachedQueue` in #2528/#2524.) Behavior is otherwise unchanged; new unit tests cover the serialized `mutate`, the bounded map, and the rate-limiter.
- **Fix the DevTools → Usage page crashing with "(providers || []).map/filter is not a function".** `services/providers.getAllProviders()` returns the wrapped `{ activeProvider, providers }` object, but `routes/usage.js` (GET `/api/usage`) and `services/providerUsage.js#getProviderQuotas` (GET `/api/usage/providers`) passed that object straight into `.map`/`.filter`, throwing on every request so the Usage page showed "Couldn't read provider usage." / "No usage data available." Both call sites now unwrap `.providers` via the `Array.isArray(result) ? result : (result?.providers || [])` pattern already used in `jiraReports.js`/`loops.js`. The two test suites mocked `getAllProviders` as a bare array (masking the bug); their mocks now return the real object shape, plus a new `getProviderQuotas` regression test asserts the unwrap.
+- **[issue-2598] Add Antigravity + Grok subscription-usage adapters via headless TUI `/usage` scrape.** DevTools → Usage previously showed "not available" placeholders for the `agy` (Antigravity) and `grok` (Grok Build) provider families, because neither CLI exposes quota in non-interactive `--print` mode (there `/usage` is treated as an LLM prompt — wrong data, and it burns tokens). Their real usage surface is an interactive slash command (`/usage` for agy, `/usage show` for grok), so a new `server/lib/tuiUsageScrape.js#scrapeTuiUsage` drives the TUI in a **sandbox PTY** (a fixed dir under the OS temp dir — never the user's project — trusted once via a primer Enter, output-idle-gated capture, hard-timeout backstop), and `providerUsage.js` parses the rendered panel into the common quota shape. Antigravity reports one card per model group (e.g. Gemini, Claude/GPT) with weekly + 5-hour meters and reset times, treating its bar percentage as **remaining**; Grok reports a single weekly meter treating `Weekly limit: N%` as **used**. Both scrapes are 0-token (the slash command renders synchronously, no LLM turn), user-triggered only, and cached 5 min with single-flight (each scrape costs ~12s). Parse failures degrade to a soft "no quota data" warning card rather than erroring the page. New unit tests cover both parsers, the relative-reset→ISO conversion, and the fetch/cache wiring.
diff --git a/server/lib/README.md b/server/lib/README.md
index 4c709e24b5..2f030dd92e 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -91,6 +91,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `promptRunner.js` | Shared LLM runner wrapper. |
| `tuiPromptRunner.js` | One-shot TUI prompt runner (PTY-driven). |
| `tuiHandshake.js` | Shared TUI invocation + paste-handshake constants. |
+| `tuiUsageScrape.js` | `scrapeTuiUsage({ command, slashCommand, … })` + `USAGE_SANDBOX_DIR` — drive an agy/grok TUI in a sandbox PTY, send a slash command, return the ANSI-stripped screen (for quota panels `--print` can't reach). |
| `stageRunner.js` | Shared staged-LLM runner. |
| `promptTemplate.js` | Mustache-flavored, dot-notation-aware prompt template engine. |
| `promptPartials.js` | Mustache-style partial expansion. |
diff --git a/server/lib/index.js b/server/lib/index.js
index 0b1f7f445c..5a864a19e9 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -108,6 +108,7 @@ export * as runners from './runners.js';
export * as stageRunner from './stageRunner.js';
export * from './tuiHandshake.js';
export * from './tuiPromptRunner.js';
+export * from './tuiUsageScrape.js';
// === File & I/O ===
export * from './boundedStateMap.js';
diff --git a/server/lib/tuiUsageScrape.js b/server/lib/tuiUsageScrape.js
new file mode 100644
index 0000000000..eba18b4e57
--- /dev/null
+++ b/server/lib/tuiUsageScrape.js
@@ -0,0 +1,148 @@
+import { spawn as ptySpawn } from 'node-pty';
+import { mkdirSync } from 'fs';
+import { tmpdir } from 'os';
+import { join } from 'path';
+import { stripAnsi } from './ansiStrip.js';
+import { sleep } from './fileUtils.js';
+
+/**
+ * Drive an interactive coding-agent TUI (Antigravity `agy`, Grok Build `grok`)
+ * in a throwaway PTY, type a slash command, and return the ANSI-stripped screen
+ * text so a caller can parse it.
+ *
+ * Why this exists: some CLIs expose subscription-quota usage ONLY through an
+ * interactive slash command (`/usage` for agy, `/usage show` for grok) — their
+ * non-interactive `--print` mode treats `/usage` as an LLM prompt (wrong data,
+ * and it burns tokens). So the only way to read that panel is to spawn the real
+ * TUI over a PTY, send the command, and scrape the rendered screen. This is the
+ * headless-TUI-scrape analogue of `claudeCodeUsage.js` (which gets to use the
+ * cheaper `echo /usage | claude -p` because Claude Code DOES honor `/usage` in
+ * print mode).
+ *
+ * The scrape runs in a dedicated **sandbox cwd** (a fixed dir under the OS temp
+ * dir) — never the user's project — so it can't read or mutate real work. The
+ * dir is stable (not per-call) on purpose: agy/grok remember "trusted folder"
+ * per path, so a stable sandbox is trusted once (via the primer Enter below)
+ * and every later scrape skips straight to the prompt.
+ *
+ * This drives a slash command that renders synchronously — it does NOT run an
+ * LLM turn — so it is 0-token and consumes no quota, matching the
+ * "user-triggered usage read" carve-out in the AI Provider Usage Policy.
+ *
+ * Read-only capture: we read the PTY output buffer from a variable and kill the
+ * child; the TUI never writes a response file (that pattern is `tuiPromptRunner`
+ * for LLM tasks — not applicable to a slash command).
+ */
+
+// Fixed, reused sandbox cwd so the "trust this folder?" gate is answered once.
+export const USAGE_SANDBOX_DIR = join(tmpdir(), 'portos-provider-usage-sandbox');
+
+// Wide PTY so quota panels/meters don't wrap and split a value across lines.
+const PTY_COLS = 200;
+const PTY_ROWS = 50;
+
+// Timing defaults (ms). The TUI needs a moment to sign in and paint its banner
+// before it accepts input; after the command we wait for the rendered panel to
+// stop changing (output-idle) rather than a fixed sleep, bounded by a hard cap.
+const DEFAULT_READY_MS = 6000; // banner + sign-in settle before first keystroke
+const DEFAULT_PRIMER_CAP_MS = 3000; // cap on waiting for the trust/menu dismissal to repaint
+const DEFAULT_IDLE_MS = 2500; // "screen finished rendering" = no output for this long
+const DEFAULT_RENDER_CAP_MS = 12000; // hard cap on waiting for the panel after the command
+const DEFAULT_HARD_TIMEOUT_MS = 45000; // absolute backstop for the whole scrape
+
+/**
+ * Spawn a TUI, send `slashCommand`, and resolve with the ANSI-stripped screen.
+ *
+ * @param {object} opts
+ * @param {string} opts.command — TUI binary (`agy`, `grok`).
+ * @param {string[]} [opts.args] — extra argv (default none).
+ * @param {string} opts.slashCommand — e.g. `/usage` or `/usage show`.
+ * @param {string} [opts.sandboxDir] — cwd override (default USAGE_SANDBOX_DIR).
+ * @param {number} [opts.readyMs] @param {number} [opts.primerCapMs]
+ * @param {number} [opts.idleMs] @param {number} [opts.renderCapMs]
+ * @param {number} [opts.timeoutMs]
+ * @returns {Promise<string>} ANSI-stripped captured output.
+ */
+export async function scrapeTuiUsage({
+ command,
+ args = [],
+ slashCommand,
+ sandboxDir = USAGE_SANDBOX_DIR,
+ readyMs = DEFAULT_READY_MS,
+ primerCapMs = DEFAULT_PRIMER_CAP_MS,
+ idleMs = DEFAULT_IDLE_MS,
+ renderCapMs = DEFAULT_RENDER_CAP_MS,
+ timeoutMs = DEFAULT_HARD_TIMEOUT_MS,
+} = {}) {
+ if (!command || typeof command !== 'string') throw new Error('scrapeTuiUsage: command is required');
+ if (!slashCommand || typeof slashCommand !== 'string') throw new Error('scrapeTuiUsage: slashCommand is required');
+
+ mkdirSync(sandboxDir, { recursive: true });
+
+ // CLAUDECODE leaks when PortOS itself runs under Claude Code; strip it so a
+ // spawned TUI doesn't think it's nested (mirrors tuiPromptRunner.js).
+ const env = { ...process.env, TERM: 'xterm-256color', COLORTERM: 'truecolor' };
+ delete env.CLAUDECODE;
+
+ let pty;
+ try {
+ pty = ptySpawn(command, args, {
+ name: 'xterm-256color', cols: PTY_COLS, rows: PTY_ROWS, cwd: sandboxDir, env,
+ });
+ } catch (err) {
+ throw new Error(`Failed to spawn TUI '${command}': ${err.message}`);
+ }
+
+ let raw = '';
+ let lastDataAt = Date.now();
+ let exited = false;
+ pty.onData((d) => { raw += d; lastDataAt = Date.now(); });
+ pty.onExit(() => { exited = true; });
+
+ const killPty = () => { try { if (!exited) pty.kill(); } catch { /* already gone */ } };
+
+ // Absolute backstop so a wedged TUI can't hang the request forever.
+ let hardTimer = null;
+ const hardStop = new Promise((resolve) => { hardTimer = setTimeout(resolve, timeoutMs); });
+ let timedOut = false;
+ hardStop.then(() => { timedOut = true; });
+
+ // Wait until the screen stops changing — no PTY output for `idleMs` — bounded
+ // by `capMs`. Each await also races the hard timeout, so a TUI that never goes
+ // idle still returns when hardStop resolves. Callers reset `lastDataAt` right
+ // after a keystroke so this measures idle relative to that input, not to stale
+ // banner output from an earlier phase.
+ const waitForIdle = async (capMs) => {
+ const deadline = Date.now() + capMs;
+ while (!exited && !timedOut && Date.now() < deadline) {
+ if (Date.now() - lastDataAt >= idleMs) return;
+ await Promise.race([sleep(250), hardStop]);
+ }
+ };
+
+ try {
+ await Promise.race([sleep(readyMs), hardStop]);
+
+ // Dismiss the first-run gate: agy shows "Do you trust this folder?" (default
+ // "Yes, I trust"), grok shows a start menu (default highlighted item). One
+ // Enter clears either. On an already-trusted sandbox there is no gate and
+ // this is a harmless empty-prompt submit. Wait for the dismissal to repaint.
+ if (!exited) { pty.write('\r'); lastDataAt = Date.now(); }
+ await waitForIdle(primerCapMs);
+
+ // Bracketed-paste the command so multi-word input (`/usage show`) lands
+ // atomically, then submit and wait for the panel to render.
+ if (!exited) {
+ pty.write(`\x1b[200~${slashCommand}\x1b[201~`);
+ await Promise.race([sleep(400), hardStop]);
+ pty.write('\r');
+ lastDataAt = Date.now();
+ }
+ await waitForIdle(renderCapMs);
+ } finally {
+ if (hardTimer) clearTimeout(hardTimer);
+ killPty();
+ }
+
+ return stripAnsi(raw);
+}
diff --git a/server/services/providerUsage.js b/server/services/providerUsage.js
index de2f514254..04551197a2 100644
--- a/server/services/providerUsage.js
+++ b/server/services/providerUsage.js
@@ -5,6 +5,7 @@ import { getAllProviders } from './providers.js';
import { getClaudeCodeUsage } from './claudeCodeUsage.js';
import { commandBasename, isClaudeCommand } from '../lib/providerModels.js';
import { isGrokCommand } from '../lib/grok.js';
+import { scrapeTuiUsage } from '../lib/tuiUsageScrape.js';
/**
* Provider subscription-quota adapters for /devtools/usage — one card per
@@ -22,11 +23,14 @@ import { isGrokCommand } from '../lib/grok.js';
* AI Provider Usage Policy: these fetches run only on user request from the
* usage page — never at server boot — and none of them consume tokens (the
* Claude `/usage` print-mode call is 0-token; the Codex adapter only reads
- * local session logs).
+ * local session logs; the Antigravity/Grok adapters drive an interactive
+ * `/usage` slash command that renders synchronously, with no LLM turn).
*
- * No registry-level cache: the claude adapter already carries its own 60s
- * cache + single-flight inside claudeCodeUsage.js, and the codex adapter is a
- * bounded local-file tail read (1-2 leaf dirs on a typical layout).
+ * Caching: the claude adapter carries its own 60s cache + single-flight inside
+ * claudeCodeUsage.js; the codex adapter is a bounded local-file tail read (1-2
+ * leaf dirs on a typical layout); the Antigravity/Grok adapters carry a 5-min
+ * cache + single-flight here (`cachedScrape`) because each TUI scrape costs
+ * ~10-15s (spawn + sign-in + render), too slow to repeat per page poll.
*/
// --- Codex: parse rate-limit telemetry out of local session logs -----------
@@ -184,6 +188,179 @@ async function fetchCodexQuota({ codexHome = codexHomeDir() } = {}) {
};
}
+// --- Antigravity + Grok: scrape the interactive TUI `/usage` panel ----------
+//
+// Neither CLI exposes quota in non-interactive `--print` mode (there, `/usage`
+// is treated as an LLM prompt — wrong data, and it burns tokens). Their only
+// usage surface is an interactive slash command, so we drive the real TUI in a
+// sandbox PTY (see lib/tuiUsageScrape.js) and parse the rendered screen. The
+// slash command renders synchronously (no LLM turn) → 0-token, user-triggered.
+
+// A short TTL cache: a TUI scrape costs ~10-15s (spawn + sign-in + render), far
+// too slow to repeat on every page poll. `refresh: true` bypasses it. Single-
+// user install, single process — a plain module-level map is sufficient.
+const SCRAPE_CACHE_TTL_MS = 5 * 60 * 1000;
+const scrapeCache = new Map(); // familyId -> { at, value } | { inflight }
+
+/** Test-only: clear the TUI-scrape TTL cache so a suite isn't order-dependent. */
+export function __resetUsageScrapeCache() {
+ scrapeCache.clear();
+}
+
+async function cachedScrape(familyId, { refresh }, produce) {
+ const hit = scrapeCache.get(familyId);
+ if (!refresh && hit?.value && Date.now() - hit.at < SCRAPE_CACHE_TTL_MS) return hit.value;
+ if (hit?.inflight) return hit.inflight; // fold concurrent callers into one scrape
+ const inflight = (async () => {
+ const value = await produce();
+ scrapeCache.set(familyId, { at: Date.now(), value });
+ return value;
+ })().catch((err) => {
+ scrapeCache.delete(familyId);
+ throw err;
+ });
+ scrapeCache.set(familyId, { inflight });
+ return inflight;
+}
+
+/**
+ * Render an acronym-preserving title label from an ALL-CAPS token: long words
+ * become Title Case (`GEMINI` → `Gemini`), short all-caps tokens stay as-is
+ * (`GPT` → `GPT`). Pure.
+ */
+function titleizeToken(token) {
+ if (token.length <= 4) return token; // GPT, GPU, etc. — keep the acronym
+ return token.charAt(0).toUpperCase() + token.slice(1).toLowerCase();
+}
+
+/** `GEMINI MODELS` → `Gemini`; `CLAUDE AND GPT MODELS` → `Claude/GPT`. Pure. */
+function agyGroupLabel(header) {
+ const core = header.replace(/\s*MODELS\s*$/i, '').trim();
+ return core
+ .split(/\s+AND\s+/i)
+ .map((part) => part.split(/\s+/).map(titleizeToken).join(' '))
+ .join('/');
+}
+
+/** `Weekly Limit` → `Weekly`; `Five Hour Limit` → `5-hour`. Pure. */
+function agyWindowLabel(raw) {
+ const core = raw.replace(/\s*Limit\s*$/i, '').trim();
+ return /^five hour$/i.test(core) ? '5-hour' : core;
+}
+
+const slug = (s) => s.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '');
+
+/**
+ * Parse `Refreshes in 167h 57m` / `4h 57m` / `2d 3h` into an absolute ISO reset
+ * time (now + duration). Returns null when no duration is found. `now` is
+ * injectable for tests. Pure given `now`.
+ */
+export function agyRefreshToIso(text, now = Date.now()) {
+ if (typeof text !== 'string') return null;
+ const d = text.match(/(\d+)\s*d/i);
+ const h = text.match(/(\d+)\s*h/i);
+ const m = text.match(/(\d+)\s*m(?!o)/i); // `m` but not `mo`(nth)
+ if (!d && !h && !m) return null;
+ const ms = ((d ? +d[1] : 0) * 86400 + (h ? +h[1] : 0) * 3600 + (m ? +m[1] : 0) * 60) * 1000;
+ return new Date(now + ms).toISOString();
+}
+
+/**
+ * Parse the Antigravity `/usage` panel text into common-shape limit rows.
+ * The panel groups models (e.g. `GEMINI MODELS`, `CLAUDE AND GPT MODELS`); each
+ * group has one or more `<window> Limit` rows showing a bar `NN.NN%` that is the
+ * percent REMAINING (a full bar = full quota), then either
+ * `NN% remaining · Refreshes in <dur>` or `Quota available` (full, no reset).
+ * Exported for tests. Pure given `now`.
+ *
+ * @returns {{ limits: Array, groups: number }}
+ */
+export function parseAgyUsage(text, { now = Date.now() } = {}) {
+ const lines = String(text || '').split('\n').map((l) => l.trim());
+ const limits = [];
+ const groups = new Set();
+ let group = null;
+ for (let i = 0; i < lines.length; i++) {
+ const line = lines[i];
+ const g = line.match(/^([A-Z][A-Z0-9 &/+-]*?MODELS)$/);
+ if (g) { group = agyGroupLabel(g[1]); groups.add(group); continue; }
+ if (!group) continue;
+ const w = line.match(/^([A-Z][A-Za-z ]{0,24}?Limit)$/);
+ if (!w) continue;
+ // Look ahead a few lines for the bar percentage + reset/quota-available.
+ let remaining = null;
+ let resetsAt = null;
+ let quotaAvailable = false;
+ for (let j = i + 1; j < Math.min(lines.length, i + 5); j++) {
+ const pct = lines[j].match(/([\d.]+)\s*%/);
+ if (pct && remaining === null) remaining = parseFloat(pct[1]);
+ if (/quota available/i.test(lines[j])) quotaAvailable = true;
+ const r = lines[j].match(/refreshes in\s+(.+?)(?:\s{2,}|·|$)/i);
+ if (r && !resetsAt) resetsAt = agyRefreshToIso(r[1], now);
+ }
+ if (remaining === null) continue; // not a real limit block
+ const windowLabel = agyWindowLabel(w[1]);
+ const percentRemaining = Math.round(remaining);
+ limits.push({
+ key: `${slug(group)}-${slug(windowLabel)}`,
+ label: `${group} · ${windowLabel}`,
+ scope: slug(windowLabel),
+ model: group,
+ percentUsed: Math.max(0, Math.round(100 - remaining)),
+ percentRemaining,
+ resetsAt: quotaAvailable ? null : resetsAt,
+ timezone: null,
+ });
+ }
+ return { limits, groups: groups.size };
+}
+
+/**
+ * Parse the Grok Build `/usage show` panel text. Grok reports a single line
+ * `Weekly limit: N%` (percent USED) plus `Next reset: <date>`. Exported for
+ * tests. Pure.
+ *
+ * @returns {{ limits: Array }}
+ */
+export function parseGrokUsage(text) {
+ const str = String(text || '');
+ const wl = str.match(/weekly limit:\s*([\d.]+)\s*%/i);
+ if (!wl) return { limits: [] };
+ const percentUsed = Math.round(parseFloat(wl[1]));
+ const nr = str.match(/next reset:\s*([A-Za-z0-9 ,:]+?)(?:\s{2,}|$)/i);
+ return {
+ limits: [{
+ key: 'weekly',
+ label: 'Weekly',
+ scope: 'week',
+ model: null,
+ percentUsed,
+ percentRemaining: Math.max(0, 100 - percentUsed),
+ // Grok gives a local-time date string without a year/zone; pass it
+ // through verbatim (the UI renders non-ISO reset strings as-is).
+ resetsAt: nr ? nr[1].trim() : null,
+ timezone: null,
+ }],
+ };
+}
+
+/**
+ * Build a family `fetch` fn that scrapes a TUI `/usage` panel and maps it to the
+ * common quota shape (cached; `refresh` bypasses). `parse` returns `{ limits }`;
+ * an empty result becomes a `supported`-but-`error` card so the UI shows a soft
+ * warning rather than a blank card. `name` is the human product name spliced
+ * into the note/error copy (e.g. `Antigravity CLI`).
+ */
+function makeTuiUsageFetcher({ id, command, slashCommand, label, parse, name }) {
+ return ({ refresh = false } = {}) => cachedScrape(id, { refresh }, async () => {
+ const { limits } = parse(await scrapeTuiUsage({ command, slashCommand }));
+ const base = { family: id, label, supported: true, plan: null, activity: [], approximate: true, fetchedAt: new Date().toISOString() };
+ return limits.length
+ ? { ...base, limits, note: `Scraped from the ${name} /usage panel — local, approximate.` }
+ : { ...base, limits: [], error: `No quota data found in the ${name} /usage panel.` };
+ });
+}
+
// --- Claude: wrap the existing /usage CLI parser ---------------------------
async function fetchClaudeQuota({ refresh = false } = {}) {
@@ -201,19 +378,6 @@ async function fetchClaudeQuota({ refresh = false } = {}) {
};
}
-// --- Unsupported families ---------------------------------------------------
-
-const unsupported = (family, label, reason) => async () => ({
- family,
- label,
- supported: false,
- limits: [],
- activity: [],
- approximate: false,
- note: reason,
- fetchedAt: new Date().toISOString()
-});
-
// --- Family registry --------------------------------------------------------
/**
@@ -239,13 +403,13 @@ const FAMILIES = [
id: 'agy',
label: 'Antigravity',
matches: (p) => commandBasename(p.command) === 'agy' || /antigravity/i.test(p.id || ''),
- fetch: unsupported('agy', 'Antigravity', 'The Antigravity CLI does not expose usage or quota telemetry.')
+ fetch: makeTuiUsageFetcher({ id: 'agy', command: 'agy', slashCommand: '/usage', label: 'Antigravity', parse: parseAgyUsage, name: 'Antigravity CLI' })
},
{
id: 'grok',
label: 'Grok',
matches: (p) => isGrokCommand(p.command) || /grok/i.test(p.id || ''),
- fetch: unsupported('grok', 'Grok', 'The Grok CLI and xAI API do not expose remaining-quota telemetry.')
+ fetch: makeTuiUsageFetcher({ id: 'grok', command: 'grok', slashCommand: '/usage show', label: 'Grok', parse: parseGrokUsage, name: 'Grok Build CLI' })
}
];
diff --git a/server/services/providerUsage.test.js b/server/services/providerUsage.test.js
index c439b6be43..8fb5f5ac58 100644
--- a/server/services/providerUsage.test.js
+++ b/server/services/providerUsage.test.js
@@ -1,4 +1,4 @@
-import { describe, it, expect, vi } from 'vitest';
+import { describe, it, expect, vi, beforeEach } from 'vitest';
// providerUsage imports the provider config service (toolkit-backed) and the
// claude CLI wrapper — mock both so this suite stays hermetic.
@@ -10,9 +10,52 @@ vi.mock('./providers.js', () => ({
vi.mock('./claudeCodeUsage.js', () => ({
getClaudeCodeUsage: vi.fn()
}));
+// The agy/grok adapters drive a real TUI over a PTY — mock the scrape so these
+// tests exercise the parse + fetch wiring without spawning a subprocess.
+vi.mock('../lib/tuiUsageScrape.js', () => ({
+ scrapeTuiUsage: vi.fn()
+}));
-import { parseCodexRateLimits, mapCodexQuota, resolveEnabledFamilies, getProviderQuotas } from './providerUsage.js';
+import {
+ parseCodexRateLimits, mapCodexQuota, resolveEnabledFamilies, getProviderQuotas,
+ parseAgyUsage, parseGrokUsage, agyRefreshToIso, __resetUsageScrapeCache,
+} from './providerUsage.js';
import { getAllProviders } from './providers.js';
+import { scrapeTuiUsage } from '../lib/tuiUsageScrape.js';
+
+// Synthetic Antigravity `/usage` panel — invented values, redacted account, in
+// the real rendered shape. The bar percentage is percent REMAINING; a full bar
+// with "Quota available" has no reset.
+const AGY_PANEL = `└ Models & Quota
+
+
+GEMINI MODELS
+ Models within this group: Gemini Flash, Gemini Pro
+
+ Weekly Limit
+ [█████████████████████████████████████████████████░] 98.99%
+ 99% remaining · Refreshes in 167h 57m
+
+ Five Hour Limit
+ [████████████████████████████████████████░░░░░░░░░░] 80.00%
+ 80% remaining · Refreshes in 4h 30m
+
+
+CLAUDE AND GPT MODELS
+ Models within this group: Claude Opus, Claude Sonnet, GPT-OSS
+
+ Weekly Limit
+ [██████████████████████████████████████████████████] 100.00%
+ Quota available
+
+ Five Hour Limit
+ [██████████████████████████████████████████████████] 100.00%
+ Quota available
+`;
+
+// Synthetic Grok `/usage show` output — `Weekly limit: N%` is percent USED.
+const GROK_PANEL = 'noise noise Weekly limit: 42% Next reset: August 1, 06:07 trailing noise';
// Synthetic rollout line matching the codex event_msg/token_count shape —
// invented values only, never a transcript from a real session.
@@ -112,8 +155,109 @@ describe('getProviderQuotas', () => {
activeProvider: 'grok',
providers: [{ id: 'grok', enabled: true, type: 'api', endpoint: 'https://api.x.ai/v1' }]
});
+ scrapeTuiUsage.mockResolvedValue('Weekly limit: 5% Next reset: Jan 1, 00:00');
const quotas = await getProviderQuotas();
expect(Array.isArray(quotas)).toBe(true);
expect(quotas.map((q) => q.family)).toEqual(['grok']);
});
});
+
+describe('agyRefreshToIso', () => {
+ const NOW = Date.parse('2026-07-14T20:00:00.000Z');
+
+ it('parses hours + minutes into an absolute ISO reset time', () => {
+ expect(agyRefreshToIso('167h 57m', NOW)).toBe(new Date(NOW + (167 * 3600 + 57 * 60) * 1000).toISOString());
+ expect(agyRefreshToIso('4h 30m', NOW)).toBe(new Date(NOW + (4 * 3600 + 30 * 60) * 1000).toISOString());
+ });
+
+ it('parses days and standalone hours', () => {
+ expect(agyRefreshToIso('2d 3h', NOW)).toBe(new Date(NOW + (2 * 86400 + 3 * 3600) * 1000).toISOString());
+ expect(agyRefreshToIso('12h', NOW)).toBe(new Date(NOW + 12 * 3600 * 1000).toISOString());
+ });
+
+ it('returns null when no duration token is present', () => {
+ expect(agyRefreshToIso('soon')).toBeNull();
+ expect(agyRefreshToIso(null)).toBeNull();
+ expect(agyRefreshToIso('')).toBeNull();
+ });
+});
+
+describe('parseAgyUsage', () => {
+ const NOW = Date.parse('2026-07-14T20:00:00.000Z');
+
+ it('maps each model group + window, treating the bar percentage as REMAINING', () => {
+ const { limits, groups } = parseAgyUsage(AGY_PANEL, { now: NOW });
+ expect(groups).toBe(2);
+ expect(limits).toHaveLength(4);
+
+ const gemWeek = limits.find((l) => l.key === 'gemini-weekly');
+ // 98.99% remaining → 1% used (100 - 98.99 = 1.01, rounded).
+ expect(gemWeek).toMatchObject({ label: 'Gemini · Weekly', percentUsed: 1, percentRemaining: 99, model: 'Gemini' });
+ expect(gemWeek.resetsAt).toBe(new Date(NOW + (167 * 3600 + 57 * 60) * 1000).toISOString());
+
+ const gem5h = limits.find((l) => l.key === 'gemini-5-hour');
+ expect(gem5h).toMatchObject({ label: 'Gemini · 5-hour', percentUsed: 20, percentRemaining: 80 });
+ });
+
+ it('preserves acronyms in group labels and null-resets a fully-available window', () => {
+ const { limits } = parseAgyUsage(AGY_PANEL, { now: NOW });
+ const cgWeek = limits.find((l) => l.key === 'claude-gpt-weekly');
+ // "CLAUDE AND GPT MODELS" → "Claude/GPT" (GPT acronym kept); 100% remaining,
+ // "Quota available" → 0% used, no reset.
+ expect(cgWeek).toMatchObject({ label: 'Claude/GPT · Weekly', percentUsed: 0, percentRemaining: 100, resetsAt: null });
+ });
+
+ it('returns no limits for text without a model group', () => {
+ expect(parseAgyUsage('Welcome to the Antigravity CLI').limits).toEqual([]);
+ expect(parseAgyUsage('').limits).toEqual([]);
+ });
+});
+
+describe('parseGrokUsage', () => {
+ it('reads the weekly limit as percent USED and passes the reset string through', () => {
+ const { limits } = parseGrokUsage(GROK_PANEL);
+ expect(limits).toHaveLength(1);
+ expect(limits[0]).toMatchObject({ key: 'weekly', label: 'Weekly', percentUsed: 42, percentRemaining: 58, resetsAt: 'August 1, 06:07' });
+ });
+
+ it('returns no limits when the panel has no weekly-limit line', () => {
+ expect(parseGrokUsage('Grok Build Beta 0.2.101').limits).toEqual([]);
+ expect(parseGrokUsage(undefined).limits).toEqual([]);
+ });
+});
+
+describe('TUI usage fetchers (via getProviderQuotas)', () => {
+ beforeEach(() => {
+ __resetUsageScrapeCache();
+ scrapeTuiUsage.mockReset();
+ });
+
+ it('surfaces a supported Antigravity card with parsed limits', async () => {
+ getAllProviders.mockResolvedValueOnce({ activeProvider: 'agy', providers: [{ id: 'antigravity-cli', enabled: true, type: 'cli', command: 'agy' }] });
+ scrapeTuiUsage.mockResolvedValueOnce(AGY_PANEL);
+ const [card] = await getProviderQuotas();
+ expect(scrapeTuiUsage).toHaveBeenCalledWith({ command: 'agy', slashCommand: '/usage' });
+ expect(card).toMatchObject({ family: 'agy', supported: true });
+ expect(card.error).toBeUndefined();
+ expect(card.limits).toHaveLength(4);
+ });
+
+ it('surfaces a supported-but-error card when the scrape yields no parseable data', async () => {
+ getAllProviders.mockResolvedValueOnce({ activeProvider: 'grok', providers: [{ id: 'grok', enabled: true, type: 'api', endpoint: 'https://api.x.ai/v1' }] });
+ scrapeTuiUsage.mockResolvedValueOnce('unrecognized banner, no usage line');
+ const [card] = await getProviderQuotas();
+ expect(card).toMatchObject({ family: 'grok', supported: true });
+ expect(card.limits).toEqual([]);
+ expect(card.error).toMatch(/No quota data/);
+ });
+
+ it('caches a scrape and folds a bypassing refresh into a fresh call', async () => {
+ getAllProviders.mockResolvedValue({ activeProvider: 'agy', providers: [{ id: 'antigravity-cli', enabled: true, type: 'cli', command: 'agy' }] });
+ scrapeTuiUsage.mockResolvedValue(AGY_PANEL);
+ await getProviderQuotas();
+ await getProviderQuotas(); // cache hit — no second scrape
+ expect(scrapeTuiUsage).toHaveBeenCalledTimes(1);
+ await getProviderQuotas({ refresh: true }); // bypasses cache
+ expect(scrapeTuiUsage).toHaveBeenCalledTimes(2);
+ });
+});