Skip to content
المشاريع

Dicklesworthstone/coding_agent_usage_tracker

عرض على GitHub

حول

Single CLI to monitor LLM coding-agent usage across 16+ providers (Codex, Claude, Gemini, Cursor, Copilot, and more): remaining quota, rate limits, and credits as terminal tables or JSON/Markdown, plus an MCP server for agents.

أدوات التطوير

كيف تُقاس هذه الأرقام

النمو المقاس للنجوم

خلال 24 ساعة
جارٍ جمع السجل
خلال 7 أيام
جارٍ جمع السجل
خلال 15 يومًا
جارٍ جمع السجل
خلال شهر
جارٍ جمع السجل

تغيّر صافي النجوم خلال فترات متداخلة، وليس مجموعًا يوميًا. تبقى القياسات المفقودة فارغة. النجوم تقيس الاهتمام لا جودة البرمجيات.

README.md

الأصل

caut - Coding Agent Usage Tracker

caut

Coding Agent Usage Tracker — monitor LLM provider usage from a single CLI

License: MIT+Rider Rust 1.89+


Quick Install

# From source (recommended)
cargo install --locked --git https://github.com/Dicklesworthstone/coding_agent_usage_tracker

# Then run
caut usage

TL;DR

The Problem

You're using multiple AI coding assistants—Codex, Claude, Gemini, Cursor, Copilot—each with different rate limits, credits, and usage dashboards. Tracking your remaining quota means:

  • Opening 5+ browser tabs
  • Remembering different login flows
  • Mentally aggregating disparate data formats

The Solution

caut fetches usage data from 16+ LLM providers through a single CLI command. Human-readable tables for your terminal, or structured JSON/Markdown for AI agents to consume.

$ caut usage

╭─ Codex (openai-web) ─────────────────────────────────────╮
│ Session  72% left   [========----]  resets in 2h 15m     │
│ Weekly   41% left   [====--------]  resets Fri 9am       │
│ Credits  112.4 left                                      │
│ Account  [email protected]                                │
│ Plan     Pro                                             │
╰──────────────────────────────────────────────────────────╯

╭─ Claude (oauth) ─────────────────────────────────────────╮
│ Chat     85% left   [==========--]  resets in 4h         │
│ Weekly   62% left   [======------]  resets Mon 12am      │
│ Opus     45% left   [====--------]  separate tier        │
│ Account  [email protected]                              │
╰──────────────────────────────────────────────────────────╯

Why caut?

Feature caut Manual Checking
Single command caut usage --provider all Open 5+ dashboards
Rate limit tracking Session + weekly + opus tiers Mental math
Credits monitoring Real-time balance Refresh each page
Status awareness Provider outage alerts Check status pages
Robot mode JSON/Markdown for agents N/A
Cross-platform macOS, Linux, Windows Browser-only
Cost tracking Local JSONL scanning Export CSVs manually

AGENTS.md

This project includes an AGENTS.md file with detailed guidelines for AI coding agents. If you're an AI assistant working on this codebase, read that file for:

  • Toolchain requirements (Rust 2024, nightly)
  • Code editing discipline and patterns
  • Testing and CI/CD requirements
  • Multi-agent coordination via MCP Agent Mail
  • Beads workflow integration

Design Philosophy

1. Dual-Mode Output

Human mode uses rich terminal formatting with colored bars, panels, and progress indicators. Robot mode emits stable JSON/Markdown schemas designed for token efficiency when consumed by AI agents.

# Human mode (default)
caut usage

# Robot mode for AI agents
caut usage --json
caut usage --format md

2. Provider Abstraction

Each of the 16 providers has a descriptor with metadata, branding, and fetch strategies. Adding a new provider means implementing one trait—not touching core logic.

┌─────────────────────────────────────────────────────────┐
│                   Provider Registry                      │
│  ┌─────────┐ ┌─────────┐ ┌─────────┐ ┌─────────┐       │
│  │  Codex  │ │ Claude  │ │ Gemini  │ │   ...   │       │
│  └─────────┘ └─────────┘ └─────────┘ └─────────┘       │
└─────────────────────────────────────────────────────────┘

3. Fail Gracefully

Network timeouts, missing credentials, and provider outages are handled with clear error messages and partial results—never crash, always inform.

4. Zero Configuration

Works out of the box by detecting installed CLI tools and browser cookies. Optional config file for power users who want to customize behavior.

5. CodexBar Parity

A faithful port of CodexBar's CLI functionality to cross-platform Rust, preserving all commands, flags, and output formats.


Comparison

Feature caut CodexBar Manual
Platform macOS, Linux, Windows macOS only Any
Language Rust Swift N/A
Providers 16+ 16 1 per tab
Robot mode JSON + Markdown JSON None
Installation Single binary App bundle N/A
Menu bar UI No (CLI only) Yes No
Memory usage ~10MB ~50MB Varies
Startup time ~10ms ~500ms N/A

Origins

caut is a cross-platform Rust port of CodexBar by Peter Steinberger. CodexBar is a beautiful macOS menu bar app for tracking AI coding tool usage. caut brings that functionality to the command line, running anywhere Rust compiles.

Author: Jeffrey Emanuel


Installation

From Source (Recommended)

git clone https://github.com/Dicklesworthstone/coding_agent_usage_tracker
cd coding_agent_usage_tracker
cargo install --locked --path .

From Git

cargo install --locked --git https://github.com/Dicklesworthstone/coding_agent_usage_tracker

Requirements

Requirement Version Notes
Rust 1.89+ Package minimum; source checkout selects the pinned nightly below
C compiler Platform toolchain Builds the bundled SQLite library
SQLite Bundled No separately installed SQLite library or headers required

The checkout uses nightly-2026-08-31 from rust-toolchain.toml, including rustfmt and clippy. Its Cargo configuration enables nightly compiler options; run the source-build commands with that toolchain. Keep --locked to use the tested dependency versions.

Verify Installation

caut --version
# caut 0.1.0 (abc1234 2026-01-18)

Quick Start

1. Check Your Usage

# Primary providers (Codex + Claude)
caut usage

# All configured providers
caut usage --provider all

# Specific provider
caut usage --provider gemini

2. View Cost Data

# Claude and Codex local cost scans (the default)
caut cost

# Include Gemini CLI conversations
caut cost --provider all

# Force refresh cached data
caut cost --refresh

3. Robot Mode for AI Agents

# Compact JSON (one line)
caut usage --json

# Pretty-printed JSON
caut usage --json --pretty

# Markdown output
caut usage --format md

4. Include Status

# Check provider operational status
caut usage --status

Gemini reports Google Cloud Service Health incidents for Gemini Code Assist. Vertex AI reports incidents for Gemini on Agent Platform and online inference. Both use the same cached feed. The displayed incident is the most severe active one affecting the selected service, with its latest update time.


Commands

caut (no args)

Prints quickstart help with top commands and examples.

caut status

Check public service health without credentials. Run caut status for every provider, caut status both for Codex and Claude, or caut status claude for one service. Use --json or --format md for structured output. Status is cached for one minute across invocations. Use --refresh to fetch immediately.

caut status claude --quiet produces only an exit code. A major or critical incident returns 2, a minor incident or maintenance returns 1, and operational services return 0. If any monitored feed is unavailable and there is no known incident, the result is 3. Providers without a registered public feed appear with a null status in JSON and only determine the exit code when no selected provider has a feed.

caut usage

Show rate limit usage for selected providers.

USAGE:
    caut usage [OPTIONS]

OPTIONS:
    --provider <NAME|both|all>  Provider selection (default: both)
    --account <LABEL>           Use specific account
    --account-index <N>         Use account by index (1-based)
    --all-accounts              Query all configured accounts
    --no-credits                Hide credits in human output
    --status                    Fetch provider status
    --offline                   Read saved usage without contacting providers
    --source <auto|web|cli|oauth>  Data source preference
    --web                       Shorthand for --source web
    --timeout <SECONDS>         Per-provider fetch timeout override
    --web-timeout <SECONDS>     Web fetch timeout (default: 30)
    --watch                     Refresh continuously
    --interval <SECONDS>        Refresh interval (default: 30)
    --tui                       Interactive dashboard; implies watch mode

Successful usage fetches save an observation scoped to the credential, account, source and API endpoint. A transient network or service failure can return that saved observation with a visible age badge and a cache object in JSON. The original error and nonzero exit status remain available to automation. Use --offline to explicitly read saved data without making network requests. Cached observations retain their original timestamps and do not create new history samples, renew the shell-prompt cache or drive account recommendations. Ambient z.ai and Copilot API credentials use the same validated credential and endpoint as live requests for this scope. Changing either prevents reuse of the previous login's data, including an observation still in flight. Copilot's gh-only login needs an explicit token for offline caching because the CLI's active account cannot be established by the passive credential check.

Continuous watch and the direct terminal dashboard keep separate provider cooldowns. A provider's Retry-After delay pauses its requests while healthy providers continue polling. Manual dashboard refreshes share those cooldowns. Retained account observations show their original age and degraded provenance; changing credentials removes the previous login's displayed data. Authentication failures can recover when the selected credentials change, while provider rate limits remain in force. Automatic polling records periodic history observations.

Fresh usage observations automatically include time-to-limit forecasts in human, JSON and Markdown output, including repeated --watch refreshes:

caut usage --provider codex --watch
caut usage --provider claude --json --pretty
caut usage --provider codex --account work --format md

The optional JSON forecasts object contains forecastAsOf, primaryForecast, scopedForecasts for individual model quotas, and providerCostForecast for a provider spending cap. Each forecast reports whether the limit is reached, likely to be reached before reset, or sustainable until reset. Human and Markdown output explain the evidence as recent history or window pace. Codex, Claude, OpenCode Go, Factory and z.ai also expose secondaryForecast for their weekly allowance; Kimi uses that field for its separate five-hour allowance. Factory, OpenCode Go and z.ai expose tertiaryForecast for their monthly allowance. Each uses that allowance's own observations and reset time. For example, watch can warn that weekly or monthly quota will run out even when the session limit is healthy. Model-specific Claude limits use named scoped forecasts so switching between Opus and Sonnet cannot mix their consumption histories.

Gemini family summaries follow the exact selected model's named history, and Copilot premium summaries keep request and credit allowances separate. A change in which model leads a summary cannot manufacture a consumption trend. MiniMax preserves every named model's history, including models promoted into summary slots. Older captures without that identity cannot establish a model's trend; the report waits for usable named observations. Ambiguous summaries use only available window-pace evidence while named model forecasts remain independent.

