README.md
September 20, 2026 · View on GitHub
quota-axi
Your agent needs to be aware of your quota
Quota CLI for agents - designed with AXI (Agent eXperience Interface).
Agents need quota state before they choose where work can safely run. Vendor dashboards are not shaped for shell automation, and local CLIs expose different windows, resets, and auth sources.
quota-axi reports local Claude, Codex, Cursor, GitHub Copilot, Grok, Kimi, Z.AI, Alibaba, OpenCode Go, Antigravity (agy), Command Code, MiniMax, MiMo, DeepSeek, OpenRouter, and ElevenLabs quota windows in one AXI-shaped call.
It is data only: it never routes, recommends a provider, model, harness, credential, or route, proxies, intercepts, logs in, imports browser cookies, or mints or rotates a credential. When the same stored access token is expired, carries a refresh token, and is definitively rejected, quota-axi may delegate renewal to that vendor's own non-interactive CLI command and re-read the result (Delegated credential refresh). Default output has no ordering preference. The opt-in models --sort runway surface applies only its documented deterministic comparator to quota evidence, preserves all evidence and explicit ties, and is not a recommendation. It publishes one derived per-scope comparative selection signal, selection, as data computed from figures it already reports; the consumer, not quota-axi, does any routing or ranking with it.
- Official sources - quota-axi reads local provider auth sources and calls first-party quota, usage, billing, entitlement, local loopback, or read-only credential-liveness endpoints used by the local agents, with read-only CLI probes where applicable. Vendor-command boundaries and the explicit inference exception are documented under Safety guarantees.
- Local first - quota and auth reports run on the machine that holds the credentials; their network calls go to first-party provider endpoints, never a third-party relay.
The separate
updatecommand contacts npm only when the user runs it. - Token efficient - default stdout is compact TOON so agents spend fewer tokens parsing quota state, with
--jsonavailable when a caller needs the normalized model.
Quick Start
Credential-source note: Claude Code and the Cursor CLI (cursor-agent) keep live tokens in the macOS Keychain; Linux cursor-agent stores its access token in ~/.config/cursor/auth.json (or the XDG/$CURSOR_CLI_CONFIG override).
quota-axi does not read macOS Keychain values until the user grants permission, so Claude quota can stay stale and CLI-only Cursor auth can appear unavailable when no other usable credential exists. On Linux it reads only the auth file's accessToken and never its refresh token.
Run quota-axi --allow-keychain-prompt once and approve Keychain access with "Always Allow".
After a successful read, future non-interactive quota calls reuse the corresponding account-scoped grant without requiring the flag. Claude grants are also profile-scoped; legacy Claude markers created before account-pinned lookup are not reused.
$ npx -y quota-axi --provider claude,codex,cursor,copilot,grok,kimi,zai,agy
bin: ~/.npm/_npx/.../quota-axi
description: Report local agent-provider quota windows for routing-aware agents
generatedAt: "2026-03-15T16:42:00.000Z"
quota[12]{provider,scope,effectivePercentRemaining,spendPriority,runway,confidence,limitedBy,resetsAt}:
claude,all_models,64,-0.3798,projected_exhaustion,established,seven_day,"2026-03-20T17:59:45.600Z"
claude,seven_day_opus,64,0.3218,projected_exhaustion,established,seven_day,"2026-03-20T17:59:45.600Z"
claude,"model:fable",64,-0.0932,projected_exhaustion,established,seven_day,"2026-03-20T17:59:45.600Z"
codex,all_models,47,-0.2383,projected_exhaustion,established,weekly,"2026-03-19T09:54:28.800Z"
codex,"model:gpt-5.1-codex",47,-0.1973,projected_exhaustion,established,weekly,"2026-03-19T09:54:28.800Z"
cursor,all_models,72,1.4067,through_reset,established,included_usage,"2026-04-01T00:00:00.000Z"
grok,all_products,67,0.5778,through_reset,established,credits,"2026-04-01T00:00:00.000Z"
kimi,all_models,74,0.2484,through_reset,established,weekly,"2026-03-20T12:17:02.400Z"
zai,all_models,50,-1.0046,projected_exhaustion,established,weekly,"2026-03-20T16:42:00.000Z"
zai,tools,100,unknown,unknown,unknown,mcp_month,"2026-04-01T00:00:00.000Z"
agy,gemini,88,unknown,unknown,unknown,gemini_weekly,"2026-03-20T00:00:00.000Z"
agy,claude_gpt,90,unknown,unknown,unknown,claude_gpt_weekly,"2026-03-21T00:00:00.000Z"
exhaustion[6]{provider,scope,usableRunwaySeconds,projectedExhaustedAt,limitingWindowId}:
claude,all_models,298906,"2026-03-19T03:43:45.600Z",seven_day
claude,seven_day_opus,298906,"2026-03-19T03:43:45.600Z",seven_day
claude,"model:fable",298906,"2026-03-19T03:43:45.600Z",seven_day
codex,all_models,10365,"2026-03-15T19:34:45.428Z",five_hour
codex,"model:gpt-5.1-codex",10365,"2026-03-15T19:34:45.428Z",five_hour
zai,all_models,172800,"2026-03-17T16:42:00.000Z",weekly
attention[4]{provider,scope,kind,detail,remedy}:
copilot,all,unresolved_windows,chat + premium_interactions,none
zai,tools,unmeasurable,"mcp_month blocks runway + spendPriority",none
agy,gemini,unmeasurable,"gemini_5h + gemini_weekly blocks runway + spendPriority",none
agy,claude_gpt,unmeasurable,"claude_gpt_5h + claude_gpt_weekly blocks runway + spendPriority",none
help[1]:
Run `quota-axi --full` for windows, pace, reserve, and account evidence
Default TOON is decision-shaped: quota[] carries one fully populated row per measurable scope, and the sparse exhaustion[] and attention[] blocks carry the finite-runway and non-nominal facts. See Default report blocks.
--json emits the normalized model instead. Derivation inputs are demoted to --full; see Output tiers.
$ quota-axi --provider claude --json
{
"generatedAt": "2026-03-15T16:42:00.000Z",
"schemaVersion": 5,
"providers": [
{
"provider": "claude",
"plan": "pro",
"windows": [
{
"id": "five_hour",
"label": "session",
"kind": "session",
"percentRemaining": 82,
"resetsAt": "2026-03-15T20:10:48.000Z",
"pace": {
"status": "behind",
"reservePercentPoints": 12.4,
"burnMultiple": 0.5921
}
},
{
"id": "seven_day",
"label": "week",
"kind": "weekly",
"percentRemaining": 64,
"resetsAt": "2026-03-20T17:59:45.600Z",
"pace": {
"status": "ahead",
"reservePercentPoints": -8.2,
"burnMultiple": 1.295
}
},
{
"id": "model:fable",
"label": "Fable week",
"kind": "model",
"percentRemaining": 71,
"resetsAt": "2026-03-20T08:25:12.000Z",
"pace": {
"status": "behind",
"reservePercentPoints": 4.5,
"burnMultiple": 0.8657
}
}
],
"state": {
"status": "fresh",
"stale": false
},
"quotaSemantics": {
"status": "known",
"effectiveAvailability": [
{
"scope": "all_models",
"status": "known",
"effectivePercentRemaining": 64,
"boundedBy": [
"five_hour",
"seven_day"
],
"limitingWindowIds": [
"seven_day"
],
"pace": {
"status": "mixed",
"aheadWindowIds": [
"seven_day"
],
"worstReservePercentPoints": -8.2,
"worstReserveWindowId": "seven_day"
},
"runway": {
"status": "projected_exhaustion",
"usableRunwaySeconds": 298906,
"projectedExhaustedAt": "2026-03-19T03:43:45.600Z",
"limitingWindowId": "seven_day",
"projectionConfidence": "established"
},
"selection": {
"status": "known",
"spendPriority": -0.3798
}
},
{
"scope": "model:fable",
"status": "known",
"effectivePercentRemaining": 64,
"boundedBy": [
"five_hour",
"seven_day",
"model:fable"
],
"limitingWindowIds": [
"seven_day"
],
"pace": {
"status": "mixed",
"aheadWindowIds": [
"seven_day"
],
"worstReservePercentPoints": -8.2,
"worstReserveWindowId": "seven_day"
},
"runway": {
"status": "projected_exhaustion",
"usableRunwaySeconds": 298906,
"projectedExhaustedAt": "2026-03-19T03:43:45.600Z",
"limitingWindowId": "seven_day",
"projectionConfidence": "established"
},
"selection": {
"status": "known",
"spendPriority": -0.0932
}
}
]
}
}
]
}
$ quota-axi auth
bin: ~/.npm/_npx/.../quota-axi
description: Inspect local quota auth sources without printing secret values
auth[31]{provider,source,path,status,error}:
claude,oauth-file,~/.claude/.credentials.json,available,none
claude,keychain,none,skipped,keychain_prompt_required
codex,auth-json,~/.codex/auth.json,available,none
codex,pi:openai-codex,~/.pi/agent/auth.json,available,none
codex,cli-rpc,~/.local/bin/codex,available,none
cursor,state-vscdb,~/Library/Application Support/Cursor/User/globalStorage/state.vscdb,available,none
cursor,cli-keychain,~/.cursor/cli-config.json,skipped,keychain_prompt_required
copilot,apps-json,~/.config/github-copilot/apps.json,available,none
copilot,gh:hosts.yml,~/.config/gh/hosts.yml,available,none
grok,auth-json,~/.grok/auth.json,available,none
grok,pi:xai,none,missing,none
kimi,pi:kimi-coding,none,available,none
kimi,kimi-code-cli,none,available,none
zai,pi:zai,~/.pi/agent/auth.json,missing,none
zai,opencode:auth.json,~/.local/share/opencode/auth.json,available,none
agy,loopback,none,available,none
alibaba,bl-cli,none,available,none
opencode-go,opencode:auth.json,~/.local/share/opencode/auth.json,available,none
commandcode,pi:commandcode,~/.pi/agent/auth.json,missing,none
commandcode,env:COMMAND_CODE_API_KEY,none,missing,none
commandcode,env:COMMANDCODE_API_KEY,none,missing,none
commandcode,commandcode-cli,~/.commandcode/auth.json,missing,none
commandcode,omp:commandcode,~/.omp/agent/auth.json,missing,none
minimax,env:MINIMAX_API_KEY,none,missing,none
minimax,pi:minimax,~/.pi/agent/auth.json,available,none
minimax,minimax:config.json,~/.mmx/config.json,missing,none
mimo,env:MIMO_API_KEY,none,available,none
deepseek,env:DEEPSEEK_API_KEY,none,missing,none
deepseek,pi:deepseek,~/.pi/agent/auth.json,available,none
openrouter,env:OPENROUTER_API_KEY,none,missing,none
openrouter,pi:openrouter,~/.pi/agent/auth.json,available,none
help[1]:
Run `quota-axi --allow-keychain-prompt auth` to permit macOS Keychain access
Install
quota-axi requires Node.js 22.19 or newer.
Agent skill (recommended)
Install the skill in the Agent Skills format with npx skills:
npx skills add kunchenguid/quota-axi --skill quota-axi -g
The minimal skill points your agent to quota-axi's live CLI guidance through npx -y quota-axi, so nothing needs to be installed ahead of time and installed skill copies do not duplicate changing CLI instructions.
-g installs the skill for all projects (e.g. ~/.claude/skills/); drop it to install for the current project only (.claude/skills/).
Direct use
npx -y quota-axi
npm
npm install -g quota-axi
From source
git clone https://github.com/kunchenguid/quota-axi.git
cd quota-axi
pnpm install
pnpm run build
pnpm run dev
Agent Skill
The npm package includes skills/quota-axi/SKILL.md, the same installable skill recommended above.
It is generated from src/skill.ts; update it with pnpm run build:skill and verify it with pnpm run build:skill -- --check.
How It Works
┌────────────┐
│ quota-axi │
└─────┬──────┘
▼
┌───────────────┐
│ provider │
│ adapters │
└─────┬─────────┘
▼
┌───────────────┐ ┌──────────────┐
│ local auth or │ ───▶ │ first-party │
│ runtime │ │ APIs/loopback│
└─────┬─────────┘ └──────┬───────┘
▼ ▼
┌───────────────┐ ┌──────────────┐
│ CLI │ ───▶ │ normalized │
│ fallbacks │ │ quota model │
└─────┬─────────┘ └──────┬───────┘
▼ ▼
┌───────────────┐ ┌──────────────┐
│ stale cache │ ◀─── │ TOON/JSON/TUI│
└───────────────┘ └──────────────┘
- Live first - provider HTTP calls and Antigravity's structured print command use 15 second timeouts, Codex JSON-RPC and Antigravity loopback reads use shorter per-call timeouts, and stale cache fallback is per provider.
- Host network policy - Claude, Codex, Copilot, Cursor, Grok, Command Code, MiniMax, DeepSeek, OpenRouter, and ElevenLabs' outbound HTTP calls honor standard
HTTP_PROXY,HTTPS_PROXY, andNO_PROXYenvironment variables (including lowercase forms). This only follows the user's configured egress path; quota-axi does not expose a proxy service or print proxy URLs. - No first-run Keychain prompt - macOS Claude and Cursor CLI Keychain value reads are skipped on plain calls until
--allow-keychain-promptsucceeds once for that source, then future plain calls reuse the corresponding grant. - Delegated refresh, never minted - when the same stored access token is expired, carries a refresh token, and is definitively rejected, quota-axi may run that vendor CLI's own smallest non-interactive refresh command and re-read the store the CLI rewrote. quota-axi never performs a refresh-token exchange itself. See Delegated credential refresh.
- Partial success is success - one provider can fail while another returns fresh or stale data, and the process still exits 0. Exit code 1 means every provider failed, and 2 means a usage error.
- No token equivalence - quota-axi does not claim that one provider percentage equals another provider percentage.
CLI Reference
| Command | Description |
|---|---|
quota-axi | Report supported local quota windows |
auth | Report local auth-source availability, no values |
models | Join curated model buckets with local quota evidence |
update | Upgrade quota-axi to the latest published version |
update --check | Report current vs. latest without installing |
Flags
| Flag | Description |
|---|---|
--provider claude,codex,cursor,copilot,grok,kimi,zai,agy,alibaba,opencode-go,commandcode,minimax,mimo,deepseek,openrouter,elevenlabs | Scope providers |
--json | Emit normalized JSON instead of TOON for quota, auth, or models |
--full | Include audit and derivation details |
--tui | Render the live human terminal report instead of TOON (quota only) |
--refresh 30s|5m|1h | Live --tui refresh interval, default 5m (30s-24h) |
--once | Render one --tui frame and exit instead of staying live |
--allow-keychain-prompt | Permit macOS provider Keychain access that could prompt |
--allow-claude-inference | Spend one bounded native Claude inference to read env-token quota headers |
--no-credential-refresh | Never run a vendor CLI's own non-interactive credential refresh |
--profile-only | Read one explicitly selected Claude or Codex credential file (quota only) |
--intelligence high|medium|low | Filter models by editorial intelligence bucket |
--sort runway | Explicitly sort models by documented usable-runway evidence |
-h, --help | Print terse AXI help |
-v, -V, --version | Print version |
Profile-only quota reads
Profile-only mode is accepted only by quota, requires exactly one --provider selector, and supports only Claude and Codex. Claude requires an explicit nonblank CLAUDE_CONFIG_DIR; Codex requires an explicit nonblank CODEX_HOME. There is no default-location fallback in this mode, and --allow-keychain-prompt and --allow-claude-inference are rejected rather than ignored.
It reads only $CLAUDE_CONFIG_DIR/.credentials.json or $CODEX_HOME/auth.json. It never reads the macOS Keychain or Pi auth, invokes a CLI RPC or other credential fallback, delegates a refresh, or reads, writes, clears, or persists quota cache data. --full --json retains non-secret account identity, the top-level source, and source attempts for provenance. Tokens and credential-file contents remain excluded. Ordinary output remains redacted.
CLAUDE_CONFIG_DIR=/path/to/claude-profile quota-axi --provider claude --profile-only --full --json
CODEX_HOME=/path/to/codex-profile quota-axi --provider codex --profile-only --full --json
Human terminal report (--tui)
quota-axi --tui renders the same redacted report as a live human terminal view instead of TOON: a two-up provider card grid with thin headroom bars and a ┃ linear-pace marker whenever pace is known. It is presentation only and is not part of the machine-readable contract.
- On an interactive terminal the report stays up and refreshes every 5 minutes until you press
q(or Ctrl+C), with aPress q to quitfooter hint.--refreshsets the interval (30s-24h) and--oncerenders a single frame. A non-TTY stdout or stdin (pipes, CI, screenshots) always renders one frame and exits. - Every refresh re-runs the same quota read as a bare
quota-axi, including delegated credential refresh when a stored session has expired in the meantime. Runquota-axi --tui --no-credential-refreshto keep the live report strictly read-only. - Live frames paint on the alternate screen and repaint immediately on terminal resize; quitting restores the screen and prints the final frame so the last report stays in scrollback.
- Height comes from the terminal too. When the report is taller than the terminal, the live view windows it instead of letting the alternate screen (which has no scrollback) push the header and first cards out of reach. The viewport accounts for physical rows after terminal-width wrapping: a full-width visible line can consume its own row without wrapping the optional scroll affordance, which is omitted when it cannot fit. At five or more rows the header stays pinned; when there is room, the last row carries a scroll affordance naming how many report lines are above and below. Below five rows the header scrolls with the other report content, and at one row the scroll affordance is omitted so content still remains visible. Use
j/k, the arrow keys,PgUp/PgDn,Space/b, org/Gto move the window. Scrolling clamps at both ends, survives a refresh, and re-clamps on resize; growing the terminal back past the report's height restores the whole frame and the ordinaryPress q to quitfooter.--once, non-TTY output, the final frame echoed on quit, and the TOON and JSON surfaces are all unaffected by terminal height. - Each live card with a combinable bound leads with the effective-availability rollup (min across bounding windows), colored by headroom: >=50% healthy, 20-50% tight, <20% critical. Per-window rows, including per-model breakouts, are the supporting detail.
- A window with
shareOfis a used-share, not an independent remaining pool: the row printsN% of <parent>(orshare of <parent>whenpercentUsedis absent) instead of a remaining bar or?, so it cannot be read as missing data or as its own headroom. - The headline is labeled with the window it actually is: the minimum across bounding windows always equals at least one named window, so the label names the
limitingWindowIdswindow (week,session,credits) and changes per provider and over time. Tied limiting windows readcredits + grok build, compacting tocredits +2when the names do not fit; a model- or product-scoped headline appends its scope, and any unresolved limiter falls back to the scope wording (all models). - The bar fill is current headroom; the
┃marker sits at the binding window'space.timeRemainingPercent, the fill position of exactly linear burn. The headline marker therefore matches the correspondinglimitingWindowIdssub-bar even when another window supplies the finite-runwayempty inverdict. Fill ending left of the marker means burning faster than the reset clock. The marker is omitted when that window's pace is unknown. - Pace is shown by the bar and marker alone, never as a numeric burn multiple. The runway verdict on the headline reads
on pace ✓forthrough_resetandempty in 7h 21mforprojected_exhaustion. Two-up rows keep both card bottoms aligned by padding the shorter card inside its border. The TUI does not display the per-scope selection signal; that signal remains on the JSON and TOON machine surfaces. Those surfaces also keep thethrough_resetvocabulary, while--full --jsonexposes the completepaceobject. The TUI renders from the complete in-memory model, so--jsontiering never removes anything it draws. - A provider whose window relationships are wholly unknown (Copilot or Antigravity, with every window unresolved) has no combined effective percentage, pace, or runway to show, so its card replaces the headline block with a single
per-window usage · no combined boundline and leads straight into its real per-window rows. Partially understood providers keep the effective-unknown headline. No combined headroom, pace, or runway number is invented. - Signed-out and failed provider/account lanes stay visible as dimmed cards and are excluded from the fleet totals in the header.
- Width comes from the terminal, clamped to 80-120 columns; below the two-up width the grid reflows to one column. Color honors
NO_COLOR,TERM=dumb, and non-TTY stdout (the glyph skeleton is kept), re-enables withFORCE_COLOR, and uses truecolor whenCOLORTERMadvertises it, falling back to 256-color then ANSI-16. --tuicomposes with--providerscoping and--full(account identity and source-attempt footers). It is mutually exclusive with--jsonand only supported by thequotacommand.
Multiple accounts
A normal invocation reports every Codex ChatGPT subscription it can discover from sibling entries in one Pi auth.json.
It keeps each account's quota windows, resets, plan, effective availability, runway, and spendPriority separate.
Each account gets its own TUI card, naming its key on an account <key> line under the card title, including accounts whose quota cannot be read.
The default key an expanded report fills in for single-account providers is a schema artefact, so the TUI leaves it out of both the card and the --full footer; TOON and JSON still publish it.
quota-axi --provider codex --json
quota-axi --provider codex --tui --no-credential-refresh
quota-axi --provider codex --full --json # adds vendor identity and source attempts per key
Pi's built-in provider id is openai-codex.
pi-codex-accounts stores additional logins under ids such as openai-codex-work in the same file.
quota-axi enrolls those already-present keys; it does not read codex-accounts.json, copy tokens, launch Pi, or change the active account.
Discovery order is the built-in openai-codex entry, then other openai-codex-* keys in lexical order.
Two keys that carry the same stored accountId are the same ChatGPT account and are not reported as extra capacity.
The later key stays a credential fallback until a probe succeeds or every candidate is rejected.
The lane keeps the first key as its accountKey, while source names the key that answered.
A key whose identity cannot be compared is left as its own lane so the uncertainty stays visible.
When only the built-in Pi entry (or none) is present, Codex keeps its existing single-winner path: native $CODEX_HOME/auth.json, then openai-codex, then the CLI fallback.
When siblings are present and a native $CODEX_HOME/auth.json exists, that login stays first as its own codex-home lane, read from auth.json and then the CLI fallback.
The built-in openai-codex entry whose stored accountId matches the native login is not a separate lane; it stays the native lane's fallback, as it was before.
Without a native auth.json, an installed Codex CLI fallback is probed once as the codex-home lane.
The lane is left out only when the app-server's account/read positively reports no ChatGPT login (account: null or a non-ChatGPT account).
A reading without the optional accountId stays its own lane with no identity.
A failed CLI reading is shown as stale or unavailable only when account/read confirmed a ChatGPT login or a codex-home snapshot is cached; a probe that fails before that evidence adds no lane, and auth still shows the cli-rpc source.
A native login (from auth.json or the CLI) for the same account as a Pi lane is not a second lane.
The account is compared by the vendor accountId a fresh reading reports, or else the stored one; email, tokens, and key names are never used as identity.
That Pi lane keeps its own reading when fresh, and shows the native reading when its own is expired, rejected, or stale and the native one is fresh, or when only the native one has stale cached windows.
A proven sign-out, or a native login that coalesces into a Pi lane with a fresh reading on either side, removes the cached codex-home snapshot so a later failed probe cannot bring that account back.
--profile-only still reads one native Codex file and never opens Pi auth.
Account keys and compatibility
When a provider expands to multiple accounts, the report uses quota schemaVersion: 6 (auth and models use version 2).
Every provider record then has an accountKey; providers still using one selected account use the literal default.
Every flat TOON block adds accountKey immediately after provider, and the quota/exhaustion/attention join becomes provider + accountKey + scope.
Models and model sort ties use provider + accountKey + id.
Models unmatchedWindowIds entries gain the same key, so an unmapped window reads provider/accountKey/scope instead of provider/scope; the key keeps two accounts of one provider from reporting the same unmapped window indistinguishably.
Declaration order remains non-preferential; quotas are never combined across accounts.
A Codex Pi lane's key is the auth.json provider id (openai-codex, openai-codex-work); the native Codex lane's key is codex-home.
It is stable across refreshes and discovery order and contains no token, email, or path, and it also names the account's cache slot.
A lone lane keeps the legacy keyless slot, which the single selected account uses too, so the snapshot itself records the stored ChatGPT account id of the credential that produced it (see Cache).
A key the report cannot publish (malformed or repeated) costs only its own lane: the lanes with usable keys still expand, so one unreadable entry never hides the accounts beside it.
The provider falls back to its single selected account only when no usable lane remains.
--full adds the vendor identity the usage endpoint supplied, when any.
If no provider expands, output stays byte-compatible in shape and field order: quota schema 5, auth/models schema 1, and no account column. A sole discovered Pi sibling uses that legacy representation. Expansion follows the lanes discovered rather than the rows published, so when a native login and a Pi sibling turn out to be one account the single surviving row still carries its key and the report stays schema 6. Consumers must honor the schema version; a legacy keyless row means the single selected lane, and keys must never be inferred from row position.
Account collection is shared in src/providers/accounts.ts.
Adapters can implement ProviderAdapter.discoverAccounts with stable keys and bound quota/auth readers; collection preserves each account's success or failure.
Codex Pi sibling entries are the first discovery implementation on this tree.
Other adapters retain their existing source-selection behavior.
Output Model
The quota command's --json emits schemaVersion: 5, or 6 when a provider expands to multiple accounts.
Normalized schema contract
The package publishes TypeScript declarations from its package root, so consumers can use import type { QuotaAxiResponse, ModelsResponse } from "quota-axi". The adapter contract is ProviderAdapter in and normalized ProviderQuota out: adapters report observed quota data, never rank, mint credentials, or retain raw responses. The narrowly bounded vendor-owned renewal path is documented under Delegated credential refresh.
schemaVersion is command-specific. Additive optional fields do not bump it. A semantic or incompatible shape change does. The legacy single-account quota report is version 5, auth is version 1, and models is version 1. When account discovery expands a provider, those versions are 6, 2, and 2 respectively.
Default report blocks
Default TOON is organized by the reading agent's decision rather than by quota-axi's data structures:
| Block | Rows |
|---|---|
quota[] | One row per measurable scope: provider, optional accountKey, scope, effectivePercentRemaining, spendPriority, runway, confidence, limitedBy, resetsAt. Every column is populated on every row. limitedBy is the scope's limitingWindowIds, and resetsAt is that binding window's own reset. |
exhaustion[] | Sparse. One row per scope with a finite exhaustion point: usableRunwaySeconds, projectedExhaustedAt, limitingWindowId. exhaustion[0]: means nothing is projected to run out. |
attention[] | Sparse. Every non-nominal fact: provider, optional accountKey, scope, kind, detail, remedy. |
A quota[] row whose runway is projected_exhaustion or exhausted_now has exactly one matching exhaustion[] row, joined on provider + scope (plus accountKey in an account-expanded report). A row with through_reset or unknown has none, by definition: through_reset deliberately has no deadline and unknown has none to state.
attention[] kinds:
kind | scope | Meaning |
|---|---|---|
stale | all | The report is stale diagnostic data. detail names the last refresh, fetch failed plus state.error when a usage fetch failed, and any state.reason; no scope gets a quota[] row. |
auth_required, rate_limited, unavailable, error | all | The provider state status. detail is state.error, any state.reason, plus the retry-after instant for a rate limit. |
no_quota | all | The provider reported no measurable scope and no raw credit balance. Emitted when nothing else names it or when needed to preserve state.authStatus. |
credits | all | The provider reported a raw credit balance but no measurable scope. detail states that balance verbatim; no percentage or bound is derived from it. |
unresolved_windows | all | quotaSemantics.unresolvedWindowIds: unfamiliar vendor windows not folded into any bound. |
untrusted_windows | all | state.untrustedWindowIds: limits that could not be parsed authoritatively. |
share | all | A window is a used-share of another window, not an independent allowance. detail is <id> of <parent> plus · <percentUsed> when that figure is present. It bounds no scope. |
headroom_unknown | scope | The scope reports no effective percentage for a reason other than a bound conflict. detail names the windows that block it and any finite runway verdict with its limiting window. |
bound_conflict | scope | A window the scope only inherits reads zero while the scope's own windows still report allowance. detail names both sides. The scope gets no quota[] row and no exhaustion[] row. |
unmeasurable | scope | Headroom is known but a bound blocks runway, spendPriority, or both. detail names which. |
degraded_source | all | A credential source was superseded: it was broken or unreadable while a sibling source answered. detail is <source> · <error>. One row per source, only on a fresh reading. |
remedy carries state.remedyCommand when one exists, and situational agent-directed advice is still prepended to help.
Two invariants hold for every report:
- Every requested provider appears at least once, in
quota[]orattention[]or both. A provider is never silently absent, and a provider with noquota[]row always states itsstate.authStatus- including a positiveusable- as(auth <status>)in itsattention[]detail. quota[]rows stay in provider-declaration order, never sorted by any metric. A compact table with aspendPrioritycolumn must never read as a published ranking.
An unknown or stale scope deliberately gets no quota[] row: the absence of a number is the correct encoding of "no number", and the scope is named in attention[] instead.
Output tiers
--full adds; it never subtracts. Default TOON carries the three decision blocks; --full TOON adds the providers[], windows[], scopeAudit[], accounts[], and attempts[] audit blocks. Default --json carries the normalized model with derivation inputs demoted; --full restores them with no renames and no re-nesting - a demoted field is simply absent until --full, in the exact position and under the exact name it has there.
Demoted to --full in --json |
|---|
providers[].label, providers[].source |
state.refreshedAt, state.sourcesTried |
windows[].percentUsed (kept when the window carries shareOf, where it is the only figure), windows[].startsAt, windows[].windowSeconds |
windows[].pace.timeRemainingPercent, elapsedPercent, cycleBasis, cycleSeconds, projectedExhaustedAt, projectionConfidence |
quotaSemantics.description |
effectiveAvailability[].pace.behindWindowIds, onPaceWindowIds |
Account identity (account) and per-source attempts |
Everything a consumer branches on stays in the default tier: state.status, stale, authStatus, error, reason, remedyCommand, retryAfter, untrustedWindowIds, and degradedSources; window pace.status, reason, reservePercentPoints, burnMultiple, and shareOf together with that share window's percentUsed; quotaSemantics.status and unresolvedWindowIds; and every scope's effectivePercentRemaining, boundedBy, limitingWindowIds, boundConflict, runway, selection, and pace aheadWindowIds / unknownWindowIds / worstReservePercentPoints. credits also stays, so a consumer can avoid misreading it as exhaustion.
--tui renders from the complete in-memory model, so demotion never changes what the human report draws.
Quota report shape
| Object | Fields |
|---|---|
| Quota report | providers |
| Provider report | provider, optional accountKey, windows, quotaSemantics, state, optional plan, and optional credits |
Provider report with --full | Also label, source, optional account identity, and per-source attempts |
Account identity (--full) | Optional email, organization, accountId, and identityStatus |
Account identity and per-source attempts are omitted unless --full is passed.
Claude identityStatus is verified only when Anthropic returns an authoritative account identifier; email and organization are display-only and must not be used for duplicate detection.
Provider state
| Field | Description |
|---|---|
status | Provider status |
stale | Whether the provider report is stale |
sourcesTried | Sources tried for the provider (--full) |
refreshedAt | Optional refresh timestamp (--full) |
error | Optional error |
retryAfter | Optional retry-after state |
reason | Optional reason |
remedyCommand | Optional remedy command |
untrustedWindowIds | Optional identifiers for limits that could not be parsed authoritatively |
authStatus | Optional machine-readable local auth usability: usable, expired_refreshable, or unusable. Distinct from quota freshness and from human error prose. |
degradedSources | Optional { source, error? } list of credential sources a working sibling superseded on a fresh reading |
When stale or unavailable quota is likely fixable by a one-time macOS Keychain grant, state.reason is keychain_access_required, state.remedyCommand is quota-axi --allow-keychain-prompt, and JSON includes an agent-directed help entry. That prompt remedy is offered only when a Keychain prompt can help (keychain_prompt_required). A denied or timed-out Keychain outcome is reported as keychain_access_denied or keychain_prompt_timeout and stays silent no longer, but it does not advertise --allow-keychain-prompt. macOS security exit 44 is cannot-reach (keychain_unreachable), not item-absent: it is not signed-out, and it does not retire the Claude cache. A successful metadata listing covering every keychain in the search list, with no matching or unrecognized Claude item, is the only evidence that establishes a missing Claude Keychain source; an empty, partial, or failed listing proves nothing and falls back to the exact profile-and-account read.
When no Grok credential establishes usability but at least one still has a valid literal refresh token, state.authStatus is expired_refreshable and state.status is unavailable (not auth_required). Stored-expired bearers are first tested with bounded read-only liveness attempts; this classification stands only after the credential's own model catalog definitively rejects it or cannot decide, and an empirically live bearer reports fresh quota or usable instead. The grok remedy (state.reason: credentials_expired, state.remedyCommand: grok, plus an agent-directed JSON help entry telling the user to run the Grok CLI once) is emitted only when the same refreshable CLI candidate is rejected by both consumer quota and the official Grok Build model catalog. It survives the delegated grok models refresh, so it names the case where that delegate could not run or did not recover the session (see Delegated credential refresh). A transient failure does not trigger the remedy. If Grok CLI OIDC is refreshable and Pi is not usable, state.error is Grok access token expired. If only Pi xai OAuth is refreshable, state.error is Pi xAI access token expired and no Grok CLI remedy is emitted because Grok cannot refresh Pi-owned credentials. Default JSON exposes authStatus; when a provider has no quota[] row, compact TOON preserves a defined auth status as (auth <status>) in attention[]. Source-appropriate advice is included only when a remedy exists. Full output shows the attempts: model_auth_probe_live means the credential's official model catalog accepted it but exposed no numeric quota. attempts[].error: credentials_expired marks a stored-expired credential that was not attempted.
True Grok sign-out or definitive remote rejection uses state.authStatus: unusable with state.status: auth_required and state.error: Grok sign-in required (no credentials_expired reason). For official Grok Build OIDC and Pi OAuth, a rejection from the consumer Usage-page operation alone is not that verdict because those access tokens can have a different audience; the matching first-party model catalog must reject the same bearer too. authStatus: unusable by itself only means that no source established usability; for example, a Pi credential-resolution failure instead has state.status: error. Callers must branch on authStatus, status, and reason, not on human error prose alone, and must not treat expired_refreshable as logged out.
When Grok Build or Pi xai OAuth passes its model-catalog probe after consumer-quota rejection, or a local Pi xai API key establishes model-only usability, and no sibling supplies consumer quota, state.authStatus is usable, windows stay empty, and state.error is Grok model access available; quota unavailable rather than sign-in required. Only transient consumer-quota failures remain eligible for same-source stale fallback; model-only success does not inherit old quota windows. This is authenticated-but-unmeasurable, not a percentage or evidence of unlimited capacity.
A provider with more than one credential source consults them in its fixed declared order and reports the one that works, so a broken store never speaks for a provider whose sibling store still answers. A store's own expiry field is advisory within that source, never a verdict or a reason to reorder sources: a stored-expired credential is still probed in its source's declared position because only the provider's own endpoint can establish that a credential is dead. The superseded source is not discarded: state.degradedSources names it on the fresh reading, and default TOON emits a degraded_source attention row for it. Pi auth readers reserve missing for an absent file or provider property; malformed stores and present non-object or structurally invalid entries are invalid. Handover is limited to credential problems - a transport, decoding, or server failure is about the request rather than the credential, so it is reported as-is instead of being retried on a second credential. When no source works the provider still reports its auth problem, and a source that only failed transiently outranks a definitive rejection so a rejected credential is never reported as a sign-out while a sibling's outage is unresolved. Claude's env source has distinct handover and failure-priority rules; see Claude provider notes.
Claude credential failures without a usable access token preserve the precise credentials_missing or credentials_invalid error. A usage response with HTTP 401 reports Claude sign-in required only when it definitively establishes account authentication failure; the Claude provider notes own the withheld-Keychain exception and cache effects. HTTP 403 is not sufficient authentication evidence because network policy and WAF denials use it too; it stays unavailable or stale rather than claiming sign-out.
Quota windows
| Field set | Fields |
|---|---|
| Required | id, label, kind |
| Optional | Percentages, shareOf, startsAt, reset fields, windowSeconds, credit-spend fields, and derived pace |
Do not interpret a model window's percentage in isolation. quotaSemantics.effectiveAvailability reports the effective percentage for each understood scope, the complete boundedBy window set used to compute it, the currently limiting window IDs, an effective runway aggregate, and a per-scope selection signal. all_models applies to any model without a more specific scope; whether a matching model:* scope also includes account bounds is provider-specific. Grok uses the analogous all_products and product:* scopes.
A model-specific scope names the model window or the shared model prefix when multiple period windows describe one Codex or MiniMax model.
An inherited bound is only ever as good as the evidence that the vendor enforces it. When a scope's own windows all still report allowance while a window the scope merely inherits from a broader scope reports zero remaining, the two readings contradict each other, and quota-axi publishes that contradiction as effectiveAvailability[].boundConflict instead of resolving it. The scope's status stays unknown with no effectivePercentRemaining, and its runway and selection are unknown with both sides of the conflict named in unmeasurableWindowIds. This is a disclosure of uncertainty, not a claim that the scope is available - and it is deliberately not the opposite assertion either, because one live call proves the inherited bound was not enforced at that moment, not that it never binds. A zero on one of the scope's own windows is not a conflict: that is the scope's own meter reporting exhaustion, and it stands as exhausted_now.
Codex is the provider this applies to today. The vendor reports a named model limit under additional_rate_limits / rateLimitsByLimitId - a separately metered budget alongside the base limit - and a base window at zero has been observed alongside that model's own windows visibly drawing down under successful calls. Claude, Grok, and Alibaba model scopes keep their established account bounds unchanged.
quotaSemantics.status is known only when quota-axi understands the relationships needed for the reported scopes. A non-definitive availability entry omits effectivePercentRemaining. Unfamiliar vendor windows produce partial or unknown semantics and are named in unresolvedWindowIds; an empty provider report is unknown without inventing an unresolved window.
Cursor's IDE windows (included_usage, auto_usage, api_usage, and optional spend_limit) all draw on the same plan billing cycle, so quota-axi treats them as jointly bounding and reports an all_models effective remaining equal to the lowest of them. That is the conservative reading: it never overstates headroom. Grok Bot weekly usage is a separate Cursor-account meter reported as its own grok_bot scope, so it never lowers IDE headroom and IDE windows never mask Grok Bot exhaustion. An unfamiliar Cursor window is not folded into either bound and does not create a bound of its own - it stays named in unresolvedWindowIds and turns the provider's semantics partial while the recognized-window bounds remain. GitHub Copilot's window relationships are still unknown, so it reports no effective remaining.
Z.AI's five_hour and weekly usage windows jointly bound model usage and are reported as one all_models scope, while the mcp_month tool window is a separate resource reported as its own tools scope; a tool window near exhaustion therefore never lowers model headroom, and model windows never mask tool exhaustion. An unfamiliar or untrusted Z.AI window is not folded into either bound: it stays named in unresolvedWindowIds, turns the provider's semantics partial, and leaves both scopes non-definitive because it could add a bound to either.
Kimi's weekly, five-hour, and monthly-total windows jointly bound model usage at all_models scope.
The monthly code window is the code-typed share of that monthly total as the vendor serves it, not a cap of its own, so it is reported as a used share with no percentRemaining and bounds no scope: monthly headroom for code work is month_total's.
That window carries shareOf: month_total so default TOON can name it as an attention[] share row and --tui can print the used percent of the parent instead of a remaining bar or ?.
share is an additive attention kind; schemaVersion is unchanged.
An unfamiliar legacy limit, and a declared map entry that carries no usable ratio, both stay named in unresolvedWindowIds - as limit:<index> or usages:<key> - and turn the provider's semantics partial.
An unrecognized usages key is not reported as a window.
Alibaba's account weekly window is reported at all_models scope, while each model:* limit is kept only at its named model scope; a model limit never becomes an account-wide bound. OpenCode Go's rolling, weekly, and monthly windows are stacked plan caps ($12 per rolling 5 hours, $30 per week, $60 per month) that jointly bound Go-plan usage at all_models scope, so effective remaining is the minimum across them. A zeroed plan window blocks Go-plan requests, but the vendor's free-model fallback or an opted-in Zen balance may still serve past it, which the usage endpoint does not report. Command Code's five_hour and weekly windows jointly pace included monthly credits and are reported as one included_credits scope only when both windows are present and trusted; extra pay-as-you-go credits can bypass those windows, so they are never an unconditional all_models bound. limited:false is credit-only: leftover five-hour or weekly fields are omitted rather than treated as a bound. An unfamiliar or untrusted Command Code limit, including a non-empty organization spend-limit list whose schema is not independently established, stays named in unresolvedWindowIds, turns the provider's semantics partial, and withholds the included_credits scalar. MiniMax model-remains windows are kept at their named model scopes and never become an account-wide bound. MiMo has no quota windows or effective model scope until a provider-owned quota source exists. DeepSeek and OpenRouter expose balances or key caps as raw credit evidence; quota-axi does not infer model headroom or effective remaining from those amounts. ElevenLabs' single characters window is the subscription plan's included character allowance and is reported as an included_characters scope, never all_models and never a model scope: plans whose can_extend_character_limit is set bill usage past that allowance, so a zeroed window means the included allowance is spent rather than that requests are refused.
Antigravity groups its Gemini windows (gemini_5h, gemini_weekly) and its Claude/GPT windows (claude_gpt_5h, claude_gpt_weekly) into two independent scopes, gemini and claude_gpt. Within each group the 5-hour and weekly windows jointly bound that group, so its effective remaining is the minimum across its named windows, and neither group's usage lowers the other's headroom. An unfamiliar Antigravity window - including a recognized group's unrecognized bucket such as gemini_unknown - is not folded into either bound: it stays named in unresolvedWindowIds and turns the provider's semantics partial, while a reading that exposes only model-config model:* windows resolves no group and stays unknown. Antigravity v1 snapshots carry no cycle history, so each group reports headroom while its pace, runway, and selection stay unmeasurable.
For every stale provider report, raw windows remain available for diagnostics but effective availability is always unknown and omits effectivePercentRemaining and limitingWindowIds. Window pace is unknown with reason stale, and each effective pace summary, effective runway, and selection is also unknown with its unmeasurable bounds named. Routing agents must not treat a stale raw percentage as current headroom.
Pace signals
Each window may include a derived pace object that compares cumulative usage to elapsed cycle time using the response generatedAt clock:
timeRemainingPercent = 100 * (resetsAt - generatedAt) / cycleDuration
reservePercentPoints = percentRemaining - timeRemainingPercent
reservePercentPoints | Meaning |
|---|---|
| Negative | Usage is ahead of the reset clock (burning faster than linear); conserve |
| Positive | Usage is behind the reset clock |
| Within ±1.0 | on_pace deadband for API rounding noise |
| Pace field | Meaning |
|---|---|
status | ahead, on_pace, behind, or unknown |
reason | Why pace is unknown (stale, missing_usage, missing_cycle, invalid_cycle, future_cycle_start, expired_reset, unsupported_period) |
timeRemainingPercent / elapsedPercent | Cycle progress from generatedAt |
reservePercentPoints | Signed residual capacity vs the linear clock |
burnMultiple | percentUsed / elapsedPercent when elapsed > 0 |
projectedExhaustedAt | Linear cycle-average exhaustion timestamp when defined |
projectionConfidence | early when elapsed < 10% of the cycle; otherwise established |
cycleBasis | starts_at_resets_at when both boundaries are trusted; otherwise window_seconds with resetsAt |
cycleSeconds | Trusted cycle duration used for the math |
Pace is calculated only from trusted cycle evidence:
- Prefer trusted
startsAt+resetsAtpairs (Grok's provider-reported current period; Cursor's monthly billing cycle, whose start comes from the payload's cycle start or the previous renewal date). - Otherwise use provider-owned
windowSecondswithresetsAt(Codex durations; Claude fixed 5h/7d; Kimi and Z.AI fixed 5h/weekly). - Do not infer monthly, rolling, or unlabeled periods.
Every projection quota-axi publishes is cycle-average. There is deliberately no projectionBasis field: its absence means cycle_average, and a future non-cycle-average basis would name itself.
Default TOON keeps token cost low: quota[] puts spendPriority immediately after effective headroom and carries the runway verdict, its confidence, and the binding window's reset, while per-window rows and raw numeric reserve live in --full. Default --json keeps pace.status, reason, reservePercentPoints, and burnMultiple, and demotes the cycle-progress inputs those are derived from. Pace, runway, and selection are recomputed on every report from generatedAt and are not written to the quota cache.
Each effectiveAvailability entry also carries a compact pace summary over every bounding window for that scope (not only the current lowest-remaining limiter): per-status window lists, including aheadWindowIds and unknownWindowIds, plus worstReservePercentPoints / worstReserveWindowId (most negative signed reserve among known-pace windows). Different windows keep their own reset horizons; quota-axi does not invent one synthetic reset for a scope. This is factual inspectable data, never a provider/model routing recommendation.
pace.worstReservePercentPoints stays a single-window diagnostic and is deliberately not a scope-level comparative signal. The published per-scope comparative signal is selection, which aggregates every bounding window instead of reporting one extreme.
Effective usable runway
effectiveAvailability[].runway is an optional, additive field derived from every authoritative boundedBy window using the report's single generatedAt clock. It is completion-risk evidence, not a score or recommendation.
runway.status | Meaning |
|---|---|
exhausted_now | A bounding window reports zero remaining now. usableRunwaySeconds is 0; limitingWindowId names that bound. Not reported when that zero is only an inherited bound the scope's own live windows contradict - see boundConflict. |
projected_exhaustion | Every bound is measurable and one or more cycle-average projections exhaust before their own resets. The earliest one supplies usableRunwaySeconds, projectedExhaustedAt, limitingWindowId, and projectionConfidence. |
through_reset | Every measurable bound reaches its own current-cycle reset before projected exhaustion. There is deliberately no synthetic finite deadline or combined reset timestamp. |
unknown | A stale, missing, malformed, or otherwise unmeasurable authoritative bound prevents a sound aggregate conclusion, as does a disclosed boundConflict. unmeasurableWindowIds names the blockers. |
In default TOON the finite-runway detail moves to exhaustion[]; runway and projectionConfidence stay as the runway and confidence columns of the scope's quota[] row, and unmeasurableWindowIds becomes an attention[] row naming the blocked signals.
usableRunwaySeconds is nonnegative and is present only for finite results. projectionConfidence is early or established. Zero observed usage with a valid current cycle proves through_reset under that same cycle-average basis. Named model or product windows are additional bounds only for their applicable scopes, so they can become the effective limiting window without changing other scopes.
A bounding window with no resetsAt at all has not been triggered yet (e.g. a Claude five_hour window before its first request this window) rather than being a data gap. When that untriggered window also reports zero usage (100% remaining, 0% used), it is treated as fully available and excluded from unmeasurableWindowIds, so it never forces runway.status: unknown by itself; the report's other bounding windows still determine the aggregate. The same runway treatment applies to a fresh named-model window when its scope's enclosing account bounds independently establish runway and it explicitly reports 0% used and 100% remaining with a valid reset no more than its declared window duration plus five minutes ahead, making its inferred cycle start slightly later than the report snapshot (pace.reason: future_cycle_start): that unopened model window has no exhaustion projection yet. The five-minute ceiling bounds request latency and clock skew; a reset beyond it is implausible cycle evidence and remains unmeasurable. Its 100% can still contribute to effectivePercentRemaining as a headroom bound. quota-axi never synthesizes a resetsAt or starts the countdown client-side. A missing resetsAt paired with any other usage shape (unknown usage, or nonzero usage without an active clock) is a real data gap, not "not yet triggered," and still fails closed into unmeasurableWindowIds - alongside stale data, missing usage percent, an expired or malformed resetsAt that is actually present, and a missing projection when usage is nonzero and the cycle is known. Likewise, a future cycle remains unmeasurable unless it is a named-model window with independently measurable enclosing account bounds, both usage fields explicitly prove that it is wholly unused, its positive declared duration is available, and its reset falls within that bounded cycle-ahead interval.
Per-scope selection signal
effectiveAvailability[].selection is an optional, per-scope object published for every scope quota-axi reports, including unknown and stale ones. It is the primary published selection signal: one scalar per scope, comparable across scopes, providers, and accounts. Consumers that need to distinguish accounts can request the optional account identity with --full.
In default TOON the scalar is the spendPriority column of the scope's quota[] row - there is no separate selection[] block, at any tier, because the column already carries it. An unmeasurable scalar renders the literal unknown, never 0: 0 is exact utilization, a completely different claim.
| Field | Meaning |
|---|---|
status | known when every bounding window is measurable and no boundConflict is disclosed; otherwise unknown |
spendPriority | The clamped scope scalar. Present only when status is known |
unmeasurableWindowIds | The bounding windows that blocked the scalar. Present whenever one made the scope unknown |
For each bounding window w of the scope:
S_w = percentRemaining_w - burnMultiple_w * timeRemainingPercent_w
gap_w = S_w / timeRemainingPercent_w
scopeMetric = SUM(gap_w * cycleSeconds_w) / SUM(cycleSeconds_w)
S_w is the percentage points of that window's paid allowance projected to reach reset unused if the observed burn continues. Dividing by timeRemainingPercent_w makes windows on different reset clocks comparable, and weighting by cycleSeconds_w keeps a short session window from dominating a weekly or monthly one. The result is clamped to [-100, +100].
spendPriority | Meaning |
|---|---|
| Positive | Paid allowance is on track to reach reset unused, so spending here reclaims allowance that would otherwise be forfeited |
0 | Exact utilization: the scope is projected to finish its cycle with nothing left over and nothing overdrawn |
| Negative | Overdrawn against the reset clock |
A higher spendPriority therefore marks the scope where spending recovers the most paid allowance that would otherwise expire unused. At burnMultiple 1, S_w reduces exactly to that window's reservePercentPoints; the metric generalizes reserve to projected forfeiture at the observed burn pace.
Any bounding window without usable pace makes the whole scope unmeasurable: status is unknown, no scalar is emitted, and unmeasurableWindowIds names the blockers. An unknown window is never assumed healthy and never treated as zero. A window whose remaining cycle time has effectively run out is unmeasurable rather than infinite. The one case where an absent burnMultiple is not a gap is a window with zero elapsed cycle time and zero usage: nothing can have been consumed yet, so its observed burn is 0 and the scope stays measurable.
selection is derived per report from the same generatedAt clock as pace and runway, and is not cached.
This is data, not routing. quota-axi still never routes, ranks a winner, orders providers preferentially, proxies, logs in, or changes provider quota state. selection is a derived comparative data signal computed entirely from figures quota-axi already reports; any routing, ranking, or preference is the consumer's decision. It is also advisory only: it never overrides runway, which remains the hard completion-risk evidence a consumer checks against its task horizon.
Quota enums
| Name | Values |
|---|---|
| Provider statuses | fresh, stale, unavailable, auth_required, rate_limited, or error |
| Provider sources | oauth, pi:openai-codex, pi:openai-codex-* sibling keys, cli-rpc, cli, api, web, cache, or unavailable |
| Current provider adapter sources | oauth, pi:openai-codex, pi:openai-codex-* sibling keys, cli-rpc, cli, api, web, cache, and unavailable |
| Window kinds | session, weekly, monthly, model, credits, or unknown |
| Window pace statuses | ahead, on_pace, behind, or unknown |
| Effective pace statuses | ahead, on_pace, behind, mixed, or unknown |
| Effective runway statuses | exhausted_now, projected_exhaustion, through_reset, or unknown |
| Effective selection statuses | known or unknown |
| Pace projection confidence | early or established |
| Pace cycle basis | starts_at_resets_at or window_seconds |
| Quota relationship statuses | known, partial, or unknown |
| Source attempt statuses | success, failed, or skipped |
Source attempts can include credentialPresent when a source is not genuinely absent, including when a read failure prevents a more precise classification. They can also carry an explicit degraded flag that overrides the derived classification in either direction: false when a non-success attempt is not a broken credential source, and true when a skipped source was itself unreadable without establishing that a credential is present. Otherwise fresh reports derive state.degradedSources from failed attempts and skipped attempts with credentialPresent.
Provider windows
| Provider | Windows and capabilities |
|---|---|
| Claude | Can report five_hour, seven_day, optional seven_day_opus, and optional extra_usage windows. Trusted session/weekly/model windows emit fixed windowSeconds (18,000 or 604,800) for pace; extra_usage does not invent a monthly duration. |
Claude scoped limits | When the account's usage response includes a scoped limits list, quota-axi surfaces every active window it describes instead, including model-scoped ones (e.g. Fable) as a model:<slug> window with the same trusted weekly duration. |
| Codex | Identifies exact 18,000-second and 604,800-second periods as five_hour and weekly, regardless of source slot; periods without a duration retain their positional identity. Additional model- or feature-scoped limits use model:<id>:5h / model:<id>:7d, and code-review limits use code_review_five_hour / code_review_weekly. Unfamiliar durations remain honest <hours>h windows instead of being classified as known periods. Duplicate derived IDs are preserved with _2, _3, and later suffixes. Optional credit balance data can also appear. |
| Cursor | Can report included_usage, auto_usage, api_usage, and optional spend_limit windows from GetCurrentPeriodUsage, plus an optional grok_bot weekly window from the same dashboard service's GetSandUsageStatus RPC. Their effective-availability interpretation is documented in Quota windows. Monthly labels alone are not trusted cycle evidence, but the billing cycle is: the monthly windows take startsAt from a reported billingCycleStart, or - with only billingCycleEnd - from the previous renewal date one calendar month earlier (clamped to the last day of that month), so pace uses starts_at_resets_at. With neither field the cycle stays unresolved; no fixed 30-day duration is invented. The Grok Bot window uses the sand payload's own currentPeriodStart / nextResetTimestampUtc pair when present, and is omitted when that RPC is missing, non-finite, or a pooled enterprise allowance. |
| GitHub Copilot | Can report quota snapshot windows such as chat, completions, and premium_interactions; when the first-party endpoint exposes entitlement but no numeric quota windows, quota-axi reports a fresh provider state with an empty windows list rather than inventing percentages. Pace stays unknown without trusted cycle boundaries. |
| Grok | With a consumer-compatible Grok session or Pi xai OAuth bearer, can report the shared credits window, optional product-scoped product:<slug> windows, the current-period startsAt and reset, and optional prepaid credit balance from the consumer Usage-page operation. Official Grok Build OAuth and Pi OAuth can remain valid for their model catalogs while that separate operation rejects their audience; in that case quota-axi reports usable auth with no windows rather than inventing a SuperGrok percentage. A Pi xai API key likewise establishes model usability only. Top-level credits.remaining is prepaid/on-demand balance, distinct from the shared period windows credits percentage used for effective availability. Pace prefers the startsAt/resetsAt pair. |
| Grok proto3 zero | For the exact consumer operation only, an omitted usage float is the official proto3 zero when a valid weekly or monthly current period proves the config is present; quota-axi reports 0 used and 100 remaining rather than deriving usage from money. |
| Kimi | Reports every window the /usages payload actually supplies: the current usages map (five_hour, weekly, month_total, month_code from limit_5h / limit_7d / limit_month_total / limit_month_code) or the legacy principal weekly object plus every valid self-described limits[] entry in wire order. Trusted 5h/weekly durations are 18,000s and 604,800s; monthly windows do not invent a duration. Only a legacy limit whose normalized duration is exactly 18,000 seconds is identified as five_hour; future limits remain limit:<index> unknown windows. The map's ratio is read from used_ratio only. Absent map entries stay absent, a declared map entry with no usable ratio is named usages:<key> in state.untrustedWindowIds rather than dropped, and an unrecognized map key is not a window. month_code stays a distinct window but carries only percentUsed plus shareOf: month_total, because it is a share of month_total rather than its own budget. |
| Z.AI | Can report the Coding Plan five_hour and weekly usage windows (with trusted 18,000s and 604,800s durations) plus the mcp_month tool window, whose duration is not invented. Token and credit limits are both identified by the endpoint's own unit/number magic values (3/5 and 6/1) rather than array position; any other limit, or a repeat of an already reported one, degrades to an untrusted limit:<index> unknown window named in state.untrustedWindowIds. |
Antigravity (agy) | On macOS and Linux, can report gemini_5h, gemini_weekly, claude_gpt_5h, and claude_gpt_weekly from the installed CLI's structured agy -p "/quota" --output-format json response (a bounded read, not an agent session), falling back to an already-running Antigravity app or agy loopback quota summary when the CLI is unavailable. If only model config quota is exposed, quota-axi reports model-scoped model:<slug> windows instead of inventing grouped windows. Antigravity v1 snapshots do not expose enough history for honest burn-rate pace, so pace stays unknown. |
| Alibaba | Reads the local bl CLI's Alibaba Coding Plan Token Plan usage; reports the plan name and weekly remaining percentage and reset time from the CLI's JSON output, plus any named model limits as separate model:<name> windows. Repeated limits for the same model remain separate with suffixed IDs such as model:<name>:2. |
| OpenCode Go | Using the credential sources documented in Security Posture, reports the provider's rolling, weekly, and monthly usage windows as stacked plan caps that jointly bound Go-plan usage at all_models scope. It uses only cycle durations present in the payload; absent durations remain absent, so pace, runway, and selection stay unknown until the vendor reports a cycle. A zeroed plan window blocks Go-plan requests, but the vendor's free-model fallback or an opted-in Zen balance may still serve past it. |
| Command Code | Reads local Command Code API keys and reports the exact aggregate credit balance (monthlyCredits + purchasedCredits + freeCredits, unit credits) plus five_hour and weekly rolling windows from Command Code's undocumented first-party GET /alpha/whoami?limits=1 and GET /alpha/billing/credits endpoints. Those windows use trusted 18,000s and 604,800s durations and jointly bound the included_credits scope, not all_models, only when both are present and trusted. limited:false omits leftover rolling fields so the report stays credit-only with empty windows. No monthly percentage or 30-day reset is invented. Pay-as-you-go/Enterprise-style responses with no rolling windows stay fresh and auth-usable with empty windows, and their balance is surfaced as a credits attention row rather than no_quota. The /alpha account endpoints are not a documented public API; unrecognized limits fail closed as untrusted/partial. |
| MiniMax | Reports Token Plan model_remains windows, or a balance in credits.remaining with unit usd on the global api.minimax.io host and cny on the China api.minimaxi.com host. Model-window IDs are model:<slug>:5h or model:<slug>:7d for the trusted 18,000-second and 604,800-second durations, and model:<slug>:window:<label> for any other or undetermined duration; all share the model:<slug> scope. Absent numeric observations remain absent, and no account-wide bound is inferred. A model_remains row with no recognized window fields degrades to an untrusted limit:<index> unknown window named in state.untrustedWindowIds. |
| MiMo | Reads only the local MIMO_API_KEY used by Pi. No first-party read-only quota endpoint is established, so a usable credential reports an empty fresh window set rather than fabricated model headroom. |
| DeepSeek | Reports credits.remaining from the USD total with unit usd, or, when no representable USD total exists, from the CNY total with unit credits; quota-axi does not infer model headroom or effective remaining from those amounts. |
| OpenRouter | Reads a local OpenRouter/Pi API key and the first-party key endpoint. A finite key cap is reported as a raw key-limit credit amount; unlimited keys are reported without an invented cap, and no model headroom is inferred. |
| ElevenLabs | Reads the deliberately exported ELEVENLABS_API_KEY and reports one characters window from the subscription plan's included allowance (character_count / character_limit) via the documented first-party GET /v1/user/subscription. resetsAt comes from next_character_count_reset_unix; the cycle start is that reset stepped back by the vendor's declared character_refresh_period, and an unrecognized period leaves the cycle - and therefore pace, runway, and selection - unknown rather than assuming one. Only monthly_period maps onto the monthly window kind; the longer declared periods stay unknown. A zero or absent character_limit reports no window instead of a percentage, and so does a response whose reported reset has already passed: those counters describe a finished cycle, so the live reading fails closed the same way the stale-cache path does. The window bounds included_characters, never all_models. |
Model catalog and models
quota-axi models [--intelligence high|medium|low] [--sort runway] [--provider ...] [--json|--full] joins a reviewed catalog of native Claude, Codex, Grok, Kimi, MiniMax, and MiMo models to the provider's effective quota evidence. MiMo has catalog names for discovery, but no quota windows are established, so its model rows remain unevidenced. It queries catalog-backed providers by default and accepts only those providers in an explicit models scope. Cursor, Copilot, Z.AI, Alibaba, OpenCode Go, DeepSeek, OpenRouter, Antigravity, and Command Code report quota but have no reviewed catalog entries yet, so they are not models providers. ElevenLabs meters speech characters rather than model usage, so it is not a models provider by construction.
Catalog buckets are coarse editorial classifications relative to the current frontier, not scores. They are curated from public provider material and public leaderboards, including Artificial Analysis as an informing source, with a documented provenance string so a stale catalog is detectable rather than silently refreshed. quota-axi does not reproduce Artificial Analysis scores, has no runtime Artificial Analysis dependency, and never commits an Artificial Analysis key. scripts/refresh-model-kb.ts is a maintainer-only review aid: it may use a private AA_API_KEY to suggest changes, but it never writes the catalog.
Every models response includes catalog.version and catalog.provenance; callers must treat catalog freshness and unmapped unmatchedWindowIds as explicit unknowns, never as missing evidence. A model row exposes the applicable effective quota scope and provider state. When no model-specific scope is known, the provider account scope remains the evidence rather than an invented model limit.
Default model order is deterministic and non-preferential: provider, then accountKey in an account-expanded report, then model ID. --sort runway is an explicit, evidence-preserving comparator only: finite usableRunwaySeconds descend, then through_reset, then exhausted_now, with unknown evidence last. Equal evidence appears in sort.tieGroups; no hidden score or model, provider, harness, credential, or route recommendation is implied. The comparator registry is intentionally extensible for a future separately sourced cost comparator, which is not shipped in v1.
auth --json shape
| Object | Fields |
|---|---|
| Auth report | generatedAt, schemaVersion (1, or 2 when account-expanded), and auth |
| Provider auth report | provider, optional accountKey, and sources |
| Auth source entry | source, optional path, status, and optional error |
Auth source entries can include credentialPresent when a source is not genuinely absent, including when a read failure prevents a more precise classification.
| Name | Values |
|---|---|
| Auth source statuses | available, missing, invalid, expired, skipped, or error |
| Auth source names | env, oauth-file, keychain, auth-json, auth-env, apps-json, gh:hosts.yml, state-vscdb, cli-keychain, cli-authfile, cli-rpc, pi:openai-codex, pi:openai-codex-* sibling keys, pi:kimi-coding, pi:xai, pi:zai, pi:commandcode, kimi-code-cli, pi:opencode-go, opencode:auth.json, minimax:config.json, pi:minimax, env:MINIMAX_API_KEY, env:MIMO_API_KEY, pi:deepseek, env:DEEPSEEK_API_KEY, pi:openrouter, env:OPENROUTER_API_KEY, bl-cli, loopback, env:COMMAND_CODE_API_KEY, env:COMMANDCODE_API_KEY, commandcode-cli, omp:commandcode, and env:ELEVENLABS_API_KEY |
Security Posture
Provider credential sources
| Provider | Credential sources read |
|---|---|
| Claude | CLAUDE_CODE_OAUTH_TOKEN when it is set to a usable literal token; $CLAUDE_CONFIG_DIR/.credentials.json or ~/.claude/.credentials.json (on macOS, not read when a nonempty secure-storage selector is set); on macOS, the discovered Claude Code Keychain value for the selected profile, pinned to Claude Code's validated current-user account, with --allow-keychain-prompt or, after a service-and-account-scoped non-secret access marker exists, on plain calls |
| Codex | $CODEX_HOME/auth.json or ~/.codex/auth.json, then Pi's $PI_CODING_AGENT_DIR/auth.json openai-codex subscription OAuth entry and any sibling openai-codex-* entries in that same file (default ~/.pi/agent/auth.json), before the read-only CLI fallback; $QUOTA_AXI_CODEX_BINARY can pin that fallback to an absolute executable path |
| Cursor | Cursor editor: $CURSOR_STATE_DB when set or the platform Cursor state database path. Cursor CLI (cursor-agent), macOS: identity from $CURSOR_CLI_CONFIG or ~/.cursor/cli-config.json plus the cursor-access-token / cursor-user Keychain value with --allow-keychain-prompt or an account-scoped marker; Linux: only accessToken from $CURSOR_CLI_CONFIG or ${XDG_CONFIG_HOME:-~/.config}/cursor/auth.json |
| GitHub Copilot | $GITHUB_COPILOT_APPS_JSON when set or the local Copilot apps auth file, then only the github.com host oauth_token from the GitHub CLI's hosts.yml ($GH_CONFIG_DIR, else $XDG_CONFIG_HOME/gh, else %AppData%\GitHub CLI on Windows, else ~/.config/gh) |
| Grok | Grok CLI session auth from $GROK_AUTH_JSON, inline $GROK_AUTH, $GROK_AUTH_PATH, or $GROK_HOME/auth.json / ~/.grok/auth.json, plus Pi's independent $PI_CODING_AGENT_DIR/auth.json xai entry (default ~/.pi/agent/auth.json) for OAuth or literal API-key model auth |
| Kimi | Pi's $PI_CODING_AGENT_DIR/auth.json (default ~/.pi/agent/auth.json) for a literal kimi-coding API key or OAuth access token first, then an official Kimi Code CLI access token from the slot $KIMI_CODE_HOME/config.toml names (default $HOME/.kimi-code/), falling back to credentials/kimi-code.json when it names none. Stored-expired tokens are probed; rejected refreshable expiry is soft, not sign-out |
| Z.AI | Pi's $PI_CODING_AGENT_DIR/auth.json (default ~/.pi/agent/auth.json) for a literal Coding Plan api_key entry under zai, then opencode's auth.json ($XDG_DATA_HOME/opencode/auth.json when set, %LOCALAPPDATA%\opencode\auth.json on Windows, otherwise ~/.local/share/opencode/auth.json) for a literal key under zai-coding-plan, zai, z-ai, z.ai, zhipu, or zhipuai |
| Antigravity | No credential files; prefers the installed CLI's bounded, noninteractive structured /quota read (agy -p "/quota", a bounded read, not an agent session), falling back to discovering already-running Antigravity or agy processes and reading their 127.0.0.1 read-only loopback endpoints |
| Alibaba | The local bl CLI (bl usage token-plan --output json); quota-axi never reads Alibaba credential files or exchanges refresh data |
| OpenCode Go | $XDG_DATA_HOME/opencode/auth.json when set, %LOCALAPPDATA%\opencode\auth.json on Windows, otherwise ~/.local/share/opencode/auth.json, for a literal opencode-go key with opencode fallback by default. When QUOTA_AXI_OPENCODE_GO_PI_AUTH is 1 or true, Pi's $PI_CODING_AGENT_DIR/auth.json (default ~/.pi/agent/auth.json) literal opencode-go api_key entry is read first. This is opt-in so an unscoped run does not read an unrelated Pi store. |
| Command Code | Pi's $PI_CODING_AGENT_DIR/auth.json commandcode entry first (default ~/.pi/agent/auth.json), then $COMMAND_CODE_API_KEY, legacy $COMMANDCODE_API_KEY, production ~/.commandcode/auth.json top-level apiKey, then ~/.omp/agent/auth.json commandcode/command-code. Stored expiry is ignored: the credential is a non-expiring API key. |
| MiniMax | MINIMAX_API_KEY, then $PI_CODING_AGENT_DIR/auth.json (default ~/.pi/agent/auth.json) for a literal minimax key, then $MMX_CONFIG_DIR/config.json (default ~/.mmx/config.json); MINIMAX_BASE_URL is accepted only for MiniMax first-party hosts |
| MiMo | MIMO_API_KEY only, as a literal secret; quota-axi does not read browser or dashboard state |
| DeepSeek | DEEPSEEK_API_KEY or $PI_CODING_AGENT_DIR/auth.json (default ~/.pi/agent/auth.json) for a literal deepseek key |
| OpenRouter | OPENROUTER_API_KEY or $PI_CODING_AGENT_DIR/auth.json (default ~/.pi/agent/auth.json) for a literal openrouter key |
| ElevenLabs | $ELEVENLABS_API_KEY only, when it holds a usable literal key. That is the credential ElevenLabs' own CLI documents for non-interactive use and sends as the xi-api-key header. Stored expiry does not apply: the credential is a non-expiring API key. |
The Claude and Codex rows describe default discovery; --profile-only narrows each to the one selected credential file.
Provider notes
Claude
- quota-axi mirrors Claude Code's Keychain account selector: nonempty
USER, otherwise the operating-system username, validated against Claude Code's safe account pattern with the sameclaude-code-userfallback. Metadata discovery filters to that account, and exact presence/value reads require it plus the selected service. There is no ambiguous service-only fallback. CLAUDE_CODE_OAUTH_TOKENis an explicit credential source and is preferred over every discovered store, because Claude Code resolves that variable before it opens any credential store: a token there names the account a live session is actually using, so reading a store instead would report a bystander account. It is an access token alone, so it has noexpiresAtto order it by, is never advisory-expired, is never eligible for the delegatedclaude doctorrefresh, and is never written to a credential store or a cache. Absent, empty, and whitespace-only values select nothing and leave stored-credential discovery exactly as it was; a non-blank value that is not a usable literal bearer is reported as anenvsource problem rather than dropped silently. An environment token also needs no Keychain grant, so--allow-keychain-promptis irrelevant to it. Because such a token selects an account the profile path and Keychain service do not describe, a reading taken with one carries its own cache identity, so its snapshot is never served as stale once the variable is gone; profiles with no environment token keep the identity they already cached under. A generic non-definitiveenvrejection can still fall through to a stored source. If that fallback fails, a stored source's definitive rejection outranks the earlier generic env failure. The specifically recognized usage-endpoint denial for missinguser:profileis different: it establishes that the selected env bearer cannot use that quota surface without asserting sign-out, so quota-axi reportsstate.status: unavailablewithstate.authStatus: usableand stops rather than letting a bystander stored credential relabel the selected session. A genuine env HTTP 401 remainsauth_requiredeven when unrelated Keychain discovery fails; it neither falls through to a stored credential nor retires its cached snapshot.- When that exact scope denial is the final Claude failure and the native fallback was not attempted,
state.reasonisinference_opt_in_required,state.remedyCommandisquota-axi --provider claude --allow-claude-inference, and JSON includes an agent-directedhelpentry naming the startup-plus-inference cost. That is advice only: it never runs the fallback, changesauthStatus, or persists consent, and a run that already passed the flag gets no such advice. --allow-claude-inferenceis the explicit numeric fallback for that specific env-token scope boundary. It launches the installed native Claude Code client once from a new empty temporary directory with safe mode enabled and tools, MCP/browser integration, permission prompts, slash commands, and session persistence disabled; the fixed prompt asks for exactlyOK, sets an inference budget, and may spend normal startup plus inference tokens. The child inherits the selected credential and route environment. SDK debug output is bounded in memory, never persisted or rendered, and reduced to validated unified five-hour/seven-day utilization and reset headers. The report uses sourcecli;--fullrecords aclaude-native-inferenceattempt. Cache eligibility is defined under Cache. Both allowlisted windows must validate before any windows are returned; an incomplete pair remains unmeasurable. Stdout and stderr are parsed independently after stripping terminal control sequences; the latest debug response in each stream is considered without joining fragments across streams. One complete observation is accepted, identical complete observations agree, and conflicting complete observations are rejected. An incomplete bare 429 in the other stream cannot displace complete evidence. The child disables native retries and the retry watchdog without changing the parent environment. Ordinary SIGINT/SIGTERM cancellation terminates the inference process group, escalating after a bounded grace period, and preserves the caller’s signal behavior. Unknown debug formats, missing headers, unavailable/incompatible Claude, timeouts, and process failures report unavailable rather than inventing quota. A native 429 reportsrate_limitedwith its bounded Retry-After and keeps any validated unified five-hour/seven-day windows that response itself carried inwindows; such a windows-carrying report uses sourcecliso those observed numbers still produce their ordinaryquota[]andexhaustion[]rows beside therate_limitedattention row, while therate_limitedstatus keeps the reading out of the cache. That observation outranks a later execution or output bound only when it is complete - a validated Retry-After or windows - so a block truncated to bare status digits, like a run with no observed rate limit, stays a timeout or output-limit failure; a complete 200 reading cut off by a bound is deliberately not rescued. Because the env token is consulted first and that scope denial ends discovery, a skipped Keychain candidate on such a reading never produceskeychain_access_requiredadvice, whether the denial or a failed native run is the final error. A nonblankANTHROPIC_API_KEYorANTHROPIC_AUTH_TOKENin the environment also reports unavailable (claude_native_api_key_presentorclaude_native_auth_token_present) before anything is launched, because the native client could bill that key instead of measuring the selected OAuth session; quota-axi checks only whether these values are nonblank and never retains, logs, or unsets them. Claude may still perform its normal transient startup cache/log writes. The flag is off by default, is rejected byauth,models, and--profile-only, and requires--oncewith--tuiso it cannot become a recurring paid probe.- The plaintext credential file is
$CLAUDE_CONFIG_DIR/.credentials.jsonor~/.claude/.credentials.json. A nonemptyCLAUDE_SECURESTORAGE_CONFIG_DIRselects the Keychain service; on macOS, where that Keychain item is the sibling source, the plaintext file is left unread so two profile selectors can never answer for one reading. Off macOS there is no Keychain sibling, so the configured file is still read. An empty value falls through toCLAUDE_CONFIG_DIR. A nonempty selector gives exactlyClaude Code-credentials-<sha256(NFC selector path).slice(0,8)>; with neither selector set, the service is the unsuffixedClaude Code-credentials. The hash uses the raw NFC-normalized path, without resolving relative paths, expanding~, or trimming it, matching Claude Code's selector. - quota-axi reads
security list-keychains, then lists metadata from those paths in onesecurity dump-keychain <search-list paths...>call (no values, raw data, or ACLs). Each command is bounded to five seconds and 16 MiB. It accepts only generic-password records for the validated current-user account whose service is the exact selected service, or - for a default selection only - a singleClaude Code-credentials-<eight lowercase hex>item (see below). The exact selected service is preferred when both exist. Duplicate matching items follow Keychain search-list order, independently of modification time or dump order; each credential pass reads at most one value, pinned to the located keychain, service, and account. - A default selection cannot re-derive the opaque suffix Claude Code gave its own item, so with no selector set quota-axi accepts a
Claude Code-credentials-<eight lowercase hex>item - but only when complete, conclusive metadata covers the entire search list and exactly one such item exists for this account, since the same naming shape can represent an explicit profile or an MCP OAuth store. Two or more leave the reading inconclusive and none is opened; recency never breaks the tie. Any other suffix shape is never accepted. Missing or unparseable records, unfamiliar Claude services, and Claude items owned by another account prevent opaque fallback; exact selected-service reads remain available. An explicit selector accepts only its own exact service: it never falls back to the unsuffixed item, to an opaque item, or to another profile's item. If the configured service cannot be located and any other Claude-prefixed generic-password item remains - including one owned by a different account name - the result stays inconclusive and eligible stale cache is preserved. - Metadata discovery runs again on each credential pass, including every TUI refresh. A replacement under the selected service, a changed search list, or a changed storage selector is picked up without restarting. A second opaque suffix appearing alongside the first leaves both unconfirmed; recency cannot establish ownership. A newly selected service still requires its own access marker or
--allow-keychain-prompt. - When the search list or metadata cannot be read completely, quota-axi falls back only to the exact selected service/account read across the search list. Empty or partial metadata and
securityexit 44 never establish sign-out. Only a parsed listing covering every searched keychain and containing no matching or unfamiliar Claude-prefixed item establishes absence. Denied and timed-out value reads retain their errors and never trigger reads of other services. - quota-axi records the non-secret access marker after any successful pinned Keychain value read. The marker is keyed by the account and the selected service, so a grant is never assumed for a differently suffixed item that Claude Code wrote later. That key changed shape in this release, so a marker recorded by an earlier version no longer authorizes a plain call; run
quota-axi --provider claude --allow-keychain-promptonce to record the current one. - When that marker exists, plain calls read the pinned Keychain value again so an already-approved "Always Allow" grant keeps live Claude quota fresh. Markers written by earlier versions remain untouched but do not authorize a value read.
- Without the flag or the current marker, quota-axi may perform a non-secret pinned Keychain item presence check so it only suggests Keychain access when the selected Claude credential item exists.
- In
--fulloutput, Claude usage attempts identifyoauth-fileorkeychainas the credential discovery source. They never include the Keychain account. - When an access token exists, local
expiresAtmetadata is advisory. quota-axi tests that token with Anthropic's existing read-only usage request; success returns fresh quota, while HTTP 401 definitively rejects that bearer. HTTP 403 alone is non-definitive because Anthropic's network-policy and WAF denials can use the same status for a valid bearer. HTTP 429 is ordinarily standard Retry-After rate limiting, but in default discovery, when the token was already stored-expired, quota-axi confirms that reading against the read-only OAuth profile endpoint: an explicit 401 there reports a non-definitive credential expiry instead, discarding the Retry-After, while a live, transient, or unclear profile answer leaves the rate-limited failure and its Retry-After untouched. A confirmed expiry allows any remaining stored credential candidate to be tried; a successful sibling returns fresh quota. If the confirmed expiry remains the final failure, it reportsClaude credential expiredas unavailable or eligible stale quota, without retiring the Claude cache or qualifying that token for delegated refresh. The confirming probe appears as anoauth-profileattempt in--fulloutput. It is not a credential source, so its outcome neither triggers nor suppresses Keychain access advice. - When that stored token was expired, carried a refresh token, and was definitively rejected, quota-axi may run
claude doctorand retry once against the store Claude Code rewrote, subject to the best-effort live-process check and residual race described under Delegated credential refresh.claude doctoris Claude Code's own installation health check: it starts no session, sends no model request, spends no quota, and does not connect to configured MCP servers. quota-axi never exchanges the Claude refresh token itself; it only checks that one is present, because Anthropic rotates it on use and a second exchange would sign Claude Code out. On macOS a withheld Keychain value read suppresses the delegate and keeps the Keychain remedy instead, because the CLI would rewrite a store quota-axi still could not read. - Missing or invalid credentials without a usable access token and usage HTTP 401 normally bypass and best-effort retire Claude cache. For stored credentials, when macOS Keychain discovery fails or its value read is denied/unreachable, a 401 from an oauth-file sidecar rejects only that candidate: quota-axi reports the Keychain failure, does not classify Claude as signed out, and preserves any eligible stale cache. Only complete search-list metadata with no matching or unfamiliar Claude item reports a missing source; every exact-read failure, including exit 44, remains a Keychain failure that preserves the cache. Stored-credential HTTP 403, timeout, network, rate-limit, server, and response-compatibility failures may use only a formerly fresh Claude snapshot less than seven days old that was captured for the same locally selected Claude configuration context (see Cache). Reset-expired windows are removed; resetless session, monthly, and credit windows expire after five hours, resetless weekly and model windows expire after seven days, and resetless unknown windows are rejected. Env-selected failures never serve stale quota. A stale Claude attention row names
fetch failedplus the usage-fetch error rather than a bare stale label. - After a successful usage read, quota-axi queries Anthropic's first-party OAuth profile endpoint with the same credential. Its authoritative root
account.uuidis exposed asaccount.accountIdonly in--fulloutput; if that field is absent,identityStatusisunverifiedinstead of deriving an identity from email, organization data, or cached account metadata.
Codex
-
Codex checks native
$CODEX_HOME/auth.jsonor~/.codex/auth.jsonOAuth first.If that does not return quota, it checks Pi ChatGPT subscription OAuth entries in
$PI_CODING_AGENT_DIR/auth.json(default~/.pi/agent/auth.json) before the CLI fallback. The built-in key isopenai-codex. Sibling keys such asopenai-codex-workfrompi-codex-accountsare enrolled from that same file when they are already present. Two or more distinct Pi entries become independent Codex account lanes; one account's failure or exhaustion does not hide or substitute another. A successful Pi-backed probe reports sourcepi:<provider-id>(pi:openai-codex,pi:openai-codex-work, …). quota-axi never readscodex-accounts.json, copies tokens, or changes Pi's active account. -
Native Codex
auth.jsonsupport is OAuth-token only; API key values such asOPENAI_API_KEYare treated as invalid for quota usage calls and are not sent to ChatGPT usage endpoints. -
Access-token JWT usability is authoritative for the native OAuth bearer probe. An expired
id_tokenalone does not markauth-jsonexpired or skip OAuth; identity-token expiry is diagnostic metadata only. A stored-expiredaccess_tokenis still probed in native OAuth's first declared source position rather than skipped, so only the usage endpoint's own rejection is an authentication verdict. A missingaccess_tokenskips OAuth and preserves the Pi and read-only CLI fallbacks. -
The Pi broker opens
auth.jsonread-only with a strict 64 KiB cap and guaranteed descriptor cleanup. It accepts only Pi's literal ChatGPT subscription OAuth shape: nonempty, control-byte-freeaccessandaccountIdstrings plus a numeric millisecondexpiresvalue. Strings containing$or beginning with!are rejected rather than resolved. Piapi_keyentries are unsupported because platform API billing is not ChatGPT subscription quota. Malformed, unsupported, expired-refreshable, and expired-non-refreshable states remain distinct diagnostics. -
quota-axi checks only whether Pi's refresh property is present; it never reads or retains the refresh-token value. It never performs a refresh-token exchange, refreshes Pi OAuth, launches Pi, or writes credential state. Pi owns refresh; quota-axi reads the current entry and sends its access token and account ID only to the existing bounded, read-only ChatGPT usage probe. Stored expiry is advisory, so the probe may test a stored-expired access token and only the endpoint's rejection marks it dead. Refresh token values are never logged, rendered, cached, or sent. Access token values are never logged, rendered, or cached.
-
It may run
codex -s read-only -a never app-serverfor Codex JSON-RPC fallback. That probe is also Codex's delegated refresh: the Codex CLI renews its own expired OAuth session and rewritesauth.jsonbefore answering, so an expired stored token still reports live quota without quota-axi touching the refresh token or spawning a second command. Codex rotates the refresh token on use, which is why the exchange stays the vendor's. -
Set
QUOTA_AXI_CODEX_BINARYto an absolute executable path when the fallback must use a specific Codex installation. Auth inspection and the app-server probe resolve the same path, and an invalid override fails closed instead of consultingPATH.
Cursor
- The Cursor editor and the Cursor CLI keep credentials in different stores, so both are independent sources and Cursor auth is usable when either one is. For quota fetching, the editor
state-vscdbsource is tried first because it never prompts; the platform CLI source is tried when the editor has no usable token or its token is rejected. Theauthcommand reports both sources. - Cursor Desktop is not required. On macOS, a CLI-only machine can refresh from the CLI Keychain token after the one-time Keychain grant described below; that quota attempt is named
cli-keychaininsourcesTried. On Linux,cursor-agentquota uses the read-onlycli-authfilesource fromauth.json; itsaccessTokenis only a bearer for the existing dashboard RPCs. The editor-credential fetch keeps its historicalapiattempt name. When credential discovery cannot produce a token, an unavailable source known to hold a credential takes precedence over a merely absent store, so a signed-incursor-agentuser sees the applicable source state rather thanCursor sign-in required. - Editor source: it uses
sqlite3 -readonlyto readcursorAuthvalues and calls Cursor's first-party dashboard RPCs. Ifsqlite3is unavailable, that source is reported as skipped withsqlite3_unavailable. - CLI source: on macOS,
cli-config.jsonholds sign-in identity only and is never a token; itsauthInfosupplies the reported account email, and the access token is read from the login Keychain itemcursor-access-token/cursor-useronly under--allow-keychain-promptor an existing account-scoped non-secret access marker. On Linux,cli-authfilereads onlyaccessTokenfrom$CURSOR_CLI_CONFIGor${XDG_CONFIG_HOME:-~/.config}/cursor/auth.json; missing, unreadable, malformed, or empty files are unavailable. The sibling refresh token is never read. - quota-axi never refreshes Cursor credentials, and Cursor has no delegated refresh. Neither the Linux auth-file refresh token nor the macOS
cursor-refresh-tokenKeychain item is read, and no non-interactivecursor-agentcommand was observed to rotate the stored session, so an expired or rejected CLI access token falls through to stale/unavailable reporting and requirescursor-agent loginoutside quota-axi. Cursor CLI session tokens are long-lived (about sixty days observed), so this costs little in practice. This is a known limitation, not a silent gap. - The token value is used only as the bearer of Cursor's read-only dashboard RPCs (
GetCurrentPeriodUsage,GetPlanInfo, andGetSandUsageStatus). It is never logged, cached, or included in any output. quota-axi does not call Grok Bot trial, banked-reset, or machine-registration methods.
GitHub Copilot
- It calls GitHub's first-party Copilot user endpoint.
- It checks two credential stores in order. Copilot's own
apps.jsonis first, and a workingapps.jsonreads exactly as before. The GitHub CLI (gh) login inhosts.ymlis second, because current Copilot sign-ins no longer writeapps.jsonand the Copilot CLI accepts aghOAuth token as a Copilot credential. A reading from the GitHub CLI login namesgh:hosts.ymlinsourcesTried. - quota-axi hands over to the GitHub CLI login only when
apps.jsonis absent, cannot be used, or its token gets HTTP 401 or 403 that is not a rate limit. A server, network, decoding, or rate-limit failure stops the search. When the GitHub CLI login answers, a presentapps.jsonthat did not answer shows as a degraded source. A rejectedapps.jsontoken keeps its attempt nameapi, as before. - From
hosts.yml, quota-axi reads only thegithub.comhost's ownoauth_token, which is the tokenghitself uses for that host. It uses a narrow block-mapping reader, not a YAML library, and it keeps no other value. Enterprise hosts, per-user token copies, and all other keys are parsed past and not kept. A file shape it cannot read with certainty is reported ascredentials_invalid, not guessed. - quota-axi never reads the OS keyring and never runs
ghorcopilotto get a token. Whenghkeeps thegithub.comtoken in the keyring,hosts.ymlholds no token for that host. The source then reportscredentials_keyring_storageas a skipped attempt. Ahosts.ymlthat cannot be read or parsed is also only a skipped attempt. Aghlogin does not prove Copilot access, so these skipped attempts never change the verdict. Aghtoken request that fails with a status other than HTTP 401 or 403, or with a network, decoding, or rate-limit failure, is a failed read. That error stays the provider verdict and is not reported as a sign-out. When every store that quota-axi can read is absent, unusable, or rejected, the provider reportsGitHub Copilot sign-in required, as before. GH_TOKEN,GITHUB_TOKEN, andCOPILOT_GITHUB_TOKENare not read.- A
ghtoken can have wider scopes than a Copilot app token. quota-axi sends it only toapi.github.com, the hostghalready sends it to, and only as the bearer of the read-only Copilot user request. - It only sends tokens associated with public GitHub hosts to that public endpoint; host-specific GitHub Enterprise tokens are treated as unavailable there.
- Neither store's OAuth token expires or carries a refresh token, so there is nothing to renew and Copilot has no delegated refresh.
Grok
- It checks two independent usability sources: Grok CLI session auth and Pi's
xaicredential in$PI_CODING_AGENT_DIR/auth.json(default~/.pi/agent/auth.json). Grok is locally usable when either source is usable, including asymmetric cases where the other source is absent, malformed, stale, or expired. True sign-out requires every applicable source to be unavailable or definitively rejected;authStatus: unusablecan also accompany an indeterminate local credential-resolution failure, but that failure remainsstate.status: errorrather thanauth_required. - Grok CLI session-scoped auth and Pi
xaiOAuth are eligible, read-only, for Grok's consumergrok_api_v2.GrokBuildBilling.GetGrokCreditsConfigoperation. The CLI source is attempted first; fresh quota makes a Pi request unnecessary, authenticated-but-unmeasurable auth falls through to Pi for numeric quota, and a transient failure stops sibling handover. CLI session-scoped entries are preferred over API-key entries. Observed Grok CLI OIDC access tokens are short-lived (about six hours on current CLI sessions) while a refresh token remains present for CLI-owned recovery. - Session-scoped Grok auth includes web/session scopes and official Grok Build OIDC records scoped to
auth.x.aiwithauth_modeorauthModeset tooidc, including scope keys with::<client id>suffixes. A consumer-operation 401/403 for official Build OIDC is followed by a GET tohttps://cli-chat-proxy.grok.com/v1/models; success proves subscription-backed model auth but that catalog carries no numeric quota, so its body is discarded. - Pi
xaiauth follows Pi's auth-file contract:type: "oauth"with literalaccess/ optionalrefresh/expires, ortype: "api_key"with a literalkey. Environment, template, and command references are not resolved. AmbientXAI_API_KEYis not a quota-axi credential source. A Pi OAuth bearer is first offered to consumer credits; if that operation rejects it,https://api.x.ai/v1/modelsis the corresponding read-only liveness check. A Pi API key establishes model usability locally (authStatus: usablewith empty windows when it cannot expose consumer quota), not grok.com credits. - The Grok CLI owns OIDC access-token refresh and rewrites
~/.grok/auth.json; Pi owns refresh of its ownauth.jsonOAuth entries. quota-axi never exchanges a refresh token, launches an agent session, or writes either auth file. Expired-session classification and recovery fields are documented under Providerstate. - When the Grok CLI session was stored-expired, carries a refresh token, and grok.com definitively rejected it, quota-axi runs
grok modelsand retries once against the file the CLI rewrote (see Delegated credential refresh).grok modelsprints the account's model list and exits: it starts no agent, opens no TUI, and spends no model quota. The delegate is skipped for a relocated store (GROK_AUTH,GROK_AUTH_JSON,GROK_AUTH_PATH), because the CLI would rotate its own default file instead. Pi'sxaientry has no delegated refresh: no non-interactive Pi command was observed to renew it, so it stays read-only. - Stored expiry is advisory within a source, never a verdict or a reason to reorder sources. Shared credential selection (
src/providers/credential-selection.ts) empirically tests stored-expired credentials in that source's declared position. A consumer-compatible bearer wins with fresh quota. An official Build/Pi OAuth bearer rejected only by consumer billing is tested against its own first-party model catalog; catalog success produces usable, unmeasurable auth instead of false expiry or sign-out. - HTTP 401/403 and auth-class gRPC codes are definitive only for the credential surface receiving them. A transient network/rate-limit failure never switches credentials or becomes an auth verdict (the stored classification stands). Such failures remain stale-cache eligible for same-source web snapshots.
- It does not send browser cookies, perform OAuth, exchange a refresh token, retain model-catalog or raw quota response bodies, or derive usage from model presence, rate-limit headers, or monetary fields. The only Grok process it ever starts is the declared
grok modelsrefresh delegate.
Kimi
- It opens Pi's
$PI_CODING_AGENT_DIR/auth.json(default~/.pi/agent/auth.json) read-only with a strict 64 KiB cap and guaranteed descriptor cleanup. It accepts only the exactkimi-codingentry, eithertype: "api_key"with a nonempty, control-byte-free literal stringkey, ortype: "oauth"with such anaccesstoken and an optional numericexpires. A stored-expired OAuth token remains eligible for the bounded read-only liveness probe in Pi's first declared source position; only the endpoint's rejection marks one dead, and a rejected expired record that still carries itsrefreshproperty reportsauthStatus: expired_refreshablewithstatus: unavailable, not sign-out. A missing file orkimi-codingentry ismissing; malformed or oversized stores, invalid entry shapes, and unsafe environment, template, or command references areinvalid; unknown credential types areunsupported; and expired OAuth isexpiredwith refresh-path presence preserved. None of these states resolves references, exposes values, or mutates Pi auth state. - If the Pi source cannot answer, it reads the official Kimi Code CLI credential from the environment
$KIMI_CODE_HOME/config.tomldescribes, defaulting to$HOME/.kimi-code/. Kimi Code keeps one credential per environment and records which one is current, so quota-axi reads[providers."managed:kimi-code".oauth]for that pointer rather than scanning or guessing: it takes onlystorage,key, andoauth_hostfrom that table andbase_urlfrom its parent (accepting either the snake_case or the camelCase spelling of the two URL keys), applies Kimi Code's own key-to-file-name rule plus its containment check, and openscredentials/<name>.json. It accepts only a non-emptyaccess_tokenwith a Unix-secondsexpires_at(a JSON number or numeric string). A token within 60 seconds of expiry is classifiedexpired, refreshably so when the record also carries arefresh_token; either way it is still tested by the bounded read-only probe in the CLI source's declared position. A successful probe returns fresh quota, a rejected refreshable record reports the softexpired_refreshableverdict, and a rejected non-refreshable record remains a hardauth_requiredfailure that retires its cache. - When
config.tomlnames no OAuth reference, quota-axi assumes only what Kimi Code itself guarantees: the unsuffixed slotcredentials/kimi-code.jsononhttps://api.kimi.com/coding/v1, the pair a mainland-China login persists, so that reading is unchanged. A file that is absent, unopenable, past the 256 KiB cap, or unparseable before its reference is reached names no reference either, and those states deliberately share the one verdict because they share their evidence - in each, quota-axi does not know what the file says. Should such a file still have recorded a non-defaultbase_url, the default slot cannot pair with it, so the result iskimi_code_cli_region_unrecognizedand no request is sent. A suffixed slot is never given an assumed deployment: with no endpoint left to place it, it iskimi_code_cli_config_invalid. - Those two states are not equally confident, and only the confident one produces a reading. No
config.tomlat all means the only slot Kimi Code could have written is the default one, so an absent file keeps the full default reading. A file that exists and could not be walked to its reference may name any slot, so quota-axi opens none: it reportskimi_code_cli_credential_unconfirmed, sends no request, and hands over to the Pi source. Nothing at a slot nobody named is read either way - not its emptiness or expiry as a sign-out, and not its contents as the current account's quota, which is what a credential left behind by a deployment the user has since left would otherwise be reported as. - A credential quota-axi cannot reach is never reported as one the user does not have: a
keyringslot iskimi_code_cli_credential_storage_unsupported, endpoints that are not one of Kimi Code's own deployments arekimi_code_cli_region_unrecognized, and configuration naming an unusable slot, or a suffixed slot with no deployment left to place it, iskimi_code_cli_config_invalid. - The Pi source always has priority. Ambient API-key environment variables are not a credential source. The CLI source is consulted whenever Pi cannot answer - no supported credential, an unreadable store, or a Pi credential the provider definitively rejected - so a broken Pi entry does not hide a working Kimi Code CLI session. Transport, decoding, timeout, cancellation, and server failures do not trigger credential switching.
- It sends one redirect-disabled
GETto<base URL>/usageswith a 15 second total deadline and a 262,144-byte decoded-body cap. That deadline also bounds how long quota-axi waits for the one reading ofconfig.tomltaken before the request, so a configuration file that never answers cannot outlast the operation; a run that cannot read it in time reports through the Pi source with no Kimi Code cache identity to reuse or stamp. The base URL travels with the credential: a Kimi Code CLI token is sent only to the deployment its own environment names, and a Pi-brokered credential, which records no deployment, keepshttps://api.kimi.com/coding/v1. A configured environment is accepted only when the endpoints it records - its OAuth host, its base URL, or whichever of the two it names - identify one of Kimi Code's two published deployments (.commainland China,.aiglobal). Slot and deployment must then agree in both directions, because Kimi Code derives the unsuffixedkimi-codeslot for the default deployment and a suffixed slot for every other: neither may appear with the other's counterpart. Configuration therefore cannot redirect the bearer to an arbitrary origin or pair one deployment's token with another's host, and an unrecognized environment sends no request at all. - It checks
refresh_tokenpresence only and never reads, renders, or exchanges its value. It never accepts an arbitrary Kimi origin, launches Pi or Kimi, makes a model request, refreshes or writes credentials, creates a device ID, imports cookies, sends device identity, retains raw responses, or exposes account, plan, token, or fingerprint data. Kimi has no delegated refresh: no non-interactive Pi or Kimi Code CLI command was established as renewing either store, so an expired record stays read-only with honest advice. - Definitive credential absence or rejection retires Kimi cache data, but only when it is the verdict that speaks for the provider: a sibling source that failed transiently outranks it, so the cache survives, and a refreshable soft-expired verdict (
expired_refreshable) is never definitive, so it also survives. Transient fallback drops reset-expired windows and applies five-hour or seven-day age bounds to windows without resets. - Because a reading can come from either Kimi Code deployment, or from a Pi credential that names neither, Kimi snapshots are cache-scoped like Claude's: each carries an opaque SHA-256 identifier for what produced it, and stale fallback reuses a snapshot only when the source whose failure is being reported asks for the identity it would have read under. A Kimi Code CLI reading is identified by the environment it was taken in; a Pi-brokered reading, which records no deployment and always asks
https://api.kimi.com/coding/v1, is identified by that source and endpoint, so its numbers are never served back as a Kimi Code deployment's stale reading. An environment quota-axi assumed rather than established is its own identity, distinct from the confirmed environment naming the same slot and host, so an unreadable or unparseableconfig.tomlreuses no snapshot at all: a mainland reading is never served to a global login that fell back to the default slot. That state withholds the cached numbers without retiring them, so the environment that produced them keeps them. Legacy context-less Kimi records are not reused. The environment identifier is derived from the resolved slot and base URL, never fromconfig.toml's bytes, so no credential in that file contributes to it and an edit that selects the same environment keeps the cache usable. It also comes from the one reading ofconfig.tomla run takes before it requests anything, never from a second reading taken afterwards, so a login that switches deployments mid-run cannot file one deployment's numbers under the other's identity. Both identifiers discriminate configuration, source, and endpoint rather than accounts, so neither distinguishes two Pi credentials.
Z.AI
- It checks two independent stores for a literal Coding Plan API key: Pi's
$PI_CODING_AGENT_DIR/auth.json(default~/.pi/agent/auth.json) first, then opencode'sauth.json($XDG_DATA_HOME/opencode/auth.jsonwhen set, otherwise~/.local/share/opencode/auth.json;%LOCALAPPDATA%\opencode\auth.jsonon Windows). Z.AI is locally usable when either source is usable. A successful Pi-backed probe reports sourcepi:zai; a successful opencode probe reportsopencode:auth.json. - Each store accepts only a nonempty, control-byte-free literal string key under a known Coding Plan provider id. In opencode's store it is taken from
key,apiKey,api_key,token,accessToken, orauth_token, or from a bare string entry. In Pi's store it must be thekeyof Pi'szaiapi_keyentry, which resolves toapi.z.ai, and a present Pizaientry of any other shape is reported asinvalidrather than missing. Environment, template, and command references are not resolved or executed, so a key that holds one is never sent as a header value. quota-axi never writes or manages Pi or opencode state. - In opencode's store, the
zai-coding-plan,zai,z-ai, andz.aiids resolve toapi.z.ai, andzhipu/zhipuairesolve toopen.bigmodel.cn; ambient API-key environment variables are not a credential source. - It sends one redirect-disabled
GETto that host's/api/monitor/usage/quota/limitwith the key in a bareAuthorizationheader (noBearerprefix), a 15 second total deadline, and a 262,144-byte decoded-body cap. The endpoint is undocumented, so normalization is deliberately schema-tolerant rather than positional. A definitive rejection for one store, either HTTP 401/403 or the vendor's HTTP 200{"code":1000,"success":false}authentication-failed body, falls through to the next store; transport, timeout, rate-limit, and server failures stop without credential switching. - Z.AI cache data is retired only when every store ends in a definitive credential failure: absence, an unparseable file or invalid entry, or a definitive rejection. The report names the highest-priority store's real failure, so a rejected or invalid Pi key is never relabeled as absence by a missing opencode entry. An auth file that exists but cannot be read is an indeterminate local failure rather than a sign-out, so it reports
state.status: errorand stays cache-eligible. Timeout, network, 408, 429, 5xx, oversized-response, and unreadable-auth-file failures may reuse a formerly fresh snapshot with reset-expired windows removed and, for windows without a reset, five-hour, seven-day, or thirty-day age bounds by window kind; a resetless untrusted unknown window has no age bound of its own and is dropped. - It never launches Pi or opencode, refreshes or writes credentials, sends cookies, retains raw responses, or exposes the account's key or plan identity beyond the plan label the endpoint reports. The Coding Plan key does not expire, so there is nothing to renew and Z.AI has no delegated refresh.
MiniMax
- It tries
MINIMAX_API_KEY, then Pi auth, then MiniMax CLI config. Within CLI config, OAuth access is tried before a co-stored API key. Candidate handover follows the Providerstaterules; it never resolves templates, commands, cookies, or refresh tokens. - It sends one redirect-disabled
GETper attempted credential to/v1/token_plan/remainsfor bearer-style keys, or/account/query_balanceforsk-api-keys. Each request has a 15 second deadline and a 262,144-byte decoded-body cap. HTTP 401/403 and application codes 1004/2049 are credential rejection; HTTP 429 and application code 1002 are rate limits, not permission to try another credential. Window normalization is documented under Provider windows. - It never launches the MiniMax CLI, performs a refresh-token exchange, writes credentials, or infers a quota from an inference request. Non-definitive failures - timeout, network, rate-limit, oversized or malformed responses, a missing quota payload, and unreadable credential stores - may reuse a formerly fresh snapshot that was captured for the same credential source and deployment host (see Cache); definitive provider-wide auth failure retires that cache only after candidates are exhausted.
MiMo
- It reads only the literal
MIMO_API_KEYenvironment value used by the local Pi provider configuration. - MiMo's provider-owned setup exposes model authentication but no established read-only quota operation. A usable key therefore yields
authStatus: usablewithwindows: []; quota-axi never probes an inference endpoint, sends cookies, or claims a model scope.
DeepSeek
- It reads only a literal
DEEPSEEK_API_KEYor the literaldeepseekentry in Pi's$PI_CODING_AGENT_DIR/auth.json(default~/.pi/agent/auth.json). Environment, template, and command references are rejected rather than resolved. - It sends one redirect-disabled
GETper attempted credential to DeepSeek's first-party/user/balanceendpoint with a bearer token, trying the environment key before Pi under the credential handover rules. The balance representation is documented under Provider windows. - It never launches DeepSeek tooling, refreshes or writes credentials, sends cookies, or retains raw responses.
OpenRouter
- It reads only a literal
OPENROUTER_API_KEYor the literalopenrouterentry in Pi's$PI_CODING_AGENT_DIR/auth.json(default~/.pi/agent/auth.json). Environment, template, and command references are rejected rather than resolved. - It sends one redirect-disabled
GETper attempted credential to OpenRouter's first-party/api/v1/keyendpoint with a bearer token, trying the environment key before Pi under the credential handover rules. Key-cap representation is documented under Provider windows; reset text comes only from the endpoint. The endpoint'sdata.labelis a per-key nickname rather than an account identifier, so it is exposed asaccount.accountIdwithidentityStatusunverifiedin--fulloutput. - It never launches OpenRouter tooling, refreshes or writes credentials, sends cookies, or retains raw responses.
Antigravity
- It never restarts, signs in to, configures, or mutates Antigravity or
agy. It reads no credential store, so it has no delegated refresh. It prefers runningagy -p "/quota" --output-format jsononce with a 15 second bound; this is the vendor's noninteractive read-only usage command (a bounded read, not an agent session or credential operation). When the CLI is unavailable or fails, it falls back to existing loopback access. Loopback HTTP 401 carryingmissing CSRF tokenis treated asunavailable(not signed-out) and retains the cached record. Any reading whoseresetsAtis in the past is marked stale. - On macOS and Linux, it discovers only the current user's processes and their owned listening ports, then sends read-only POST requests with operation-specific bodies to local endpoints on
127.0.0.1. On macOS, an app language server qualifies only when the executable path itself is inside an.appbundle whose name containsAntigravity, including bundle names with spaces; wrapper or prompt text that merely mentions such a path does not qualify. An app-advertised extension port is eligible only when the same process owns its listener. - For loopback access, it uses
RetrieveUserQuotaSummarywith the vendor's read-onlyrequest: {}/forceRefresh: falseenvelope, forwards a runtime CSRF token only when an app process advertises one, usesGetUserStatusfor plan identity and account identity exposed only behind--full, and can fall back to model quota data fromGetUserStatus/GetCommandModelConfigswhen grouped quota summary is unavailable. Conversation text, token counters, and subprocess error output are discarded. - Percent remaining and reset times come only from vendor
remainingFraction/resetTimefields. It does not invent windows, resets, or percentages. - Burn rate is not reported for Antigravity v1 because the local payload exposes point-in-time quota snapshots, not enough history to compute a rate honestly.
Command Code
- It consults local API-key sources in a fixed order: Pi's
$PI_CODING_AGENT_DIR/auth.jsoncommandcodeentry first (default~/.pi/agent/auth.json), then$COMMAND_CODE_API_KEY, legacy$COMMANDCODE_API_KEY, production~/.commandcode/auth.jsontop-levelapiKey, then~/.omp/agent/auth.jsoncommandcode/command-code. A process--api-keyis not observable and is not guessed. Environment, template, and command references are rejected rather than resolved. Staging/local Command Code auth files are not read, and the API origin is fixed athttps://api.commandcode.ai. - Pi's Command Code login stores a non-expiring API key in OAuth-shaped fields. quota-axi ignores stored expiry, never reads the duplicate refresh value, and never labels the credential
expired_refreshable. A stored-expired access value is still probed in Pi's declared position. - It sends two redirect-disabled
GETs through the shared proxy-aware transport:/alpha/whoami?limits=1then/alpha/billing/creditswithorgIdonly whenwhoami.org.idis a non-empty string. A 15 second total deadline and a 262,144-byte decoded-body cap apply. OnlywhoamiHTTP 401 is a definitive auth rejection for that key; HTTP 403 and transport failures are not sign-out. A livewhoamikeepsauthStatus: usableeven when the credits call fails. - The
/alphaaccount endpoints are undocumented first-party surfaces (the public Provider API documents model routes only, which quota-axi never calls). Normalization fails closed: missing credit components omitcreditsrather than treating them as zero;limited:falseis credit-only and leftover five-hour/weekly fields are omitted from trusted windows;limited:truewith a missing expected window emits an untrusted placeholder; unknownwindowLimitsentries and non-empty organization spend limits are untrusted/partial until their contract is independently established. - Extra pay-as-you-go credits can bypass the rolling windows, so effective availability is published only for
included_credits. No monthly percentage, USD unit, 30-day reset, or unlimited status is invented. A credit-only reading (no rolling windows) still reports its raw balance: default TOON names it as acreditsattention row and--tuistates it on the card, instead of ano_quotarow that would contradict the same run'scredits. - Command Code has no delegated refresh.
ProviderOptions.refreshCredentialsis ignored. quota-axi never runs Pi,cmd, or Command Code, never writes credentials, and never prints token values. - Because several sources can point at different accounts, Command Code snapshots are cache-scoped: each carries an opaque SHA-256 of the winning source plus the account identity
whoamiestablished. Stale fallback is available only after a successfulwhoamimatches that context. A credits failure after a confirmed identity may reuse pruned same-context windows, and it defines the report over an earlier context-less source failure so that fallback stays reachable; a failed or unidentifiedwhoamipreserves the old snapshot without serving it and neither caches nor clears that provider's existing record. Fresh identified credit-only success (windows: []) clears an old window snapshot. Definitive all-source auth failure retires the cache.
ElevenLabs
- ElevenLabs' character allowance is a subscription allowance with a reset date, not metered platform billing, which is why it is reported here at all. It is a speech allowance rather than a coding-agent lane; it is published as its own
included_charactersscope and never bounds a model. - The one credential source is
$ELEVENLABS_API_KEY, and it is read as an explicitly supplied credential rather than as an ambient one. It is the variable ElevenLabs' own CLI documents for non-interactive use (export ELEVENLABS_API_KEY=xi-..., sent as thexi-api-keyheader), so a value there names the account the user put there on purpose - the same reasoning that makes$COMMAND_CODE_API_KEYand$CLAUDE_CODE_OAUTH_TOKENcredential sources. Absent, empty, and whitespace-only values select nothing; a non-blank value that is not a usable literal secret is reported as anenvsource problem rather than sent as a header. elevenlabs auth loginstores an OAuth bundle in the OS keyring, falling back to<config dir>/elevenlabs/auth-keyring.json. That store is deliberately not read: its entry is an opaque token bundle whose shape this tree has not established, and guessing at one would risk sending the wrong string as a credential. A user who wants quota-axi to see that account exports the key instead.- It sends one redirect-disabled
GET https://api.elevenlabs.io/v1/user/subscriptionthrough the shared proxy-aware transport, authenticated with thexi-api-keyheader and never withAuthorization. A 15 second deadline and a 262,144-byte decoded-body cap apply. The key leaves the process only as that header: it is never printed, logged, cached, or written into a fixture. - HTTP 401 is a definitive auth rejection unless its bounded JSON body carries
detail.status: missing_permissions. That recognized permission error and HTTP 403 are not sign-out: ElevenLabs keys carry scope restrictions (the subscription read needs theuser_readpermission) and an optional IP allowlist, either of which rejects this one operation while the key stays live. It is reported aselevenlabs_user_read_deniedwithauthStatus: usable, and it preserves the cache. Provider error messages are never retained. - ElevenLabs has no delegated refresh and no vendor rotation command.
ProviderOptions.refreshCredentialsis ignored, and the key has no expiry field, so no candidate is ever skipped before the endpoint itself has answered. - Because the key is the account, ElevenLabs snapshots are cache-scoped by an opaque SHA-256 of the answering source plus a one-way digest of that key. A different key gets a different identity, so a rotated or second key never inherits the previous subscription's windows, and the key itself never enters the cache. A definitive rejection retires only a snapshot whose identity matches the rejected key; absent or locally invalid keys leave the snapshot intact.
Delegated credential refresh
quota-axi reports quota; it is not an auth app. It never mints a credential, never rotates one, and never performs a refresh-token exchange over HTTP. Those refresh tokens rotate on use, so a second holder performing the exchange would spend the vendor's own single-use token and sign the user out of the harness being measured.
Instead, when the same stored access token is expired, carries a refresh token, and is definitively rejected, quota-axi may run the vendor CLI's own smallest non-interactive command that already owns rotation, then re-read the store that CLI rewrote and retry the same read-only quota request once. Rotation is always the vendor's; quota-axi only reads the result.
| Provider | Vendor-owned recovery path | Store the vendor rewrites |
|---|---|---|
| Claude | claude doctor delegate | the Claude Code Keychain item, or .credentials.json |
| Codex | existing app-server quota probe | $CODEX_HOME/auth.json |
| Grok | grok models delegate | $GROK_HOME/auth.json |
| Cursor, GitHub Copilot, Kimi, Z.AI, Alibaba, OpenCode Go, Antigravity, Command Code, MiniMax, MiMo, DeepSeek, OpenRouter, ElevenLabs | none | read-only; see the per-provider notes below |
The Claude and Grok delegated runs are bounded the same way:
- Fixed argv declared in this repository, resolved through
PATH(or a provider's absolute binary override), never through a shell and never assembled from provider responses, configuration, or user input. - No interactive surface: the child gets no stdin, so a vendor command that would prompt exits instead of waiting;
TERM=dumb,NO_COLOR=1, and the vendors' ownNO_BROWSER/NO_OPEN_BROWSERopt-outs are forced. No delegate opens a browser, starts a session, or spends the quota being measured. - A wall-clock budget that bounds how long quota-axi waits, never how long the vendor may run. quota-axi never signals a delegated run: the command is the vendor performing a single-use OAuth refresh-token exchange against its own store, and interrupting one part way through is the sign-out this whole design exists to prevent. When the budget expires quota-axi stops waiting, leaves the vendor running, and reports the refresh as unconfirmed. The delegate also runs in its own process group, so a Ctrl+C that quits a live
--tuicannot land on a vendor mid-exchange. - At most one delegated refresh per credential source per quota read. That bound is per read rather than per process, so a long-running
--tuistill recovers from a session that expires while it is up. - Vendor output is discarded at the operating system, never read. A credential is never parsed out of a vendor's stdout; the refreshed value only ever comes from re-reading the vendor's own store.
- It runs only for soft expiry: a stored-expired credential that carries a refresh token and was definitively rejected. Transient failures, missing or malformed stores, stored-valid credentials the server revoked, and relocated stores the vendor would not rewrite all stay read-only.
- Claude adds a best-effort check before delegating: the process list must show no Claude Code process. Claude Code owns that session and refreshes it on its own schedule, so
claude doctoralongside a live session is at best redundant and at worst a second holder racing a single-use refresh token. This also means a detachedclaude doctorthat outlives quota-axi's wait is visible to the next read, which stays read-only instead of stacking another refresh on it. Not knowing counts as not safe: where the process list cannot be read (Windows, no effective uid, nops), quota-axi stays read-only rather than guessing. The check and spawn are not atomic, so a Claude Code session starting after the check or another concurrent quota-axi read can still overlap the delegate. This narrows the common repeated five-minute--tuiversus live-session collision and, together with never signaling the delegate, is strictly safer than force-killing without adding a failure mode beyond the pre-existing vendor-owned race. --no-credential-refreshdisables it entirely, the read-onlyauthcommand never delegates a refresh, and neither does--profile-only.
A Claude or Grok delegated run appears in --full output as its own attempt (claude-cli-refresh, grok-cli-refresh). Its error says what happened, so a report shows why no refresh took place:
| Attempt error | Meaning |
|---|---|
refresh_command_not_found | The vendor CLI is not installed, so there was nothing to delegate to (skipped). |
refresh_spawn_failed | The vendor command could not be started. |
refresh_live_vendor_process | Claude Code is already running and owns its own refresh (skipped). |
refresh_vendor_processes_unknown | quota-axi could not read the process list, so it stayed read-only (skipped). |
refresh_timed_out | The vendor outran quota-axi's wait and was left running; the outcome is unknown. |
refresh_exit_status | The vendor ran and exited non-zero; the store was still re-read. |
A refresh_timed_out run is never treated as a credential verdict. Claude reports that read as unmeasured (claude_refresh_unconfirmed), falling back to a stale cached snapshot when one applies, and keeps the cached snapshot rather than retiring it. On Windows, a resolved .cmd or .bat command shim runs through the platform command interpreter without enabling Node's shell mode, preserving the no-shell argument boundary. Quota accuracy and the no-shell safety guarantee are unchanged. Codex needs no extra spawn: its existing read-only cli-rpc app-server probe both refreshes auth.json and returns the rate limits, so an expired Codex token already reports live quota through the vendor CLI.
Providers with no established non-interactive rotation command stay read-only on purpose. That is a documented limitation rather than a reason to force an unsafe path: Cursor's CLI token is long-lived and no non-interactive cursor-agent command was observed to rotate it, GitHub Copilot's stored OAuth tokens (in apps.json and the GitHub CLI's hosts.yml) do not expire, Z.AI uses a non-expiring API key, Alibaba is accessed through the read-only bl usage command, OpenCode Go has no vendor-owned rotation command, Pi-owned OAuth entries (openai-codex, xai, kimi-coding, commandcode) have no non-interactive Pi refresh command, Command Code API keys do not expire, ElevenLabs API keys do not expire either, and Antigravity exposes no credential store at all.
Safety guarantees
- Quota and auth HTTP requests go only to first-party provider usage, quota, billing, entitlement, or read-only credential-liveness endpoints with the user's local credentials; quota-axi's direct Antigravity requests stay on 127.0.0.1 loopback.
- The user-initiated
updatecommand is the only outbound non-provider network surface, and it is not part of quota measurement. - It sends credential values only to the first-party provider request they authenticate.
- It never prints, logs, or caches credential values.
- It never mints, rotates, or writes a credential, and never performs a refresh-token exchange. Credential renewal is always delegated to the vendor CLI that owns the store (see Delegated credential refresh).
- It never retains, prints, logs, renders, caches, sends, or exchanges a refresh token's value. The Pi credential brokers read a stored refresh value only to derive a usability boolean - whether it is a usable literal secret rather than absent or an environment, template, or command reference - and discard it immediately; elsewhere only its presence is checked, as evidence that the vendor can still recover.
- It never launches the Cursor, GitHub (
gh), Copilot, Pi, Kimi, MiniMax, OpenCode, Command Code, or ElevenLabs CLIs. It runs the read-only Alibabablusage command, the declared read-only Codex app-server probe, Antigravity's noninteractive structured/quotaread (agy -p "/quota"), preferred ahead of its loopback access, and the two declared refresh delegates (claude doctor,grok models); none starts an agent session or spends the quota being measured. The one explicit exception is--allow-claude-inference, whose fixed native Claude request spends inference quota and is documented above. - It never signals or kills a delegated refresh. A vendor that outruns quota-axi's wait is left to finish its own token exchange, and quota-axi reports an unconfirmed refresh instead of a credential verdict.
- It never routes, ranks a winner, or orders providers preferentially. Derived comparative signals, including
effectiveAvailability[].selection, are published as data for the consumer to act on.
Cache
| Item | Behavior |
|---|---|
| Quota cache | Lives at ~/.cache/quota-axi/quotas.json or under $XDG_CACHE_HOME/quota-axi/ when XDG_CACHE_HOME is set. |
| Quota cache permissions | Uses 0600 file permissions. |
| Quota cache contents | Stores normalized non-secret snapshots only. |
| Claude Keychain access marker | Lives alongside the quota cache as claude-keychain-access-granted-<service-hash>-account-<account-hash>, where the service hash is eight hexadecimal characters and the account hash is sixteen. It uses 0600 file permissions, contains no credential material, raw account name, or raw service name, and markers written by earlier versions are ignored rather than deleted. |
| Cursor CLI Keychain access marker | Lives alongside the quota cache as cursor-cli-keychain-access-granted-account-<account-hash>, where the account hash is sixteen hexadecimal characters. It uses 0600 file permissions and contains no credential material or raw account identity. |
| Cached reports | Only fresh provider snapshots with windows are cached. Cache schema 3 slots one snapshot per provider plus accountKey; a snapshot with no key holds that provider's default slot, and the filler default key an expanded report stamps on single-account providers is never written, so a stale reading can never expand a report in which nothing expanded. Each lane reads only its own slot, and a slot name alone cannot say which account signed in there, so a provider whose slot can be rebound stamps the snapshot with its own account identity (see Codex cache identities below). Schema 1 and 2 files without accountKey remain readable. A context-scoped snapshot for Claude, Kimi, Command Code, MiniMax, or ElevenLabs is written only when the current reading supplies its context identity. |
| Fresh provider reports with no windows | Clear any cached snapshot for that provider/account lane, so entitlement-only reports do not leave stale quota windows behind. Claude, Kimi, Command Code, MiniMax, and ElevenLabs skip both cache write and clear when the current reading has no context identity. |
| Reports and details not cached | Failed providers, stale providers, account identity, and source attempts are not cached. Claude native inference readings (source: cli) are excluded from both cache writes and clears, leaving existing stored-session snapshots untouched. |
| Claude cache fallback | Follows the Claude provider rules, including the denied-Keychain exception. Eligible fallback uses a formerly fresh snapshot from the same selected Claude configuration context, with a seven-day provider bound plus reset and resetless-window pruning. Its opaque SHA-256 context identifier includes the configuration directory and the selected Keychain service, which already encodes any secure-storage selector. Legacy context-less records and snapshots from the earlier broad suffix-discovery context are withheld without deleting them. |
| Codex cache identities | Cached Codex windows are accepted only when ID, label, kind, duration, and duplicate suffix order agree; stale snapshots with mismatched identities are rejected. A snapshot also records an opaque SHA-256 identifier of the ChatGPT account id the credential that produced it stored, and is withheld when the credentials a failed reading actually tried store only other accounts' ids, because a slot name alone cannot say whose windows it holds: a credential that reading never tried does not vouch for the snapshot, and a probe that fails transiently is vouched for only by its own credential. The vendor's response id is not the stamp: it can differ from the store while the same token is live, and a failed probe only has the store. A snapshot without that identifier, or a run whose credentials name no account, proves nothing either way and is still reused. |
| Grok cache provenance | Only snapshots produced by the current web consumer operation can be used as Grok stale fallback; legacy api billing-proxy snapshots are rejected. |
| Kimi cache provenance | Follows the Kimi provider rules: a snapshot is reused only when its opaque SHA-256 identifier still matches the source that produced it - the selected Kimi Code environment, or the Pi source and its default endpoint - and legacy context-less Kimi records are not reused. A reusable snapshot written before shareOf existed stores month_code with percentUsed alone, so reading it restores the shareOf: month_total marker; a stale fallback after upgrading therefore still presents that window as a used share rather than as missing data. |
| Command Code cache provenance | Follows the Command Code provider rules: a snapshot is reused only after the current whoami identifies the account and the opaque SHA-256 source-plus-account identifier still matches; a failed or unidentified whoami cannot select stale data from an unknown account and does not cache or clear the existing record. |
| MiniMax cache provenance | Follows the MiniMax provider rules: a snapshot is reused only when its opaque SHA-256 identifier still matches the credential source and deployment host that produced it, and legacy context-less MiniMax records are not reused. |
| ElevenLabs cache provenance | Follows the ElevenLabs provider rules: each snapshot carries an opaque SHA-256 of the answering source plus a one-way digest of the key that produced it, and stale fallback requires that identity to match. A reading with no usable key neither caches nor clears the record, and a cached window whose own reported reset has already passed is never served. |
Development
pnpm install # Install dependencies
pnpm run build # Compile TypeScript to dist/
pnpm run lint # Run ESLint
pnpm run format:check # Check Prettier formatting
pnpm test # Run fixture parser and CLI tests
pnpm run build:skill -- --check # Verify the generated skill is current
pnpm run dev # Run the CLI with tsx
Contributing
See CONTRIBUTING.md for the no-mistakes PR workflow, generated-file rules, and release-please conventions.
License
MIT