Skip to content

Agent Usage Collectors

Every agent or provider in the agents panel is a collector: bin/omarchy-agent-usage-<id>, a Python script that prints one JSON record. omarchy-agent-usage-update finds collectors by globbing bin/omarchy-agent-usage-*, runs them, and the panel (shell/plugins/agents/Main.qml, Panel.qml) reads the records. This is the contract every collector follows, so that each agent behaves the same in the panel. bin/omarchy-agent-usage-claude is the reference implementation.

New collectors build on the shared module, shell/plugins/agents/collectors.py, which holds the parts of this contract every collector shares. A collector keeps only what is its own: its credentials, its endpoint and how to read it, its provider filter, and the specifics of its record.

The command

  • #!/usr/bin/python3, two-space indentation, and the header lines # omarchy:summary=..., # omarchy:args=[--force] [--limits-only], and # omarchy:hidden=true.
  • argparse accepts --force and --limits-only, and both mean something:
  • A normal run reuses a local scan for SCAN_REUSE_SECONDS = 20 and a limits probe for PROBE_MIN_INTERVAL_SECONDS = 15.
  • --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.

The shared module

The module ships with the agents panel in the omarchy package. A collector loads it from $OMARCHY_PATH, never from a path derived from its own file or $HOME:

sys.dont_write_bytecode = True
sys.path.insert(0, os.path.join(os.environ["OMARCHY_PATH"], "shell", "plugins", "agents"))
from collectors import Stats, base_record, cached_scan, ...