Recent-history estimates use only the selected account's observations from the six hours before the provider observation. forecastAsOf is that observation's timestamp; reading it later does not invent another sample, change its pace or renew its freshness. Repeated observations at the same timestamp count once. Stable token IDs or the provider's email and organization keep accounts separate even when display labels coincide or change. Ambiguous account labels and history failures remain visible through historyError; they never cause histories from different accounts to be combined.

When a provider supplies no account identity, verified credential scopes keep its measured history and alert cooldowns separate. These internal scopes are not exposed in JSON or treated as saved token accounts. Missing or incompatible quota observations break a history trend instead of joining unrelated windows.

With insufficient history, a primary quota can use window pace when its duration and reset are known; otherwise it reports insufficientData. Scoped and spending forecasts also include sample counts and reasons when an estimate is unavailable. Spending uses its counter's own observation timestamp and reported currency or credit units. Offline observations and failed-refresh fallbacks omit forecasts, so an old estimate is never presented as newly calculated live usage.

Gemini usage reads the Google sign-in created by gemini, including a relocated GEMINI_CLI_HOME, and refreshes expired OAuth credentials when a refresh token is available. It reports model-specific Code Assist quotas and supports named token accounts. Gemini API keys do not expose Code Assist subscription quotas.

Claude OAuth also accepts CLAUDE_CODE_OAUTH_TOKEN for headless monitoring:

caut usage --provider claude --source oauth --json

Set the token in the process environment before starting caut. A selected saved account takes precedence; otherwise this override wins over the keyring and Claude Code's credential files. Account identity stays unknown, and an opaque token has no locally readable expiration. Doctor reports this source without borrowing metadata from a local login. Automatic fetching stops if this token fails; an explicit --source web or --source cli still selects that source. Offline results and the shell prompt are isolated by the token. Environment tokens carry no refresh credential: replace an expired token and restart caut, or unset the variable to return to the local Claude Code login. See the Claude Code environment reference.

For native Claude file logins, a rejected access token can recover when Claude Code has already persisted a replacement. On HTTP 401, caut rereads the same credential file once and retries only when the original account and organization IDs still match and the replacement token is well formed and not expired. It verifies a fresh quota measurement within the original timeout before saving history or offline data. Claude Code continues to own renewal and credential persistence. Expired logins remain authentication errors, and other OAuth failures stay visible to monitors. The corresponding failure or rate-limit cooldown applies, with cached observations retained only for the same credential scope. Use Claude Code's normal login flow when no replacement is available. Explicit --source cli and --source web remain available.

Claude's CLI source reads authentication status without starting a conversation. caut checks claude --help and claude auth --help before invoking the supported claude auth status command; older CLIs fall back to local identity metadata. This source reports identity only. Use OAuth, web, or the local capture below for Claude quotas; authentication status alone leaves usage unknown.

Claude Code status line quota capture

Claude Code can pass its observed subscription quotas directly to caut. Merge this setting into your Claude Code settings (normally ~/.claude/settings.json), with caut available on the command's PATH:

{
  "statusLine": {
    "type": "command",
    "command": "caut claude-statusline"
  }
}

After sending a message in Claude Code, read or watch the capture:

caut usage --provider claude --source local --json
caut usage --provider claude --source local --watch
caut usage --provider claude --source local --offline --json

The status line prints the known five-hour and seven-day percentages, plus a gateway spend-limit percentage when supplied. It uses Claude Code's documented rate_limits fields. They are available after the first API response for supported subscription or gateway sessions. Context utilization and estimated session cost are separate measurements and are not treated as quota.

This source requires explicit --source local. The latest reporting session in the resolved CLAUDE_CONFIG_DIR (default ~/.claude) owns the capture; it is not attributed to an installed login or a selected saved token account. Use the same configuration directory when capturing and reading. Only normalized quota data and hashed profile/session identifiers are saved, without native credentials, transcript paths, or session metadata.

Local reads discard reset windows and reject captures older than one hour. Repeated unchanged status line frames do not extend their age. An empty initialization frame invalidates the previous capture, so offline mode cannot revive it. Explicit offline reads return the last saved observation with its original timestamps, while the same reporting session still has current quota.

caut dashboard and caut usage --tui

Monitor providers in an interactive terminal, or use the usage command's account selectors to show saved logins across providers:

caut dashboard --provider both --interval 30
caut usage --provider claude --all-accounts --tui

Panels identify saved account labels and show available quota windows, model-specific allowances and spending caps. Reset countdowns use the provider's reported reset timestamp; a window duration alone does not imply a reset time. Available forecasts include their observation time and evidence. Cached data and failed refreshes retain the observation age and omit forecasts.

Key Action
Arrow keys or h / j / k / l Move between panels in the current grid
Enter or Space Expand the selected account; press again to return to the grid
r or F5 Refresh now
? or F1 Show help
q, Esc or Ctrl+C Quit

The layout adapts to the terminal size and pages through accounts as selection moves. Refreshes preserve the selected provider and account when it remains available.

To browse the accounts accumulated by a running daemon, use its saved observations as the dashboard source:

caut daemon start --provider both --interval 60
caut dashboard --daemon
caut dashboard --daemon --provider claude --interval 10
caut dashboard --daemon --pid-file ./monitor.json --api-token-file ./caut-api-token

Daemon mode defaults to all observed providers. It polls /accounts at the chosen interval, using the same discovery and authentication as caut query. It does not fetch provider credentials or switch installed provider logins. Press Tab/Shift+Tab to change the provider filter and o to cycle account order within each provider: reported headroom, name, or observation recency. Selection tracks the stable account ID through sorting, refreshes, and label changes.

Press H on an account to open its saved history for the last seven UTC days. The history view shows daily average and peak primary quota usage, a trend sparkline, and observed daily cost in USD. Missing observations remain marked as unknown; they are not treated as zero. The current day is shown through the read time, and each view identifies the stable account ID it belongs to. Use the arrow keys to browse other accounts, r to reload, H to return to quota details, or Enter to return to the grid. These reads use stored history without calling the provider. If a history read fails, the previous results remain visible with their original read time and an explicit warning.

The fleet summary distinguishes available, near-limit, limit-reached, blocked, stale, and unknown observations. Blocked means the provider explicitly denied ordinary requests at the observation time. Measured percentages stay visible, and the account has no usable headroom estimate. MCP exposes the same decision in health and healthAtObservation. Near-limit means a reported quota is at least 75% used; limit-reached means at least one quota is exhausted. These assessments consider all reported windows, model quotas, and capped spending, without summing incompatible plans. Legacy/partial records cannot establish available capacity, and observations over an hour old, future timestamps, elapsed resets, or invalid counters are marked conservatively. Panels retain their original observation time and coverage. A failed daemon read leaves the last observations visible with an explicit connection warning; it never refreshes their age.

Quota alerts in watch mode, dashboards and the daemon

Quota alerts are opt-in. Add this to config.toml to warn at usage thresholds and when recent history predicts an approaching limit:

[notifications]
enabled = true
thresholds_percent = [70, 85, 95]
cooldown_seconds = 900

[notifications.channels]
desktop = true  # optional, off by default

[notifications.forecast]
enabled = true
warning_minutes = 60
urgent_minutes = 30
critical_minutes = 10
caut usage --provider both --watch --json
caut dashboard --provider both
# Or select a separate configuration for a background collector:
CAUT_CONFIG=./monitor.toml caut daemon start --provider both
caut daemon logs --lines 20

Watch mode and foreground serve write [quota] warnings to stderr; a background daemon retains them in its log. JSON usage frames on stdout keep their normal format. Forecast alerts require measured recent history; window pace estimates do not trigger them. Cached or stale observations do not generate new alerts.

Direct dashboards (caut dashboard and caut usage --tui) use the same opt-in threshold and forecast alerts. A panel shows the three most recent warnings with UTC observation times, separate from provider errors. Configured desktop and webhook delivery runs in background workers, and cooldowns survive restarts. Daemon-backed dashboards rely on their daemon's alerts and do not send them again when viewing saved observations.

Desktop delivery works in caut serve, caut daemon start, caut usage --watch, and direct dashboards. Set notifications.enabled and notifications.channels.desktop to true, then restart the monitor in your signed-in desktop session. Linux uses notify-send (from libnotify-bin on Debian/Ubuntu) and the session notification service. macOS uses the system osascript and Notification Center. The desktop can display the account and model names from the alert, including on the lock screen if your system allows notification previews.

Concurrent detections are summarized in one banner showing the most urgent condition and the number of additional alerts. Banners are at least 15 seconds apart per monitor. The highest configured percentage or the critical forecast produces a critical alert. Linux also receives the native urgency level. Use caut alerts list for individual detections or caut dashboard --daemon for the current observations. Native delivery is best effort. If a helper is unavailable, the monitor continues polling and records the error in its log.

Detections and cooldowns are stored in the usage-history database. Restarting a monitor preserves each account/source/quota's cooldown, and concurrent watch and daemon processes with matching notification settings share those decisions. Recovery below a threshold and a newly observed quota period rearm alerts; these transitions persist even when no warning is emitted.

If the database cannot be opened or updated, the monitor logs a warning and continues with in-memory cooldowns until restart. Alerts during that fallback may be absent from history. Settings are read at startup. Percentages must be strictly increasing from 1 through 100, cooldowns must be 1–86400 seconds, and forecast minutes must satisfy 0 < critical < urgent < warning <= 1440.

Webhook delivery for headless monitors

Watch mode and the daemon can send quota warnings to a generic HTTP receiver, Slack incoming webhook, or Discord webhook. Webhooks are opt-in. This minimal notification configuration enables both threshold and forecast delivery using the default thresholds and forecast settings described above:

[notifications]
enabled = true

[[notifications.channels.webhooks]]
url = "https://alerts.example.com/caut"
format = "generic"
events = ["usage.threshold", "usage.forecast"]

Merge these settings into your existing notification configuration, then restart the monitor. Add another [[notifications.channels.webhooks]] table for each destination, up to 16. Replace the URL with your receiver and choose generic, slack, or discord. Omitting format selects generic JSON; omitting events includes both event types. Desktop delivery can remain enabled alongside webhooks.

Generic payloads contain schemaVersion, eventId, event, timestamp, severity, provider, account, message, and the public alert document in data. timestamp is the detection time; data.observedAt identifies the underlying observation. Credential tokens and private observation scopes are not included. Slack receives plain-text blocks. Discord disables mention parsing and requests confirmation that the message was saved; a configured thread_id query parameter is preserved.

Slow receivers do not block usage polling or other destinations. Each destination has a queue of up to 64 pending alerts. Transient failures receive up to three attempts within a 30-second delivery budget, with an eight-second request timeout. A receiver's Retry-After pauses that destination across subsequent alerts, even when the current alert cannot be retried within its budget. Permanent HTTP errors and redirects are not retried. HTTPS is required except for HTTP receivers on loopback addresses.

