From 36beb6a5d03d587c03a4743f0b17c1b0fa3d19bd Mon Sep 17 00:00:00 2001 From: Ivan Schneider Date: Sun, 25 Oct 2026 10:40:03 +0000 Subject: [PATCH 1/4] Share the installed-CLI lookup that never runs a mise launcher Co-Authored-By: Claude Opus 5.5 --- bin/omarchy-agent-usage-codex | 51 ++---------------------------- docs/agent-usage-collectors.md | 1 + shell/plugins/agents/collectors.py | 49 ++++++++++++++++++++++++++++ 3 files changed, 53 insertions(+), 48 deletions(-) diff --git a/bin/omarchy-agent-usage-codex b/bin/omarchy-agent-usage-codex index a5c593cd7212..b398f726b40e 100755 --- a/bin/omarchy-agent-usage-codex +++ b/bin/omarchy-agent-usage-codex @@ -40,6 +40,7 @@ from collectors import ( # noqa: E402 codex_scan_match, emit, find_command, + find_installed_command, jwt_claims, now_ms, number, @@ -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")) @@ -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" @@ -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 diff --git a/docs/agent-usage-collectors.md b/docs/agent-usage-collectors.md index 3f14573515a1..c08053c8a08a 100644 --- a/docs/agent-usage-collectors.md +++ b/docs/agent-usage-collectors.md @@ -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. diff --git a/shell/plugins/agents/collectors.py b/shell/plugins/agents/collectors.py index 509a2c528975..cf41e727357b 100644 --- a/shell/plugins/agents/collectors.py +++ b/shell/plugins/agents/collectors.py @@ -109,6 +109,55 @@ def find_command(name: str) -> str | None: return shutil.which(name, path=runtime_env().get("PATH")) +def mise_shims_dir() -> str: + data_home = os.environ.get("MISE_DATA_DIR") or os.path.join( + os.environ.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: str) -> bool: + # 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, as is each account + # wrapper in mise's command-wrappers/bin, 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_installed_command(name: str) -> str | None: + """An agent CLI already installed, never a launcher that would install or + update it first: the first on PATH that isn't one, else what mise names.""" + env = runtime_env() + for directory in env.get("PATH", "").split(os.pathsep): + candidate = os.path.join(directory, name) + 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 tool managed by mise without running the launcher. + # `mise which` can resolve a configured `latest` over the network; a usage + # probe stays offline. + mise = find_command("mise") + if mise: + try: + out = subprocess.run([mise, "which", name], 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 + + # --------------------------------------------------------- untrusted values From 4f4067d3c7c7ace25542101ee97abf599668ea0c Mon Sep 17 00:00:00 2001 From: Ivan Schneider Date: Sun, 25 Oct 2026 10:51:55 +0000 Subject: [PATCH 2/4] Keep the mise launcher checks private to the shared module Co-Authored-By: Claude Opus 5.5 --- shell/plugins/agents/collectors.py | 14 ++++++-------- 1 file changed, 6 insertions(+), 8 deletions(-) diff --git a/shell/plugins/agents/collectors.py b/shell/plugins/agents/collectors.py index cf41e727357b..62fa55863b4d 100644 --- a/shell/plugins/agents/collectors.py +++ b/shell/plugins/agents/collectors.py @@ -109,19 +109,17 @@ def find_command(name: str) -> str | None: return shutil.which(name, path=runtime_env().get("PATH")) -def mise_shims_dir() -> str: - data_home = os.environ.get("MISE_DATA_DIR") or os.path.join( - os.environ.get("XDG_DATA_HOME") or os.path.join(str(Path.home()), ".local", "share"), "mise") - return os.path.join(data_home, "shims") +def _mise_shims_dir() -> str: + return os.path.join(os.environ.get("MISE_DATA_DIR") or str(data_home() / "mise"), "shims") -def is_lazy_launcher(path: str) -> bool: +def _is_lazy_launcher(path: str) -> bool: # 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, as is each account # wrapper in mise's command-wrappers/bin, 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(): + if os.path.dirname(os.path.abspath(path)) == _mise_shims_dir(): return True if os.path.islink(path): mise = find_command("mise") @@ -140,7 +138,7 @@ def find_installed_command(name: str) -> str | None: env = runtime_env() for directory in env.get("PATH", "").split(os.pathsep): candidate = os.path.join(directory, name) - if os.path.isfile(candidate) and os.access(candidate, os.X_OK) and not is_lazy_launcher(candidate): + 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 tool managed by mise without running the launcher. @@ -151,7 +149,7 @@ def find_installed_command(name: str) -> str | None: try: out = subprocess.run([mise, "which", name], 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): + if out.returncode == 0 and os.path.isfile(resolved) and not _is_lazy_launcher(resolved): return resolved except Exception: pass From b7f015b83fb7cc60ada2aa6b2ef44f8832ef8042 Mon Sep 17 00:00:00 2001 From: Ivan Schneider Date: Sun, 25 Oct 2026 10:54:29 +0000 Subject: [PATCH 3/4] Refresh a lapsed Claude Code access token by running its CLI Co-Authored-By: Claude Opus 5.5 --- bin/omarchy-agent-usage-claude | 116 +++++++++++++++--- docs/agent-usage-collectors.md | 4 +- shell/plugins/agents/README.md | 2 +- .../shell.d/agent-usage-claude-limits-test.sh | 108 ++++++++++++++-- 4 files changed, 203 insertions(+), 27 deletions(-) diff --git a/bin/omarchy-agent-usage-claude b/bin/omarchy-agent-usage-claude index 0b81f76c9bab..f3c580cbff03 100755 --- a/bin/omarchy-agent-usage-claude +++ b/bin/omarchy-agent-usage-claude @@ -19,6 +19,7 @@ import datetime as dt import json import os import re +import subprocess import sys import time import urllib.request @@ -35,6 +36,7 @@ from collectors import ( # noqa: E402 LimitsCache, Stats, account_entry, + age_below, base_record, cache_root, cached_scan, @@ -45,6 +47,8 @@ from collectors import ( # noqa: E402 claude_code_scan_match, emit, empty_bucket, + find_installed_command, + now_ms, number, obj, open_json, @@ -54,10 +58,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" @@ -68,6 +76,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: @@ -409,12 +427,72 @@ 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. Whether it ran: the caller reads the credentials again to see. +def refresh_sign_in(home: Path, cache_name: str, force: bool) -> bool: + attempt = limits_cache_path(AGENT_ID, cache_name, kind="refresh") + if not force and age_below(stamp(read_json(attempt).get("attemptedAtMs")) / 1000, REFRESH_RETRY_SECONDS): + return False + 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 False + claude = find_installed_command("claude") + if not claude: + return False + 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 False + 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 False + 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__})") + return True + + +# 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 @@ -592,12 +670,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 @@ -611,20 +690,24 @@ 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 and 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"] = ( @@ -687,7 +770,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 @@ -701,8 +783,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 @@ -729,13 +811,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 diff --git a/docs/agent-usage-collectors.md b/docs/agent-usage-collectors.md index c08053c8a08a..30890daec09b 100644 --- a/docs/agent-usage-collectors.md +++ b/docs/agent-usage-collectors.md @@ -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 @@ -77,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 | | `" limits unavailable"` | A check failed with nothing kept to show | | `" 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 | diff --git a/shell/plugins/agents/README.md b/shell/plugins/agents/README.md index 4794316f7c6f..c205f9a2545a 100644 --- a/shell/plugins/agents/README.md +++ b/shell/plugins/agents/README.md @@ -101,7 +101,7 @@ When `~/.local/state/omarchy/agents/accounts/.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. diff --git a/test/shell.d/agent-usage-claude-limits-test.sh b/test/shell.d/agent-usage-claude-limits-test.sh index 79ff59ebc774..bfe6895f6cf6 100644 --- a/test/shell.d/agent-usage-claude-limits-test.sh +++ b/test/shell.d/agent-usage-claude-limits-test.sh @@ -14,6 +14,8 @@ source "$SHELL_TEST_DIR/agent-usage-helpers.sh" agent_sandbox python3 - <<'PY' +from unittest.mock import patch + from agent_usage_fixtures import * USAGE = "api.anthropic.com/api/oauth/usage" @@ -22,8 +24,8 @@ ROUTES = {USAGE: {"five_hour": {"utilization": 40.0, "resets_at": iso_in(3600)}, # The sign-in the Claude Code CLI leaves: an access token living about eight # hours, and the refresh token behind it about thirty days. -def signed_in(token="token", expires=None, refresh_expires=0): - write_json(home() / ".claude" / ".credentials.json", {"claudeAiOauth": { +def signed_in(token="token", expires=None, refresh_expires=0, where=None): + write_json((where or home() / ".claude") / ".credentials.json", {"claudeAiOauth": { "accessToken": token, "expiresAt": ms_in(3600) if expires is None else expires, "refreshTokenExpiresAt": refresh_expires, "subscriptionType": "max", "rateLimitTier": "default_claude_max_5x", }}) @@ -44,6 +46,51 @@ def kept_limits(fetched_ago, limits): write_json(cache_root() / "claude-limits.json", {"fetchedAtMs": ms_in(-fetched_ago), "limits": limits}) +# Only the interpreter and file tools, so no claude or mise on this machine +# can answer for the stand-in CLI. +CLI_BIN = Path(os.environ["SANDBOX"]) / "claude-cli" +os.environ["PATH"] = f"{CLI_BIN}:{Path(os.environ['SANDBOX']) / 'tools'}" + + +# A stand-in Claude Code CLI that logs every run to ~/claude-calls, names its +# version, and on `auth status` renews the access token of the home +# CLAUDE_CONFIG_DIR names (else ~/.claude) when RENEWS. +FAKE_CLAUDE = r''' +import json, os, sys, time +from pathlib import Path +with open(Path.home() / "claude-calls", "a") as log: + log.write(json.dumps({"args": sys.argv[1:], "env": dict(os.environ)}) + "\n") +if sys.argv[1:] == ["--version"]: + print(VERSION + " (Claude Code)") +elif sys.argv[1:] == ["auth", "status"] and RENEWS: + path = Path(os.environ.get("CLAUDE_CONFIG_DIR") or Path.home() / ".claude") / ".credentials.json" + credentials = json.loads(path.read_text()) + credentials["claudeAiOauth"].update(accessToken="renewed", expiresAt=int(time.time() * 1000) + 8 * 3600 * 1000) + path.write_text(json.dumps(credentials)) +''' + + +def fake_claude(renews=False, version="2.1.310"): + CLI_BIN.mkdir(exist_ok=True) + (CLI_BIN / "claude").write_text(f"#!/usr/bin/python3\nVERSION, RENEWS = {version!r}, {renews!r}\n{FAKE_CLAUDE}") + (CLI_BIN / "claude").chmod(0o755) + + +# The CLI runs logged since the last call, and the log emptied. +def cli_calls(): + log = home() / "claude-calls" + calls = [json.loads(line) for line in log.read_text().splitlines()] if log.exists() else [] + log.unlink(missing_ok=True) + return calls + + +def cli_args(): + return [call["args"] for call in cli_calls()] + + +REFRESH = [["--version"], ["auth", "status"]] + + # ------------------------------------------------------------ the answer sandbox() @@ -170,15 +217,18 @@ WINDOWS = [ {"label": "Session (5-hour)", "percent": 0.31, "resetsAt": iso_in(-3 * 3600)}, {"label": "Weekly (7-day)", "percent": 0.11, "resetsAt": iso_in(3 * 3600)}, ] +fake_claude() # Both tokens lapsed is a genuine sign-out. It used to return an empty limits # list and no status at all, which hides the panel's whole limits section -# without saying why. Nothing is asked of Anthropic. +# without saying why. Nothing is asked of Anthropic, nor of the CLI, which +# has nothing left to refresh with. signed_in(expires=1000, refresh_expires=1000) kept_limits(3600, WINDOWS) record, http = claude() check("Claude collector reports an expired sign-in instead of hiding the section, asking nothing", - record["usageStatusText"] == "Sign-in expired" and "claude auth login" in record["authHelpText"] and http.count == 0, record) + record["usageStatusText"] == "Sign-in expired" and "claude auth login" in record["authHelpText"] + and http.count == 0 and cli_args() == [], record) expect("Claude collector keeps cached windows and resets just the elapsed one", [(entry["label"], entry["percent"], entry["resetsAt"]) for entry in record["limits"]], [("Session (5-hour)", 0.0, ""), ("Weekly (7-day)", 0.11, WINDOWS[1]["resetsAt"])], record) @@ -191,13 +241,57 @@ check("Claude collector resets a wholly elapsed cache to zero, with its guidance and "last known" in record["authHelpText"], record) # A machine left overnight finds the access token lapsed and the refresh -# token fine: routine, and nothing a person fixes by signing in again. +# token fine: routine, and nothing a person fixes by signing in again. The +# CLI is run to refresh it, and one that renews nothing leaves it paused. signed_in(expires=1000, refresh_expires=ms_in(30 * 86400)) kept_limits(3600, WINDOWS) record, http = claude() -check("Claude collector calls a lapsed access token paused, not signed out", +check("Claude collector calls a lapsed access token the CLI didn't renew paused, not signed out", record["usageStatusText"] == "Limits paused" and "claude auth login" not in record["authHelpText"] - and labels(record) == ["Session (5-hour)", "Weekly (7-day)"] and http.count == 0, record) + and labels(record) == ["Session (5-hour)", "Weekly (7-day)"] and http.count == 0 and cli_args() == REFRESH, record) + +# The CLI is asked again for the same sign-in once the half hour is up, not on +# every panel refresh, unless refresh is pressed. +claude("--limits-only") +expect("Claude collector runs the CLI once per half hour", cli_args(), []) +claude("--force") +expect("Claude collector runs the CLI again when refresh is pressed", cli_args(), REFRESH) +write_json(next(cache_root().glob("claude-refresh-*.json")), {"attemptedAtMs": ms_in(-1801)}) +claude("--limits-only") +expect("Claude collector runs the CLI again half an hour on", cli_args(), REFRESH) + +# Before 2.1.301 `claude auth status` could exit mid-refresh and sign the +# home out, so an older CLI is only asked its version. +fake_claude(renews=True, version="2.1.300") +with contextlib.redirect_stderr(io.StringIO()): + record, _ = claude() +expect("Claude collector never refreshes with a CLI older than 2.1.301", + [record["usageStatusText"], cli_args()], ["Limits paused", [["--version"]]], record) + +# A CLI that renews the token unpauses the limits, probed with the new token. +# It runs without the variables that would hand it a Claude Code session's +# sign-in or another credential, and with no CLAUDE_CONFIG_DIR for +# ~/.claude, whose profile is ~/.claude.json rather than one inside it. +fake_claude(renews=True) +SESSION_VARS = {"CLAUDECODE": "1", "CLAUDE_CODE_ENTRYPOINT": "claude-desktop", "ANTHROPIC_BASE_URL": DEAD_PROXY} +with patch.dict(os.environ, SESSION_VARS): + record, http = claude() +expect("Claude collector probes with the token the CLI renewed", + [record["usageStatusText"], record["limitsStale"], [request["headers"]["authorization"] for request in http.requests]], + ["", False, ["Bearer renewed"]], record) +expect("Claude collector runs the CLI clear of a session's variables and the default home's config dir", + [[name for name in call["env"] if name in {*SESSION_VARS, "CLAUDE_CONFIG_DIR"}] for call in cli_calls()], [[], []]) + +# Another account's home is refreshed in place, the CLI pointed at it. +side = home() / "side" +signed_in(token="side-token", expires=1000, refresh_expires=ms_in(30 * 86400), where=side) +write_json(side / ".claude.json", {"oauthAccount": {"accountUuid": "acct-side"}}) +accounts = registry("claude", [{"id": "main", "primary": True}, {"id": "side", "home": str(side)}], active="main") +record, _ = claude() +expect("Claude collector refreshes another account's lapsed token in its own home", + [[entry["usageStatusText"] for entry in record["accounts"]], [call["env"].get("CLAUDE_CONFIG_DIR") for call in cli_calls()]], + [["", ""], [str(side.resolve())] * 2], record) +accounts.unlink() # A signed-out machine says so, and still shows what it last knew. (home() / ".claude" / ".credentials.json").unlink() From df59f2ec97d4c0e5b3a2b0b531256c11fb9ed5b3 Mon Sep 17 00:00:00 2001 From: Ivan Schneider Date: Sun, 25 Oct 2026 17:30:32 +0000 Subject: [PATCH 4/4] Run one Claude sign-in refresh at a time Co-Authored-By: Claude Opus 5.5 --- bin/omarchy-agent-usage-claude | 65 ++++++++++--------- .../shell.d/agent-usage-claude-limits-test.sh | 19 +++++- 2 files changed, 52 insertions(+), 32 deletions(-) diff --git a/bin/omarchy-agent-usage-claude b/bin/omarchy-agent-usage-claude index f3c580cbff03..5686ac17974b 100755 --- a/bin/omarchy-agent-usage-claude +++ b/bin/omarchy-agent-usage-claude @@ -47,6 +47,7 @@ from collectors import ( # noqa: E402 claude_code_scan_match, emit, empty_bucket, + exclusive_lock, find_installed_command, now_ms, number, @@ -446,35 +447,40 @@ def default_home(home: Path) -> bool: # 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. Whether it ran: the caller reads the credentials again to see. -def refresh_sign_in(home: Path, cache_name: str, force: bool) -> bool: +# 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") - if not force and age_below(stamp(read_json(attempt).get("attemptedAtMs")) / 1000, REFRESH_RETRY_SECONDS): - return False - 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 False - claude = find_installed_command("claude") - if not claude: - return False - 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 False - 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 False - 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__})") - return True + # 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 @@ -692,7 +698,8 @@ def collect_limits(home: Path, force: bool, cache_name: str = "claude-limits.jso # refreshes the credential file when it runs, so a machine left alone long # 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 and refresh_sign_in(home, cache_name, force): + 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 diff --git a/test/shell.d/agent-usage-claude-limits-test.sh b/test/shell.d/agent-usage-claude-limits-test.sh index bfe6895f6cf6..a0d5c00789da 100644 --- a/test/shell.d/agent-usage-claude-limits-test.sh +++ b/test/shell.d/agent-usage-claude-limits-test.sh @@ -14,6 +14,7 @@ source "$SHELL_TEST_DIR/agent-usage-helpers.sh" agent_sandbox python3 - <<'PY' +import subprocess from unittest.mock import patch from agent_usage_fixtures import * @@ -54,7 +55,7 @@ os.environ["PATH"] = f"{CLI_BIN}:{Path(os.environ['SANDBOX']) / 'tools'}" # A stand-in Claude Code CLI that logs every run to ~/claude-calls, names its # version, and on `auth status` renews the access token of the home -# CLAUDE_CONFIG_DIR names (else ~/.claude) when RENEWS. +# CLAUDE_CONFIG_DIR names (else ~/.claude) when RENEWS, DELAY seconds on. FAKE_CLAUDE = r''' import json, os, sys, time from pathlib import Path @@ -63,6 +64,7 @@ with open(Path.home() / "claude-calls", "a") as log: if sys.argv[1:] == ["--version"]: print(VERSION + " (Claude Code)") elif sys.argv[1:] == ["auth", "status"] and RENEWS: + time.sleep(DELAY) path = Path(os.environ.get("CLAUDE_CONFIG_DIR") or Path.home() / ".claude") / ".credentials.json" credentials = json.loads(path.read_text()) credentials["claudeAiOauth"].update(accessToken="renewed", expiresAt=int(time.time() * 1000) + 8 * 3600 * 1000) @@ -70,9 +72,9 @@ elif sys.argv[1:] == ["auth", "status"] and RENEWS: ''' -def fake_claude(renews=False, version="2.1.310"): +def fake_claude(renews=False, version="2.1.310", delay=0): CLI_BIN.mkdir(exist_ok=True) - (CLI_BIN / "claude").write_text(f"#!/usr/bin/python3\nVERSION, RENEWS = {version!r}, {renews!r}\n{FAKE_CLAUDE}") + (CLI_BIN / "claude").write_text(f"#!/usr/bin/python3\nVERSION, RENEWS, DELAY = {version!r}, {renews!r}, {delay!r}\n{FAKE_CLAUDE}") (CLI_BIN / "claude").chmod(0o755) @@ -282,6 +284,17 @@ expect("Claude collector probes with the token the CLI renewed", expect("Claude collector runs the CLI clear of a session's variables and the default home's config dir", [[name for name in call["env"] if name in {*SESSION_VARS, "CLAUDE_CONFIG_DIR"}] for call in cli_calls()], [[], []]) +# Two runs at once, the panel's own and one someone started, refresh once: +# the second waits for the first and finds the token renewed. +signed_in(expires=1000, refresh_expires=ms_in(30 * 86400)) +fake_claude(renews=True, delay=1.5) +runs = [subprocess.Popen([ROOT / "bin" / "omarchy-agent-usage-claude", "--force"], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) + for _ in range(2)] +for run in runs: + run.wait(timeout=60) +expect("Claude collector runs the CLI once for two runs at once", cli_args().count(["auth", "status"]), 1) +fake_claude(renews=True) + # Another account's home is refreshed in place, the CLI pointed at it. side = home() / "side" signed_in(token="side-token", expires=1000, refresh_expires=ms_in(30 * 86400), where=side)