+14








75250d37ac
* Read Codex app-server replies from the raw fd (#13703) * Resolve Codex through mise which instead of running the lazy launcher (#13109) * Skip the Codex app-server probe when there are no credentials (#13106) Adapted: credentials are checked in the home being probed rather than in the CODEX_HOME environment variable, since each registered account is probed in its own home, so a signed-out secondary account isn't hidden behind the primary's login. A home without credentials reports "Waiting for auth" like any other signed-out home. The credentials store setting is read with tomllib, so a single-quoted value counts too. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Show the Codex CLI's own error when its app-server dies (#8977) Detect an app-server that exits or stops answering, and report the end of its stderr instead of a bare RPC method name. Rebased onto the raw-fd reply reader; the switch from "-a on-request" to "-a never" is left out, keeping the current approval flags. * Count pi sessions when HOME is a git checkout (#13209) * Count only OpenAI-backed native sessions as Codex usage (#12032) * Deduplicate Pi usage across forked sessions (#8602) * Skip unchanged native Codex token snapshots (#10531) * Count omp and pi profile sessions in the agent usage collectors (#9546) `omp --profile=<name>` (and pi's equivalent) relocates the whole agent tree under <base>/profiles/<name>/. The Claude and Codex collectors only ever scanned <base>/agent/sessions, so a subscription driven entirely through a profile was invisible to the agents panel: no tokens by day, no tokens by model, no prompt or session counts. Discover the profile roots alongside the default one. Sessions are keyed by file path, so a profile adds sessions instead of double-counting the default root, and a missing or unreadable profiles directory leaves the existing behavior untouched. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_014zFbJcDEEpV5BAmsH6kAB3 * Skip unrelated Codex session lines before JSON parsing (#12803) Adapted: session_meta lines also pass the pre-filter, since the provider filter from #12032 reads them to skip rollouts served by a non-OpenAI provider. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Read only the Codex session files that changed since the last scan (#12595) Native Codex rollouts keep per-file totals between runs, replayed while a file's mtime and size are unchanged. Rebased onto the session_meta provider filter, snapshot dedup, and line pre-filter, which now live in the per-file reader. pi and omp sessions are left out of the per-file cache: a forked pi session repeats its parent's messages, so they are deduplicated across the whole tree on every scan. * Count streamed Claude messages by their highest-output usage line (#10606) Claude Code writes a streamed assistant response as several transcript lines that share one message id, one per content block. Each line carries a usage object. The first line's output_tokens is a placeholder, often 1, and the last line has the real count. Input and cache fields usually match across the lines. The scanner dedupes by message id and keeps the first line it sees, so it under-counts output tokens. On a machine with 2,577 transcripts it reported 39.0M output tokens against 60.1M used, a 35% shortfall. Input and both cache fields differed by under 0.01%. Keep the line with the highest output count, with the last one scanned winning a tie. The whole line is kept because a response can fall back to another model mid-stream. Those lines are separate snapshots with different cache figures and a different model, and taking a maximum per field across them over-counts cache tokens and credits the wrong model. The zero-usage check now runs before dedup, so a zero-usage first line no longer claims a message id and hides a later line with real usage. Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com> Co-authored-by: GPT-6 Astra <noreply@openai.com> * Index Claude transcripts so the agents refresh reads only what was appended (#8313) omarchy-agent-usage-claude re-parsed every line of every transcript under ~/.claude/projects on each refresh: no mtime cutoff, no memory of the last pass. The agents widget is on by default and ticks every 15 minutes, so the cost grew for the life of the machine. After one month here that was 803 files, 640 MB, 127k lines and 57k JSON parses per tick, about 1 core-second, pushed through the page cache every quarter hour forever. Keep a per-file index next to the scan cache: the unique usage records already parsed out of each transcript and the byte offset they end at. A file whose size and mtime match is not opened; a file that grew is read from the stored offset; a file that shrank or was rewritten is read from the start. --force drops the index and rescans from scratch. The summary is built from the indexed records in the same directory order the walk always used. That matters: when a resumed session carries earlier messages, the same message id appears in two files with different usage, and the first file visited wins. 91 ids differed on this machine; sorting the walk moved one model's output total by 25k tokens. Output is now byte-identical to the previous scan on a frozen copy of the corpus, cold, warm, and after an append. Warm refresh: 1.0 s -> 0.10 s of CPU, of which the scan itself is 70 ms; the index for this corpus is 2.9 MB. Adapted: - Rebased onto #10606: the highest-output rule for streamed messages now lives where the index parses records, and decides between files too. - The index records the timezone it was written in, and a change rereads every transcript, since its records hold local days. - A file only counts as appended to when its inode and the hash of what was already read still match, so a transcript replaced by a larger one, or rewritten in place, is read from the start. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Label a Claude Team seat by its subscription, not its rate-limit tier (#11109) The collector built the plan label from the OAuth rateLimitTier first, so a Team premium seat, which runs on default_claude_max_5x, showed in the agents panel as "Max 5x". Lead with subscriptionType and keep the multiplier as its qualifier: Max still reads "Max 5x", a Team seat reads "Team 5x". Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * Label the Claude plan from the profile the CLI refreshes (#7225) Adapted: the profile is found the same way current_account_id() finds it, now shared as profile_path(): ~/.claude.json for the default home, the home's own .claude.json otherwise. The original fell back to ~/.claude.json for any home without CLAUDE_CONFIG_DIR set, so a secondary account read the primary's tier. The profile's tier also keeps the subscription in the label, so a Team seat stays "Team" (#11109). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Call a lapsed Claude access token paused, not signed out (#8093) * Refresh Claude usage after the clock moves backwards (#9956) * Bound unreadable Claude transcript warnings (#12414) * Count Claude usage from opencode v2 sessions (#13894) * Reload agent usage records when an inotify watch fails to rearm (#10067) * Reload agent usage records after each update run instead of on a timer Rather than #10067's two-minute timer per record, reload every record when the omarchy-agent-usage-update process exits, the moment its files can have been replaced. A reload that finds a file unchanged keeps its record, so the panel isn't stirred up by identical data. The grep test now runs the QML functions. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Show the agent status when the trouble line has no help text (#8497) * Clear stale agent login guidance after a successful probe (#8892) * Clear the Grok login hint after a successful probe #8892 cleared the default login hint after a successful probe in the Claude and Codex collectors; Grok's collector had the same stale hint. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Read Fireworks credentials from pi's auth.json (#7455) The Fireworks collector skipped pi, Omarchy's default agent, when walking its credential ladder, so a machine signed in to Fireworks only through pi (/login fireworks) never showed the tab. Insert the key pi stores in $PI_CODING_AGENT_DIR/auth.json (default ~/.pi/agent) between the firectl auth.ini and the opencode fallback. pi keys can be literals, $ENV_VAR/${ENV_VAR} references, or !command shell lookups. The collector resolves the first two; command lookups stay pi-only and are skipped rather than sent to the API verbatim. * Call a lapsed Grok access token paused, not signed out Grok's access token lives six hours and Grok mints a new one from its refresh token whenever it starts, so a lapsed one is routine. Reporting it as an expired sign-in made the panel offer Sign-in required several times a day, sending people through grok login for nothing. With a refresh token present it now reads as paused, like Claude's. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Keep showing Grok's last limits while it sits idle While Grok hasn't run, nothing on the machine has spent its allowance, so with a refresh token on hand the last numbers still stand: they show as current rather than dimmed under a status line. A weekly window that reset in the meantime starts over at 0%, a whole number of weeks on. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Ask for a Grok sign-in once its refresh token is past 30 days A refresh token older than Grok's 30-day sign-in can't renew anything, so the panel offers Sign-in required again instead of showing the last limits as current. With nothing cached yet it says to start Grok, rather than showing an empty section without a word. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Check both ends of what the Claude index read before resuming a transcript A transcript rewritten in place could grow and change only after its first kilobytes, and the index took it for an append. It now compares the last kilobytes before the resume point too. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Simplify the agent usage collectors - Codex: pass the forced-scan choice down instead of a module global, make the per-file reader's cache arguments required, shrink the cache record check, and drop guards for shapes that can't occur: an empty launcher path, realpath raising, mise itself being a lazy launcher, multi-line `mise which` output, and probing without a temp file for stderr. - Claude: decide an append by the digest of both ends of what was read alone; the inode and mtime checks it made redundant are gone. - Snapshot: the device id falls back to the hostname, which always exists. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Share fixture setup in the agent usage scanner tests Every fixture home lives under one scratch directory with a single cleanup trap, instead of a trap rewritten with a longer list for each new home, and the Codex test builds its signed-in homes with one helper. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Treat a replaced Claude transcript as new even when its ends match Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Probe Codex without its error text when there's no temporary space Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: tossbaws <17258053+tossbaws@users.noreply.github.com> Co-authored-by: surim0n <suritech@gmail.com> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: anonwurcod <anonwurcod@proton.me> Co-authored-by: Kevin Rajan <7121943+kvnloo@users.noreply.github.com> Co-authored-by: Nate Ashby <nate.ashby11@gmail.com> Co-authored-by: Aris Gysel <aris.gysel@me.com> Co-authored-by: Brams <76213579+Brams-s@users.noreply.github.com> Co-authored-by: This_Is_NPC <gabrielfollone27@gmail.com> Co-authored-by: sanjyay <102979855+sanjyay@users.noreply.github.com> Co-authored-by: PapistProtocol <12738904+PapistProtocol@users.noreply.github.com> Co-authored-by: steez <stevedimakos97@gmail.com> Co-authored-by: GPT-6 Astra <noreply@openai.com> Co-authored-by: Ryan Yogan <ryanyogan@gmail.com> Co-authored-by: Oli Denton <41393837+omdenton@users.noreply.github.com> Co-authored-by: Igor Kramar <i@ikramar.ru> Co-authored-by: Martin Eidensten <martin@meibe.se> Co-authored-by: Romain Perron <rdj.perron@gmail.com> Co-authored-by: Omarchy Contributor <contributor@users.noreply.github.com> Co-authored-by: manuaudio <manu@arimaka.com> Co-authored-by: Tyler South <tsouth2@gmail.com> Co-authored-by: whathek <Hek846@users.noreply.github.com> Co-authored-by: Ty Richards <me@tyrichards.com>
362 lines
14 KiB
Python
Executable File
362 lines
14 KiB
Python
Executable File
#!/usr/bin/python3
|
|
# omarchy:summary=Print the Grok usage record as JSON
|
|
# omarchy:args=[--force] [--limits-only]
|
|
# omarchy:hidden=true
|
|
"""Collect Grok usage into one display-ready JSON record.
|
|
|
|
The plan comes from the settings Grok caches from xAI, and the limit from the
|
|
credits endpoint the Grok CLI itself reads for its /usage view, asked with
|
|
each account's own sign-in. Sessions come from the summary Grok keeps beside
|
|
each session, and tokens and prompts from its usage.json, the ledger `grok
|
|
usage` prints: one entry per finished turn, with when it ended and its tokens
|
|
by model. The agents panel only ever reads the JSON this prints.
|
|
"""
|
|
|
|
import argparse
|
|
import json
|
|
import os
|
|
import re
|
|
import tempfile
|
|
import time
|
|
import urllib.error
|
|
import urllib.request
|
|
from datetime import datetime, timedelta, timezone
|
|
from pathlib import Path
|
|
|
|
AGENT_ID = "grok"
|
|
AGENT_NAME = "Grok"
|
|
AUTH_HELP = "Start Grok, or run `grok login`, to sign in."
|
|
CREDITS_URL = "https://cli-chat-proxy.grok.com/v1/billing?format=credits"
|
|
# Grok's own CLI watches its subscription once a minute; a panel opened and
|
|
# shut repeatedly reuses an answer for about that long.
|
|
PROBE_REUSE_SECONDS = 60
|
|
# Grok's docs give a saved sign-in 30 days; a refresh token older than that
|
|
# can't renew the access token, so it no longer counts as signed in.
|
|
REFRESH_LIFETIME_SECONDS = 30 * 24 * 3600
|
|
# A limits-only refresh needs fresh limits, not a fresh history scan.
|
|
LIMITS_ONLY_SCAN_REUSE_SECONDS = 900
|
|
|
|
|
|
def read_json(path):
|
|
try:
|
|
return json.loads(Path(path).read_text(encoding="utf-8"))
|
|
except Exception:
|
|
return None
|
|
|
|
|
|
# A temporary file of its own per write, so overlapping runs can't rename
|
|
# each other's away.
|
|
def write_json(path, payload):
|
|
path = Path(path)
|
|
path.parent.mkdir(parents=True, exist_ok=True)
|
|
fd, tmp = tempfile.mkstemp(prefix=path.name + ".", dir=str(path.parent))
|
|
try:
|
|
with os.fdopen(fd, "w", encoding="utf-8") as handle:
|
|
json.dump(payload, handle)
|
|
os.replace(tmp, path)
|
|
except Exception:
|
|
Path(tmp).unlink(missing_ok=True)
|
|
raise
|
|
|
|
|
|
def cache_root():
|
|
return Path(os.environ.get("XDG_CACHE_HOME") or (Path.home() / ".cache")) / "omarchy" / "agent-usage"
|
|
|
|
|
|
def parse_time(value):
|
|
try:
|
|
parsed = datetime.fromisoformat(str(value or "").replace("Z", "+00:00"))
|
|
except ValueError:
|
|
return None
|
|
return parsed if parsed.tzinfo else parsed.replace(tzinfo=timezone.utc)
|
|
|
|
|
|
# The home Grok uses when nothing selects an account: GROK_HOME when set,
|
|
# as the CLI itself reads it, else ~/.grok.
|
|
def default_home():
|
|
return Path(os.environ.get("GROK_HOME") or (Path.home() / ".grok"))
|
|
|
|
|
|
# Every session under <home>/sessions/<folder>/<session>/: its summary says
|
|
# when it was last active and how many prompts it had, and its usage.json
|
|
# lists each finished turn with its tokens by model. Added accounts link
|
|
# their sessions to the primary's, so this covers all of them. Grok counts
|
|
# cached input inside inputTokens; the record keeps the two apart, as the
|
|
# other collectors do.
|
|
def local_stats(home):
|
|
now = datetime.now().astimezone()
|
|
today = now.date().isoformat()
|
|
week = [(now.date() - timedelta(days=offset)).isoformat() for offset in range(6, -1, -1)]
|
|
prompts = sessions = today_sessions = today_prompts = today_tokens = 0
|
|
days = set()
|
|
by_day = {day: 0 for day in week}
|
|
today_by_model = {}
|
|
models = {}
|
|
for session in (Path(home) / "sessions").glob("*/*/"):
|
|
summary = read_json(session / "summary.json")
|
|
if isinstance(summary, dict):
|
|
active = parse_time(summary.get("last_active_at"))
|
|
if active:
|
|
day = active.astimezone().date().isoformat()
|
|
sessions += 1
|
|
prompts += int(summary.get("num_messages") or 0)
|
|
days.add(day)
|
|
if day == today:
|
|
today_sessions += 1
|
|
|
|
usage = read_json(session / "usage.json")
|
|
turns = usage.get("turns") if isinstance(usage, dict) else None
|
|
for turn in turns if isinstance(turns, list) else []:
|
|
ended = parse_time(turn.get("endedAt")) if isinstance(turn, dict) else None
|
|
if not ended:
|
|
continue
|
|
day = ended.astimezone().date().isoformat()
|
|
days.add(day)
|
|
if day == today:
|
|
today_prompts += 1
|
|
for model, bucket in (turn.get("modelUsage") or {}).items():
|
|
if not isinstance(bucket, dict):
|
|
continue
|
|
# Grok's totalTokens leaves cache writes out; counting them here keeps
|
|
# the day's total equal to the sum of its model's buckets.
|
|
cached = int(bucket.get("cachedReadTokens") or 0)
|
|
uncached = max(0, int(bucket.get("inputTokens") or 0) - cached)
|
|
output = int(bucket.get("outputTokens") or 0)
|
|
created = int(bucket.get("cacheCreationTokens") or 0)
|
|
tokens = uncached + cached + output + created
|
|
totals = models.setdefault(model, {"inputTokens": 0, "outputTokens": 0, "cacheReadInputTokens": 0, "cacheCreationInputTokens": 0})
|
|
totals["inputTokens"] += uncached
|
|
totals["outputTokens"] += output
|
|
totals["cacheReadInputTokens"] += cached
|
|
totals["cacheCreationInputTokens"] += created
|
|
if day in by_day:
|
|
by_day[day] += tokens
|
|
if day == today:
|
|
today_tokens += tokens
|
|
today_by_model[model] = today_by_model.get(model, 0) + tokens
|
|
|
|
return {
|
|
"hasLocalStats": sessions > 0,
|
|
"todayPrompts": today_prompts,
|
|
"todaySessions": today_sessions,
|
|
"todayTotalTokens": today_tokens,
|
|
"todayTokensByModel": today_by_model,
|
|
"recentDays": [{"date": day, "messageCount": by_day[day]} for day in week],
|
|
"totalPrompts": prompts,
|
|
"totalSessions": sessions,
|
|
"activeDays": len(days),
|
|
"activeDates": sorted(days),
|
|
"modelUsage": models,
|
|
}
|
|
|
|
|
|
# A scan from before midnight would count yesterday's sessions as today's.
|
|
def cached_local_stats(home, max_age):
|
|
cache = cache_root() / "grok-stats.json"
|
|
cached = read_json(cache) or {}
|
|
today = datetime.now().astimezone().date().isoformat()
|
|
if cached.get("home") == str(home) and cached.get("day") == today and time.time() - float(cached.get("at") or 0) < max_age:
|
|
return cached["stats"]
|
|
stats = local_stats(home)
|
|
write_json(cache, {"home": str(home), "day": today, "at": time.time(), "stats": stats})
|
|
return stats
|
|
|
|
|
|
# One login per issuer in auth.json; the first is the CLI's own.
|
|
def login(home):
|
|
auth = read_json(Path(home) / "auth.json")
|
|
if not isinstance(auth, dict):
|
|
return {}
|
|
return next((v for v in auth.values() if isinstance(v, dict)), {})
|
|
|
|
|
|
def plan(home):
|
|
cached = read_json(Path(home) / "settings_cache.json") or {}
|
|
try:
|
|
settings = json.loads(cached.get("payload") or "{}").get("settings") or {}
|
|
except Exception:
|
|
return ""
|
|
return str(settings.get("subscription_tier_display") or "")
|
|
|
|
|
|
# The credits answer as one limit window: how much of this period's included
|
|
# usage is gone, and when the period ends. The answer is protobuf JSON, which
|
|
# leaves out a field holding zero, so a period with nothing used yet has no
|
|
# percentage at all.
|
|
def credits_limit(data):
|
|
config = data["config"]
|
|
period = config["currentPeriod"]
|
|
return {
|
|
"label": "Weekly" if "WEEK" in str(period.get("type")) else "Monthly",
|
|
"percent": max(0.0, min(1.0, float(config.get("creditUsagePercent") or 0) / 100)),
|
|
"resetsAt": parse_time(period["end"]).isoformat(),
|
|
}
|
|
|
|
|
|
# A window whose reset has passed starts over empty. A weekly one's next
|
|
# reset is a whole number of weeks later; a monthly one's isn't known.
|
|
def rolled_forward(limits):
|
|
now = datetime.now(timezone.utc)
|
|
rolled = []
|
|
for limit in limits:
|
|
resets = parse_time(limit.get("resetsAt"))
|
|
if resets and resets <= now:
|
|
limit = dict(limit, percent=0.0, resetsAt="")
|
|
if limit.get("label") == "Weekly":
|
|
weeks = (now - resets) // timedelta(weeks=1) + 1
|
|
limit["resetsAt"] = (resets + weeks * timedelta(weeks=1)).isoformat()
|
|
rolled.append(limit)
|
|
return rolled
|
|
|
|
|
|
def collect_limits(home, key, force):
|
|
result = {"limits": [], "usageStatusText": "", "authHelpText": AUTH_HELP, "live": False, "fetchedAtMs": 0}
|
|
entry = login(home)
|
|
token = str(entry.get("key") or "")
|
|
if not token:
|
|
result["usageStatusText"] = "Waiting for auth"
|
|
return result
|
|
|
|
cache = cache_root() / f"grok-limits-{key}.json"
|
|
cached = read_json(cache) or {}
|
|
fetched_at = float(cached.get("fetchedAtMs") or 0)
|
|
result["fetchedAtMs"] = fetched_at
|
|
|
|
expires = parse_time(entry.get("expires_at"))
|
|
if expires and expires.timestamp() <= time.time():
|
|
result["limits"] = cached.get("limits") or []
|
|
# The access token lives six hours and Grok mints a new one from its
|
|
# refresh token whenever it starts, so a lapsed one is routine, not a
|
|
# sign-out. And while Grok hasn't run, nothing here has spent its
|
|
# allowance, so the last numbers still stand, rolled past any reset.
|
|
if entry.get("refresh_token") and time.time() - expires.timestamp() < REFRESH_LIFETIME_SECONDS:
|
|
result.update(limits=rolled_forward(result["limits"]), live=True)
|
|
if not result["limits"]:
|
|
result["usageStatusText"] = "Limits paused"
|
|
result["authHelpText"] = "Start Grok to see its limits; signing in again is not needed."
|
|
else:
|
|
result["usageStatusText"] = "Sign-in expired"
|
|
result["authHelpText"] = "Grok's saved sign-in expired. Start Grok to refresh it."
|
|
return result
|
|
|
|
if cached.get("limits") and not force and time.time() - fetched_at / 1000 < PROBE_REUSE_SECONDS:
|
|
result.update(limits=cached["limits"], live=True, authHelpText="")
|
|
return result
|
|
|
|
request = urllib.request.Request(CREDITS_URL, headers={"Authorization": f"Bearer {token}", "Accept": "application/json"})
|
|
try:
|
|
with urllib.request.urlopen(request, timeout=8) as response:
|
|
limit = credits_limit(json.loads(response.read()))
|
|
except urllib.error.HTTPError as error:
|
|
limit = None
|
|
if error.code in (401, 403):
|
|
result["usageStatusText"] = "Waiting for auth"
|
|
except Exception:
|
|
limit = None
|
|
|
|
if limit:
|
|
result.update(limits=[limit], live=True, fetchedAtMs=round(time.time() * 1000), authHelpText="")
|
|
write_json(cache, {"fetchedAtMs": result["fetchedAtMs"], "limits": result["limits"]})
|
|
else:
|
|
result["limits"] = cached.get("limits") or []
|
|
if not result["usageStatusText"] and not result["limits"]:
|
|
result["usageStatusText"] = "Grok limits unavailable"
|
|
return result
|
|
|
|
|
|
# The accounts `omarchy agent account` registered, read straight from its
|
|
# registry. Only a registry holding a second account matters: with one, the
|
|
# record describes ~/.grok alone.
|
|
def registered_accounts():
|
|
state = Path(os.environ.get("XDG_STATE_HOME") or (Path.home() / ".local" / "state"))
|
|
registry = read_json(state / "omarchy" / "agents" / "accounts" / "grok.json") or {}
|
|
accounts = [a for a in registry.get("accounts") or [] if isinstance(a, dict) and a.get("id")]
|
|
if len(accounts) < 2:
|
|
return []
|
|
active_id = registry.get("active") or accounts[0]["id"]
|
|
if not any(a["id"] == active_id for a in accounts):
|
|
active_id = accounts[0]["id"]
|
|
for account in accounts:
|
|
account["active"] = account["id"] == active_id
|
|
account["switch"] = {
|
|
"mode": "auto" if registry.get("switch") == "auto" else "manual",
|
|
"threshold": registry.get("threshold") or 95,
|
|
}
|
|
return accounts
|
|
|
|
|
|
def home_of(account):
|
|
return Path(account.get("home") or (Path.home() / ".grok"))
|
|
|
|
|
|
# Keyed by who the home is signed in as, so a home signed in to someone else
|
|
# never shows the last one's numbers.
|
|
def cache_key(home, fallback):
|
|
user = str(login(home).get("user_id") or "")
|
|
return re.sub(r"[^A-Za-z0-9_-]", "", user) or fallback
|
|
|
|
|
|
def account_limits(account, force):
|
|
home = home_of(account)
|
|
limits = collect_limits(home, cache_key(home, account["id"]), force)
|
|
return {
|
|
"id": account["id"],
|
|
"label": str(account.get("label") or account["id"]),
|
|
"email": str(account.get("email") or ""),
|
|
"plan": plan(home) or str(account.get("plan") or ""),
|
|
"active": account["active"],
|
|
"primary": bool(account.get("primary")),
|
|
"limits": limits["limits"],
|
|
"stale": not limits["live"],
|
|
"fetchedAt": limits["fetchedAtMs"],
|
|
"usageStatusText": limits["usageStatusText"],
|
|
"authHelpText": limits["authHelpText"],
|
|
}
|
|
|
|
|
|
def main():
|
|
parser = argparse.ArgumentParser()
|
|
parser.add_argument("--force", action="store_true")
|
|
parser.add_argument("--limits-only", action="store_true")
|
|
args = parser.parse_args()
|
|
|
|
registered = registered_accounts()
|
|
accounts = [account_limits(account, args.force) for account in registered]
|
|
current = next((a for a in accounts if a["active"]), None)
|
|
if current:
|
|
tier = current["plan"]
|
|
limits = current
|
|
stale, fetched_at = current["stale"], current["fetchedAt"]
|
|
else:
|
|
home = default_home()
|
|
tier = plan(home)
|
|
limits = collect_limits(home, cache_key(home, "main"), args.force)
|
|
stale, fetched_at = not limits["live"], limits["fetchedAtMs"]
|
|
|
|
# Nobody signed in to Grok here: an empty record, which the panel skips.
|
|
# With accounts registered, the primary is ~/.grok by definition.
|
|
stats_home = Path.home() / ".grok" if accounts else default_home()
|
|
signed_in = bool(accounts) or bool(login(stats_home))
|
|
record = {
|
|
"schemaVersion": 1,
|
|
"id": AGENT_ID,
|
|
"name": AGENT_NAME,
|
|
"updatedAt": datetime.now(timezone.utc).isoformat(),
|
|
"ready": signed_in,
|
|
"tierLabel": tier,
|
|
"usageStatusText": limits["usageStatusText"],
|
|
"authHelpText": limits["authHelpText"],
|
|
"limits": limits["limits"],
|
|
"limitsStale": stale,
|
|
"limitsFetchedAt": fetched_at,
|
|
}
|
|
record.update(cached_local_stats(stats_home, LIMITS_ONLY_SCAN_REUSE_SECONDS if args.limits_only and not args.force else 0))
|
|
if accounts:
|
|
record["accountSwitch"] = registered[0]["switch"]
|
|
record["accounts"] = accounts
|
|
print(json.dumps(record, separators=(",", ":")))
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|