Requests reuse an Idempotency-Key across retries; generic receivers can also deduplicate using eventId. Remote delivery is best effort: a receiver that ignores the key may show duplicates after an ambiguous timeout. Full queues, alerts waiting beyond five minutes, and monitor shutdown can discard pending deliveries. Errors identify the destination by its configuration index without exposing the webhook URL.

Adding or changing a webhook preserves existing detector cooldowns and does not replay earlier alerts. Recorded detections remain available through caut alerts list; they are separate from delivery acknowledgements. Check caut daemon logs or the foreground monitor's logs for delivery failures.

caut alerts

Inspect detected warnings without contacting providers:

caut alerts list
caut alerts list --provider claude --kind threshold --json
caut alerts list --account work --since 2026-11-01 --format md
caut alerts export --export-format csv --output quota-alerts.csv
caut alerts export --provider codex --export-format json

List output defaults to the newest 100 events; --limit accepts 1–10000. Exports include all matching events unless a limit is supplied, stream JSON or CSV, and create a new output file when --output is given. Existing files are preserved. Both commands support provider, exact recorded account label/email, condition (threshold or forecast), and --since/--until filters. Dates use UTC and an --until calendar date includes the entire day; RFC 3339 timestamps are also accepted.

Records include the observation time, detection time, source, quota, condition, and detecting monitor (watch or daemon). They describe what was observed when the warning was detected; they are not current quota readings or delivery receipts. Queries are read-only: an absent or older database produces an empty alert list without creating directories or applying migrations. Normal history collection applies the additive migration and preserves existing usage data.

caut cost

Scan local Claude Code, Codex, and Gemini CLI session logs for daily token counts and estimated USD costs, including today and the last 30 days. Alternate log locations honor CLAUDE_CONFIG_DIR, CODEX_HOME, and GEMINI_CLI_HOME.

USAGE:
    caut cost [OPTIONS]

OPTIONS:
    --provider <NAME|both|all>  Provider selection (default: both)
    --refresh                   Ignore cache, rescan files
caut cost --provider both --json
caut cost --provider gemini --json
caut cost --provider all --json

Unchanged cost logs reuse a persistent scan cache. Appended, replaced, added or removed logs, a changed log directory, a new UTC day or a new binary build invalidate it. --refresh forces a fresh scan.

Codex scans reconcile modern token_usage_record responses with matching legacy token_count summaries, so a response recorded in both formats is charged once. Response IDs also connect replayed records across active and archived files. The response's recorded model and billing time determine its model breakdown and day, even when the summary arrives later. Compaction checkpoints and context estimates do not create additional billable responses.

Legacy-only records remain supported. Matching requires recorded response identity or a summary linked by the native counters; caut does not merge unrelated responses merely because their token counts are equal. Incomplete log fragments without that link can therefore retain separate records.

Gemini scans native JSON sessions and append-only JSONL journals under ~/.gemini/tmp/<project>/chats, including nested subagent sessions. When GEMINI_CLI_HOME is set, that directory replaces the home directory before .gemini is appended; Gemini's SANDBOX=sandbox-exec layout is also supported. Project attribution uses the recorded .project_root marker. Copied responses, token updates, and conversation checkpoints retain their original response IDs and are charged once. Rewinding a conversation does not erase consumed tokens. Cached prompt tokens use the cache-read rate, thinking tokens count as output, and tool prompt tokens count as input. Long-context rates apply to each response's full prompt, including cached tokens. The built-in Gemini rates estimate standard text usage; these logs do not establish audio tariffs, tool fees, cache storage charges, or subscription bills. Custom prices can override the estimates below. both keeps its Codex-and-Claude meaning; use gemini or all to include Gemini costs.

These are API-price estimates from local records. Actual invoices and subscription charges can differ. caut cost includes unknown models in token counts but omits their dollar cost: a mixed-model total covers only priced responses, and dollars are unavailable when usage exists but none can be priced. Claude's stats-cache fallback reports tokens without estimating dollars. caut session can use fallback prices for unknown models and marks those estimates with low confidence.

Responses without a usable billing timestamp appear in undatedUsage across native JSON, the daemon, and MCP. This object gives their response count, token total, unpriced tokens, and estimated dollars for the priced portion. Dated totals exclude those responses. When no usage can be assigned to a period, its counts and dollar amounts are unknown. Human and Markdown reports flag this coverage gap. The CodexBar compatibility format cannot express it and omits the affected provider with a diagnostic and a nonzero exit status.

Readable responses survive damaged or unreadable transcripts. Native JSON, daemon, and MCP cost payloads report sourceIssues for malformed lines, skipped links, discovery or read failures, and files that change during scanning. Amounts then cover only the observed records; a period without readable usage is unknown, rather than zero. Human reports mark these subtotals with ≥, and Markdown includes period_coverage: observed_subtotals_only. CodexBar output omits an affected provider and exits with a diagnostic because its format cannot represent incomplete source coverage. Repairing or replacing a damaged log invalidates the cost cache automatically.

Claude and Codex usage records must contain valid, nonnegative integer input and output counts. Missing required counters, invalid numbers and inconsistent cache counts leave source coverage incomplete; they cannot establish zero spending. A complete replay of the same response can supply the missing usage. The shared accounting path applies these checks to cost and session reports, CLI budget checks, and MCP budget results. Valid responses remain visible as subtotals, while caut budget --check fails until every applicable budget has complete evidence below its limits and alert thresholds.

Claude's stats-cache fallback also reports incomplete coverage when its lastComputedDate is older than today, invalid, or in the future, or when an activity day has no per-model token counts. Available token subtotals remain visible, but a stale cache cannot establish today's usage as zero. Refreshing the cached scan does not make the underlying Claude cache current.

Each daily JSON entry includes modelBreakdowns when the log supplies model usage. Each row has modelName, totalTokens, and an estimated cost in USD when it can be calculated. The 30-day totals.unpricedTokens gives the number of tokens excluded from the dollar amount. The human report shows today's models and marks partial dollar totals with ≥. Markdown lists daily model costs for the seven most recent reported dates.

Custom model pricing

To price a new model or use negotiated rates, add pricing.toml to the caut configuration directory (CAUT_CONFIG_DIR overrides the directory). The cost, session and budget commands share these rates with the daemon and MCP reports. CAUT_PRICING_PATH can select a separate pricing file:

CAUT_PRICING_PATH=./team-pricing.toml caut cost --provider claude --json

Use ordered pattern rules for rates that cover several model names:

updated_at = "2026-11-01" # optional date when you verified these rates

[[model]]
pattern = "claude-team-model"
input_per_mtok = 3.0
output_per_mtok = 15.0
cache_read_per_mtok = 0.3
cache_write_per_mtok = 3.75

Rates are USD per million tokens. Each pattern is a regular expression matching the entire canonical model ID after date suffixes and Claude provider prefixes are removed. The first matching rule sets rates for all prompt sizes. Omitted cache-read and 5-minute write rates default to the rule's input rate. Claude 1-hour writes use twice the input rate unless cache_write_1h_per_mtok is set.

For a complete tariff with optional long-prompt pricing, use an exact model family entry. Exact entries take precedence over pattern rules and require explicit input, output, cache-read and ordinary cache-write prices:

[models."claude-private-model"]
input_per_million = 2.0
output_per_million = 4.0
cache_read_per_million = 0.5
cache_creation_per_million = 3.0
cache_creation_1h_per_million = 7.0 # Optional; defaults to twice input price

# Optional: replace the rates for a response whose total input-side tokens
# exceed this threshold. The threshold includes cache reads and writes.
[models."claude-private-model".long_prompt]
threshold_tokens = 100000
input_per_million = 6.0
output_per_million = 12.0
cache_read_per_million = 1.5
cache_creation_per_million = 9.0
cache_creation_1h_per_million = 21.0

These are illustrative rates. Overrides apply to the normalized model family, including dated snapshots and supported provider-prefixed identifiers. Duplicate family definitions, missing required rates, misspelled fields, negative or nonfinite prices, and invalid thresholds are errors. A complete override also replaces any bundled long-prompt tier; omit long_prompt for one tariff at every prompt size. Models absent from the file retain their bundled prices.

Cost caches include the effective pricing, so adding, changing or removing an override recalculates costs on the next scan without --refresh. An invalid configuration cannot silently reuse previously cached prices. A missing default pricing.toml uses bundled rates; a missing file explicitly selected with CAUT_PRICING_PATH is an error. The selected rates apply to all responses in the report, including historical responses; the file does not define dated tariffs.

caut budget

Check daily, weekly and monthly dollar budgets against deduplicated local Claude and Codex response logs. Set daily or weekly quota percentage limits for any provider that reports a matching window. caut budgets is an alias; omitting status shows the same report. Human, JSON and Markdown output include limits, known costs, coverage, alert thresholds and calendar reset times.

# Create a commented starter file, then edit it to enable your limits
caut budget init

caut budget status --provider both
caut budget --format md

# Print the report and return a nonzero exit status if a check fails
caut budget --check --json

# Choose a different configuration file
caut budget --config ./budgets.toml --provider claude

Configuration defaults to budgets.toml in caut's platform configuration directory (~/.config/caut on Linux, or $XDG_CONFIG_HOME/caut when set). --config PATH takes precedence over CAUT_BUDGETS, which takes precedence over the default path. init creates a new file and refuses to overwrite an existing one. A minimal configuration is:

[settings]
timezone = "America/New_York"  # IANA time zone, "utc", or "local" (default)
week_starts_on = "monday" # "monday" or "sunday"

[global]
daily_cost_usd = 10.0
weekly_cost_usd = 50.0
monthly_cost_usd = 150.0
alert_at_percent = [50, 75, 90]

[claude]
monthly_cost_usd = 75.0
weekly_usage_percent = 80.0

Global limits are per-provider defaults: selected providers receive separate budgets. Provider settings override individual global limits; sections such as [claude.override], [codex.override], or [gemini.override] take priority over both. Gemini dollar budgets use the same native response records and API-price estimates as caut cost --provider gemini. Alert thresholds are merged. Periods begin at calendar midnight, the configured start of the week, or the first day of the month; full months are counted, including 31-day months. The default calendar uses local time and Monday weeks.

To cap combined spending across providers, configure a separate aggregate budget:

[aggregate]
providers = ["claude", "codex"]
monthly_cost_usd = 100.0
alert_at_percent = [50, 75, 90]

