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
--forceand--limits-only, and both mean something: - A normal run reuses a local scan for
SCAN_REUSE_SECONDS = 20and a limits probe forPROBE_MIN_INTERVAL_SECONDS = 15. --limits-only(the panel's near-limit refresh) reuses a local scan forLIMITS_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)andemit(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 (oradd_row()one row from a reader),add_prompts(day, session, count=1)prompts a store books apart from their tokens, andsnapshot()the record's stats fields. A store that books prompts on their own passesprompts=0with the tokens; one keeping running totals passes how many prompts they cover. AdayofNonecounts toward the lifetime totals alone, asessionofNonetoward no session, and zero tokens make no model bucket.todaydates the record against another day (adateor an ISO day).cached_scan(id, sources, max_age, scan, match=None, with_complete=False)withscan_max_age(force, limits_only): the per-day scan cache underflock, reused for 20, 900, or 0 seconds, never caching an incomplete scan.with_complete=Trueanswers(stats, complete), a cached scan being a complete one.scan_pi_sessions(pattern, accept, roots=None)andscan_opencode(providers, accept): the pi/omp and opencode readers, handing back deduplicatedUsageRows for the replies the collector'saccept(provider, model, entry)takes.rootsreads other pi-format trees instead ofpi_session_roots()(a harness's own, or pi's and omp's with another beside them), throughcanonical_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)(orclaude_code_usage(), which also says whether every transcript was read, so a scan that missed one isn't cached) withclaude_code_owner(model, base_url)andclaude_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'scost-statetotals hold beyond its replies, typed prompts, sessions in use) of the one collectorclaude_code_ownernames for each reply. A collector that reads them addsclaude_code_dir() / "projects"to its scan sources andclaude_code_scan_match()to itsmatch, since where Claude Code is sent decides whose its replies are.codex_provider_urls(): every Codexmodel_providersid'sbase_url, from/etc/codex/config.toml,config.tomland the profiles, remembered per Codex home inlocal-codex-providers.jsonafter the config drops one, and the built-inopenaiprovider'sopenai_base_urlunderopenai, from/etc/codex/config.tomlandconfig.tomlonly, never remembered (a profile applies only with--profile, so itsopenai_base_urlis kept underopenai@<model>for the model it sets, unless that is an OpenAI model, the oneconfig.tomlsets, or one two profiles send to different places);codex_route_owner(provider, model, urls)says which collector bills a rollout, andcodex_native_endpoint(urls, model)where the built-in provider sent a turn onmodel.codex_rollouts(cache_file, reuse=True, native=False)withcodex_rollout_cache(): the Codex rollouts of the last 30 days off the built-in provider, and on it (or naming no provider) too withnative, as the Codex collector reads them and every collector whileopenai_base_urlsends 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 (onetoken_usage_recordper response where Codex 0.163 writes them, else eachtoken_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 (anycache_filestands 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-updateexports when the refresh began asOMARCHY_AGENT_USAGE_REFRESH_AT; a lone--forcebegins its own), so the collectors one refresh forces read each rollout once between them, whenever each gets to them.scan_routed(owner, reuse=True)withrouted_sources()androuted_match(): Claude Code's, MiniMax Code's and Codex's usage one collector bills (scan_claude_code,scan_mcodeandscan_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, andlocal) reads them, adding the sources and match to its scan cache.scan_dsh_sessions(accept)andkimchi_sessions_root(): DeepSeek Harness's billed attempts on the routesaccept(provider, model, request)takes, a fork's inherited history left out, each carrying as its prompts the typed messages (a user message whose source isuser) 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)andcloud_model(model): which collector bills a base URL (a provider host inPROVIDER_HOSTS,localfor 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, andsave(limits, only_if_newer=False, **extra).kindkeeps another answer beside the limits under the same key (credits, a balance, usage rows);allow_empty=Truelets any answer stamped inside the age guard stand in, limits or none;only_if_newer=Trueleaves a file another run stamped later alone.LimitsCache.at(path)opens one under a name that predates the shared one.open_json(request)andHttpError: a request that refuses redirects and says whether a failure was a refusal (status, with itsheaders), a transport failure (transport, the only cause forretryAdvised), 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), withjwt_claims(),token_lapsed(),account_key()andfinite(): the Cursor account the Cursor and Grok Bot collectors both ask as (an exportedCURSOR_AUTH_TOKEN; withCURSOR_API_KEYexported, only the token the CLI traded that key for, never the key itself; else the CLI'sauth.jsonatCURSOR_AUTH_PATHor its default, then the editor'sstate.vscdb, a lapsed sign-in giving way to one that isn't), and reading any JWT's claims, expiry and subject.registered_accounts(id)andaccount_entry(account, limits, plan, **extra): the accountsomarchy agent accountregistered, and one entry of the record'saccounts.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, ...}, wherecache_root()is$XDG_CACHE_HOME/omarchy/agent-usageand<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: trueasks 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_shortand nottransport, 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: trueand theirlimitsFetchedAt. 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
resetsAthas passed comes back atpercent: 0withresetsAt: "", 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 whileANTHROPIC_BASE_URL(itssettings.jsonenv, else the environment) names a provider's host inPROVIDER_HOSTS, every reply is that provider's, earlier ones included. Otherwise an Ollama cloud tag isollama's and a Claude modelclaude's (through a proxy too), a self-hosted base URL makes any other modellocal's, and with no override the model's name decides:glm-*iszai's,MiniMax-*minimax's,deepseek-*deepseek's,kimi-*andmoonshot*kimi's,hf:*andsyn:*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 theirmodel_provider, bycodex_route_owner(): the built-inopenaiiscodex's untilopenai_base_url(the config key only; Codex ignoresOPENAI_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 isollama's, OpenAI's own models staycodex's through any other URL, a self-hosted one makes any other modellocal's, and a host nothing can place counts it nowhere; amodel_providersentry whosebase_urlis a host inPROVIDER_HOSTSis that provider's whatever its id (anollamaentry at ollama.com included),--osson the local daemon'sollamaislocal's unless the model is cloud-tagged, which isollama's along with a provider namedollama-cloud, an entry on the user's own hardware islocal'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,codexincluded, 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 aturn_contextor athread_settings_applied(written by-mon 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 aredeepseek's and its pi-aiopenrouterrouteopenrouter's (scan_dsh_sessions), Kimchi's gateway routes (kimchi,kimchi-dev,kimchi-dev/<upstream>,kimchi-experimental) arekimchi's in its harness sessions (pi format, underkimchi_sessions_root()) and in pi's, omp's and opencode's alike, and a harness session on--provider openrouterisopenrouter's; its gateway's hosts (kimchi.dev, every region) are inPROVIDER_HOSTS, so the Claude Code and Codex setupskimchi claudecodeandkimchi codexwrite arekimchi's whatever the model, whilekimchi claudesetsANTHROPIC_BASE_URLonly 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 isminimax's on its own routes and on acustom_provider:<name>whatever collector bills that provider'sconfig.yamlbaseURL(mcode_route_owner, which gives a cloud-tagged model on a self-hosted route toollama, 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 exposesharness_rows(owner), which reads its store and keeps the rowsownerbills, a base URL read byclaude_code_owner(): Kimi Code's model alias resolves through itsconfig.tomlto the provider's base URL (Kimi's endpoint iskimi's, as is an alias the config no longer names when it is one of the plan'skimi-code/models orKIMI_MODEL_NAME's; a removed provider's alias counts nowhere), a Qwen Code reply's auth type and its model'smodelProvidersbaseUrlinsettings.json, else theOPENAI_BASE_URLorANTHROPIC_BASE_URLits auth type takes from the environment, the first ofQWEN_HOME/.env,~/.qwen/.envand~/.envthat sets it,settings.json'senv, or thesecurity.auth.baseUrl/authsaved (Alibaba's hosts and Qwen OAuth areqwen'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 ishermes's, as is a row from before Hermes kept the route), and a Vibe session's providerapi_base(Mistral's API isvibe's). Only Hermes and Vibe's oldersession_*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 modelsettings.jsonselects. The harness's own collector counts its rows andlocalthe 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/sessionsand~/.omp/agent/sessions, plusprofiles/<name>/agent/sessionsunder each.PI_CODING_AGENT_DIR's sessions,PI_CODING_AGENT_SESSION_DIR, and an absolutesessionDirin any of those agent trees'settings.jsonare read as well as those defaults, never instead of them (a relativesessionDir, a project's.pi/settings.json, and--session-dircan't be found and aren't read); roots are compared by realpath, and one nested inside another is dropped. They are found withrg --no-ignore, since a$HOMEthat is a git checkout would otherwise hide them. pi'sreasoningand omp'sreasoningTokensare the part ofoutputthat was thinking, so they are never added to it again (opencode'stokens.reasoningis 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'susage, ausageentry (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 nousageon its compaction entries (18.12 keeps onlytokensBeforeandtokensAfter), nor anywhere else in the session or itsagent.db, so omp's compactions can't be counted and are missing from its tokens, as those of a Claude Code session with nocost-stateline are (every session before 2.1.278, and many since). A reply is deduplicated by its provider,responseIdandtimestampwhen 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 byparentSession: 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 aparentSessionnaming a file that is gone (pi deletes a session from/resumeand 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 itspatternmatches, or a model switch itsaccepttakes, 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
messagestore and V2'ssession_message, V2 first, deduplicated by message id, leaving out the copies a fork makes (in V2, asession_v2.fork_session_idsession's messages older than it; in the original store, a message whosetime.createdpredates itssessionrow, 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 isOPENCODE_DBwhen set (or the olderopencode-v2.db), opened read-only.scan_opencodein the shared module is the reference reader, andtest/shell.d/agent-usage-partition-test.shholds 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.promptssays which rows book one: in pi and omp the first reply that spent tokens after a user message (omp's ownattribution: "agent"messages aside; a file with no user messages at all keeps one per reply), in opencode'smessagestore the first step answering a user message (they share itsparentID) whose tokens and time the reader trusts, and in V2'ssession_messagethe first reply after auserrow (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 itserrorIdand noduration, such as an invalid credential) counts nowhere; in opencode'smessagestore themodelits 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'ssession_messagethe reply after theuserrow, 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 underflock, 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.svgwhen 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 byagent-usage-partition-test.sh, and the shared reading mechanics (pi, omp and opencode stores, untrusted values, cache files and locks, HTTP failure classes) byagent-usage-shared-test.sh, so a collector's test doesn't repeat them. Its adapter handscheck_limits_contractfresh limits, the probe reuse and--force, stale limits after a failed check,retryAdvisedon an unreachable service, an elapsed kept window at zero, and a refused credential, andcheck_scan_cachethe scan reuse windows;testing.mddescribes the helpers andagent-usage-grok-test.shis the worked example.