diff --git a/bin/omarchy-agent-usage-grok b/bin/omarchy-agent-usage-grok new file mode 100755 index 000000000000..2e31a95e84e1 --- /dev/null +++ b/bin/omarchy-agent-usage-grok @@ -0,0 +1,553 @@ +#!/usr/bin/python3 +# omarchy:summary=Print the Grok usage record as JSON +# omarchy:args=[--force] [--limits-only] +# omarchy:hidden=true +"""Collect Grok CLI usage into one display-ready JSON record. + +Token stats come from the session transcripts under ~/.grok/sessions. The +weekly credit allowance and the plan come from Grok's ACP `_x.ai/billing` +method over `grok agent stdio`, falling back to the reading grok writes to +its own log. The agents panel only ever reads the JSON this prints. +""" + +from __future__ import annotations + +import argparse +import json +import os +import select +import shutil +import subprocess +import sys +import time +from datetime import datetime, timedelta, timezone +from collections.abc import Iterator +from pathlib import Path +from typing import Any + +AGENT_ID = "grok" +AGENT_NAME = "Grok" +AUTH_HELP = "Run `grok` and sign in to record usage." + +# A bar refresh must not stall on Grok. The ACP round-trip is typically well +# under a second; this bound is the ceiling, not the expected wait. +ACP_TIMEOUT_SECONDS = 4 + +# `_x.ai/billing` is a vendor extension, and from here a method grok has +# renamed looks the same as a grok that is signed out. Grok also logs the +# config it fetched at startup, so that log stands in when the call says +# nothing. Matching on a log message is the more brittle of the two, which is +# why it is the fallback rather than the source. +CREDITS_MARKER = b'"billing: fetched credits config"' +LOG_CHUNK_BYTES = 256 * 1024 +LOG_SCAN_LIMIT_BYTES = 8 * 1024 * 1024 + + +def number(value: Any) -> int: + try: + return int(value or 0) + except (TypeError, ValueError): + return 0 + + +def local_day(value: Any) -> str: + if value is None: + return datetime.now().strftime("%Y-%m-%d") + if isinstance(value, (int, float)): + # Grok stamps session updates in seconds; tolerate milliseconds. + if value > 10_000_000_000: + value = value / 1000 + return datetime.fromtimestamp(value).strftime("%Y-%m-%d") + parsed = parse_iso(value) + if parsed is None: + return datetime.now().strftime("%Y-%m-%d") + return parsed.astimezone().strftime("%Y-%m-%d") + + +def parse_iso(value: Any) -> datetime | None: + text = str(value or "").strip() + if text == "": + return None + try: + parsed = datetime.fromisoformat(text.replace("Z", "+00:00")) + except ValueError: + return None + return parsed if parsed.tzinfo is not None else parsed.replace(tzinfo=timezone.utc) + + +def grok_home() -> Path: + home = os.environ.get("GROK_HOME") + return Path(home) if home else Path.home() / ".grok" + + +def sessions_root() -> Path: + return grok_home() / "sessions" + + +def log_path() -> Path: + configured = os.environ.get("GROK_LOG_FILE") + return Path(configured) if configured else grok_home() / "logs" / "unified.jsonl" + + +def model_name(raw: Any) -> str: + return str(raw or "").strip() or "grok" + + +# Grok folds its detail counters into the two totals: totalTokens == +# inputTokens + outputTokens on every record on disk, with the cache and +# reasoning figures nested inside. Subtract the cache ones so nothing doubles. +def split_tokens(stats: dict[str, Any]) -> tuple[int, int, int, int]: + cache_read = number(stats.get("cachedReadTokens")) + cache_creation = number(stats.get("cacheCreationTokens")) + input_tokens = max(0, number(stats.get("inputTokens")) - cache_read - cache_creation) + output_tokens = number(stats.get("outputTokens")) + return input_tokens, output_tokens, cache_read, cache_creation + + +class SessionUsage: + """The running totals every completed turn on disk adds up to.""" + + def __init__(self, today: str | None = None): + self.today = today or datetime.now().strftime("%Y-%m-%d") + start = datetime.strptime(self.today, "%Y-%m-%d") + self.recent_dates = [(start - timedelta(days=offset)).strftime("%Y-%m-%d") for offset in range(6, -1, -1)] + self.recent = {day: 0 for day in self.recent_dates} + self.today_tokens_by_model: dict[str, int] = {} + self.model_usage: dict[str, dict[str, int]] = {} + self.today_prompts: dict[str, int] = {} + self.today_total_tokens = 0 + self.total_prompts: dict[str, int] = {} + self.active_days: set[str] = set() + self.seen_turns: set[str] = set() + # Sessions a subagent ran in. Their tokens count, but no one typed their + # prompts or started them, so they stay out of the session and prompt + # totals. A parent can be scanned after its child, so these are left out + # when the totals are read rather than as turns arrive. + self.child_sessions: set[str] = set() + + def add_turn(self, day: str, session_key: str, per_model: list[tuple[str, int, int, int, int]]) -> None: + # One completed turn is one prompt, however many models answered it. + # Counting per model would inflate the prompt and session totals on any + # turn that handed work to a secondary model. + self.total_prompts[session_key] = self.total_prompts.get(session_key, 0) + 1 + self.active_days.add(day) + + turn_total = 0 + for model, input_tokens, output_tokens, cache_read, cache_creation in per_model: + bucket = self.model_usage.setdefault(model, { + "inputTokens": 0, + "outputTokens": 0, + "cacheReadInputTokens": 0, + "cacheCreationInputTokens": 0, + }) + bucket["inputTokens"] += input_tokens + bucket["outputTokens"] += output_tokens + bucket["cacheReadInputTokens"] += cache_read + bucket["cacheCreationInputTokens"] += cache_creation + + model_total = input_tokens + output_tokens + cache_read + cache_creation + turn_total += model_total + if day == self.today: + self.today_tokens_by_model[model] = self.today_tokens_by_model.get(model, 0) + model_total + + if day in self.recent: + self.recent[day] += turn_total + + if day == self.today: + self.today_prompts[session_key] = self.today_prompts.get(session_key, 0) + 1 + self.today_total_tokens += turn_total + + def typed(self, prompts: dict[str, int]) -> dict[str, int]: + return {session: count for session, count in prompts.items() if session not in self.child_sessions} + + def stats(self) -> dict[str, Any]: + today_prompts = self.typed(self.today_prompts) + total_prompts = self.typed(self.total_prompts) + return { + "todayPrompts": sum(today_prompts.values()), + "todaySessions": len(today_prompts), + "todayTotalTokens": self.today_total_tokens, + "todayTokensByModel": self.today_tokens_by_model, + "recentDays": [{"date": day, "messageCount": self.recent[day]} for day in self.recent_dates], + "totalPrompts": sum(total_prompts.values()), + "totalSessions": len(total_prompts), + # Days with any recorded usage, for the all-time "N days" summary. The + # dates travel too: merging snapshots from several machines needs their + # union, which a count alone cannot give. + "activeDays": len(self.active_days), + "activeDates": sorted(self.active_days), + "modelUsage": self.model_usage, + } + + +def turn_models(update: dict[str, Any]) -> list[tuple[str, int, int, int, int]]: + usage = update.get("usage") or {} + if not isinstance(usage, dict) or not usage: + return [] + + models = usage.get("modelUsage") + per_model = [] + if isinstance(models, dict) and models: + for model, stats in models.items(): + if not isinstance(stats, dict): + continue + input_tokens, output_tokens, cache_read, cache_creation = split_tokens(stats) + if input_tokens or output_tokens or cache_read or cache_creation: + per_model.append((model_name(model), input_tokens, output_tokens, cache_read, cache_creation)) + else: + input_tokens, output_tokens, cache_read, cache_creation = split_tokens(usage) + if input_tokens or output_tokens or cache_read or cache_creation: + per_model.append((model_name(update.get("model")), input_tokens, output_tokens, cache_read, cache_creation)) + return per_model + + +def scan_sessions(usage: SessionUsage) -> None: + root = sessions_root() + if not root.is_dir(): + return + + # sessions///updates.jsonl + for path in sorted(root.glob("*/*/updates.jsonl")): + session_key = path.parent.name + try: + with path.open(errors="replace") as handle: + for raw in handle: + # Turn records are a thin minority of a transcript that also carries + # every message and tool payload, so skip the rest before paying for + # a parse. + spawn = '"subagent_spawned"' in raw + if not spawn and '"usage"' not in raw: + continue + try: + entry = json.loads(raw) + except json.JSONDecodeError: + continue + update = (entry.get("params") or {}).get("update") or {} + # The child runs in a session directory of its own beside this one, + # named by its session id. + if update.get("sessionUpdate") == "subagent_spawned": + child = str(update.get("child_session_id") or "") + if child: + usage.child_sessions.add(child) + continue + # Only the end-of-turn record carries usage, and it reports that turn + # rather than a running total, so these sum rather than replace. + if update.get("sessionUpdate") != "turn_completed": + continue + + prompt_id = str(update.get("prompt_id") or "") + turn_key = session_key + ":" + prompt_id if prompt_id else "" + if turn_key and turn_key in usage.seen_turns: + continue + + # Claim the id once the turn is known to count. An interrupted turn + # is written with no usage key at all and never reaches this, so the + # order is semantics rather than a fix for a shape grok emits. + per_model = turn_models(update) + if not per_model: + continue + if turn_key: + usage.seen_turns.add(turn_key) + + try: + fallback = path.stat().st_mtime + except OSError: + fallback = None + usage.add_turn(local_day(entry.get("timestamp") or fallback), session_key, per_model) + except OSError: + continue + + +def period_label(raw: Any, start: datetime, end: datetime) -> str: + kind = str(raw or "").upper().replace("USAGE_PERIOD_TYPE_", "") + if kind == "WEEKLY": + return "Weekly (7-day)" + if kind == "MONTHLY": + return "Monthly" + if kind == "DAILY": + return "Daily" + days = max(1, round((end - start).total_seconds() / 86400)) + if days == 7: + return "Weekly (7-day)" + if days in (30, 31): + return "Monthly" + return f"{days}-day window" + + +def limit_from_config(config: Any) -> dict[str, Any] | None: + if not isinstance(config, dict): + return None + + percent = config.get("creditUsagePercent") + period = config.get("currentPeriod") or {} + start = parse_iso(period.get("start") or config.get("billingPeriodStart")) + end = parse_iso(period.get("end") or config.get("billingPeriodEnd")) + # A window with no percentage is not a meter of 0 — it is no meter. + if percent is None or start is None or end is None: + return None + + # A percentage belongs to the period it was measured in, so one from a period + # that has since rolled over is not merely stale, it is a different week's. + # Showing nothing beats showing last week's number against this week's reset. + now = datetime.now(timezone.utc) + if not (start <= now <= end): + return None + + try: + fraction = float(percent) / 100.0 + except (TypeError, ValueError): + return None + + return { + "label": period_label(period.get("type"), start, end), + "percent": max(0.0, min(1.0, fraction)), + "resetsAt": end.isoformat(), + } + + +def empty_credits() -> dict[str, Any]: + return {"tierLabel": "", "limits": []} + + +def runtime_env() -> dict[str, str]: + # The bar may not inherit the login PATH that holds the grok wrapper + # Omarchy installs into ~/.local/bin (and mise shims). + home = str(Path.home()) + path_parts = [ + os.environ.get("PATH", ""), + f"{home}/.local/bin", + f"{home}/.local/share/mise/shims", + ] + env = os.environ.copy() + env["PATH"] = os.pathsep.join(part for part in path_parts if part) + return env + + +def rpc_request(proc: subprocess.Popen[str], request_id: int, method: str, params: dict[str, Any] | None = None, + timeout: float = ACP_TIMEOUT_SECONDS) -> dict[str, Any]: + if proc.stdin is None or proc.stdout is None: + raise TimeoutError(method) + proc.stdin.write(json.dumps({"jsonrpc": "2.0", "id": request_id, "method": method, "params": params or {}}) + "\n") + proc.stdin.flush() + deadline = time.monotonic() + timeout + while time.monotonic() < deadline: + ready, _, _ = select.select([proc.stdout], [], [], 0.25) + if not ready: + continue + line = proc.stdout.readline() + if not line: + break + try: + message = json.loads(line) + except json.JSONDecodeError: + continue + if isinstance(message, dict) and message.get("id") == request_id: + return message + raise TimeoutError(method) + + +def terminate(proc: subprocess.Popen[str]) -> None: + try: + proc.terminate() + proc.wait(timeout=1) + except Exception: + try: + proc.kill() + proc.wait(timeout=1) + except Exception: + pass + + +def credits_from_billing(message: dict[str, Any]) -> dict[str, Any]: + if message.get("error"): + return empty_credits() + result = message.get("result") + if not isinstance(result, dict): + return empty_credits() + # Grok 1.0.5 returns subscription_tier; accept camelCase if a later build + # matches the rest of the ACP surface. + tier = str(result.get("subscription_tier") or result.get("subscriptionTier") or "").strip() + limit = limit_from_config(result.get("config")) + return {"tierLabel": tier, "limits": [limit] if limit else []} + + +def fetch_acp_credits() -> dict[str, Any]: + env = runtime_env() + grok = shutil.which("grok", path=env.get("PATH")) + if not grok: + return empty_credits() + + try: + proc = subprocess.Popen( + [grok, "agent", "stdio"], + stdin=subprocess.PIPE, + stdout=subprocess.PIPE, + stderr=subprocess.DEVNULL, + text=True, + env=env, + ) + except OSError: + return empty_credits() + + try: + initialize = rpc_request(proc, 1, "initialize", { + "protocolVersion": 1, + "clientCapabilities": {"terminal": False}, + "_meta": { + "clientType": "omarchy-agent-usage", + "clientVersion": "1", + "startupHints": { + "nonInteractive": True, + "skipGitStatus": True, + "skipProjectLayout": True, + }, + }, + }) + if initialize.get("error"): + return empty_credits() + return credits_from_billing(rpc_request(proc, 2, "_x.ai/billing", {})) + except Exception: + return empty_credits() + finally: + terminate(proc) + + +def credits_records() -> Iterator[dict[str, Any]]: + """Every logged credits reading, newest first.""" + path = log_path() + try: + size = path.stat().st_size + except OSError: + return + + # The log is append-only and the newest reading is the one that counts, so + # walk back from the end in chunks instead of parsing a log that grows without + # bound. The scan limit keeps a huge log from stalling a bar refresh. + position = size + scanned = 0 + partial = b"" + try: + with path.open("rb") as handle: + while position > 0 and scanned < LOG_SCAN_LIMIT_BYTES: + step = min(LOG_CHUNK_BYTES, position) + position -= step + scanned += step + handle.seek(position) + lines = (handle.read(step) + partial).split(b"\n") + # The first piece is only a whole line once the read reaches the start + # of the file; until then it is the tail of an earlier line. + partial = lines.pop(0) if position > 0 else b"" + for raw in reversed(lines): + if CREDITS_MARKER not in raw: + continue + try: + record = json.loads(raw) + except json.JSONDecodeError: + continue + if isinstance(record, dict): + yield record + except OSError: + return + + +def logged_credits() -> dict[str, Any]: + """The newest logged tier, and the newest usable limit behind it. + + Grok logs a config on every startup, and some of them carry no usage + percentage at all — a period with a reading is not necessarily the one + logged last. An older reading is still this period's, since + limit_from_config drops anything whose period has closed, so the newest + usable one beats no meter at all. + """ + tier = "" + limit = None + for record in credits_records(): + context = record.get("ctx") + if not isinstance(context, dict): + continue + tier = tier or str(context.get("subscriptionTier") or "").strip() + limit = limit or limit_from_config(context.get("config")) + if tier and limit: + break + return {"tierLabel": tier, "limits": [limit] if limit else []} + + +def read_credits() -> dict[str, Any]: + # Grok owns the billing call, so the plan and the meter come from the CLI + # rather than from its credentials and a private endpoint. + credits = fetch_acp_credits() + if credits["tierLabel"] and credits["limits"]: + return credits + + # Either half can come back missing on its own — a signed-out CLI answers + # with neither, a renamed method with neither, and a window still waiting on + # its first reading with a plan and no meter — so fill them independently + # rather than dropping a good ACP tier to take the log's. + logged = logged_credits() + return { + "tierLabel": credits["tierLabel"] or logged["tierLabel"], + "limits": credits["limits"] or logged["limits"], + } + + +def scan() -> dict[str, Any]: + usage = SessionUsage() + scan_sessions(usage) + stats = usage.stats() + credits = read_credits() + + record = { + "schemaVersion": 1, + "id": AGENT_ID, + "name": AGENT_NAME, + "updatedAt": datetime.now(timezone.utc).isoformat(), + "ready": stats["totalPrompts"] > 0 or len(credits["limits"]) > 0, + "hasLocalStats": True, + "tierLabel": credits["tierLabel"], + # Grok bills one weekly credit allowance, with no session window beside it. + "limits": credits["limits"], + "usageStatusText": "", + "authHelpText": AUTH_HELP, + } + # A plan with no meter is normal — a fresh window has no reading to report + # yet. Knowing neither means both the ACP call and the log told us nothing at + # all, which is worth saying out loud beside the empty meter. + if not credits["tierLabel"] and not credits["limits"]: + record["usageStatusText"] = "Grok limits unavailable" + record.update(stats) + return record + + +def main() -> int: + parser = argparse.ArgumentParser(description="Print the Grok usage record as JSON") + # Local transcripts are cheap, ACP billing is a short stdio round-trip, and + # the log is only read when that says nothing. There is no cache to force + # past and no faster limits-only path. The flags exist so every collector + # accepts the same invocation. + parser.add_argument("--force", action="store_true") + parser.add_argument("--limits-only", action="store_true") + parser.parse_args() + + try: + record = scan() + except Exception as error: + record = { + "schemaVersion": 1, + "id": AGENT_ID, + "name": AGENT_NAME, + "updatedAt": datetime.now(timezone.utc).isoformat(), + "ready": False, + "hasLocalStats": False, + "tierLabel": "", + "limits": [], + "usageStatusText": "Grok unavailable", + "authHelpText": "Grok usage scan failed", + } + record.update(SessionUsage().stats()) + print(f"omarchy-agent-usage-grok: {type(error).__name__}", file=sys.stderr) + print(json.dumps(record, separators=(",", ":"))) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/manual/17-ai.md b/manual/17-ai.md index 6739a612777b..16c6ef94b09e 100644 --- a/manual/17-ai.md +++ b/manual/17-ai.md @@ -36,7 +36,7 @@ There are terminal shortcuts too: `a` runs the default agent inline in the curre ### The agents panel -The top bar grows an agents icon the first time Omarchy finds AI coding usage on the machine (and stays out of the way until then). The panel behind it tracks every subscription in one place: your plan, the percentage used of the 5-hour session and weekly limits (or the remaining prepaid balance), and token usage by day and by model. Claude Code, Codex, and Fireworks are covered out of the box. +The top bar grows an agents icon the first time Omarchy finds AI coding usage on the machine (and stays out of the way until then). The panel behind it tracks every subscription in one place: your plan, the percentage used of the 5-hour session and weekly limits (or the remaining prepaid balance), and token usage by day and by model. Claude Code, Codex, Grok, and Fireworks are covered out of the box. Left-click the bar icon for the panel, right-click to launch your default agent. The usage records behind it are regenerated every 15 minutes by `omarchy agent usage-update`, and the panel can even merge usage from your other machines via a synced folder. See the README under `$OMARCHY_PATH/shell/plugins/agents/` for the full settings. diff --git a/shell/plugins/agents/README.md b/shell/plugins/agents/README.md index 51ad4e43c2d2..309cb5eee034 100644 --- a/shell/plugins/agents/README.md +++ b/shell/plugins/agents/README.md @@ -54,16 +54,58 @@ light surfaces — and the bar glyph stands in when there is none. |---|---|---| | `claude` | Anthropic's OAuth usage endpoint (5-hour session + 7-day weekly) | `~/.claude/projects` transcripts, opencode sessions on an Anthropic provider, plus `stats-cache.json` and `history.jsonl` as fallback | | `codex` | The Codex app-server RPC | native Codex CLI session files (plus pi and opencode sessions) | +| `grok` | The weekly credit allowance from grok's ACP billing method (or its log), when the reading includes a percentage | `~/.grok/sessions` transcripts | | `fireworks` | Estimated prepaid balance: configured funding minus rated account costs | Fireworks billing API, grouped by day and model for the last 30 days | Claude limits need a signed-in CLI; without credentials the panel says so and falls back to local stats only. A non-default Claude directory is honored via -`CLAUDE_CONFIG_DIR`, Codex via `CODEX_HOME`. Fireworks reads +`CLAUDE_CONFIG_DIR`, Codex via `CODEX_HOME`, Grok via `GROK_HOME`. Fireworks reads `FIREWORKS_API_KEY` and `FIREWORKS_ACCOUNT_ID` first, then `~/.fireworks/auth.ini` (which `firectl set-api-key` creates), then the key opencode stores in `~/.local/share/opencode/auth.json` when Fireworks is signed in there. +### Grok credits + +The plan and the weekly allowance come from grok's own ACP `_x.ai/billing` +method, asked over `grok agent stdio`. Grok owns that call, so the collector +never reads `auth.json` and never talks to an xAI endpoint itself — the same +boundary the Codex collector keeps. + +`_x.ai/billing` is a vendor extension with no stability promise, and from +here a method grok has renamed looks the same as a grok that is signed out. +Grok also logs the config it fetched at startup, so the newest usable reading +in `~/.grok/logs/unified.jsonl` stands in when the call says nothing. That +fallback matches on a log message, which is the more brittle of the two — +hence the fallback rather than the source. The plan and the meter are filled +independently, so an answer that carries one but not the other keeps what it +gave. + +A usable reading is a percentage that belongs to a period that is still open, +and neither half is guaranteed. A reading from a closed week is the wrong +week's number, and a window with no percentage in it is not a meter of zero — +it is no meter. Either way the meter is omitted rather than guessed, and the +tab shows tokens only. + +That omission is not hypothetical: grok 1.0.0 stopped reporting the +percentage for every reading, where 0.2.118 had carried one in 100 of 102 on +the same account. It came back in 1.0.5, and the meter lit up again on its +own — which is the behaviour to expect the next time the field moves. + +The same reply carries `prepaidBalance`, `onDemandCap`, and `onDemandUsed`, +each as a `{"val": N}` object. None of them feed the panel's balance ledger: +they read `0` on every account this has been seen on, and nothing in the reply +names a unit, so credits, dollars, and cents are indistinguishable at zero. +Mapping them would mean guessing the scale of a number nobody has yet seen be +non-zero, and the failure mode of guessing wrong is a confidently wrong +balance rather than a missing one. + +Worth knowing when reading the panel: the meter and the token chart do not +agree and cannot be made to. Grok's transcripts are overwhelmingly cache +reads, and the allowance is billed per X identity rather than per machine, so +usage from the web or another box lands in the meter with nothing local to +explain it. + ### Fireworks balance The collector first asks the account's `:getBalance` endpoint for the real @@ -128,6 +170,7 @@ edit `shell.json` directly): omarchy bar set omarchy.agents providers '{ "claude": { "enabled": true }, "codex": { "enabled": false }, + "grok": { "enabled": true }, "fireworks": { "enabled": true } }' --json ``` diff --git a/shell/plugins/agents/assets/grok-light.svg b/shell/plugins/agents/assets/grok-light.svg new file mode 100644 index 000000000000..85be6381170a --- /dev/null +++ b/shell/plugins/agents/assets/grok-light.svg @@ -0,0 +1 @@ +Grok diff --git a/shell/plugins/agents/assets/grok.svg b/shell/plugins/agents/assets/grok.svg new file mode 100644 index 000000000000..98ab9ccbbe18 --- /dev/null +++ b/shell/plugins/agents/assets/grok.svg @@ -0,0 +1 @@ +Grok diff --git a/shell/plugins/agents/manifest.json b/shell/plugins/agents/manifest.json index 1743a7982141..7ca52484b122 100644 --- a/shell/plugins/agents/manifest.json +++ b/shell/plugins/agents/manifest.json @@ -5,7 +5,7 @@ "version": "1.0.0", "author": "Omarchy", "license": "MIT", - "description": "Claude Code, Codex, and Fireworks usage, limits, and pace in a native Omarchy bar panel.", + "description": "Claude Code, Codex, Grok, and Fireworks usage, limits, and pace in a native Omarchy bar panel.", "kinds": ["bar-widget"], "activation": "on-demand", "entryPoints": { @@ -21,6 +21,7 @@ "providers": { "claude": { "enabled": true }, "codex": { "enabled": true }, + "grok": { "enabled": true }, "fireworks": { "enabled": true } }, "refreshIntervalSec": 900, diff --git a/test/shell.d/agent-usage-grok-scanner-test.sh b/test/shell.d/agent-usage-grok-scanner-test.sh new file mode 100755 index 000000000000..9abfd8af5d4d --- /dev/null +++ b/test/shell.d/agent-usage-grok-scanner-test.sh @@ -0,0 +1,323 @@ +#!/bin/bash + +source "$(dirname "$0")/base-test.sh" + +require_command jq +require_command python3 + +TEST_HOME=$(mktemp -d) +trap 'rm -rf "$TEST_HOME"' EXIT + +GROK_HOME="$TEST_HOME/.grok" +mkdir -p "$GROK_HOME/sessions/%2Fhome%2Fdev%2Fone/session-a" \ + "$GROK_HOME/sessions/%2Fhome%2Fdev%2Ftwo/session-b" \ + "$GROK_HOME/logs" \ + "$TEST_HOME/bin" \ + "$TEST_HOME/empty-bin" + +now=$(date +%s) +open_period_start=$(date -u -d '2 days ago' +%Y-%m-%dT%H:%M:%S+00:00) +open_period_end=$(date -u -d '5 days' +%Y-%m-%dT%H:%M:%S+00:00) +expired_period_start=$(date -u -d '14 days ago' +%Y-%m-%dT%H:%M:%S+00:00) +expired_period_end=$(date -u -d '7 days ago' +%Y-%m-%dT%H:%M:%S+00:00) + +usage_line() { + local prompt_id="$1" models="$2" + jq -cn --argjson ts "$now" --arg id "$prompt_id" --argjson models "$models" \ + '{timestamp: $ts, method: "_x.ai/session/update", params: {update: { + sessionUpdate: "turn_completed", prompt_id: $id, stop_reason: "end_turn", + usage: {modelUsage: $models}}}}' +} + +# Grok reports each completed turn on its own, with cache reads folded into +# inputTokens. Every record on disk also carries cacheCreationTokens, always +# zero so far, so the non-zero one below assumes it nests inside inputTokens +# the way cache reads do — symmetry, not an observed shape. The same +# prompt_id appears twice to stand in for a resumed or replayed transcript. A +# cancelled turn has no usage and is not a prompt. +{ + usage_line p1 '{"grok-4.5-build":{"inputTokens":100,"cachedReadTokens":60,"outputTokens":20,"reasoningTokens":5,"totalTokens":120}}' + usage_line p1 '{"grok-4.5-build":{"inputTokens":100,"cachedReadTokens":60,"outputTokens":20,"reasoningTokens":5,"totalTokens":120}}' + usage_line p2 '{"grok-4.5-build":{"inputTokens":80,"cachedReadTokens":50,"cacheCreationTokens":10,"outputTokens":10,"totalTokens":90}}' + echo '{"timestamp":'"$now"',"method":"_x.ai/session/update","params":{"update":{"sessionUpdate":"turn_completed","prompt_id":"cancelled","stop_reason":"cancelled"}}}' +} >"$GROK_HOME/sessions/%2Fhome%2Fdev%2Fone/session-a/updates.jsonl" + +# One turn answered by two models, plus a line the prefilter must skip. +{ + echo '{"timestamp":0,"method":"session/update","params":{"update":{"sessionUpdate":"agent_message_chunk","content":"noise"}}}' + usage_line p3 '{"grok-4.5-build":{"inputTokens":200,"cachedReadTokens":150,"outputTokens":40,"totalTokens":240},"grok-4.5":{"inputTokens":100,"cachedReadTokens":0,"outputTokens":10,"totalTokens":110}}' +} >"$GROK_HOME/sessions/%2Fhome%2Fdev%2Ftwo/session-b/updates.jsonl" + +write_fake_grok() { + local mode="$1" + cat >"$TEST_HOME/bin/grok" </dev/null; then + jq -cn --argjson id "\$id" '{jsonrpc:"2.0",id:\$id,result:{}}' + else + jq -cn --argjson id "\$id" '{jsonrpc:"2.0",id:\$id,error:{code:-32602,message:"bad initialize"}}' + fi + ;; + _x.ai/billing) + if [[ $mode == noise ]]; then + echo 'not-json' + echo '{"jsonrpc":"2.0","method":"_x.ai/mcp/servers_updated","params":{}}' + fi + if [[ $mode == error ]]; then + jq -cn --argjson id "\$id" '{jsonrpc:"2.0",id:\$id,error:{code:-32000,message:"Authentication required"}}' + elif [[ $mode == expired ]]; then + jq -cn --argjson id "\$id" --arg start "$expired_period_start" --arg end "$expired_period_end" \ + '{jsonrpc:"2.0",id:\$id,result:{config:{creditUsagePercent:22.0,currentPeriod:{type:"USAGE_PERIOD_TYPE_WEEKLY",start:\$start,end:\$end}},subscription_tier:"SuperGrok"}}' + elif [[ $mode == nopercent ]]; then + # The plan and the current window, with no reading in it — the shape a + # window that has not been measured yet comes back as. This is also + # what grok 1.0.0 returned for every reading. + jq -cn --argjson id "\$id" --arg start "$open_period_start" --arg end "$open_period_end" \ + '{jsonrpc:"2.0",id:\$id,result:{config:{currentPeriod:{type:"USAGE_PERIOD_TYPE_WEEKLY",start:\$start,end:\$end},prepaidBalance:{val:0},onDemandCap:{val:0},onDemandUsed:{val:0},isUnifiedBillingUser:true},subscription_tier:"SuperGrok"}}' + elif [[ $mode == noise ]]; then + jq -cn --argjson id "\$id" --arg start "$open_period_start" --arg end "$open_period_end" \ + '{jsonrpc:"2.0",id:\$id,result:{config:{creditUsagePercent:22.0,currentPeriod:{type:"USAGE_PERIOD_TYPE_WEEKLY",start:\$start,end:\$end}},subscriptionTier:"SuperGrok"}}' + else + jq -cn --argjson id "\$id" --arg start "$open_period_start" --arg end "$open_period_end" \ + '{jsonrpc:"2.0",id:\$id,result:{config:{creditUsagePercent:22.0,currentPeriod:{type:"USAGE_PERIOD_TYPE_WEEKLY",start:\$start,end:\$end}},subscription_tier:"SuperGrok"}}' + fi + ;; + esac +done +EOF + chmod +x "$TEST_HOME/bin/grok" +} + +run_collector() { + HOME="$TEST_HOME" GROK_HOME="$GROK_HOME" PATH="$TEST_HOME/bin:$PATH" \ + "$ROOT/bin/omarchy-agent-usage-grok" "$@" +} + +# The reading grok writes to its own log, which stands in when the ACP call +# says nothing. A negative percent stands for a logged config that carries a +# window and no reading at all. +credits_record() { + local percent="$1" start="$2" end="$3" + jq -cn --argjson percent "$percent" --arg start "$start" --arg end "$end" \ + '{ts: "2026-01-01T00:00:00Z", src: "shell", lvl: "info", + msg: "billing: fetched credits config", + ctx: {config: ({currentPeriod: {type: "USAGE_PERIOD_TYPE_WEEKLY", start: $start, end: $end}} + + (if $percent < 0 then {} else {creditUsagePercent: $percent} end)), + subscriptionTier: "SuperGrok"}}' +} + +write_credits_log() { + credits_record "$@" >"$GROK_HOME/logs/unified.jsonl" +} + +clear_credits_log() { + rm -f "$GROK_HOME/logs/unified.jsonl" +} + +write_fake_grok ok +result=$(run_collector) + +# 120 + 90 from session-a, 350 from the two-model turn in session-b. +[[ $(jq -r '.todayTotalTokens' <<<"$result") == "560" ]] || + fail "Grok collector sums each turn once" "$result" +pass "Grok collector sums each turn once" + +[[ $(jq -r '.totalPrompts' <<<"$result") == "3" ]] || + fail "Grok collector counts one prompt per turn and ignores repeated prompt ids" "$result" +pass "Grok collector counts one prompt per turn and ignores repeated prompt ids" + +[[ $(jq -r '.totalSessions' <<<"$result") == "2" ]] || + fail "Grok collector counts sessions by transcript" "$result" +pass "Grok collector counts sessions by transcript" + +[[ $(jq -c '.modelUsage["grok-4.5-build"]' <<<"$result") == '{"inputTokens":110,"outputTokens":70,"cacheReadInputTokens":260,"cacheCreationInputTokens":10}' ]] || + fail "Grok collector does not double-count cache or reasoning tokens" "$result" +pass "Grok collector does not double-count cache or reasoning tokens" + +[[ $(jq -c '.modelUsage["grok-4.5"]' <<<"$result") == '{"inputTokens":100,"outputTokens":10,"cacheReadInputTokens":0,"cacheCreationInputTokens":0}' ]] || + fail "Grok collector splits a turn across the models that served it" "$result" +pass "Grok collector splits a turn across the models that served it" + +contract='{"schemaVersion":1,"id":"grok","name":"Grok","ready":true,"hasLocalStats":true,"recentDays":7,"usageStatusText":""}' +[[ $(jq -c '{schemaVersion, id, name, ready, hasLocalStats, recentDays: (.recentDays | length), usageStatusText}' <<<"$result") == "$contract" ]] || + fail "Grok collector prints the display-ready record contract" "$result" +pass "Grok collector prints the display-ready record contract" + +[[ $(jq -c '.limits' <<<"$result") == '[{"label":"Weekly (7-day)","percent":0.22,"resetsAt":"'"$open_period_end"'"}]' ]] && + [[ $(jq -r '.tierLabel' <<<"$result") == "SuperGrok" ]] || + fail "Grok collector reads the weekly credit allowance from ACP billing" "$result" +pass "Grok collector reads the weekly credit allowance from ACP billing" + +write_fake_grok expired +expired=$(run_collector) + +[[ $(jq -r '.limits | length' <<<"$expired") == "0" ]] || + fail "Grok collector drops a credit reading from a period that has ended" "$expired" +pass "Grok collector drops a credit reading from a period that has ended" + +write_fake_grok noise +noisy=$(run_collector) + +[[ $(jq -c '.limits' <<<"$noisy") == '[{"label":"Weekly (7-day)","percent":0.22,"resetsAt":"'"$open_period_end"'"}]' ]] && + [[ $(jq -r '.tierLabel' <<<"$noisy") == "SuperGrok" ]] || + fail "Grok collector ignores non-JSON stdout and unrelated ACP notifications" "$noisy" +pass "Grok collector ignores non-JSON stdout and unrelated ACP notifications" + +write_fake_grok error +errored=$(run_collector) + +[[ $(jq -r '.limits | length' <<<"$errored") == "0" ]] && + [[ $(jq -r '.totalPrompts' <<<"$errored") == "3" ]] && + [[ $(jq -r '.usageStatusText' <<<"$errored") == "Grok limits unavailable" ]] || + fail "Grok collector keeps local stats when ACP billing returns an error" "$errored" +pass "Grok collector keeps local stats when ACP billing returns an error" + +# `_x.ai/billing` is a vendor extension: a grok that renames it looks the same +# from here as one that is signed out, and the log may still hold this week's +# reading. Losing the meter to either is what the fallback exists to prevent. +write_credits_log 22.0 "$open_period_start" "$open_period_end" +write_fake_grok error +logged=$(run_collector) + +[[ $(jq -c '.limits' <<<"$logged") == '[{"label":"Weekly (7-day)","percent":0.22,"resetsAt":"'"$open_period_end"'"}]' ]] && + [[ $(jq -r '.tierLabel' <<<"$logged") == "SuperGrok" ]] || + fail "Grok collector falls back to the log when ACP billing fails" "$logged" +pass "Grok collector falls back to the log when ACP billing fails" + +# An answer is not a reading. A window with no percentage has to yield to the +# log rather than blank the meter — and the tier ACP did give must survive it, +# since the two halves are filled independently. +write_fake_grok nopercent +half=$(run_collector) + +[[ $(jq -r '.limits[0].percent' <<<"$half") == "0.22" ]] && + [[ $(jq -r '.tierLabel' <<<"$half") == "SuperGrok" ]] || + fail "Grok collector falls back to the log when ACP reports a window with no reading" "$half" +pass "Grok collector falls back to the log when ACP reports a window with no reading" + +# Grok logs a config on every startup and not all of them carry a percentage, +# so the meter must come from the newest reading that has one — still this +# period's, because a closed period is rejected either way. +{ + credits_record 20.0 "$open_period_start" "$open_period_end" + credits_record -1 "$open_period_start" "$open_period_end" +} >"$GROK_HOME/logs/unified.jsonl" +walked_back=$(run_collector) + +[[ $(jq -r '.limits[0].percent' <<<"$walked_back") == "0.2" ]] || + fail "Grok collector walks back to the newest usable logged reading" "$walked_back" +pass "Grok collector walks back to the newest usable logged reading" + +# And a live ACP reading has to win over the log's older number. +write_fake_grok ok +live=$(run_collector) + +[[ $(jq -r '.limits[0].percent' <<<"$live") == "0.22" ]] || + fail "Grok collector prefers a usable ACP reading over the log" "$live" +pass "Grok collector prefers a usable ACP reading over the log" + +# A logged reading from a period that has since rolled over is the wrong +# week's number, so it cannot stand in for one ACP would not give. +write_credits_log 22.0 "$expired_period_start" "$expired_period_end" +write_fake_grok error +stale=$(run_collector) + +[[ $(jq -r '.limits | length' <<<"$stale") == "0" ]] && + [[ $(jq -r '.totalPrompts' <<<"$stale") == "3" ]] || + fail "Grok collector drops a logged reading from a period that has ended" "$stale" +pass "Grok collector drops a logged reading from a period that has ended" + +clear_credits_log + +missing=$(HOME="$TEST_HOME" GROK_HOME="$GROK_HOME" PATH="$TEST_HOME/empty-bin" \ + "$ROOT/bin/omarchy-agent-usage-grok") + +[[ $(jq -r '.limits | length' <<<"$missing") == "0" ]] && + [[ $(jq -r '.totalPrompts' <<<"$missing") == "3" ]] && + [[ $(jq -r '.usageStatusText' <<<"$missing") == "Grok limits unavailable" ]] || + fail "Grok collector still reports tokens when grok is absent" "$missing" +pass "Grok collector still reports tokens when grok is absent" + +# A turn from yesterday must not inflate today. local_day is easy to get +# wrong around UTC midnight — this machine's sessions stamp unix seconds. +mkdir -p "$GROK_HOME/sessions/%2Fhome%2Fdev%2Fthree/session-c" +yesterday=$(date -d 'yesterday 15:00:00' +%s) +yesterday_date=$(date -d 'yesterday 15:00:00' +%Y-%m-%d) +jq -cn --argjson ts "$yesterday" \ + '{timestamp: $ts, method: "_x.ai/session/update", params: {update: { + sessionUpdate: "turn_completed", prompt_id: "old", stop_reason: "end_turn", + usage: {modelUsage: {"grok-4.5-build":{"inputTokens":30,"outputTokens":10,"totalTokens":40}}}}}}' \ + >"$GROK_HOME/sessions/%2Fhome%2Fdev%2Fthree/session-c/updates.jsonl" +write_fake_grok ok +dated=$(run_collector) + +[[ $(jq -r '.todayPrompts' <<<"$dated") == "3" ]] && + [[ $(jq -r '.todayTotalTokens' <<<"$dated") == "560" ]] && + [[ $(jq -r --arg day "$yesterday_date" '.recentDays[] | select(.date == $day) | .messageCount' <<<"$dated") == "40" ]] || + fail "Grok collector files a turn on the local day it happened" "$dated" +pass "Grok collector files a turn on the local day it happened" + +# Interrupting a prompt and running it again reuses the prompt id, and the +# turn that spent the tokens is the second one. The cancelled record carries +# no usage key, so the prefilter is what drops it here. +mkdir -p "$GROK_HOME/sessions/%2Fhome%2Fdev%2Ffour/session-d" +{ + echo '{"timestamp":'"$now"',"method":"_x.ai/session/update","params":{"update":{"sessionUpdate":"turn_completed","prompt_id":"p4","stop_reason":"cancelled"}}}' + usage_line p4 '{"grok-4.5-build":{"inputTokens":30,"cachedReadTokens":0,"outputTokens":10,"totalTokens":40}}' +} >"$GROK_HOME/sessions/%2Fhome%2Fdev%2Ffour/session-d/updates.jsonl" +retried=$(run_collector) + +[[ $(jq -r '.todayTotalTokens' <<<"$retried") == "600" ]] && + [[ $(jq -r '.todayPrompts' <<<"$retried") == "4" ]] || + fail "Grok collector counts a retried turn whose cancelled attempt shared its id" "$retried" +pass "Grok collector counts a retried turn whose cancelled attempt shared its id" + +# A subagent runs in a session directory of its own beside its parent's, and +# the parent names it in a subagent_spawned record. The child's turns hold +# tokens the parent never folded in, so they count, but nobody typed them: the +# child is not a session or a prompt. The child sorts ahead of its parent, so +# the scan meets it before the record that names it. +mkdir -p "$GROK_HOME/sessions/%2Fhome%2Fdev%2Ffive/session-0child" \ + "$GROK_HOME/sessions/%2Fhome%2Fdev%2Ffive/session-e" +{ + jq -cn --argjson ts "$now" \ + '{timestamp: $ts, method: "_x.ai/session/update", params: {sessionId: "session-e", update: { + sessionUpdate: "subagent_spawned", subagent_id: "session-0child", + parent_session_id: "session-e", parent_prompt_id: "p5", child_session_id: "session-0child", + subagent_type: "general-purpose", model: "grok-4.5-build"}}}' + usage_line p5 '{"grok-4.5-build":{"inputTokens":30,"cachedReadTokens":0,"outputTokens":10,"totalTokens":40}}' +} >"$GROK_HOME/sessions/%2Fhome%2Fdev%2Ffive/session-e/updates.jsonl" +usage_line c1 '{"grok-4.5-build":{"inputTokens":50,"cachedReadTokens":0,"outputTokens":10,"totalTokens":60}}' \ + >"$GROK_HOME/sessions/%2Fhome%2Fdev%2Ffive/session-0child/updates.jsonl" +spawned=$(run_collector) + +[[ $(jq -r '.todayTotalTokens' <<<"$spawned") == "700" ]] && + [[ $(jq -r '.todayPrompts' <<<"$spawned") == "5" ]] && + [[ $(jq -r '.todaySessions' <<<"$spawned") == "4" ]] && + [[ $(jq -r '.totalPrompts' <<<"$spawned") == "6" ]] && + [[ $(jq -r '.totalSessions' <<<"$spawned") == "5" ]] || + fail "Grok collector counts a subagent's tokens but not its session or prompts" "$spawned" +pass "Grok collector counts a subagent's tokens but not its session or prompts" + +# No sessions and no grok is a machine that has never signed in: a full record +# the update runner can write, with nothing in it for the panel to show. +empty=$(GROK_HOME="$TEST_HOME/.grok-empty" HOME="$TEST_HOME" PATH="$TEST_HOME/empty-bin" \ + "$ROOT/bin/omarchy-agent-usage-grok") + +[[ $(jq -r '.id + ":" + (.ready | tostring) + ":" + (.totalPrompts | tostring)' <<<"$empty") == "grok:false:0" ]] || + fail "Grok collector prints a valid record with nothing installed" "$empty" +pass "Grok collector prints a valid record with nothing installed"