This is one shared limit; [global] continues to supply per-provider defaults. Every configured aggregate member is checked even with --provider, so filtering the report cannot bypass the combined limit. CLI, MCP, daemon budget reports and watch alerts use the same aggregate result. Missing logs or unpriced responses retain known subtotals but cannot pass --check; known spending can still prove that a threshold or limit has already been crossed. Unknown model entries in aggregate results include the provider name.

Costs are API-rate estimates from local records, so subscription charges and invoices can differ. Alternate log locations honor CLAUDE_CONFIG_DIR and CODEX_HOME. Missing or unreadable logs, malformed or changing files, undated responses and unpriced models leave coverage incomplete. JSON keeps the priced lower bound in knownCostUsd and makes spentUsd null when a complete total is unavailable. Known spending can still prove that a threshold or limit was reached. --check fails for these warnings, exceeded limits, incomplete coverage, unsupported limit types, or an absence of configured budgets.

Quota limits use the latest saved observation for each tracked account. Capture one with caut usage --provider claude, for example. daily_usage_percent matches a 1,440-minute provider window, and weekly_usage_percent matches a 10,080-minute window. A five-hour session cannot satisfy a daily limit. Calendar settings apply to dollar budgets. Provider reset times apply to quota windows.

The JSON quotaBudgets rows name the account, source, window or model scope, observed percentage, limit and evidence state. For an 80% weekly limit and a 75% alert, a warning starts at 60% of the provider's weekly allowance. Each matching meter is checked independently. A missing measurement, a future timestamp, an observation older than one hour, or a reset already reached makes the check unknown. Old values remain visible with their observation times. Legacy rows can still show known windows and crossings. A legacy row without model-level detail cannot certify that all quotas are below budget. Deactivated accounts are excluded. A remaining credit balance alone cannot establish how many credits were spent today.

caut usage --watch automatically monitors budgets when the default file exists at startup or CAUT_BUDGETS selects a file:

CAUT_BUDGETS=./budgets.toml caut usage --provider both --watch --json

The same budget file enables monitoring in caut serve and caut daemon start. Read the last completed check with caut query budget. The endpoint reports disabled when no budget file was selected at startup and starting before the first check completes. A ready response includes the full report, its completion time (checkedAt) and the decision from caut budget --check (checkPasses). A failed evaluation replaces the preceding result with failed and an error. Reading the endpoint uses the cached result. Budget warnings appear in daemon logs.

Budget scans run independently of provider refreshes, with at least one minute between completed scans and the next scan. Threshold crossings, incomplete coverage and configuration failures produce transition alerts on stderr; repeated unchanged states stay quiet and provider frames retain their stdout format. Dollar budgets cover each provider's discovered local responses. Quota warnings identify the tracked account and meter whose budget changed.

caut session

Inspect costs and token usage from local Claude Code, Codex, and Gemini transcripts, or aggregate them by project or model. Without other options, caut session includes usage recorded in the preceding 24 hours. --by-project (also spelled --project) defaults to the preceding 30 days and ranks working directories by their combined estimated costs across these providers. Both defaults are rolling time windows ending at the start of the report.

caut session --today
caut session --provider codex --list --limit 10 --json
caut session --provider gemini --by-model --json
caut session --id session-id-or-unique-prefix
caut session --by-project --json
caut session --by-project --since 2026-10-01 --until 2026-10-31 --format md
caut session --since 2026-10-01T09:00:00Z --until 2026-10-01T17:00:00Z --json

Date filters apply to individual usage records after replayed responses and resumed transcript fragments are merged and deduplicated. A session resumed today contributes only its included responses; its older work does not inflate today's cost. Token counts, models, costs, and session durations reflect the included records. File modification times do not determine whether usage belongs in a report.

--today starts at local midnight. --since and --until accept either a local YYYY-MM-DD date or an RFC 3339 timestamp with an explicit offset. The start is inclusive and a timestamp end is exclusive. A date-only --until includes that entire local day by ending at the following midnight. With only --since, the end is the report's start time; with only --until, there is no lower bound. Invalid or reversed ranges are rejected, and --today cannot be combined with --since or --until. JSON reports expose the resolved period.startInclusive and period.endExclusive bounds.

Without date filters, --id searches all local history and reports the available responses in the matching session; an exact ID takes precedence over a unique partial match. Missing or ambiguous matches are errors. --list likewise searches all history, showing the newest 10 recorded sessions by default (--limit changes the count). Explicit date filters also work with ID and list queries. Records without a usable timestamp are excluded from bounded reports with a warning; unrestricted --id and --list retain them.

For a single session, --id also breaks down spend by model. Each row shows the number of billable responses, input and output tokens, cache reads and writes, and estimated cost. JSON exposes these rows under sessions[].model_breakdown, keyed by the model ID recorded in the transcript. Each row's fallback_cost_usd is the portion estimated for models without a configured or built-in price.

Project reports combine matching working directories across providers and keep sessions with unknown project paths in a separate group. Reports flag project totals that include unknown-model pricing; fallbackCostUsd in JSON totals and project summaries identifies the portion calculated at fallback rates.

Use caut session --by-model to compare model usage across the preceding 30 days, or add --today, --since and --until to select another period. Models are ranked by estimated cost, with separate rows for each provider and recorded model ID. Each row reports session and response counts, input and output tokens, cache reads and writes, total estimated cost, and the portion using fallback pricing. Mixed-model sessions attribute each response to its actual recorded model. Archive copies and resumed responses are deduplicated before dates are applied.

JSON exposes the aggregate rows under models, with sessionCount, responseCount, inputTokens, outputTokens, cacheReadTokens, cacheCreationTokens, totalCostUsd and fallbackCostUsd. Model cost and token subtotals reconcile to the report totals. Session counts across model rows can sum to more than the unique session total because a session may use several models. --by-model cannot be combined with --id, --list or --by-project.

Session, project and model reports share the same transcript reader as cost and budget reports. Readable records survive malformed JSON or invalid UTF-8, and replayed records remain deduplicated across active files and archives. JSON exposes coverageComplete: false when discovery failures, damaged records or omitted undated responses may hide usage; errors describes the gaps. Human and Markdown reports label the amounts as observed subtotals. The daemon's /sessions response exposes the same coverage information. Repairing source files clears the diagnostics on the next scan.

API providers: z.ai and Copilot

Both providers support saved token accounts and --all-accounts. Add credentials through stdin so they do not appear in your shell history:

caut token-accounts add --provider zai --label work --activate
caut usage --provider zai --source api --json

caut token-accounts add --provider copilot --label work --activate
caut usage --provider copilot --source api --json

z.ai also accepts ZAI_API_KEY or GLM_API_KEY, followed by the caut keyring entry. Use a Coding Plan key. Its quota response supplies five-hour and weekly allowances for both token and credit plans, plus the separate monthly MCP allowance when present. Reset timestamps come from the provider; an absent quota or reset stays unknown. For a regional endpoint, configure its base URL:

[providers.zai]
api_base = "https://open.bigmodel.cn"

Copilot accepts COPILOT_GITHUB_TOKEN, then GH_TOKEN, then GITHUB_TOKEN, followed by the caut keyring entry. If none is configured, it can reuse gh auth login --hostname github.com. That CLI fallback is restricted to the official HTTPS GitHub API; a custom api_base requires explicitly configured credentials. The token needs access to the account's Copilot subscription.

Copilot reports premium requests or AI credits, chat quotas, and completion quotas when GitHub supplies them. Unlimited or unallocated quotas do not become invented percentages. GitHub's internal quota endpoint can change independently of its public API; rejected credentials and malformed quota responses remain explicit errors.

Cursor usage and spending

Supply a session cookie from your signed-in cursor.com account. Saved accounts accept either the cookie value or a complete Cookie header through stdin:

caut token-accounts add --provider cursor --label work --activate
caut usage --provider cursor --source web --json
caut usage --provider cursor --all-accounts --json

Cursor also accepts CURSOR_COOKIE_HEADER or CURSOR_COOKIE, followed by the caut keyring entry. An explicitly selected account takes precedence. A configured providers.cursor.api_base can point to a compatible proxy or test server.

Usage comes from the dashboard's usage summary. Legacy request quotas and explicitly confirmed shared weekly allowances are supported, as are monthly Total, Cursor and Third Party percentages. Fractional percentages retain their original scale. On-demand spending appears in providerCost in USD, with the reported cap when available; uncapped spending remains visible without an invented utilization percentage. Separate finite team pools remain visible as scoped allowances.

Optional identity and supplemental quota requests share a bounded time budget. Slow or unavailable supplemental endpoints therefore do not discard a valid usage summary. The dashboard endpoints are internal and can change independently of Cursor's public API.

Antigravity CLI quota observations

Antigravity CLI delivers its model-group quotas to the configured status line command. To let caut receive those observations, add the following block to ~/.gemini/antigravity-cli/settings.json and start the CLI. The command must be on the CLI's PATH. If you already use a custom status line, pass the same JSON input to both commands in your existing script.

{
  "statusLine": {
    "type": "command",
    "command": "caut antigravity-statusline",
    "stack_with_default": true
  }
}

Open /usage inside Antigravity to refresh its quota view. Run caut usage --provider antigravity --source local --json to read the most recently delivered observation. The hook runs silently and stores the reported identity, observation time and quota windows in caut's cache. Workspace paths, conversation titles, and transcripts are excluded. The hook and reader must use the same cache directory. With several CLI sessions sharing that directory, the last published frame supplies the account.

Each enabled bucket with a remaining fraction becomes a named scoped window. Absolute or relative resets are anchored to the capture time. Elapsed windows are omitted and captures an hour old or from the future are rejected. Buckets reporting only an amount lack the capacity required to calculate a percentage. updatedAt is the time caut received the frame. Antigravity status line documentation

Kimi Code subscription quotas

Kimi supports saved token accounts, --all-accounts, KIMI_CODE_API_KEY, KIMI_API_KEY, and the caut keyring entry, in that order. Use a Kimi Code credential, rather than a Moonshot Platform pay-as-you-go key:

caut token-accounts add --provider kimi --label work --activate
caut usage --provider kimi --source api --json

The current official Kimi Code quota contract supplies independent seven-day and five-hour ratios, plus monthly total and monthly coding allowances when included in the subscription. All reported windows retain their own reset times; missing limits stay unknown. Monthly allowances appear in usage.scoped without an invented thirty-day duration. Explicit monthly extra-usage spending and a positive enabled spending cap appear in providerCost in the currency reported by Kimi. A disabled cap is represented as uncapped spending. No account identity is inferred from another local login.

