Repository navigation
Agents panel: add a Grok usage collector #7198
Replies: 4 comments
|
+1 — this machine’s default agent is already Grok ( I installed a local copy of the collector from #6485 (the one that reads #7200 is the same idea, but it looks for a top-level |
|
Confirmed on a real install — this gap is still present. Environment
What I see A first-party Grok collector for the existing Agents panel would close this. Happy to test a branch if that helps. |
|
I built and tested an extension of @scottjones's collector from #6485 (c7e5d80) against Grok 1.0.30. This builds on that proposal and the discussion here; the original ACP billing transport, token splitting, and log fallback are credited to #6485. The attached patch adds Changes relative to #6485:
Tokens still come from Validation:
Limitations: child-session accounting remains an open follow-up from #6485 and has not been validated with real subagent fixtures here. A log fallback reading can lag live account usage within its billing period. Missing token ledgers do not yield estimated tokens, and missing/expired allowance readings do not yield a guessed meter. This validation covers collector/updater behavior; the panel was not visually verified in this run. Proposal: incorporate these robustness and prompt-count changes into the existing collector work. The patch below applies to upstream commit Source branch: GianlucaMinoprio/omarchy — grok-usage-proposal. The logo assets also come from #6485 and match the installed local customization. Both SVG files passed XML validation. Collector, logos, tests, and documentation patchdiff --git a/bin/omarchy-agent-usage-grok b/bin/omarchy-agent-usage-grok
new file mode 100755
index 00000000..b37c79fc
--- /dev/null
+++ b/bin/omarchy-agent-usage-grok
@@ -0,0 +1,576 @@
+#!/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.
+
+Based on Scott Jones' collector in omacom/omarchy#6485 (c7e5d801).
+
+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 math
+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."
+
+# Each of the two ACP requests has a deadline, followed by bounded cleanup.
+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 max(0, int(value or 0))
+ except (TypeError, ValueError, OverflowError):
+ 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
+ try:
+ return datetime.fromtimestamp(value).strftime("%Y-%m-%d")
+ except (ValueError, OverflowError, OSError):
+ return ""
+ parsed = parse_iso(value)
+ if parsed is None:
+ return ""
+ 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_sessions: set[str] = set()
+ self.today_prompts = 0
+ self.today_total_tokens = 0
+ self.total_prompts = 0
+ self.total_sessions: set[str] = set()
+ self.active_days: set[str] = set()
+ self.seen_turns: set[str] = set()
+ self.seen_prompts: set[tuple[str, int]] = set()
+
+ def add_turn(self, day: str, session_key: str, per_model: list[tuple[str, int, int, int, int]]) -> None:
+ # One prompt event (or completed turn fallback) counts once, 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 += 1
+ self.total_sessions.add(session_key)
+ self.active_days.add(day)
+ if day == self.today:
+ self.today_prompts += 1
+ self.today_sessions.add(session_key)
+ self.add_tokens(day, per_model)
+
+ def add_tokens(self, day: str, per_model: list[tuple[str, int, int, int, int]]) -> None:
+ 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_total_tokens += turn_total
+
+ def stats(self) -> dict[str, Any]:
+ return {
+ "todayPrompts": self.today_prompts,
+ "todaySessions": len(self.today_sessions),
+ "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": self.total_prompts,
+ "totalSessions": len(self.total_sessions),
+ # 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 json_records(path: Path, marker: str) -> Iterator[dict[str, Any]]:
+ try:
+ with path.open(errors="replace") as handle:
+ for raw in handle:
+ if marker not in raw:
+ continue
+ try:
+ record = json.loads(raw)
+ except json.JSONDecodeError:
+ continue
+ if isinstance(record, dict):
+ yield record
+ except OSError:
+ return
+
+
+def scan_sessions(usage: SessionUsage) -> None:
+ root = sessions_root()
+ if not root.is_dir():
+ return
+
+ # Events are the prompt source when available, including interrupted turns
+ # and sessions from builds that did not persist token ledgers. Never read
+ # chat content or interpret streamed token counters as billed usage.
+ directories = {p.parent for name in ("updates.jsonl", "events.jsonl") for p in root.glob(f"*/*/{name}")}
+ for directory in sorted(directories):
+ session_key = directory.name
+ prompts = {}
+ for event in json_records(directory / "events.jsonl", '"turn_started"'):
+ if event.get("type") != "turn_started":
+ continue
+ day = local_day(event.get("ts")) if event.get("ts") is not None else ""
+ turn = event.get("turn_number")
+ if day and isinstance(turn, int) and not isinstance(turn, bool):
+ prompts.setdefault(turn, day)
+ for turn, day in prompts.items():
+ key = (session_key, turn)
+ if key not in usage.seen_prompts:
+ usage.seen_prompts.add(key)
+ usage.add_turn(day, session_key, [])
+
+ path = directory / "updates.jsonl"
+ for entry in json_records(path, '"usage"'):
+ params = entry.get("params")
+ if not isinstance(params, dict):
+ continue
+ update = params.get("update")
+ if not isinstance(update, dict) or update.get("sessionUpdate") != "turn_completed":
+ continue
+ prompt_id = update.get("prompt_id")
+ if not isinstance(prompt_id, str) or not prompt_id:
+ continue
+ turn_key = session_key + ":" + prompt_id
+ if turn_key in usage.seen_turns:
+ continue
+ day = local_day(entry.get("timestamp")) if entry.get("timestamp") is not None else ""
+ per_model = turn_models(update)
+ if not day or not per_model:
+ continue
+ usage.seen_turns.add(turn_key)
+ if prompts:
+ usage.add_tokens(day, per_model)
+ else:
+ usage.add_turn(day, session_key, per_model)
+
+
+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 {}
+ if not isinstance(period, dict):
+ return None
+ 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
+
+ if not math.isfinite(fraction) or fraction < 0:
+ 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[bytes], 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").encode())
+ proc.stdin.flush()
+ deadline = time.monotonic() + timeout
+ pending = b""
+ while time.monotonic() < deadline:
+ ready, _, _ = select.select([proc.stdout], [], [], 0.25)
+ if not ready:
+ continue
+ chunk = os.read(proc.stdout.fileno(), 65536)
+ if not chunk:
+ break
+ pending += chunk
+ if len(pending) > 1024 * 1024:
+ raise ValueError("ACP response too large")
+ while b"\n" in pending:
+ line, pending = pending.split(b"\n", 1)
+ try:
+ message = json.loads(line)
+ except (json.JSONDecodeError, UnicodeDecodeError):
+ continue
+ if isinstance(message, dict) and message.get("id") == request_id:
+ return message
+ raise TimeoutError(method)
+
+
+def terminate(proc: subprocess.Popen[bytes]) -> 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,
+ bufsize=0,
+ 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, UnicodeDecodeError):
+ 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/shell/plugins/agents/README.md b/shell/plugins/agents/README.md
index 51ad4e43..800df72e 100644
--- a/shell/plugins/agents/README.md
+++ b/shell/plugins/agents/README.md
@@ -55,6 +55,9 @@ 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) |
| `fireworks` | Estimated prepaid balance: configured funding minus rated account costs | Fireworks billing API, grouped by day and model for the last 30 days |
+| `grok` | Grok's ACP billing method, with its current-period log reading as fallback | `~/.grok/sessions` prompt events and completed-turn token ledgers |
+
+Grok honors `GROK_HOME` and `GROK_LOG_FILE`. Prompt counts use `events.jsonl` when available and completed turns otherwise. Token statistics use `turn_completed` records in `updates.jsonl`; sessions without these ledgers contribute prompt counts but no estimated tokens. Cache and reasoning detail are already included in Grok's input/output totals and are not added twice. The collector asks `grok agent stdio` for billing data without reading credentials. Missing, invalid, or expired allowance readings leave the meter empty. Log fallback readings can lag current usage within the open billing period. Child-session prompt/session counts are not separated from primary sessions; this retains the limitation of the existing proposal in PR #6485.
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
diff --git a/shell/plugins/agents/assets/grok-light.svg b/shell/plugins/agents/assets/grok-light.svg
new file mode 100644
index 00000000..85be6381
--- /dev/null
+++ b/shell/plugins/agents/assets/grok-light.svg
@@ -0,0 +1 @@
+<svg fill="#111" fill-rule="evenodd" height="1em" style="flex:none;line-height:1" viewBox="0 0 24 24" width="1em" xmlns="http://www.w3.org/2000/svg"><title>Grok</title><path d="M9.27 15.29l7.978-5.897c.391-.29.95-.177 1.137.272.98 2.369.542 5.215-1.41 7.169-1.951 1.954-4.667 2.382-7.149 1.406l-2.711 1.257c3.889 2.661 8.611 2.003 11.562-.953 2.341-2.344 3.066-5.539 2.388-8.42l.006.007c-.983-4.232.242-5.924 2.75-9.383.06-.082.12-.164.179-.248l-3.301 3.305v-.01L9.267 15.292M7.623 16.723c-2.792-2.67-2.31-6.801.071-9.184 1.761-1.763 4.647-2.483 7.166-1.425l2.705-1.25a7.808 7.808 0 00-1.829-1A8.975 8.975 0 005.984 5.83c-2.533 2.536-3.33 6.436-1.962 9.764 1.022 2.487-.653 4.246-2.34 6.022-.599.63-1.199 1.259-1.682 1.925l7.62-6.815"></path></svg>
diff --git a/shell/plugins/agents/assets/grok.svg b/shell/plugins/agents/assets/grok.svg
new file mode 100644
index 00000000..98ab9ccb
--- /dev/null
+++ b/shell/plugins/agents/assets/grok.svg
@@ -0,0 +1 @@
+<svg fill="#fff" fill-rule="evenodd" height="1em" style="flex:none;line-height:1" viewBox="0 0 24 24" width="1em" xmlns="http://www.w3.org/2000/svg"><title>Grok</title><path d="M9.27 15.29l7.978-5.897c.391-.29.95-.177 1.137.272.98 2.369.542 5.215-1.41 7.169-1.951 1.954-4.667 2.382-7.149 1.406l-2.711 1.257c3.889 2.661 8.611 2.003 11.562-.953 2.341-2.344 3.066-5.539 2.388-8.42l.006.007c-.983-4.232.242-5.924 2.75-9.383.06-.082.12-.164.179-.248l-3.301 3.305v-.01L9.267 15.292M7.623 16.723c-2.792-2.67-2.31-6.801.071-9.184 1.761-1.763 4.647-2.483 7.166-1.425l2.705-1.25a7.808 7.808 0 00-1.829-1A8.975 8.975 0 005.984 5.83c-2.533 2.536-3.33 6.436-1.962 9.764 1.022 2.487-.653 4.246-2.34 6.022-.599.63-1.199 1.259-1.682 1.925l7.62-6.815"></path></svg>
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 00000000..751851fd
--- /dev/null
+++ b/test/shell.d/agent-usage-grok-scanner-test.sh
@@ -0,0 +1,366 @@
+#!/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" <<EOF
+#!/bin/bash
+while read -r request; do
+ id=\$(jq -r '.id // empty' <<<"\$request")
+ method=\$(jq -r '.method // empty' <<<"\$request")
+ [[ -n \$id ]] || continue
+ case "\$method" in
+ initialize)
+ if [[ $mode == noise ]]; then
+ echo 'mise tools: grok@1.0.5'
+ echo '{"jsonrpc":"2.0","method":"_x.ai/mcp/servers_updated","params":{"mcpServers":[]}}'
+ fi
+ if jq -e '.params | .protocolVersion == 1 and .clientCapabilities.terminal == false
+ and ._meta.clientType == "omarchy-agent-usage"
+ and (._meta.clientVersion | type) == "string" and ._meta.clientVersion == "1"
+ and ._meta.startupHints.nonInteractive and ._meta.startupHints.skipGitStatus
+ and ._meta.startupHints.skipProjectLayout' <<<"\$request" >/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"
+
+# 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"
+
+# Prompt counts must survive missing token ledgers, and events must not add
+# prompts a second time when a completed turn has a token ledger as well.
+GROK_HOME="$TEST_HOME/events-home"
+mkdir -p "$GROK_HOME/sessions/project/events-only" "$GROK_HOME/sessions/project/with-tokens"
+for session in events-only with-tokens; do
+ jq -cn --arg ts "$(date --iso-8601=seconds)" \
+ '{ts:$ts,type:"turn_started",turn_number:1,session_relationship:"primary"}' \
+ >"$GROK_HOME/sessions/project/$session/events.jsonl"
+done
+cat "$GROK_HOME/sessions/project/events-only/events.jsonl" >>"$GROK_HOME/sessions/project/with-tokens/events.jsonl"
+usage_line p1 '{"grok-test":{"inputTokens":100,"cachedReadTokens":60,"outputTokens":20}}' \
+ >"$GROK_HOME/sessions/project/with-tokens/updates.jsonl"
+events=$(run_collector)
+[[ $(jq -c '[.totalPrompts,.totalSessions,.todayTotalTokens]' <<<"$events") == '[2,2,120]' ]] ||
+ fail "Grok counts event-only sessions without double-counting completed prompts" "$events"
+pass "Grok counts event-only sessions without double-counting completed prompts"
+
+# A copied session retains its identity across project directories.
+mkdir -p "$GROK_HOME/sessions/copied"
+cp -r "$GROK_HOME/sessions/project/with-tokens" "$GROK_HOME/sessions/copied/"
+copied=$(run_collector)
+[[ $(jq -c '[.totalPrompts,.totalSessions,.todayTotalTokens]' <<<"$copied") == '[2,2,120]' ]] ||
+ fail "Grok deduplicates copied session events and usage" "$copied"
+pass "Grok deduplicates copied session events and usage"
+
+# One malformed object, invalid date or partial trailing write must not erase
+# usage successfully read from this session or another one.
+cat >>"$GROK_HOME/sessions/project/with-tokens/updates.jsonl" <<'JSON'
+["usage"]
+{"usage":true,"params":[]}
+{"usage":true,"params":{"update":[]}}
+{"timestamp":"invalid","params":{"update":{"sessionUpdate":"turn_completed","prompt_id":"bad-date","usage":{"inputTokens":999}}}}
+{"timestamp":1e99,"params":{"update":{"sessionUpdate":"turn_completed","prompt_id":"overflow-date","usage":{"inputTokens":999}}}}
+{"params":{"update":{"sessionUpdate":"turn_completed","prompt_id":"partial","usage":
+JSON
+malformed=$(run_collector)
+[[ $(jq -c '[.totalPrompts,.totalSessions,.todayTotalTokens]' <<<"$malformed") == '[2,2,120]' ]] ||
+ fail "Grok skips malformed records without discarding valid usage" "$malformed"
+pass "Grok skips malformed records without discarding valid usage"
+
+ROOT="$ROOT" python3 - <<'PY'
+import os, runpy, subprocess, sys, time
+from datetime import datetime, timedelta, timezone
+from pathlib import Path
+m = runpy.run_path(str(Path(os.environ['ROOT']) / 'bin/omarchy-agent-usage-grok'))
+now = datetime.now(timezone.utc)
+period = {'start': (now-timedelta(days=1)).isoformat(), 'end': (now+timedelta(days=6)).isoformat()}
+for value in ('NaN', 'Infinity', -1, {}, []):
+ assert m['limit_from_config']({'creditUsagePercent':value, 'currentPeriod':period}) is None
+assert m['limit_from_config']({'creditUsagePercent':22, 'currentPeriod':[]}) is None
+print('ok - Grok rejects malformed and non-finite billing readings')
+
+# A subprocess that writes half a JSON line and hangs must respect the RPC
+# timeout. Buffered readline() after select() would block here indefinitely.
+proc = subprocess.Popen([sys.executable, '-c',
+ 'import sys,time;sys.stdin.readline();sys.stdout.write("{\\\"id\\\":");sys.stdout.flush();time.sleep(10)'],
+ stdin=subprocess.PIPE, stdout=subprocess.PIPE, bufsize=0)
+start = time.monotonic()
+try:
+ try:
+ m['rpc_request'](proc, 1, 'initialize', timeout=0.15)
+ raise AssertionError('expected timeout')
+ except TimeoutError:
+ assert time.monotonic() - start < 1
+finally:
+ m['terminate'](proc)
+print('ok - Grok enforces the ACP deadline on a partial response')
+PY
+[[ $? == 0 ]] || fail "Grok billing validation and deadline tests" |
Uh oh!
There was an error while loading. Please reload this page.
Why
Setup already offers Grok as a first-party default coding agent (
omarchy default agent grok, Super+Shift+Ctrl+A). The agents bar widget does not.omarchy.agentshides itself until a collector writes a usage record with prompts, sessions, limits, or a balance. The packaged collectors are only Claude, Codex, and Fireworks. A machine whose default agent is Grok therefore gets an empty slot even after many local sessions.This is the designed extension point: add
bin/omarchy-agent-usage-grok, andomarchy-agent-usage-updateplus the existing panel pick it up. A marketplace plugin cannot register a collector — discovery is$OMARCHY_PATH/bin/omarchy-agent-usage-*.What it would show
Local stats from
$GROK_HOME/sessions(default~/.grok/sessions/<cwd>/<id>/):events.jsonlturn_started, falling back tochat_history.jsonl)That is enough for
providerHasDatato light the existing icon. The panel grows a Grok tab. No second widget, no bar-layout change.Follow-up
I have a PR ready against
quattrowith the collector, tests, and an optionalassets/grok.svgmark.All reactions