Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
111 changes: 85 additions & 26 deletions bin/omarchy-agent-usage-agy
Original file line number Diff line number Diff line change
Expand Up @@ -10,14 +10,15 @@ by, so the record and the default agent agree on which agent this is.
Local stats come from Antigravity's history log, conversation summaries, and
conversation transcripts under ~/.gemini/antigravity-cli/, and from the
Antigravity answers pi, omp, OpenClaw, and opencode's Antigravity plugin
recorded; no other collector counts those. The plan and
limits come from the Google Cloud Code API (v1internal:loadCodeAssist,
recorded; no other collector counts those. When the `agy` CLI is installed and
signed in, limits come from `agy -p /usage --output-format json` so the
official CLI handles auth, token refresh, and Google's API itself. For omp,
pi, or opencode sign-ins (or when `agy` is absent), the plan and limits come
from the Google Cloud Code API (v1internal:loadCodeAssist,
v1internal:retrieveUserQuotaSummary, and v1internal:retrieveUserQuota when the
summary omits Gemini), asked with the sign-in agy keeps in the
Secret Service keyring (or its antigravity-oauth-token file), or with the
Antigravity sign-in omp, pi, or opencode's Antigravity plugin keeps; a lapsed
omp sign-in is asked through `omp usage`, which renews it. Those stores are
only ever read. The agents panel only ever reads the JSON this prints.
summary omits Gemini), with a lapsed omp sign-in asked through `omp usage`.
Credential stores are only ever read. The agents panel only ever reads the
JSON this prints.
"""

import argparse
Expand Down Expand Up @@ -45,6 +46,7 @@ from collectors import ( # noqa: E402
cached_scan,
canonical_roots,
emit,
find_command,
jwt_claims,
now_ms,
number,
Expand Down Expand Up @@ -89,8 +91,8 @@ def parse_time(value):
parsed = parsed.replace(tzinfo=timezone.utc)
except (ValueError, OverflowError, OSError):
return None
# Go's zero time marks an uninitialized summary, not dated activity.
return None if parsed == datetime.min.replace(tzinfo=timezone.utc) else parsed
# Go's zero time and Unix epoch 0 mark an unset timestamp, not dated activity.
return None if parsed <= datetime(1970, 1, 1, tzinfo=timezone.utc) else parsed


def local_day(value):
Expand Down Expand Up @@ -126,13 +128,15 @@ def login():

token = data.get("token") if isinstance(data.get("token"), dict) else {}
expires = parse_time(token.get("expiry") or data.get("expiry"))
raw_tier = str(data.get("user_tier") or "").strip()
return {
"source": "agy",
"accessToken": str(token.get("access_token") or data.get("access_token") or ""),
"expiresAt": expires.timestamp() if expires else 0,
"refresh": str(token.get("refresh_token") or data.get("refresh_token") or ""),
"authMethod": str(data.get("auth_method") or "consumer"),
"email": str(data.get("id_token_email") or "") or email_of(data.get("id_token")),
"tier": normalize_tier_label(raw_tier) if raw_tier else "",
}


Expand Down Expand Up @@ -294,9 +298,9 @@ def listed(data, key):
# The Gemini group's 5-hour and weekly buckets are the plan's own limits; the
# other groups (Claude and GPT models) are scoped allowances, shown once
# they have been touched. An answer that lists its buckets without groups
# lists the Gemini ones. One without a Gemini group (Ultra's summary lists only
# Claude and GPT) never lets those groups stand in for Gemini — collect_limits
# falls back to retrieveUserQuota for Gemini's own 5-hour bucket. An answer of
# lists the Gemini ones. One without a Gemini group never lets those other
# groups stand in for Gemini — collect_limits falls back to retrieveUserQuota
# for Gemini's own 5-hour bucket. An answer of
# another shape (not an object, an error, groups or the Gemini buckets that
# aren't a list) is None, a failed check rather than a plan without quotas;
# another group's buckets of the wrong shape skip that group.
Expand All @@ -308,7 +312,7 @@ def extract_limits(data):
groups = [{"displayName": "Gemini", "buckets": data["buckets"]}]
if not groups:
return []
gemini = next((g for g in groups if "gemini" in str(g.get("displayName") or "").lower()), None)
gemini = next((g for g in groups if "gemini" in str(g.get("displayName") or g.get("name") or "").lower()), None)
if gemini and not listed(gemini, "buckets"):
return None

Expand All @@ -318,8 +322,8 @@ def extract_limits(data):
if not isinstance(bucket, dict) or used(bucket) is None:
continue
window = str(bucket.get("window") or "").lower()
bucket_id = str(bucket.get("bucketId") or "").lower()
name = str(bucket.get("displayName") or "").lower()
bucket_id = str(bucket.get("bucketId") or bucket.get("id") or "").lower()
name = str(bucket.get("displayName") or bucket.get("name") or "").lower()
if window == "5h" or "5h" in bucket_id or "five" in name:
session = bucket
elif window == "weekly" or "weekly" in bucket_id or "week" in name:
Expand All @@ -332,7 +336,7 @@ def extract_limits(data):
for group in groups:
if group is gemini:
continue
group_name = str(group.get("displayName") or "").strip()
group_name = str(group.get("displayName") or group.get("name") or "").strip()
short = "Claude/GPT" if "claude" in group_name.lower() else (group_name or "3P")
buckets = group.get("buckets")
for bucket in buckets if isinstance(buckets, list) else []:
Expand All @@ -342,10 +346,10 @@ def extract_limits(data):
return limits


# Google AI Ultra omits Gemini from retrieveUserQuotaSummary, while
# retrieveUserQuota still reports every model's 5-hour bucket. Pick the fullest
# Gemini bucket — the most constrained one when models don't share a pool — and
# drop the rolling now+5h reset Google sends on untouched (0% used) buckets.
# When retrieveUserQuotaSummary omits Gemini, retrieveUserQuota still reports
# every model's 5-hour bucket. Pick the fullest Gemini bucket — the most
# constrained one when models don't share a pool — and drop the rolling now+5h
# reset Google sends on untouched (0% used) buckets.
def extract_model_limits(data):
if not isinstance(data, dict) or "error" in data or not listed(data, "buckets"):
return None
Expand Down Expand Up @@ -385,6 +389,38 @@ def post(endpoint, token, body=None):
return open_json(request, timeout=8)


# Ask agy's own headless /usage command so the official CLI handles auth,
# token refresh, and Google's API itself without calling private endpoints
# directly with agy's OAuth token.
def agy_usage(agy_bin):
try:
proc = subprocess.run(
[agy_bin, "-p", "/usage", "--output-format", "json", "--log-file", "/dev/null"],
stdin=subprocess.DEVNULL, capture_output=True, text=True, timeout=20,
)
payload = json.loads(proc.stdout) if proc.stdout.strip() else None
except subprocess.TimeoutExpired:
return None, "transport"
except (OSError, ValueError, subprocess.SubprocessError):
return None, "error"
if not isinstance(payload, dict):
return None, "error"
status = str(payload.get("status") or "").upper()
if proc.returncode != 0 or (status and status != "SUCCESS"):
err = f"{payload.get('error') or ''} {payload.get('response') or ''} {proc.stderr or ''}".lower()
if any(word in err for word in ("auth", "login", "sign in", "sign-in", "unauthenticated", "unauthorized", "401", "403")):
return None, "auth"
if any(word in err for word in ("timeout", "timed out", "connection", "dial", "lookup", "dns", "network", "unreachable", "eof")):
return None, "transport"
return None, "error"
command = payload.get("command")
data = command.get("data") if isinstance(command, dict) else None
if not isinstance(data, dict):
return None, "error"
limits = extract_limits(data)
return (limits, "") if limits is not None else (None, "error")


def kept_tier(entry):
cache = limits_cache(entry)
return str(cache.data.get("tierLabel") or "") if cache else ""
Expand Down Expand Up @@ -415,7 +451,9 @@ def collect_limits(entries, force):
# one last.
ordered = sorted(entries, key=lambda e: (not token_fresh(e, now), -e["expiresAt"]))
fresh = [e for e in ordered if token_fresh(e, now)]
lead = next(iter(fresh or [e for e in ordered if e["accessToken"]] or ordered), None)
agy_bin = find_command("agy") if any(e["source"] == "agy" for e in entries) else None
agy_entries = [e for e in ordered if e["source"] == "agy"] if agy_bin else []
lead = next(iter(fresh or agy_entries or [e for e in ordered if e["accessToken"]] or ordered), None)
omp = shutil.which("omp") if any(e["source"] == "omp" for e in entries) else None
omp_entries = [e for e in ordered if e["source"] == "omp"] if omp else []

Expand All @@ -438,22 +476,37 @@ def collect_limits(entries, force):
return result

keep(lead)
if not lead or not lead["accessToken"]:
if not lead or (not lead["accessToken"] and not agy_entries):
result.update(usageStatusText="Waiting for auth", authHelpText=AUTH_HELP)
return result

# A panel that is opened and shut repeatedly must not turn into a request
# per flick; --force is a person asking for fresh numbers.
if not force:
for entry in fresh + [e for e in omp_entries if e not in fresh]:
for entry in fresh + [e for e in agy_entries + omp_entries if e not in fresh]:
# An answer with no windows is an answer too: a plan without quotas.
cache = limits_cache(entry)
if cache and cache.fresh(force, allow_empty=True):
keep(entry)
result["live"] = True
return result

refused, failure = [], None
refused, failure, agy_failure = [], None, None
if agy_entries:
entry = agy_entries[0]
limits, err_kind = agy_usage(agy_bin)
if limits is not None:
refreshed = login() or entry
return answered(refreshed, refreshed.get("tier") or kept_tier(refreshed), limits)
if err_kind == "auth":
refused.append(entry)
elif err_kind == "transport":
agy_failure = entry, "Couldn't reach Google's quota service. Retrying shortly.", True
else:
agy_failure = entry, "Couldn't read usage from `agy`.", False
# Never call Google's private API directly with agy's OAuth token when
# the official agy binary is installed.
fresh = [e for e in fresh if e["source"] != "agy"]
for entry in fresh:
try:
assist = post("loadCodeAssist", entry["accessToken"])
Expand Down Expand Up @@ -488,21 +541,27 @@ def collect_limits(entries, force):
break
return answered(entry, tier, limits)

if failure:
entry, help_text, transport = failure
def failed(info):
entry, help_text, transport = info
keep(entry)
result.update(authHelpText=help_text, retryAdvised=transport)
if not result["limits"]:
result["usageStatusText"] = "Gemini limits unavailable"
return result

if failure:
return failed(failure)

# No token in hand answered, but omp renews its own sign-in when asked
# for usage.
answer = omp_answer(omp, omp_entries) if omp_entries else None
if answer:
entry, tier, limits = answer
return answered(entry, tier or kept_tier(entry), limits)

if agy_failure:
return failed(agy_failure)

if refused:
keep(refused[0])
result.update(usageStatusText="Sign-in expired", authHelpText=refused_help(refused[0]))
Expand Down
4 changes: 2 additions & 2 deletions shell/plugins/agents/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -172,7 +172,7 @@ Adding an agent needs no QML changes: ship a collector that follows the contract
| `grokbot` | Grok Bot's weekly included usage from Cursor's `GetSandUsageStatus` RPC, asked as the Cursor sign-in | none; limit only |
| `copilot` | Account-wide AI credit allowance (GitHub quota endpoint, or estimated locally) | the Copilot CLI session store's `assistant_usage_events`, with `~/.copilot/session-state` transcripts as fallback |
| `muse` | The client's key endpoint (session + weekly percents), else local metering only — never estimated | native `muse` CLI session files, with prompt and session counts from its `session-index.db`, plus pi/omp and opencode sessions on the `meta` provider and omp's `muse-code` |
| `agy` | Google's Cloud Code API (`loadCodeAssist` for the plan, `retrieveUserQuotaSummary` for the 5-hour and weekly windows and any touched Claude/GPT allowance), asked with the sign-in agy, omp, pi, or opencode's Antigravity plugin keeps | `history.jsonl`, `conversation_summaries.db`, and each conversation's `transcript.jsonl` under `~/.gemini/antigravity-cli/` (`AGY_DIR`), plus pi, omp, and OpenClaw sessions on the `google-antigravity` provider and opencode's `antigravity-` models |
| `agy` | `agy -p /usage --output-format json` when the `agy` CLI is installed and signed in (5-hour and weekly Gemini windows plus any touched Claude/GPT allowance); otherwise Google's Cloud Code API (`loadCodeAssist` and `retrieveUserQuotaSummary`), asked with the sign-in omp, pi, or opencode's Antigravity plugin keeps | `history.jsonl`, `conversation_summaries.db`, and each conversation's `transcript.jsonl` under `~/.gemini/antigravity-cli/` (`AGY_DIR`), plus pi, omp, and OpenClaw sessions on the `google-antigravity` provider and opencode's `antigravity-` models |
| `kimchi` | The plan, prepaid credits, and any spend budgets from the gateway's `/v1/credits` and `/v1/budget`, the endpoints Kimchi's own status line reads | Kimchi's pi session files under `~/.config/kimchi/harness/sessions` (`KIMCHI_CODING_AGENT_DIR`): tokens by model per assistant reply on Kimchi's own `kimchi` and `kimchi-dev` routes; a session `--provider openrouter` is OpenRouter's, and one on a custom provider counts nowhere. Also pi/omp sessions and opencode replies on those provider ids, and Claude Code turns and Codex rollouts sent to Kimchi's gateway (`llm.kimchi.dev`, `llm.eu.kimchi.dev`), as `kimchi claudecode` and `kimchi codex` set them up |
| `hermes` | None (Hermes has no subscription of its own) | `state.db` in Hermes' home and in each named profile under its root's `profiles/`, read-only, scanned once per refresh window: the sessions Nous Portal billed, and those from before Hermes kept the route |
| `devin` | The daily and weekly quota (plus credit buckets on credit plans) from the GetUserStatus answer the Devin CLI caches in `$XDG_CACHE_HOME/devin/cli/user_status.*.bin`; no network call | the CLI's `$XDG_DATA_HOME/devin/cli/sessions.db` (per-message metrics and `prompt_history`), plus pi/omp and opencode sessions on the `devin` provider |
Expand Down Expand Up @@ -265,7 +265,7 @@ The collector asks the client's own key endpoint for the subscription's session

### Gemini

The panel names the section for the subscription, Gemini; Antigravity is the harness that codes on it. The record's id is `agy`, the name the default agent knows it by. The plan and limits are asked of Google's Cloud Code API with whichever Antigravity sign-in is on the machine: the one `agy` keeps in the Secret Service keyring (service `gemini`, username `antigravity`) or, without a keyring, in `antigravity-oauth-token` under `AGY_DIR`; omp's `google-antigravity` sign-in in `~/.omp/agent/agent.db`; pi's in `auth.json` (under `PI_CODING_AGENT_DIR` when set); and opencode's `google` sign-in, only when the Antigravity plugin's `antigravity-accounts.json` is there. The token refreshed most recently is asked first, and one Google refuses gives way to the next. Those stores are only ever read. A lapsed token shows the last limits as paused until the harness that owns it runs again; a lapsed omp sign-in is asked through `omp usage`, which renews it. Each Google account keeps its own last answer, so another account's limits never stand in. `CLOUD_CODE_URL` moves the endpoint, over https only.
The panel names the section for the subscription, Gemini; Antigravity is the harness that codes on it. The record's id is `agy`, the name the default agent knows it by. When the `agy` CLI is installed and signed in (its sign-in kept in the Secret Service keyring under service `gemini`, username `antigravity`, or in `antigravity-oauth-token` under `AGY_DIR`), limits are asked through `agy -p /usage --output-format json` so the official CLI handles auth, token refresh, and Google's API itself. For omp (`~/.omp/agent/agent.db`), pi (`auth.json` under `PI_CODING_AGENT_DIR` when set), and opencode's Antigravity plugin (`google` sign-in when `antigravity-accounts.json` is present), or when `agy` is absent, the plan and limits are asked of Google's Cloud Code API (`CLOUD_CODE_URL` moves the endpoint, over https only), with the token refreshed most recently asked first and a lapsed omp sign-in renewed through `omp usage`. Those credential stores are only ever read. Each Google account keeps its own last answer, so another account's limits never stand in.

Local stats count `agy`'s history prompts, its conversations (a subagent's conversation counts toward the one that spawned it), and the tokens each transcript step reports, under the model the step or the last Model Selection names. Antigravity answers that pi, omp, OpenClaw (`OPENCLAW_STATE_DIR`), and opencode's plugin recorded count too, a forked copy once. No other collector counts these.

Expand Down
Loading