The default endpoint is https://api.kimi.com/coding/v1/usages. For the global region, set KIMI_CODE_BASE_URL=https://api.kimi.ai/coding/v1 or configure providers.kimi.api_base with that base URL. The config setting takes precedence. Offline observations are scoped to the exact credential and effective endpoint.

MiniMax M Plan and Coding Plan quotas

MiniMax supports saved subscription token accounts and --all-accounts. Add a key through stdin, then query the active account:

caut token-accounts add --provider minimax --label work --activate
caut usage --provider minimax --source api --json

An explicitly selected or active token account takes precedence. Otherwise, credentials resolve from MINIMAX_CODING_API_KEY, then MINIMAX_API_KEY, then the caut keyring. Use a subscription key for the configured region.

Reports preserve independent five-hour and weekly allowances, including current percentage-based responses and legacy remaining-count responses. Additional model and service limits appear as scoped windows, and explicit unlimited allowances are labeled. Missing or malformed quota data produces an error. This command reports quotas without estimating MiniMax dollar spending.

The default endpoint is https://api.minimax.io/v1/token_plan/remains, following the MiniMax subscription quota API. For mainland China:

[providers.minimax]
api_base = "https://api.minimaxi.com"

Custom base prefixes are preserved; caut appends /v1/token_plan/remains. Only HTTP 404 or 405 triggers a retry at /v1/api/openplatform/coding_plan/remains on the same configured host. Authentication errors do not switch accounts or regions. Reset times use valid future absolute timestamps supplied by the API; missing timestamps or relative timers alone leave the reset unknown.

Factory / Droid

Factory uses the authenticated billing limits API to report independent Standard 5-hour, 7-day and 30-day quotas, plus the corresponding Droid Core quotas. Limits require an active paid subscription. Standard windows appear in the primary, secondary and tertiary slots; Core windows appear in usage.scoped.

caut token-accounts add --provider factory --label work --activate
caut usage --provider factory --source api --json

Credential precedence is the selected token account, FACTORY_API_KEY, FACTORY_BEARER_TOKEN, the caut keyring, then FACTORY_API_KEY in ~/.factory/.env. The request uses the credential's default Factory scope. API keys are scoped to their own organization.

A visible prepaid extra-usage balance appears as credits.remaining in USD. A missing or member-hidden balance remains unknown. Unlimited windows are omitted from metered-quota output. When every window is unlimited, no percentage windows are returned, and the human view may describe rate limits as unavailable.

Vertex AI project quotas

Vertex AI reads measured project quotas from Google Cloud Monitoring. Enable the Monitoring API and use an identity with monitoring.timeSeries.list access to the selected project.

# Use the authorized-user ADC created by gcloud
gcloud auth application-default login
GOOGLE_CLOUD_PROJECT=my-project caut usage --provider vertexai --source oauth

# Or supply an OAuth access token explicitly
GOOGLE_CLOUD_PROJECT=my-project \
VERTEXAI_ACCESS_TOKEN='OAUTH_ACCESS_TOKEN' \
caut usage --provider vertexai --source oauth --json

GOOGLE_CLOUD_ACCESS_TOKEN is also supported. ADC lookup honors GOOGLE_APPLICATION_CREDENTIALS and CLOUDSDK_CONFIG; authorized-user ADC can refresh tokens using its own client and refresh credentials. Selected token accounts accept an access token or authorized-user credential JSON. Include project_id in saved credential JSON to bind it to a project. Selected credentials never fall back to another local account.

Raw access tokens must be replaced when they expire. Service-account/federated JSON and metadata-server authentication are not implemented directly, but an OAuth access token obtained for that identity can be supplied.

Observations use the account label project:<project-id>. History and cache remain isolated by project even when the same saved credential accesses multiple projects. Allocation and rate-v2 gauges appear in usage.scoped, labeled by quota, limit, location and additional dimensions. Rate resets require explicit window metadata.

Google's allocation metrics may repeat unchanged values only daily. Allocation usage and limits therefore allow a 25-hour lookback; rate-v2 usage requires a measurement within 15 minutes. updatedAt retains the actual observation time. Missing, stale, unlimited or ambiguous quotas stay unavailable. Dynamic Shared Quota has no fixed utilization percentage, and these gauges do not produce spending or depletion forecasts.

caut accounts

Inspect and manage accounts recorded by successful usage fetches and the monitor:

caut accounts list --provider claude
caut accounts list --all --json
caut accounts show ACCOUNT_ID --limit 20 --format md
caut accounts label ACCOUNT_ID work
caut accounts label ACCOUNT_ID --clear
caut accounts deactivate ACCOUNT_ID
caut accounts reactivate ACCOUNT_ID

Listings include the latest saved quotas, credits, spending, source and freshness; show also includes bounded observation history. Select an account by registry ID, exact email or exact label. Ambiguous names require an ID or provider filter. Custom labels survive later observations, and clearing a label restores the most recent provider label. Deactivation hides an account from the default listing while retaining its history; a new successful observation makes it active again. Viewing, labeling and reactivating accounts never make old usage appear freshly observed. Use token-accounts to configure authentication credentials.

caut history patterns

Inspect when an account tends to have the highest observed quota utilization.

caut history patterns --provider claude --account work --days 30 --by hour
caut history patterns --provider codex --window secondary --by weekday --json
caut history patterns --provider claude --scope Fable --by weekday --json

--by accepts hour, weekday, week-of-month (days 1–7 through 29–31), and month (January through December). All buckets use UTC. --window selects primary (default), secondary, or tertiary. Use --scope for an exact model-quota label. Scopes with the same label and different quota kinds have separate series. Older observations lacking full model detail contribute no scoped samples. Select an account by its registry ID, exact label, or exact observed email. Omitting the selector shows each identified account separately, including deactivated accounts.

The report gives the number of observations, arithmetic mean and maximum percentage used within each bucket. Sources and window lengths remain separate. Repeated reads of the same stored observation count once. Buckets without a usable measurement are omitted. Results cover the retained detailed history for the requested number of days. Frequent polling contributes more samples. For example, a 75% hourly average means the selected quota was three-quarters used on average when sampled during that UTC hour.

caut history anomalies

Find unusually fast quota consumption in retained account history:

caut history anomalies --provider claude --account work --days 30 --json
caut history anomalies --provider codex --window secondary --min-increase 10
caut history anomalies --provider gemini --scope gemini-3.1-pro --format md

Each account, source and quota keeps its own rolling baseline. By default, a spike must exceed the preceding 20 intervals' mean by both three standard deviations and five percentage points per hour, with at least eight prior intervals available. Use --baseline-intervals, --min-samples, --sigma and --min-increase to tune those requirements. --max-gap-minutes defaults to 60.

Reset crossings, falling counters, duplicate timestamps, missing quotas and long gaps do not establish consumption intervals. Gemini, Copilot and MiniMax summary slots can change quota identity, so select an exact saved --scope label for those providers. Vertex allocation gauges are excluded. The report identifies insufficient evidence and truncated history explicitly; zero detected spikes does not establish that missing or compacted history was normal. Analysis reads at most 20,000 recent observations per account and displays the newest 100 anomalies by default (--limit changes the display limit). It makes no provider requests and does not change stored history.

caut history export

Export detailed observations for analysis. The default interval is the last 365 days.

caut history export --provider claude --format json --output usage.json
caut history export --format csv --limit 1000 --output usage.csv

Use --since and --until with a date or RFC3339 timestamp to select a period. Exports keep the existing summary fields and include the full stored observation: JSON adds usage and usage_complete; CSV appends usage_complete and a quoted usage_json column. Model-specific quotas, spending limits, reset descriptions and identity metadata survive either format. Older records are explicitly marked incomplete because those fields were not retained when they were captured.

Only selected rows are validated. If one is corrupt or disappears during export, the command fails before opening the output file, preserving any existing file. Rows excluded by the provider, date or row limit do not block the export.

caut history backup

Create a standalone SQLite copy of the complete history database while caut is running. The copy includes all retained observations, account identities, daily summaries, alert history and schema metadata. Use a fresh destination filename.

caut history backup --output usage-history-backup.sqlite

SQLite includes committed observations from the live write-ahead log. The command checks the copy before publishing it. JSON and CSV exports contain detailed observations only.

caut auth refresh

Refresh the Codex CLI's existing managed ChatGPT login:

caut auth refresh codex
caut auth refresh codex --json
CODEX_HOME=/path/to/profile caut auth refresh codex

The installed Codex CLI owns token renewal and credential persistence. The command checks the native authentication mode and account identity, requests a refresh, and confirms that the access token changed. It has a 30-second deadline and never starts a login flow or conversation. Tokens and raw CLI diagnostics are excluded from output. If the CLI returns an unchanged token, caut reports an unconfirmed refresh instead of claiming success.

This command currently supports Codex only. API keys, externally managed tokens, and caut's saved token accounts require renewal through their credential owner. For a revoked or expired login that cannot be refreshed, use codex login.

Ordinary Codex usage collection, including --source oauth, also attempts one managed native renewal when its access token is expiring or the usage API returns HTTP 401. Recovery verifies the original user, workspace, credential file, and persisted replacement before retrying. It takes a fresh quota measurement under the new credential scope within the existing provider timeout; an account change during that measurement still prevents caching or recording the result. Automatic recovery requires the native file credential store; an explicit keyring, auto, or ephemeral store and environment-supplied Codex credentials are left to their credential owner. Concurrent requests within the same monitor share the renewal operation. Permission failures (403), rate limits (429), and network/server failures do not trigger token renewal.

caut token-accounts

Save named credentials for providers that support token accounts.

# Reads the credential from stdin when --token is omitted
caut token-accounts add --provider zai --label team --activate
caut token-accounts list --provider zai
caut token-accounts use --provider zai --label team

# Select one account or query saved accounts across providers
caut usage --provider zai --account team
caut usage --provider zai --all-accounts --json
caut usage --provider both --all-accounts --json
caut usage --provider all --all-accounts --offline --json

Ordinary usage and MCP queries use the provider's saved active account by default, falling back to local credential discovery when none is configured. --all-accounts expands each selected provider independently, including configured provider lists. Providers without saved accounts or token-account support use local credentials. Successful accounts remain in the output alongside errors from failed accounts. --account and --account-index require a single provider. --source cli and --source local use the provider's own local source unless an account is explicitly selected. Claude's local source reads the reporting session's quota capture and rejects saved-account selectors. Activating an account changes caut's default; the provider's own CLI login remains independent.

Preview a quota-based rotation or apply it to caut's saved default:

caut token-accounts rotate --provider codex --min-remaining 20 --json
caut token-accounts rotate --provider codex --min-remaining 20 --apply