Its main entry points, each documented where it is defined:

  • base_record(id, name, **fields) and emit(record): the record with every field and the zeroed stats block, as an unused machine prints it, and printing it.
  • Stats(today=None): add(day, session, model, input, output, cache_read, cache_write, prompts=1) tokens and the prompts they answered (or add_row() one row from a reader), add_prompts(day, session, count=1) prompts a store books apart from their tokens, and snapshot() the record's stats fields. A store that books prompts on their own passes prompts=0 with the tokens; one keeping running totals passes how many prompts they cover. A day of None counts toward the lifetime totals alone, a session of None toward no session, and zero tokens make no model bucket. today dates the record against another day (a date or an ISO day).
  • cached_scan(id, sources, max_age, scan, match=None, with_complete=False) with scan_max_age(force, limits_only): the per-day scan cache under flock, reused for 20, 900, or 0 seconds, never caching an incomplete scan. with_complete=True answers (stats, complete), a cached scan being a complete one.
  • scan_pi_sessions(pattern, accept, roots=None) and scan_opencode(providers, accept): the pi/omp and opencode readers, handing back deduplicated UsageRows for the replies the collector's accept(provider, model, entry) takes. roots reads other pi-format trees instead of pi_session_roots() (a harness's own, or pi's and omp's with another beside them), through canonical_roots(); a collector that passes them keys its scan cache by the same roots.
  • scan_claude_code(owner, projects=None, index_file=..., base_url=None) (or claude_code_usage(), which also says whether every transcript was read, so a scan that missed one isn't cached) with claude_code_owner(model, base_url) and claude_code_scan_match(): Claude Code's transcripts, read through the per-file index every reader shares (one reader at a time brings it up to date under its .lock, and a reader finding it current for every transcript reads it without the lock), handing back the rows (replies, what a lineage's cost-state totals hold beyond its replies, typed prompts, sessions in use) of the one collector claude_code_owner names for each reply. A collector that reads them adds claude_code_dir() / "projects" to its scan sources and claude_code_scan_match() to its match, since where Claude Code is sent decides whose its replies are.
  • codex_provider_urls(): every Codex model_providers id's base_url, from /etc/codex/config.toml, config.toml and the profiles, remembered per Codex home in local-codex-providers.json after the config drops one, and the built-in openai provider's openai_base_url under openai, from /etc/codex/config.toml and config.toml only, never remembered (a profile applies only with --profile, so its openai_base_url is kept under openai@<model> for the model it sets, unless that is an OpenAI model, the one config.toml sets, or one two profiles send to different places); codex_route_owner(provider, model, urls) says which collector bills a rollout, and codex_native_endpoint(urls, model) where the built-in provider sent a turn on model.
  • codex_rollouts(cache_file, reuse=True, native=False) with codex_rollout_cache(): the Codex rollouts of the last 30 days off the built-in provider, and on it (or naming no provider) too with native, as the Codex collector reads them and every collector while openai_base_url sends it elsewhere, each with its provider, the session it counts under (codex_rollout_session: a subagent's, guardian's or review's thread its parent's, a memory consolidation none) and per-day, per-model tokens (one token_usage_record per response where Codex 0.163 writes them, else each token_count's last request; interactive Codex's thread-title requests are written to no rollout and are missing) and typed prompts, replayed from a per-file cache while a file's size and mtime stand, and read on from where the last read stopped when the same file only grew. The records hold every provider's turns, so every collector reading Codex shares one cache per Codex home (any cache_file stands for it, None reads uncached), brought up to date by one reader at a time under its .lock; a forced read (reuse=False) takes what another forced read of the same refresh wrote (omarchy-agent-usage-update exports when the refresh began as OMARCHY_AGENT_USAGE_REFRESH_AT; a lone --force begins its own), so the collectors one refresh forces read each rollout once between them, whenever each gets to them.
  • scan_routed(owner, reuse=True) with routed_sources() and routed_match(): Claude Code's, MiniMax Code's and Codex's usage one collector bills (scan_claude_code, scan_mcode and scan_codex_routed), since all three send to whatever endpoint they are given; the local collector reads Codex with its own classifier instead; every collector a base URL can name (PROVIDER_HOSTS, and local) reads them, adding the sources and match to its scan cache.
  • scan_dsh_sessions(accept) and kimchi_sessions_root(): DeepSeek Harness's billed attempts on the routes accept(provider, model, request) takes, a fork's inherited history left out, each carrying as its prompts the typed messages (a user message whose source is user) it answered, so a turn's tool steps and retries, and a turn dsh starts on its own, answer none; and where Kimchi keeps its pi-format sessions.
  • endpoint_owner(url), self_hosted(url) and cloud_model(model): which collector bills a base URL (a provider host in PROVIDER_HOSTS, local for the user's own hardware, or nobody), and whether a model carries Ollama's cloud tag.
  • LimitsCache(id, *identity, kind="limits"): one credential's last good answer at <id>-<kind>-<key>.json, with elapsed windows zeroed, fresh(force, seconds=15, allow_empty=False) for the probe reuse, kept() for the stale fallback, and save(limits, only_if_newer=False, **extra). kind keeps another answer beside the limits under the same key (credits, a balance, usage rows); allow_empty=True lets any answer stamped inside the age guard stand in, limits or none; only_if_newer=True leaves a file another run stamped later alone. LimitsCache.at(path) opens one under a name that predates the shared one.
  • open_json(request) and HttpError: a request that refuses redirects and says whether a failure was a refusal (status, with its headers), a transport failure (transport, the only cause for retryAdvised), a reply cut short (cut_short), or an invalid answer. See Limits for where the line falls.
  • 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.
  • 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.

The record

Field Meaning
schemaVersion 1
id, name The id matches the filename; name is the product name
updatedAt ISO time the record was made
ready true once the agent is in use on this machine (a credential or local usage)
tierLabel The plan as the service names it, or ""; never a placeholder or a guess. "Prepaid" is special to the panel
usageStatusText, authHelpText See Status
limits [{label, percent, resetsAt, title?}], percent in 0..1, resetsAt ISO or "", never null. Add title (Session, Weekly, Monthly) when the label doesn't parse as one
limitsStale, limitsFetchedAt Whether limits were kept past a failed check, and when they were measured (epoch ms, 0 when never)
retryAdvised true only when the service couldn't be reached at all (DNS, connection, timeout), so the panel retries this agent in 30 seconds
balance {remaining, funded, spent, currency, estimated} for prepaid accounts
accounts, accountSwitch Only when two or more accounts are registered; each account carries limits, stale, fetchedAt, usageStatusText, authHelpText
hasLocalStats Whether the stats below come from this machine
hasPromptStats false when the source has no real prompt or session counts (an API that counts requests, not prompts)
scope "account" when the stats are account-wide rather than this machine's
Stats todayPrompts, todaySessions, todayTotalTokens, todayTokensByModel, recentDays (seven {date, messageCount}, where messageCount holds tokens), totalPrompts, totalSessions, activeDays, activeDates (every date), and modelUsage buckets of inputTokens, outputTokens, cacheReadInputTokens, cacheCreationInputTokens

The full stats block is always present, zeroed when there is nothing. An agent the machine doesn't use prints ready: false with empty stats, no limits and no balance, and the panel skips it. That's the normal answer for a missing credential on an agent with no local usage; it isn't an error.

Status

The panel acts on a small vocabulary in usageStatusText, so the same situation reads the same for every agent:

Status When
"" 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
"<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
"Out of credits" A prepaid account has no credit left, or its gateway rate limits it for that reason; urgent, since a balance with no funded figure raises no low-balance alarm of its own

The detail goes in authHelpText: what failed and the one thing to do about it. It is "" when healthy. A plan the service doesn't offer limits for (pay-as-you-go, no Go plan, a free tier) isn't trouble: the status stays "" and local stats show alone. Any other status shows under the name in the urgent color, so collectors don't invent new ones.

Limits

  • Each credential or account caches its own last good answer at cache_root() / "<id>-limits-<key>.json", {fetchedAtMs, limits, ...}, where cache_root() is $XDG_CACHE_HOME/omarchy/agent-usage and <key> is a short hash of who the credential signs in as (a JWT subject, an email, an account id) or of the credential itself. Another sign-in never shows this one's numbers. An answer of another kind from the same credential (credits, a balance) sits beside it as <id>-<kind>-<key>.json.
  • An answer stands in for a probe for 15 seconds, even one with no windows (a plan without quotas, credits, a balance), so long as the collector keeps it. Refreshes can overlap, so an answer that only replaces one fetched before it never rolls a newer one back.
  • Where a failed check falls decides retryAdvised:
  • A connection that fails or drops before any reply (no DNS, no route, refused, reset, a timeout, a server hanging up without a word) is transport: nothing answered, so retryAdvised: true asks the panel to try again soon.
  • A reply that arrived but was cut short or garbled on the way (http.client.HTTPException: an incomplete read, a bad status line) is an answer, cut_short and not transport, so there is no sooner retry. Neither is there for an error status or a body that isn't the expected JSON.
  • The cache is read whatever its file time, so a clock that went back doesn't lose it, and every age check is 0 <= age < N. Stamps are floored (int(time.time() * 1000)), never rounded: a stamp half a millisecond ahead reads as a clock that went back, and the next run probes again.
  • A failed check keeps the cached limits with limitsStale: true and their limitsFetchedAt. The panel shows their age on hover. The one exception is a service that rate-limits its own usage endpoint (Claude's answers 429 readily): a 429 only says "ask later", so numbers measured within the last 15 minutes still read as current.
  • A kept window whose resetsAt has passed comes back at percent: 0 with resetsAt: "", never dropped: a reset allowance is untouched, not unknown. A window with no reset time is kept as it is. Reset times are only ever the service's own, never computed.
  • A meter for a balance or allowance is a real ratio of the service's numbers, never estimated from local usage unless its label says (est.).

Local stats

The local collector counts usage on self-hosted models; Local models covers running the managed model server.

  • Tokens are counted once, under the provider that bills them. pi, omp, and opencode sessions are split by provider into the matching collector; there is no harness tab that counts them again. Claude Code transcripts are split the same way, by claude_code_owner(), which every collector reading them applies. Claude Code records only the model that answered, not where it sent the request, so while ANTHROPIC_BASE_URL (its settings.json env, else the environment) names a provider's host in PROVIDER_HOSTS, every reply is that provider's, earlier ones included. Otherwise an Ollama cloud tag is ollama's and a Claude model claude's (through a proxy too), a self-hosted base URL makes any other model local's, and with no override the model's name decides: glm-* is zai's, MiniMax-* minimax's, deepseek-* deepseek's, kimi-* and moonshot* kimi's, hf:* and syn:* synthetic's. Any other model with no override (qwen3-coder), and any non-Claude model behind a host nothing can place (a gateway or proxy), counts nowhere. Codex rollouts are split by their model_provider, by codex_route_owner(): the built-in openai is codex's until openai_base_url (the config key only; Codex ignores OPENAI_BASE_URL) sends it elsewhere, read the way Claude Code's base URL is: a provider's host bills every built-in rollout, an Ollama cloud tag is ollama's, OpenAI's own models stay codex's through any other URL, a self-hosted one makes any other model local's, and a host nothing can place counts it nowhere; a model_providers entry whose base_url is a host in PROVIDER_HOSTS is that provider's whatever its id (an ollama entry at ollama.com included), --oss on the local daemon's ollama is local's unless the model is cloud-tagged, which is ollama's along with a provider named ollama-cloud, an entry on the user's own hardware is local's whatever its id (one another collector claims included), and one at a host nothing can place counts nowhere; codex_rollouts() reads them for all of them, codex included, and books each typed prompt with the model of the first request after it (else the model the rollout was last set to), so a rollout that switches models between turns splits its prompts the way it splits its tokens; the model in effect is the last one a turn_context or a thread_settings_applied (written by -m on a resume or /model, ahead of the compaction a switch can send on the new model) names. Other harnesses that route by provider are split the same way: DeepSeek Harness's DeepSeek routes are deepseek's and its pi-ai openrouter route openrouter's (scan_dsh_sessions), Kimchi's gateway routes (kimchi, kimchi-dev, kimchi-dev/<upstream>, kimchi-experimental) are kimchi's in its harness sessions (pi format, under kimchi_sessions_root()) and in pi's, omp's and opencode's alike, and a harness session on --provider openrouter is openrouter's; its gateway's hosts (kimchi.dev, every region) are in PROVIDER_HOSTS, so the Claude Code and Codex setups kimchi claudecode and kimchi codex write are kimchi's whatever the model, while kimchi claude sets ANTHROPIC_BASE_URL only in the environment of the Claude Code it starts, which leaves its transcripts read like any with no override, and a self-hosted Kimchi gateway's own host is placed by nothing, and a MiniMax Code reply is minimax's on its own routes and on a custom_provider:<name> whatever collector bills that provider's config.yaml baseURL (mcode_route_owner, which gives a cloud-tagged model on a self-hosted route to ollama, and each answered prompt the model of its reply), nobody's for a host nothing can place. Kimi Code, Qwen Code, Hermes and Mistral Vibe keep stores of their own, and each one's collector exposes harness_rows(owner), which reads its store and keeps the rows owner bills, a base URL read by claude_code_owner(): Kimi Code's model alias resolves through its config.toml to the provider's base URL (Kimi's endpoint is kimi's, as is an alias the config no longer names when it is one of the plan's kimi-code/ models or KIMI_MODEL_NAME's; a removed provider's alias counts nowhere), a Qwen Code reply's auth type and its model's modelProviders baseUrl in settings.json, else the OPENAI_BASE_URL or ANTHROPIC_BASE_URL its auth type takes from the environment, the first of QWEN_HOME/.env, ~/.qwen/.env and ~/.env that sets it, settings.json's env, or the security.auth.baseUrl /auth saved (Alibaba's hosts and Qwen OAuth are qwen's; an OpenAI-compatible reply with no URL went to OpenAI's API, Qwen Code's default, and like Anthropic, Gemini and Vertex AI is nobody's), a Hermes session's and request's billing base URL (Nous Portal is hermes's, as is a row from before Hermes kept the route), and a Vibe session's provider api_base (Mistral's API is vibe's). Only Hermes and Vibe's older session_* folders record the route with each request; Kimi Code's aliases, Qwen Code's base URLs and the providers of Vibe's Unified Harness sessions resolve through the current config, so a route change moves earlier usage too, history included. Each prompt goes with the request that answered it; in Kimi Code and Qwen Code with the next request sent for it, answered or not, else with the alias its agent was bound to or the model settings.json selects. The harness's own collector counts its rows and local the self-hosted ones; rows another provider bills count nowhere, since no other collector reads these stores yet. A route nothing names stays uncounted rather than guessed.
  • pi and omp sessions live under ~/.pi/agent/sessions and ~/.omp/agent/sessions, plus profiles/<name>/agent/sessions under each. PI_CODING_AGENT_DIR's sessions, PI_CODING_AGENT_SESSION_DIR, and an absolute sessionDir in any of those agent trees' settings.json are read as well as those defaults, never instead of them (a relative sessionDir, a project's .pi/settings.json, and --session-dir can't be found and aren't read); roots are compared by realpath, and one nested inside another is dropped. They are found with rg --no-ignore, since a $HOME that is a git checkout would otherwise hide them. pi's reasoning and omp's reasoningTokens are the part of output that was thinking, so they are never added to it again (opencode's tokens.reasoning is kept apart from its output, and is added). Besides replies, the usage pi counts in a session's totals counts too: a compaction's or branch summary's usage, a usage entry (cache warming), and a tool result's nested usage, under the provider the entry names or else the model the session was on (the last model switch or reply before it in the file), answering no prompt; with neither, nothing says who billed it and it is skipped. omp writes no usage on its compaction entries (18.12 keeps only tokensBefore and tokensAfter), nor anywhere else in the session or its agent.db, so omp's compactions can't be counted and are missing from its tokens, as those of a Claude Code session with no cost-state line are (every session before 2.1.278, and many since). A reply is deduplicated by its provider, responseId and timestamp when it has a response id, since omp writes a reply that overflowed the model's declared context window twice under new ids, and any other message is deduplicated by (id, timestamp) when it has both, so a forked session doesn't count its parent's messages again, and a line without an id always counts. A typed prompt counts once by its own (id, timestamp) as well, under one collector whichever reply books it: the first reply that answered it in any copy (the oldest session's first), else the oldest session's booking of it unanswered, so one a session left unanswered and a fork copying it answered counts once, on the fork's provider even when that is another collector's. The copies are found by parentSession: the other files in the fork tree of each file a collector parses that hold the id of a prompt it booked are read for their bookings alone, and a parentSession naming a file that is gone (pi deletes a session from /resume and leaves its forks) is no parent, so the fork's copies count under it and the scan stays complete. A row with no time is today's; a row whose time is untrusted, zero included, counts nowhere. Each collector parses only the session files holding its own lines (one its pattern matches, or a model switch its accept takes, which says whose a summary's usage or an unanswered prompt there is), so another provider's history costs it no more than rg's search.
  • opencode is read from both its message store and V2's session_message, V2 first, deduplicated by message id, leaving out the copies a fork makes (in V2, a session_v2.fork_session_id session's messages older than it; in the original store, a message whose time.created predates its session row, since a fork there is a plain new session holding its source's messages under new ids and their original times), with compactions counted like replies. The database is OPENCODE_DB when set (or the older opencode-v2.db), opened read-only. scan_opencode in the shared module is the reference reader, and test/shell.d/agent-usage-partition-test.sh holds every collector to it.
  • A prompt is a typed user message, never a model request, so a tool step, a compaction or summary, and a subagent's session answer none. UsageRow.prompts says which rows book one: in pi and omp the first reply that spent tokens after a user message (omp's own attribution: "agent" messages aside; a file with no user messages at all keeps one per reply), in opencode's message store the first step answering a user message (they share its parentID) whose tokens and time the reader trusts, and in V2's session_message the first reply after a user row (a session without any keeps one per reply). In both stores that first step is chosen across every provider, so a prompt a tool loop answers on two providers counts once, under the collector that took the first step. A prompt no reply answered (its request failed, or none came) still counts once, as a row without tokens on the model the session was set to use for it, so the collector billing that model counts it and its session: in pi and omp the failed reply, which they write with its provider and no usage, before the next user message, else the last model switch or reply before the prompt, so a prompt whose agent was killed mid-request never rides on the next provider's reply (and a fork copying it books it once), while one omp refused before sending it (an error with its errorId and no duration, such as an invalid credential) counts nowhere; in opencode's message store the model its user row names, once a step answering it shows the request was made (a failed or cut-off step without tokens; a user row with no step at all was refused before sending, an unknown model or provider, and counts nowhere; a compaction's marker is answered by its summary, failed or not); and in V2's session_message the reply after the user row, spent or not. With no model known it counts nowhere, and like every prompt it is dated by when it was typed, an untrusted time counting nowhere.
  • Timestamps and token fields from disk are untrusted: a zero, huge, negative, NaN, boolean or non-numeric value skips that field or row, never the record.
  • A scan is cached per day (scanDate) and rebuilt under flock, and a scan that couldn't read all its sources isn't cached.

Assets, docs and tests

  • shell/plugins/agents/assets/<id>.svg, plus <id>-light.svg when the mark is white and needs a dark twin for light surfaces.
  • A provider entry in shell/plugins/agents/manifest.json, a row in the README's collector table, and a ### section in the README naming where its credentials and data come from.
  • test/shell.d/agent-usage-<id>-test.sh (or several, agent-usage-<id>-<part>-test.sh) covering the collector's own sources, credentials and answer, and an adapter for the contract checks. The record an unused machine prints is held for every collector by agent-usage-partition-test.sh, and the shared reading mechanics (pi, omp and opencode stores, untrusted values, cache files and locks, HTTP failure classes) by agent-usage-shared-test.sh, so a collector's test doesn't repeat them. Its adapter hands check_limits_contract fresh limits, the probe reuse and --force, stale limits after a failed check, retryAdvised on an unreachable service, an elapsed kept window at zero, and a refused credential, and check_scan_cache the scan reuse windows; testing.md describes the helpers and agent-usage-grok-test.sh is the worked example.