Skip to content
Open
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
123 changes: 106 additions & 17 deletions bin/omarchy-agent-usage-claude
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import datetime as dt
import json
import os
import re
import subprocess
import sys
import time
import urllib.request
Expand All @@ -35,6 +36,7 @@ from collectors import ( # noqa: E402
LimitsCache,
Stats,
account_entry,
age_below,
base_record,
cache_root,
cached_scan,
Expand All @@ -45,6 +47,9 @@ from collectors import ( # noqa: E402
claude_code_scan_match,
emit,
empty_bucket,
exclusive_lock,
find_installed_command,
now_ms,
number,
obj,
open_json,
Expand All @@ -54,10 +59,14 @@ from collectors import ( # noqa: E402
recent_dates,
registered_accounts,
claude_code_usage,
limits_cache_path,
runtime_env,
scan_opencode,
scan_pi_sessions,
stamp,
today as today_string,
warn,
write_json,
)

AGENT_ID = "claude"
Expand All @@ -68,6 +77,16 @@ USAGE_ENDPOINT = "https://api.anthropic.com/api/oauth/usage"
# numbers this recent still describes the account; only older ones are
# reported as stale.
CURRENT_ENOUGH_SECONDS = 900
# Before 2.1.301 a command as short as `claude auth status` could exit in the
# middle of a token refresh and sign the home out, and 2.1.278 did not refresh
# at all, so an older CLI is never run to refresh: a lost sign-in is worse
# than paused limits.
REFRESH_MIN_VERSION = (2, 1, 301)
# A CLI that couldn't refresh (offline, refused) is asked again for the same
# sign-in at most this often, not on every panel refresh.
REFRESH_RETRY_SECONDS = 1800
# Far past the second a refresh takes; only a stalled network reaches it.
REFRESH_TIMEOUT_SECONDS = 20


def config_dir() -> Path:
Expand Down Expand Up @@ -409,12 +428,77 @@ def profile_path(home: Path) -> Path:
legacy = home / ".config.json"
if legacy.exists():
return legacy
configured = os.environ.get("CLAUDE_CONFIG_DIR")
if home == expand_path("~/.claude") and not (configured and expand_path(configured) == home):
if default_home(home):
return Path.home() / ".claude.json"
return home / ".claude.json"


# Whether the CLI reaches this home with no CLAUDE_CONFIG_DIR: ~/.claude,
# unless the environment points it there by name.
def default_home(home: Path) -> bool:
configured = os.environ.get("CLAUDE_CONFIG_DIR")
return home == expand_path("~/.claude") and not (configured and expand_path(configured) == home)


# Only the Claude Code CLI renews the access token, from the refresh token,
# and only when it runs. Claude Code in the Claude desktop app keeps a sign-in
# of its own, so a machine that only uses it never runs the CLI and its token
# stays lapsed. `claude auth status` asks the model nothing and refreshes on
# the way, so it is run for a home whose refresh token still holds. The CLI
# rewrites the file itself, under its own lock: the refresh token changes with
# every use, so a collector that refreshed or wrote it would take it from the
# CLI. The caller reads the credentials again to see what came of it.
def refresh_sign_in(home: Path, cache_name: str, force: bool) -> None:
attempt = limits_cache_path(AGENT_ID, cache_name, kind="refresh")
# One run at a time, or two would race each other for the refresh token. A
# run that waited on another finds the token renewed, or the attempt
# stamped, and runs nothing.
with exclusive_lock(attempt.with_name(attempt.name + ".lock")):
if not 0 < oauth_login(home)[1] <= time.time() * 1000:
return
if not force and age_below(stamp(read_json(attempt).get("attemptedAtMs")) / 1000, REFRESH_RETRY_SECONDS):
return
try:
write_json(attempt, {"attemptedAtMs": now_ms()})
except Exception as exc:
# Without the stamp, every panel refresh would run the CLI again.
warn(f"could not stamp the sign-in refresh ({exc})")
return
claude = find_installed_command("claude")
if not claude:
return
env = refresh_env(home)
try:
version = subprocess.run([claude, "--version"], capture_output=True, text=True, env=env, stdin=subprocess.DEVNULL, timeout=REFRESH_TIMEOUT_SECONDS).stdout
except (OSError, subprocess.SubprocessError):
return
found = re.match(r"\s*(\d+)\.(\d+)\.(\d+)", version)
if not found or tuple(int(part) for part in found.groups()) < REFRESH_MIN_VERSION:
minimum = ".".join(map(str, REFRESH_MIN_VERSION))
warn(f"Claude Code is older than {minimum} or names no version, so it is not run to refresh the sign-in")
return
try:
subprocess.run([claude, "auth", "status"], capture_output=True, env=env, stdin=subprocess.DEVNULL, timeout=REFRESH_TIMEOUT_SECONDS)
except (OSError, subprocess.SubprocessError) as exc:
warn(f"claude auth status failed ({type(exc).__name__})")


# Run inside a Claude Code session (CLAUDECODE, CLAUDE_CODE_*), the CLI takes
# that session's sign-in, and with an Anthropic key, token or base URL
# (ANTHROPIC_*) another credential altogether: either way it never refreshes
# this home's file. CLAUDE_CONFIG_DIR names the home, unless it is the one the
# CLI reaches without it, whose profile lives elsewhere. A run nobody asked
# for sends nothing but the refresh: no telemetry, error report or update check.
def refresh_env(home: Path) -> dict[str, str]:
env = {name: value for name, value in runtime_env().items()
if name != "CLAUDECODE" and not name.startswith(("CLAUDE_CODE_", "ANTHROPIC_"))}
env["CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC"] = "1"
env.pop("CLAUDE_CONFIG_DIR", None)
if not default_home(home):
env["CLAUDE_CONFIG_DIR"] = str(home)
return env


# The rate-limit tier names the ceiling, not the plan: a Team premium seat
# runs on `default_claude_max_5x` while paying for Team. Lead with the
# subscription and keep the multiplier as its qualifier, so Max still reads
Expand Down Expand Up @@ -592,12 +676,13 @@ def probe_limits(access_token: str) -> dict[str, Any]:
return {"ok": True, "limits": limits}


def collect_limits(access_token: str, expires_at_ms: int, refresh_expires_at_ms: int, force: bool, cache_name: str = "claude-limits.json") -> dict[str, Any]:
def collect_limits(home: Path, force: bool, cache_name: str = "claude-limits.json") -> dict[str, Any]:
access_token, expires_at_ms, refresh_expires_at_ms, plan = oauth_login(home)
# `live` says the numbers came from Anthropic just now (or within the reuse
# window) rather than from a cache kept past a failed or impossible probe.
# `fetchedAtMs` says when they were measured, so a stale account can say
# how old they are.
result = {"limits": [], "usageStatusText": "", "authHelpText": AUTH_HELP, "live": False, "fetchedAtMs": 0}
result = {"limits": [], "usageStatusText": "", "authHelpText": AUTH_HELP, "live": False, "fetchedAtMs": 0, "plan": plan}

# A panel that is opened and shut repeatedly must not turn into a request
# per flick, so recent probe results are reused for a short window — and
Expand All @@ -611,20 +696,25 @@ def collect_limits(access_token: str, expires_at_ms: int, refresh_expires_at_ms:

# Probing needs a live token and only the Claude Code CLI can mint one: it
# refreshes the credential file when it runs, so a machine left alone long
# enough finds the saved token lapsed. Say so — an empty limits list with
# nothing else set hides the whole section and explains nothing — and keep
# showing the last numbers, resetting elapsed windows to zero.
# enough finds the saved token lapsed. A lapsed access token is routine, not
# a sign-out, so while the refresh token holds the CLI is run to renew it.
if access_token and 0 < expires_at_ms <= time.time() * 1000 < refresh_expires_at_ms:
refresh_sign_in(home, cache_name, force)
access_token, expires_at_ms, refresh_expires_at_ms, result["plan"] = oauth_login(home)

# Without a live token, say so — an empty limits list with nothing else set
# hides the whole section and explains nothing — and keep showing the last
# numbers, resetting elapsed windows to zero.
if access_token == "":
result["limits"] = fallback
result["usageStatusText"] = "Waiting for auth"
return result
if expires_at_ms > 0 and expires_at_ms <= time.time() * 1000:
result["limits"] = fallback
# A lapsed access token is routine, not a sign-out: it lives about eight
# hours, and the CLI mints a new one from the refresh token the next time
# it runs. Only a lapsed *refresh* token is a sign-in a person must redo,
# and saying so either way sends people to `claude auth login` nightly --
# which does not restore anything the CLI would not have restored itself.
# Only a lapsed *refresh* token is a sign-in a person must redo, and
# saying so for a lapsed access token sends people to `claude auth login`
# nightly -- which does not restore anything the CLI would not have
# restored itself.
if refresh_expires_at_ms > time.time() * 1000:
result["usageStatusText"] = "Limits paused"
result["authHelpText"] = (
Expand Down Expand Up @@ -687,7 +777,6 @@ def current_account_id(home: Path) -> str:

def account_limits(account: dict[str, Any], force: bool) -> dict[str, Any]:
home = expand_path(account["home"]) if account.get("home") else expand_path("~/.claude")
access_token, expires_at_ms, refresh_expires_at_ms, plan = oauth_login(home)
# Keyed by the subscription, not the label: forget "Work" and add a different
# "Work", and the new one must never fall back on the old one's allowance.
# Who the home is signed in as now, not when it was added: a `claude auth
Expand All @@ -701,8 +790,8 @@ def account_limits(account: dict[str, Any], force: bool) -> dict[str, Any]:
cache_name = "claude-limits.json"
else:
cache_name = f"claude-limits-{key}.json"
limits = collect_limits(access_token, expires_at_ms, refresh_expires_at_ms, force, cache_name)
return account_entry(account, limits, plan)
limits = collect_limits(home, force, cache_name)
return account_entry(account, limits, limits["plan"])


# -------------------------------------------------------------------- record
Expand All @@ -729,13 +818,13 @@ def main() -> int:
limits = {key: current[key] for key in ("limits", "usageStatusText", "authHelpText", "retryAdvised")}
stale, fetched_at = current["stale"], current["fetchedAt"]
else:
access_token, expires_at_ms, refresh_expires_at_ms, plan = oauth_login(claude_dir)
# Keyed by who the home is signed in as, as a registered primary is, so
# signing in to another subscription never shows the last one's numbers
# and registering the home later keeps its cache.
identity = re.sub(r"[^A-Za-z0-9_-]", "", current_account_id(claude_dir))
cache_name = f"claude-limits-{identity}.json" if identity else "claude-limits.json"
limits = collect_limits(access_token, expires_at_ms, refresh_expires_at_ms, args.force, cache_name)
limits = collect_limits(claude_dir, args.force, cache_name)
plan = limits["plan"]
stale, fetched_at = not limits["live"] and bool(limits["limits"]), limits["fetchedAtMs"]
# Asking for a sign-in only makes sense where Claude Code is in use: its
# config home or profile exists, or there is local usage. A machine that
Expand Down
51 changes: 3 additions & 48 deletions bin/omarchy-agent-usage-codex
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ from collectors import ( # noqa: E402
codex_scan_match,
emit,
find_command,
find_installed_command,
jwt_claims,
now_ms,
number,
Expand Down Expand Up @@ -88,52 +89,6 @@ def model_name(raw):
ENV = runtime_env()


def mise_shims_dir():
data_home = ENV.get("MISE_DATA_DIR") or os.path.join(
ENV.get("XDG_DATA_HOME") or os.path.join(str(Path.home()), ".local", "share"), "mise")
return os.path.join(data_home, "shims")


def is_lazy_launcher(path):
# omarchy-mise-install writes a regular file whose first step is `mise use
# -g`, and mise's shims exec `mise x`; running either installs the tool it
# wraps. A shim is a symlink to the mise binary itself, so the symlink
# check comes after the shim checks: a symlink elsewhere is the user's own
# binary.
if os.path.dirname(os.path.abspath(path)) == mise_shims_dir():
return True
if os.path.islink(path):
mise = find_command("mise")
return bool(mise) and os.path.realpath(path) == os.path.realpath(mise)
try:
with open(path, "rb") as handle:
head = handle.read(4096)
return b"mise use" in head or b"mise x " in head
except OSError:
return False


def find_codex_binary():
for directory in ENV.get("PATH", "").split(os.pathsep):
candidate = os.path.join(directory, "codex")
if os.path.isfile(candidate) and os.access(candidate, os.X_OK) and not is_lazy_launcher(candidate):
return candidate
# `mise which` only prints a binary that is already installed, so it is the
# safe way to resolve a codex managed by mise without running the launcher.
# `mise which` can resolve a configured `latest` over the network; the usage
# probe stays offline.
mise = find_command("mise")
if mise:
try:
out = subprocess.run([mise, "which", "codex"], capture_output=True, text=True, env=dict(ENV, MISE_OFFLINE="1"), timeout=10)
resolved = out.stdout.strip()
if out.returncode == 0 and os.path.isfile(resolved) and not is_lazy_launcher(resolved):
return resolved
except Exception:
pass
return None



def codex_home():
return Path(ENV.get("CODEX_HOME") or (Path.home() / ".codex"))
Expand Down Expand Up @@ -550,7 +505,7 @@ def home_env(home=None, primary=True):
def fetch_codex_rpc(home=None, primary=True):
result = {"limits": [], "tierLabel": "", "usageStatusText": "", "authHelpText": AUTH_HELP}
env = home_env(home, primary)
codex = find_codex_binary()
codex = find_installed_command("codex")
if not codex:
result["usageStatusText"] = "Codex limits unavailable"
result["authHelpText"] = "codex not found in PATH"
Expand Down Expand Up @@ -794,7 +749,7 @@ def account_limits(account, force):
def codex_in_use(stats):
return (
bool(find_command("codex"))
or bool(find_codex_binary())
or bool(find_installed_command("codex"))
or codex_home().exists()
or bool(ENV.get("CODEX_ACCESS_TOKEN"))
or number(stats.get("totalSessions")) > 0
Expand Down
5 changes: 3 additions & 2 deletions docs/agent-usage-collectors.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ New collectors build on the shared module, [`shell/plugins/agents/collectors.py`
- `--limits-only` (the panel's near-limit refresh) reuses a local scan for `LIMITS_ONLY_REUSE_SECONDS = 900`, but asks for limits like a normal run.
- `--force` (a person pressing refresh) reuses nothing.
- The record is printed on stdout. Diagnostics go to stderr and never carry a credential.
- A collector never writes to an agent's own files. Credentials are only read, and a token is refreshed only where the agent's own CLI does the same under its lock, never by rewriting another harness's store.
- A collector never writes to an agent's own files. Credentials are only read, and a token is refreshed only where the agent's own CLI does the same under its lock, or by running that CLI to do it (the Claude collector runs `claude auth status`), never by rewriting another harness's store.

## The shared module

Expand Down Expand Up @@ -41,6 +41,7 @@ Its main entry points, each documented where it is defined:
- `trusted_endpoint(url)`: whether an endpoint override a person set (`CURSOR_API_ENDPOINT`, `MUSE_KEY_ENDPOINT`, …) may carry a credential: https anywhere, plain http only to this machine. Every override that moves where a token goes passes through it.
- `cursor_token(auth_path=None, state_db=None)`, with `jwt_claims()`, `token_lapsed()`, `account_key()` and `finite()`: the Cursor account the Cursor and Grok Bot collectors both ask as (an exported `CURSOR_AUTH_TOKEN`; with `CURSOR_API_KEY` exported, only the token the CLI traded that key for, never the key itself; else the CLI's `auth.json` at `CURSOR_AUTH_PATH` or its default, then the editor's `state.vscdb`, a lapsed sign-in giving way to one that isn't), and reading any JWT's claims, expiry and subject.
- `registered_accounts(id)` and `account_entry(account, limits, plan, **extra)`: the accounts `omarchy agent account` registered, and one entry of the record's `accounts`.
- `find_installed_command(name)`: an agent CLI a collector may run, the first on `PATH` that isn't a mise shim, an account wrapper or a launcher that would install or update the tool first, else the binary `mise which` names offline.
- `local_day()`, `token_count()`, `usage_tokens()`, `number()`, `now_ms()`, `stamp()`, `age_below()`, `read_json()`, `write_json()`, `cache_root()`: reading untrusted values and files the same way everywhere.

`test/shell.d/agent-usage-shared-test.sh` holds the module to this contract directly. Something goes in the module only once two collectors need it.
Expand Down Expand Up @@ -76,7 +77,7 @@ The panel acts on a small vocabulary in `usageStatusText`, so the same situation
| `""` | Healthy, or a failed check that kept the last good limits (`limitsStale` says the rest) |
| `"Waiting for auth"` | The agent is in use but has no credential for its limits |
| `"Sign-in expired"` | The credential was refused, or a refresh token lapsed; signing in again is needed |
| `"Limits paused"` | An access token lapsed that the agent's own CLI renews the next time it runs; signing in again is not needed |
| `"Limits paused"` | An access token lapsed that the agent's own CLI renews the next time it runs (or didn't renew when the collector ran it); signing in again is not needed |
| `"<Name> limits unavailable"` | A check failed with nothing kept to show |
| `"<Name> unavailable"` | The agent's stats source failed (an unreadable database, a billing API that answered nothing) with nothing kept to show |
| `"Balance unavailable"` | A prepaid balance couldn't be read and none was kept |
Expand Down
2 changes: 1 addition & 1 deletion shell/plugins/agents/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,7 @@ When `~/.local/state/omarchy/agents/accounts/<claude|codex|grok>.json` registers

### Claude Code

Limits come from Anthropic's OAuth usage endpoint, asked with the access token the Claude Code CLI keeps in `.credentials.json` under `CLAUDE_CONFIG_DIR` (default `~/.claude`); the plan comes from the CLI's profile, else the credentials. Only the CLI refreshes that token, so one left to lapse reads "Limits paused" and keeps the last numbers until Claude Code runs again; a lapsed refresh token reads "Sign-in expired". Without credentials the panel says so and falls back to local stats only.
Limits come from Anthropic's OAuth usage endpoint, asked with the access token the Claude Code CLI keeps in `.credentials.json` under `CLAUDE_CONFIG_DIR` (default `~/.claude`); the plan comes from the CLI's profile, else the credentials. Only the CLI refreshes that token, and only when it runs, so a machine where Claude Code runs only in the Claude desktop app, which keeps a sign-in of its own, would find it lapsed for good. While the refresh token still holds, the collector therefore runs `claude auth status` in that account's home, which refreshes the token without asking the model anything: at most every half hour for each sign-in unless refresh is pressed, only with an installed Claude Code 2.1.301 or later (an older one could sign the home out by exiting mid-refresh), and never through a mise launcher that would install or update it first. The CLI rewrites the credentials itself; the collector only reads them again. A token still lapsed after that reads "Limits paused" and keeps the last numbers until Claude Code runs again; a lapsed refresh token reads "Sign-in expired" and runs nothing. Without credentials the panel says so and falls back to local stats only.

Local stats come from the CLI's transcripts under `projects/`, falling back to `stats-cache.json` and `history.jsonl` (the cache's days are UTC dates that stop at yesterday, so its daily tokens are approximate and rarely cover today), plus pi and omp sessions (honouring `PI_CODING_AGENT_DIR` and `PI_CODING_AGENT_SESSION_DIR`) and opencode sessions on the `anthropic` provider.

Expand Down
Loading