Rotation fetches the configured accounts and keeps the active one when all its measured limits have sufficient headroom. Otherwise it selects the account with the most capacity in its tightest limit. Model-specific quotas and capped spending are included. A cached observation or a wallet balance alone cannot establish a current percentage. If no account qualifies, the command returns a nonzero exit status. Applying a switch rechecks the saved credentials under the account-file lock to avoid overwriting a concurrent change. A preview or MCP recommendation preserves the shell prompt. A completed switch updates that provider's prompt with the new account's measured quota.

Claude's OAuth quota endpoint does not identify the account. Usage fetched with a selected token account, environment token or standalone caut keyring token therefore leaves email and organization unknown instead of borrowing another local login's identity. The selected account label is still preserved.

caut switch log

Inspect account selections and confirmed native login transitions:

caut switch log --provider codex --since 7d --json
caut switch log --since 24h --limit 20 --format md

Saved-account activation through token-accounts add/use/remove, applied quota rotation and MCP switching records an audit event when the selection changes. Failed selection attempts are recorded too. caut_default events identify changes to caut's saved selection; native_login events identify login changes confirmed by a subsequent usage observation. The two account-ID namespaces stay separate, and creating an audit event does not invent an observed account.

Saved-account changes record their intent before writing the token file and then finalize as succeeded or failed. An interrupted operation remains pending, meaning its outcome is unconfirmed. If the intent cannot be recorded, the selection is left unchanged. Re-selecting the active account does not add a switch. Events include the origin, account IDs and labels, fixed failure codes, and measured headroom for quota-based rotation; credential contents and raw provider errors are excluded. Viewing the log is read-only and also works with older databases that only contain native switch history. --since accepts durations, RFC3339 timestamps, or UTC dates.

caut serve and caut query

Run a local HTTP server that refreshes usage on a timer and when watched credential files change. It runs in the foreground and listens on 127.0.0.1:19485 by default.

Use caut daemon to keep the same collector running after the launching command returns. Startup waits for the listener and reports the assigned port.

caut daemon start --provider both --interval 60
caut daemon status --json
caut daemon logs --lines 20
caut daemon stop

Add --all-accounts to caut daemon start or caut serve to refresh every saved token account of the selected providers. Providers with no saved accounts use their local credentials. For example, caut daemon start --provider both --all-accounts monitors the saved Codex and Claude accounts. Each account keeps its own history, forecasts, cached observations, and prompt entry. An invalid credential appears in the response errors while successful accounts keep updating. Provider cooldowns apply to the whole provider. Registry edits take effect on the next polling interval, and a response obtained with a replaced credential is discarded before it can update history or caches.

The default monitor uses caut-server.json in caut's data directory. Supply the same --pid-file PATH to each command to manage a separate instance. Logs from background starts append to PATH.log. Stop requests are local to the discovery file and target one running instance, including a foreground caut serve.

# Refresh Codex and Claude every 30 seconds; interval must be greater than zero
caut serve --provider both --interval 30

# Run these in another terminal; query prints JSON
caut query usage
caut query accounts
caut query health
caut query budget

The REST API accepts both the short paths below and the /api/v1 prefix. For example, /usage/codex and /api/v1/usage/codex return the same response. All routes use the same authentication and request limits.

Method Path Result
GET /usage or /usage/{provider} Latest cached usage, including every monitored account
GET /status or /status/{provider} Last observed provider service status; null when unknown
GET /history or /history/{provider} Retained observations and daily summaries, with account and time filters
POST /usage/{provider}/refresh Request a refresh through the daemon's polling scheduler

/accounts, /budget, /cost, /session, /health, and /events also accept the versioned prefix. Usage, status, history, and accepted refresh responses use the caut.v1 envelope with command, data, errors, and meta. Usage and status reads add fromCache: true and lastRefresh; they preserve observation timestamps rather than treating an HTTP read as a new measurement. Usage cache ages advance on each read, and expired observations are marked stale.

caut query 'usage/codex'
caut query 'status/claude'

Request a refresh without waiting for the next interval:

curl -X POST http://127.0.0.1:19485/api/v1/usage/codex/refresh

Add the bearer authorization header when authentication is configured. A 202 response reports data[0].status as scheduled or inFlight; it acknowledges pending work, not a successful provider fetch. Read the returned usageUrl or subscribe to eventsUrl for results. Requests coalesce with an existing fetch, preserve credential-switch protections, and respect provider cooldowns. A provider rate limit returns 429 with Retry-After; other open cooldowns return 503 with the same header. An unavailable or full scheduler returns 503. Admission has a five-second deadline, including time spent waiting for server state; expired requests cannot later start a manual fetch. Without bearer authentication, browser POST requests must come from the loopback listener's own origin. CLI requests need no Origin header.

Follow the daemon from another terminal with caut query events, or follow a single provider with caut query 'events?provider=claude'. HTTP clients can open GET /events as a Server-Sent Events stream. Each usage_updated event contains the current providers and errors arrays. The first event supplies a full snapshot, including on reconnect. Later events replace it when an observation changes, a credential is invalidated, or a fetch fails. Slow readers receive the latest state and idle connections receive a keep-alive every 15 seconds.

Query saved observations or daily summaries through the same listener:

caut query 'history/claude?days=30&limit=100'
caut query 'history/claude?account=Work%2FTeam%2BOne&days=30'
caut query 'history?resolution=daily&days=30'

HTTP clients can use GET /history or GET /history/{provider}; the /api/v1/history aliases return the same response. These routes share the server's authentication and request limits. Queries read saved history without contacting providers or changing the database. If no history database exists, the response has an empty data array and storageAvailable: false.

Parameter Meaning
provider One provider, as an alternative to the provider in the path.
account Exact account ID, stable key, email, or label; requires one provider. Ambiguous selectors return an error. URL-encode labels and preserve their case.
days UTC calendar days including the current day; defaults to 7, from 1 to 3650.
resolution snapshots (default) or daily.
limit Rows per page; defaults to 100, from 1 to 1000.
cursor The previous response's pagination.nextCursor; keep the same provider, account, days, and resolution.

Detailed pages are ordered by observation time at millisecond precision, newest first, with snapshot IDs breaking ties. Each row includes the complete saved quota observation where available; usageComplete: false identifies older records whose original quota detail was not retained. Daily pages are ordered by provider and UTC date and include compacted history. Their usage averages are weighted by observation count, and costs use each account's highest cumulative daily reading. Unknown measurements remain null.

Pagination retains the first page's time window and binds account filters to the resolved identity. If a label or email selects a different account between pages, the continuation returns HTTP 409; restart the query or select the account ID. Continue until pagination.hasMore is false. Every response labels the data as historical and includes its period; saved observations do not establish current provider usage.

To require authentication, put a bearer token in a private file and pass the same file to the server and client:

caut serve --api-token-file ./caut-api-token
caut query usage --api-token-file ./caut-api-token

# Background alternative to serve:
caut daemon start --api-token-file ./caut-api-token
caut query health --api-token-file ./caut-api-token

CAUT_API_TOKEN supplies the token when --api-token-file is absent; an explicit file takes precedence. All HTTP routes, including /health, then require Authorization: Bearer <token>. Empty or invalid configured tokens are errors. Binding to a non-loopback address, such as --bind 0.0.0.0, requires a token. Unauthenticated loopback access accepts localhost or loopback IP hostnames. The built-in listener uses HTTP; use a protected tunnel or TLS proxy for remote access. caut query sends the token as a header and does not follow redirects.

All HTTP routes share a request budget per connection IP address, including requests with missing or invalid authentication. The defaults allow 100 requests per minute with a burst of 20. Configure the monitor at startup with:

[api.rate_limit]
enabled = true
requests_per_minute = 100
burst = 20
max_clients = 4096

Exhausted budgets return HTTP 429 with a Retry-After header and a JSON retry delay. Reconnecting does not reset the budget. Forwarded-address headers are ignored, so clients behind a reverse proxy share the proxy's budget. Client tracking is bounded; when full, new addresses receive 429 until an idle entry can expire without restoring unearned capacity. Set enabled = false to disable limiting for a trusted deployment. This is an IP-based budget for the current shared-token server, not separate quotas for individual API keys.

The server follows installed provider logins, even when caut has saved active token accounts. /usage returns the latest refresh; /accounts returns the most recent stored observation of each identified account, including accounts used earlier. Check each observation's timestamp: inactive accounts are not continuously polled. A verified credential scope can identify observations even when the provider supplies no email or organization; the public account uses an observed UUID and keeps those identity fields empty. Observations without any usable identity or verified scope are omitted from /accounts. /health reports startup/degraded status, refresh times, error counts, and credential watch counts. /cost exposes local scans for the daemon's selected providers, including Gemini; /session reports local sessions across supported providers. caut query discovers the listener's port automatically, including ports assigned by --port 0. Use caut query health --pid-file PATH for a separate monitor or supply --host or --port for a direct connection.

Each provider has an independent circuit breaker. Three consecutive failures open the circuit; authentication failures and HTTP 429 responses open it immediately. After a 60-second cooldown, one recovery request is allowed. Failed recovery requests double the wait, up to 15 minutes, while a provider's Retry-After can extend it further. Healthy providers keep updating, and failed providers retain cached observations with their original timestamps.

Credential changes clear observations from the previous login and retry the affected provider, while preserving any active rate-limit cooldown. /health reports each circuit's state, failures and next retry time. Circuit state lasts for the current daemon process and resets on restart.

Provider requests complete independently, so a slow provider does not hold up updates from faster providers. Credential watching continues while requests are in flight. A login change cancels the affected request; its old results cannot update history, offline observations or the prompt cache. Other providers keep their requests and circuit state. An already-received rate-limit response still sets its retry cooldown even when the login changes before publication.

The shell prompt cache also drops the affected provider when credentials change. Refreshing one provider retains the others with their original observation times, so a successful refresh cannot make another provider's old quota appear fresh.

caut mcp

Connect an MCP client to caut as a subprocess:

caut mcp

# Example registration in Claude Code
claude mcp add caut -- caut mcp

The transport is newline-delimited JSON-RPC over stdin/stdout, with logs on stderr. It runs independently of the HTTP server. The client can discover these tools:

Tool Example arguments Purpose
caut_usage_status {"provider":"zai","account":"team"} Fetch quota windows for one account
caut_forecast {"provider":"zai","all_accounts":true} Forecast each saved account separately
caut_recommend_account {"provider":"zai","min_remaining_percent":20} Find the saved account with the most headroom in its tightest window
caut_switch_account {"provider":"zai","account":"team"} Set caut's active token account
caut_cost {"provider":"both"} Scan local costs; select claude, codex, gemini, both, or all
caut_history {"provider":"claude","account":"Work","days":30,"resolution":"daily"} Read saved account observations or daily summaries
caut_budget {"provider":"claude"} Check calendar spending limits and each account’s daily or weekly quota thresholds

Call caut_history with {} for the last seven UTC calendar days of saved observations across providers. It uses the same read-only history reader as the HTTP API, including compacted daily summaries, bounded pages, complete saved quota detail, and account identity checks. No daemon or provider requests are required. Account selectors are literal strings here: pass Work/Team+One without URL encoding. An account filter requires one provider.

The optional days (1–3650), limit (1–1000), resolution (snapshots or daily), and cursor arguments match the HTTP history query. Continue with pagination.nextCursor, keeping the provider, account, days, and resolution unchanged. A reassigned label returns a tool error with instructions to restart pagination; selecting the registry account ID avoids label changes. Responses include their fixed period, live: false, storageAvailable, and meta.runtime: "mcp".

Call caut_budget with {} to inspect the default budget selection. It reads the same CAUT_BUDGETS or configuration-directory budgets.toml as caut budget. Its structured result includes checkPasses, the decision from caut budget --check, plus reconciled costs, per-account quota observations and coverage. An exceeded threshold, missing evidence or an unconfigured budget returns a report with checkPasses: false.

Usage and forecast tools accept account for a single provider, or all_accounts: true with a single provider, both, all, or the configured provider selection. Forecasts use each account's recent history within the current quota window, excluding resets and usage discontinuities. Without usable history they can report window pace or insufficient data. Recommendations exclude exhausted accounts and accounts without known quota; switching requires a separate tool call. The caut://providers resource describes provider metadata.

Forecast results also include scopedForecasts for model-specific allowances and providerCostForecast for spending caps. These use complete observations from the selected account, keeping different models, resets, currencies, caps and billing periods separate. An ambiguous account or malformed stored observation is reported through historyError on the live tool instead of borrowing another account's history.

Spending forecasts use the cost counter's own updatedAt as forecastAsOf, which can precede the enclosing usage observation. Repeated polls of the same cost counter do not create extra samples. A label such as "Monthly" does not imply a period length; uncapped spending has no exhaustion estimate. Each added forecast includes a sample count and an explicit reason when evidence is insufficient. Cached live observations suppress these forecasts. Stored-resource estimates remain evaluated at the observation time.

Clients can also read stored state through MCP resources without making provider requests. resources/templates/list advertises these URI templates:

Resource URI Contents
caut://status/{provider} Latest stored quota windows, model-specific allowances and spending limits for each identified account
caut://accounts/{provider} Configured account labels/defaults and observed account IDs; no credentials
caut://forecast/{provider}/{account} Forecast from that account's stored history, evaluated at its last observation

For example, read caut://status/codex, then use an accountId or forecastUri from caut://accounts/codex. Forecast selectors also accept an unambiguous account label or email; percent-encode the account URI segment.

Stored status and forecasts include observation timestamps, age and staleness. They are marked live: false; forecasts use forecastAsOf rather than treating old observations as current samples. A missing history database yields empty status/account history and is not created by a resource read. Capture usage with the CLI or daemon first to populate history.

New observations retain the full provider snapshot, including model-specific quotas, spending limits, reset descriptions and plan metadata. Stored account health includes scoped allowances and spending limits, so an exhausted model quota remains visible even when the session window has room. MCP responses mark these observations with usageComplete: true. Older records remain available with usageComplete: false and explicit partial quota coverage; they can prove exhaustion but cannot establish that the whole account is healthy. The daemon's /accounts response includes the full usage and a usage_complete flag.

Clients may call resources/subscribe or resources/unsubscribe with a resource uri. The stdio server emits notifications/resources/updated when the underlying stored data or its availability changes. Changes in the age counter alone do not trigger notifications.

Global Options

--format <human|json|md>  Output format (default: human)
--json                    Shorthand for --format json
--pretty                  Pretty-print JSON
--no-color                Disable colored output
--log-level <LEVEL>       Log level (trace|debug|info|warn|error)
--json-output             Emit JSONL logs to stderr
-v, --verbose             Enable debug logging

Diagnosing provider setup

caut doctor --provider kimi --json checks the inputs caut can use to read that provider's quota. Use --provider all to inspect every provider. API and web providers can use their active token account or their normal local credential sources. Amp requires the amp executable. Antigravity and JetBrains are checked by reading the quota data their local integrations actually supplied.

Doctor runs passively. A configured credential, an installed CLI or a readable quota capture establishes local setup. The apiReachable check is skipped because doctor does not contact the provider. To verify live access for an API provider, run caut usage --provider kimi --source api --json. JSON retains the existing authenticated field for the quota-source check and names its evidence in the check details.

Doctor also checks local monitoring and history storage. Use --local to run these checks without inspecting provider setups:

caut doctor --local --json
caut doctor --local --pid-file /path/to/monitor.json --api-token-file /path/to/api-token

History checks open SQLite read-only, verify its structure and migration ledger, check expected tables, columns and indexes, and detect orphaned or cross-provider account links. Older valid schemas are reported as awaiting migration; doctor does not migrate, prune or repair them. Missing history and an optional monitor that has never been started are skipped. A stale discovery file, inaccessible health endpoint, failed monitor authentication, collection errors or stalled refreshes require attention. --timeout bounds SQLite scans and monitor HTTP requests as well as provider checks. Human, Markdown and JSON output include the local checks (systemChecks in JSON), and local problems produce a nonzero exit status suitable for scripts.

Supported Providers

Provider CLI Name Source Types Features
Codex codex oauth, web, cli Session, weekly, credits
Claude claude oauth, web, cli, local Chat, weekly, opus tier; explicit status line captures
Gemini gemini oauth Pro, Flash, Flash Lite and model-specific quotas
Cursor cursor web Monthly and weekly allowances, legacy request quotas, on-demand spending
Copilot copilot api Premium requests/credits, chat and completions
z.ai zai api Five-hour, weekly and monthly MCP allowances
MiniMax minimax api Five-hour, weekly and model/service quotas
Kimi kimi api Five-hour, weekly and monthly quotas; extra-usage spending
Kimi K2 (Kimrel) kimik2 api Prepaid wallet balance. Set KIMREL_API_KEY, KIMI_K2_API_KEY, or select a Kimrel token account.
Kiro kiro cli Session limits
Vertex AI vertexai oauth Measured project allocation and rate-v2 quotas
JetBrains AI jetbrains local Local file
Antigravity antigravity local Per-bucket quotas and resets from the CLI status line hook
OpenCode Go opencode api Five-hour, weekly, and monthly Go usage with reset times. Set OPENCODE_GO_API_KEY or select a Go API key from token accounts.
Factory / Droid factory api Standard and Droid Core five-hour, seven-day and thirty-day quotas, plus prepaid USD when reported
Amp amp cli Amp Free daily usage, personal and workspace USD balances

Amp uses the installed amp usage command. An explicit token account supplies AMP_API_KEY to the child CLI process. Otherwise Amp uses its active login. The daily Free allowance reports its remaining percentage and daily cadence. Each personal or workspace USD balance appears separately in usage.balances. The CLI reports remaining funds without a spending cap or exact daily reset time.

All 16 providers in this table have a usage fetcher. Each row lists the supported source and the measurements it can report.


Data Sources

caut uses multiple strategies to fetch usage data:

Source How it works Platform
CLI Invokes provider CLI via PTY All
Web Uses supplied session cookies; discovery varies by provider All
OAuth Uses stored tokens All
API Direct API calls All
Local Scans local JSONL logs All

Strategy order depends on the provider. --source auto follows its fetch plan; use --source to select a specific supported source.


Configuration

Config File Location

Platform Path
macOS ~/Library/Application Support/com.steipete.caut/config.toml
Linux ~/.config/caut/config.toml
Windows %APPDATA%\steipete\caut\config\config.toml

Linux follows the XDG base directories when set. These environment variables override the corresponding application directories on every platform:

Variable Directory contents
CAUT_CONFIG_DIR config.toml, token-accounts.json, default budgets.toml
CAUT_CACHE_DIR Usage, cost, dashboard and shell-prompt caches
CAUT_DATA_DIR usage-history.sqlite and default daemon discovery/log files

Each nonempty override is the exact directory to use; caut does not append a caut suffix. Empty directory overrides use the platform default. CAUT_CONFIG selects the main TOML file and takes precedence over CAUT_CONFIG_DIR/config.toml. It does not relocate token accounts, budgets, caches or history. For example, CAUT_CONFIG=./monitor.toml caut serve uses that file while retaining the configured storage directories.

Import CodexBar provider preferences

caut config import codexbar
caut config import codexbar --file ./config.json --json

The importer reads CODEXBAR_CONFIG, then the CodexBar XDG or legacy JSON location. It transfers the order and enabled state of supported providers. CodexBar's opencodego maps to caut's opencode. The separate Zen service is skipped. When every imported provider is disabled, an explicit caut usage --provider <name> still works. The JSON report lists the enabled and disabled providers and counts unsupported entries.

On macOS, when the JSON file is absent, caut also supports legacy CodexBar UserDefaults provider toggles and reset-time preferences. In human usage output, [display] reset_time = "absolute" shows reset timestamps in UTC. Import updates the native TOML in place, preserving unrelated settings and comments. It copies no accounts, keys, cookies, hooks or source overrides.

Example Config

[general]
timeout_seconds = 30
include_status = false

# Output preferences
[output]
format = "human"
color = true

[providers]
default_providers = ["codex", "claude"]

[providers.gemini]
enabled = true

[storage]
retention = "unlimited"
# retention = 365      # Alternatively, expire history older than one year
# max_size_mb = 512    # Optional database size cap

[storage.compaction]
enabled = false
raw_retention_days = 90

History is retained indefinitely by default. caut history stats reports the effective policy, and caut history prune --dry-run previews cleanup. The same policy is applied to CLI, watch, dashboard, daemon and MCP collection. Compaction is opt-in and operates on complete UTC days; the current daily-summary schema cannot safely combine multiple accounts or late samples, so those cases preserve the raw records and report an error instead of discarding them.

Restricting provider sources

Each provider can have a nonempty strategy allowlist. Use full strategy IDs or names without the provider prefix:

[providers.claude]
strategies = ["oauth", "cli-pty"]

[providers.codex]
strategies = ["codex-oauth"]

The provider's normal fallback order is preserved; array order does not change it, and duplicate aliases run only once. Invalid names produce a configuration error listing the provider's supported strategies. Use enabled = false to disable a provider instead of an empty allowlist.

--source selects from the permitted strategies. For example, the Codex policy above rejects --source cli and prevents implicit CLI credential renewal after an OAuth failure. Doctor checks also skip disabled sources. Claude's statusline strategy still requires --source local; adding it to an allowlist does not make it an automatic fallback.

For Kiro, strategies = ["cli"] also skips the CLI's optional direct API enrichment. Its displayed quota then comes entirely from the CLI report.

Offline and failure-fallback caches are scoped to the effective source policy. Changing that policy requires a fresh observation before cached usage can be returned; equivalent full and short names share the same cache scope.

A running daemon checks for changed source policies and endpoints before refreshing and before publishing completed requests. It discards affected current observations and outdated in-flight results while retaining account history and provider cooldowns. Invalid configuration clears current usage and reports the error; correcting it allows collection to resume without a restart. Watch mode and direct dashboards also reject a refresh whose source policy changed in flight, including native providers without cacheable credentials.

Token Accounts

Multi-account support uses token-accounts.json:

{
  "version": 1,
  "providers": {
    "claude": {
      "accounts": [
        {
          "id": "uuid-here",
          "label": "personal",
          "token": "sk-ant-...",
          "addedAt": 1704067200
        }
      ],
      "activeIndex": 0
    }
  }
}

JSON Output Schema

Schema Version

The native usage --json and cost --json responses include schemaVersion: "caut.v1".

CodexBar-compatible JSON

Use caut usage --provider codex --codexbar or caut cost --provider both --codexbar to write one JSON array to stdout. Add --pretty for indentation. Usage entries include all three quota windows, with JSON null for unavailable windows, and include account identity fields both inside usage.identity and beside the windows. Cost entries use sessionCostUSD, last30DaysCostUSD, and totalCost on daily and total rows. A missing price leaves the affected dollar totals absent. Token counts, model names and individually priced models remain available.

The same account selection, data sources and cache rules apply in both formats. Cached entries retain their source and observation timestamp and add a cache object with age, staleness and reason. Model-scoped windows and separate prepaid balances use the optional usage.scoped and usage.balances extensions. Errors and incomplete-price notices go to stderr. Native ledger events and daily dashboard rows lack the service-level credit amounts that CodexBar expects. Their compatible arrays stay empty, and native --json retains the original rows. A live fetch failure returns a nonzero exit code even when a prior observation is available. The compatibility array is for single reports. Watch mode and forecasts use the native format.

Usage Response

{
  "schemaVersion": "caut.v1",
  "generatedAt": "2026-01-18T12:00:00Z",
  "command": "usage",
  "data": [
    {
      "provider": "codex",
      "account": "[email protected]",
      "version": "0.6.0",
      "source": "openai-web",
      "status": {
        "indicator": "none",
        "description": "Operational",
        "updatedAt": "2026-01-18T11:00:00Z",
        "url": "https://status.openai.com"
      },
      "usage": {
        "primary": {
          "usedPercent": 28.0,
          "remainingPercent": 72.0,
          "windowMinutes": 180,
          "resetsAt": "2026-01-18T14:15:00Z"
        },
        "secondary": {
          "usedPercent": 59.0,
          "remainingPercent": 41.0,
          "windowMinutes": 10080,
          "resetsAt": "2026-01-24T09:00:00Z"
        },
        "tertiary": null,
        "updatedAt": "2026-01-18T12:00:00Z",
        "identity": {
          "accountEmail": "[email protected]",
          "loginMethod": "google"
        }
      },
      "credits": {
        "remaining": 112.4,
        "events": [],
        "updatedAt": "2026-01-18T12:00:00Z"
      }
    }
  ],
  "errors": [],
  "meta": {
    "format": "json",
    "runtime": "cli"
  }
}

Cost Response

{
  "schemaVersion": "caut.v1",
  "generatedAt": "2026-01-18T12:00:00Z",
  "command": "cost",
  "data": [
    {
      "provider": "claude",
      "source": "local",
      "updatedAt": "2026-01-18T12:00:00Z",
      "sessionCostUSD": 2.45,
      "sessionTokens": 124500,
      "last30DaysCostUSD": 47.82,
      "last30DaysTokens": 2400000,
      "daily": [
        {
          "date": "2026-01-18",
          "totalTokens": 124500,
          "totalCost": 2.45,
          "modelsUsed": ["claude-3-opus", "claude-3-sonnet"]
        }
      ],
      "totals": {
        "inputTokens": 1800000,
        "outputTokens": 600000,
        "totalTokens": 2400000,
        "totalCost": 47.82
      }
    }
  ],
  "errors": [],
  "meta": {
    "format": "json",
    "runtime": "cli"
  }
}

Architecture

┌──────────────────────────────────────────────────────────────┐
│                         CLI Entry                             │
│                        (src/main.rs)                          │
└──────────────────────────┬───────────────────────────────────┘
                           │
              ┌────────────┴────────────┐
              │                         │
              ▼                         ▼
    ┌─────────────────┐       ┌─────────────────┐
    │  Usage Command  │       │  Cost Command   │
    │ (cli/usage.rs)  │       │  (cli/cost.rs)  │
    └────────┬────────┘       └────────┬────────┘
             │                         │
             └──────────┬──────────────┘
                        │
                        ▼
    ┌──────────────────────────────────────────────────────────┐
    │                   Provider Registry                       │
    │                  (core/provider.rs)                       │
    │  ┌─────────┐ ┌─────────┐ ┌─────────┐ ┌─────────┐        │
    │  │  Codex  │ │ Claude  │ │ Gemini  │ │   ...   │        │
    │  └────┬────┘ └────┬────┘ └────┬────┘ └────┬────┘        │
    └───────┼───────────┼───────────┼───────────┼─────────────┘
            │           │           │           │
            └─────┬─────┴─────┬─────┴─────┬─────┘
                  │           │           │
                  ▼           ▼           ▼
    ┌─────────────────────────────────────────────────────────┐
    │                    Fetch Strategies                      │
    │                   (core/fetch_plan.rs)                   │
    │                                                          │
    │  ┌──────────┐  ┌──────────┐  ┌──────────┐  ┌─────────┐ │
    │  │   CLI    │  │   Web    │  │  OAuth   │  │   API   │ │
    │  │  (PTY)   │  │ (cookies)│  │ (tokens) │  │ (keys)  │ │
    │  └──────────┘  └──────────┘  └──────────┘  └─────────┘ │
    └─────────────────────────────────────────────────────────┘
                              │
                              ▼
    ┌─────────────────────────────────────────────────────────┐
    │                      Renderers                           │
    │                    (render/*.rs)                         │
    │                                                          │
    │  ┌──────────────────┐    ┌──────────────────┐           │
    │  │   Human Mode     │    │   Robot Mode     │           │
    │  │   (rich_rust)    │    │   (JSON/MD)      │           │
    │  └──────────────────┘    └──────────────────┘           │
    └─────────────────────────────────────────────────────────┘

Exit Codes

Code Meaning Example
0 Success Normal operation
1 General error Network failure, I/O error
2 Binary not found Provider CLI not installed
3 Parse/config error Invalid arguments, bad JSON
4 Timeout Web fetch exceeded limit

Performance

caut is designed for fast startup and minimal resource usage:

Metric Value
Binary size ~3MB (release, stripped)
Startup time ~10ms
Memory usage ~10MB peak
First response <500ms (cached)

Release builds use aggressive optimization:

[profile.release]
opt-level = "z"     # Optimize for size
lto = true          # Link-time optimization
codegen-units = 1   # Better optimization
panic = "abort"     # Smaller binary
strip = true        # Remove symbols

Troubleshooting

"Provider CLI not found" (Exit 2)

The provider's CLI tool isn't installed or not in PATH.

# Check if codex is installed
which codex

# Check if claude is installed
which claude

"No available fetch strategy" (Exit 3)

No data source is available for the provider:

  • Web source: Requires browser cookies (macOS only)
  • CLI source: Requires provider CLI installed
  • OAuth source: Requires token configuration

Try specifying a source: caut usage --source cli

"Request timeout" (Exit 4)

Web fetch took too long. Increase timeout:

caut usage --web-timeout 60

Colors not showing

TTY detection may fail in some terminals:

# Force colors
TERM=xterm-256color caut usage

# Or disable if corrupted
caut usage --no-color

Cache issues

Force refresh cached data:

caut cost --refresh

Limitations

Limitation Workaround
No GUI Use CodexBar for menu bar app
Web sources (macOS only) Use CLI or OAuth sources on Linux/Windows
Local cost scanning Available for Codex, Claude, and Gemini; other providers expose quota or credit usage
Token account sync Manual token management required

FAQ

How is this different from CodexBar?

caut is a cross-platform CLI port of CodexBar's core functionality. CodexBar is a macOS-native menu bar app with a GUI. caut runs anywhere Rust compiles.

Can I use this with my AI agent?

Yes. Use --json or --format md for structured output. The schema is stable and versioned (caut.v1).

Does it store my credentials?

Token accounts are stored locally in token-accounts.json. Passwords/cookies are read from your system keychain or browser profile—never stored by caut.

How do I add a new provider?

Implement the FetchStrategy trait in src/providers/ and register in the provider registry. See existing providers for examples.

Why Rust?

  • Single static binary, no runtime dependencies
  • Cross-platform (macOS, Linux, Windows)
  • Memory safety without GC overhead
  • Fast startup (~10ms) for CLI tool ergonomics

Why not just use each provider's API?

Most providers don't expose rate limit data via API. caut uses the same data sources as official dashboards: CLI RPC, browser cookies, and OAuth tokens.


About Contributions

Please don't take this the wrong way, but I do not accept outside contributions for any of my projects. I simply don't have the mental bandwidth to review anything, and it's my name on the thing, so I'm responsible for any problems it causes; thus, the risk-reward is highly asymmetric from my perspective. I'd also have to worry about other "stakeholders," which seems unwise for tools I mostly make for myself for free. Feel free to submit issues, and even PRs if you want to illustrate a proposed fix, but know I won't merge them directly. Instead, I'll have Claude or Codex review submissions via gh and independently decide whether and how to address them. Bug reports in particular are welcome. Sorry if this offends, but I want to avoid wasted time and hurt feelings. I understand this isn't in sync with the prevailing open-source ethos that seeks community contributions, but it's the only way I can move at this velocity and keep my sanity.


License

MIT License (with OpenAI/Anthropic Rider). See LICENSE for details.


Acknowledgments

  • CodexBar by Peter Steinberger — the original macOS app this project ports
  • rich_rust — Rust port of Python Rich for terminal output
  • clap — CLI argument parsing
  • tokio — async runtime
  • serde — serialization framework

استكشف مشاريع مشابهة ومرتبطة

جارٍ التحميل…