Skip to content

Latest commit

 

History

28 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Tokenhawk

Tokenhawk is a local, live token-usage monitor for Claude Code, Codex, Gemini CLI, Antigravity CLI (agy), Pi, and OpenCode. It indexes session metadata from the tools' normal home-directory stores and presents active sessions, history, per-model usage, spend since a chosen date, and API-rate costs in a Bubble Tea terminal UI.

Tokenhawk never stores prompts, responses, tool arguments, credentials, or transcript content in its index or normal exports. The explicit transcript-search features read provider transcripts on demand and show only matching user/assistant text; they do not persist that text.

The dashboard uses a responsive control-center layout with persistent four-view navigation, live activity context, compact filters, and an adaptive command dock. Session rows include input, cached input, output, total, normalized input-to-output ratios, running/total subagents, and cost at medium and wide terminal sizes. Press Tab or Shift+Tab to move between views, use 14 to jump directly, and press ? for the built-in keyboard reference. Session detail breaks out Claude, Codex, and OpenCode subagents with their model, token categories, ratio, status, and cost.

Sessions with at least 100,000 input tokens and less than an 80% cached-input ratio are highlighted with a red warning in the dashboard. Detail identifies low-cache parent and subagent workloads separately.

Screenshots

The dashboard lists session history across multiple providers with per-model usage, API-rate and reported cost, normalized input-to-output ratios, running subagent counts, and red high-input, low-cache warnings.

Tokenhawk dashboard showing session history across Claude, Codex, Gemini, and Pi

Selecting a session opens a detail view that breaks out parent and subagent usage per model, marks running versus inactive subagents, and includes a copy-ready resume command.

Tokenhawk session detail with parent and subagent breakdown

Option 4 searches user and assistant transcript text on demand across providers. Literal matching is the default; Ctrl+R toggles Go regular-expression matching.

Tokenhawk transcript search using a regular expression across multiple providers

Option 3 opens spend analysis with UTC token and cost line graphs, provider/model/day breakdowns, and explicit JSON/CSV export shortcuts.

Tokenhawk spend analysis with token and cost line graphs, breakdowns, and JSON/CSV exports

The layout is responsive: narrow terminals collapse the table columns, navigation, and context labels to fit.

Tokenhawk in a narrow terminal

Screenshots use synthetic demo data.

Features

  • Live, local monitoring of Claude Code, Codex, Gemini CLI, Antigravity CLI (agy), Pi, and OpenCode sessions
  • Compact per-session status output for shell, JSON, ANSI, and tmux integrations
  • Native Claude Code and Antigravity status-line integrations and tmux-backed wrappers for every supported client
  • Separate Live, Session History, and Spend views
  • On-demand, local search across current and previous user/assistant messages
  • Spend totals, input-to-output ratios, and UTC token/cost line graphs since any relative or absolute date, broken out by provider, model, and day
  • Per-session and per-model input, cached, output, reasoning, tool, and total tokens
  • Parent/subagent accounting with running-agent counts and detailed child usage
  • Public API-rate costs and provider-reported costs with explicit status
  • High-input, low-cache warnings at a documented threshold
  • View-specific JSON and CSV exports: visible sessions, selected-session detail with loaded conversation, or spend totals, breakdowns, and daily UTC points
  • Rebuildable SQLite index; provider transcript files remain untouched

Install, build, and run

Install the latest compiled release on macOS or Linux:

/bin/sh -c "$(curl -fsSL https://tokenhawk.dev/install.sh)"
tokenhawk

The installer detects your operating system and architecture, verifies the release checksum, and installs to ~/.local/bin. Add that directory to your PATH if the installed command is not found.

Alternatively, with Go 1.26 or newer, install the latest tagged release directly from the module root:

go install github.com/polera/tokenhawk@latest
tokenhawk

Ensure $(go env GOPATH)/bin is on PATH if the installed command is not found.

Precompiled binaries for Linux, macOS, and Windows on amd64 and arm64 are also available from GitHub Releases. Download the archive for your platform, extract tokenhawk (tokenhawk.exe on Windows), and place it somewhere on your PATH. Each release includes checksums.txt for verifying the download.

Tokenhawk checks GitHub Releases once a day when starting the interactive UI. If a newer release is available, choose to install it or defer the prompt for 24 hours. To check and upgrade immediately, run:

tokenhawk upgrade

Upgrades download the release archive for the current operating system and architecture, verify it against the published SHA-256 checksum, and replace the current executable.

Or build a local checkout with Go 1.26 or newer:

go build -o tokenhawk .
./tokenhawk

Run it in a dedicated terminal tab or window. By default Tokenhawk reads:

  • Claude: ~/.claude/projects/**/*.jsonl
  • Codex: $CODEX_HOME/sessions/**/*.jsonl and archived_sessions, or ~/.codex
  • Gemini: ~/.gemini/tmp/*/chats/session-*.json
  • Antigravity (agy): ~/.gemini/antigravity-cli/conversations/*.db
  • Pi: ${PI_CODING_AGENT_SESSION_DIR:-~/.pi/agent/sessions}/**/*.jsonl
  • OpenCode: ${XDG_DATA_HOME:-~/.local/share}/opencode/opencode.db

The rebuildable SQLite index lives under the operating system's user cache directory. OpenCode's database is opened read-only, including live WAL data. Missing provider directories and databases are allowed.

Search session contents

Search current and previous sessions with a case-insensitive literal query:

tokenhawk search "database migration"
tokenhawk search --provider codex --project "$PWD" --since 30d "SQLite"
tokenhawk search --role user --session SESSION_ID --format json "cache invalidation"
tokenhawk search --regex 'migration \d+_\w+'

Search reads Claude, Codex (including archived sessions), Gemini, Antigravity CLI, Pi, and OpenCode transcripts directly each time it runs. Results contain the provider, session, project, timestamp, role, and a short matching snippet, newest first. Use --until, --limit, or --case-sensitive to narrow the result set, or --regex to treat the query as a Go regular expression. Search flags must precede the query.

Inside the interactive TUI, press 4 to open Transcript Search, type a query, and press Enter. Use the arrow or page keys to select a result, Enter to open its normal session detail view, p to search the next provider, / to edit the query, ctrl+r to toggle between literal and regex matching, and r to refresh results from the provider stores.

The numbered views remain available from every dashboard screen. Tab and Shift+Tab move forward and backward through Live, History, Spend, and Search; ? opens the complete shortcut reference without leaving the current view.

Every session detail view automatically loads and displays a chronological conversation from the raw transcript after its usage breakdown, containing user and assistant text while excluding tool traffic and reasoning. Use the arrow keys to move by line, Page Up/Page Down (or Left/Right) to move by page, / to find text, n/N to move between matches, r to reload, and Escape to return to the session list. Exporting from session details includes the complete loaded conversation with each message's role, timestamp, subagent ID, and text; bulk and headless exports remain metadata-only.

Only user and assistant text is searched. Tool calls, tool results, reasoning blocks, structured credential fields, and other non-message payloads are excluded, and no transcript content is added to Tokenhawk's SQLite index. Search returns one review entry per matching session, represented by its newest hit. As with any transcript viewer, a matching secret that was pasted into a user or assistant message can appear in its snippet. Antigravity conversation bodies are protobuf payloads inside their SQLite stores; Tokenhawk decodes only their user-input and assistant-prose fields and leaves reasoning summaries, tool invocations, and every other field opaque.

Live metrics inside agent sessions

The compact renderer always selects one session; it never combines usage from multiple sessions. Claude provides an exact session ID. The wrappers for other clients select the active, most recently updated session belonging to the current project directory.

Example output:

TOKENHAWK  codex · in 11.80M · cache 96.6% · out 76.4k · I:O 154:1 · $4.2800 · 2/4 agents

At 100,000 or more input tokens, a cache ratio below 80% changes the status display to the red LOW CACHE alarm. Use the renderer directly when integrating with another terminal tool:

tokenhawk status --provider codex --project "$PWD"
tokenhawk status --provider claude --session SESSION_ID --format json
tokenhawk status --provider gemini --project "$PWD" --format ansi

By default the command incrementally scans the provider stores before rendering. Add --no-scan when another Tokenhawk process is already maintaining the index. Set NO_COLOR=1 to turn ANSI status-line output into plain text.

Claude Code: native status line

Claude Code's status-line command can run Tokenhawk directly and supplies the exact session_id. Add this to ~/.claude/settings.json, merging it with any existing settings:

{
  "statusLine": {
    "type": "command",
    "command": "tokenhawk statusline claude",
    "refreshInterval": 2,
    "padding": 0
  }
}

The line refreshes on Claude events and every two seconds while the session is idle. The command consumes Claude's status JSON from stdin; it does not add anything to the model context. Claude can also use the universal wrapper below with tokenhawk wrap claude.

Codex: live tmux status bar

Codex's configurable footer accepts built-in item identifiers, not external command output. Run Codex through Tokenhawk to add a live project-session status row:

tokenhawk wrap codex
tokenhawk wrap codex --cd /path/to/project
tokenhawk wrap codex resume SESSION_ID

Gemini CLI: live tmux status bar

Gemini's footer likewise exposes built-in items rather than an external renderer:

tokenhawk wrap gemini
tokenhawk wrap gemini --model gemini-2.5-pro
tokenhawk wrap gemini --resume SESSION_ID

Antigravity CLI (agy): native status line

AGY's custom status line supplies the exact conversation ID, workspace, active model, and cumulative input/output totals. Add this block to ~/.gemini/antigravity-cli/settings.json, merging it with the settings already there:

{
  "statusLine": {
    "type": "command",
    "command": "tokenhawk statusline agy",
    "enabled": true,
    "stack_with_default": true
  }
}

AGY invokes Tokenhawk whenever its agent state changes. Tokenhawk ignores account and quota fields in the payload, stores the live usage snapshot under the conversation UUID, and renders the compact line inside AGY. AGY exposes cumulative input and output but only the current cache counters, so cached input is recorded as the best lower bound available.

Conversation files that predate this configuration are still discovered, but their token totals remain empty until the conversation is resumed and AGY emits a status payload. The universal tmux wrapper is also available:

tokenhawk wrap agy
tokenhawk wrap agy --model "Gemini 3.5 Flash (High)"
tokenhawk wrap agy --conversation SESSION_ID

Pi: live tmux status bar

Pi records provider/model token categories and its own calculated cost in each JSONL session; Tokenhawk preserves that reported cost rather than repricing it:

tokenhawk wrap pi
tokenhawk wrap pi --model anthropic/claude-sonnet-4-5
tokenhawk wrap pi --session SESSION_ID

Tokenhawk respects PI_CODING_AGENT_DIR and PI_CODING_AGENT_SESSION_DIR when discovering sessions.

OpenCode: live tmux status bar

Tokenhawk reads current OpenCode session, message, child-session, token, cache, reasoning, and reported-cost data from its SQLite database. OpenCode documents the database location through opencode db path:

tokenhawk wrap opencode
tokenhawk wrap opencode /path/to/project
tokenhawk wrap opencode --session SESSION_ID

tokenhawk wrap prefers tmux. Outside tmux it creates a dedicated temporary session with Tokenhawk's colors. Inside tmux it temporarily replaces the current session's right-side status, runs the client, and restores the previous settings when the client exits. All remaining arguments are forwarded unchanged to the selected client.

Without tmux — or with tokenhawk wrap --no-tmux <provider> — the wrapper runs the client in a built-in pseudo-terminal that reserves the bottom terminal row for the same live status line (macOS and Linux only). The client sees a terminal one row shorter; everything else, including keystrokes, resizes, and colors, passes through unchanged.

Controls

Key Action
1, 2 Live sessions, session history
3 Spend since a date
4 Search current and previous transcript contents
i Toggle between active and inactive session lists
j/k, arrows, page keys Navigate
p Cycle provider filter
s Sort by updated time, tokens, or cost
/ Filter by project or model metadata
t Cycle the spend window (spend view)
d Type a spend window (spend view)
e Export the current view as JSON
x Export the current view as CSV
enter Session detail, including a provider-specific resume command
q Quit

Spend since a date

Press 3 for tokens and cost across a window instead of per session. The view totals input, cached input, output, and cost for the window, graphs token usage and cost over time, then breaks the same window out by provider, by model, and by day:

SPEND · last 7 days
2026-07-13 09:41 → now  •  23 of 25 sessions  •  usage counted on the UTC day it was indexed

TOTAL  tokens 17.30M  in 16.71M  cached 15.99M (96%)  out 238.3k  i:o 70.1:1
       $20.184584 API rate

TOKEN USAGE & COST OVER TIME (UTC)  · daily totals
  TOKENS  peak 5.17M
   6.00M│                         ⣀●
       │ · · · · · · · · · · ⡠⠊
   2.00M│       ●⠢⡀     ⡠●⠊
       │⡠●⠊     ⠑●⠊
      0└──────────────────────────
       Jul 07      Jul 10       Jul 13

  COST (USD)  peak $6.29
  $7.50│                         ⣀●
       │ · · · · · · · · · · ⡠⠊
  $2.50│       ●⠢⡀     ⡠●⠊
       │⡠●⠊     ⠑●⠊
  $0.00└──────────────────────────
       Jul 07      Jul 10       Jul 13

BY PROVIDER
  codex  ████████████    12 sess  tokens 10.25M  in 10.14M  cached 9.42M  out 117.5k  i:o 86.3:1  $11.8310
  claude ████████····    11 sess  tokens  7.04M  in  6.57M  cached 6.57M  out 120.8k  i:o 54.4:1  $8.3536

BY MODEL
  gpt-5.6-sol ████████████  8 sess  tokens 8.20M  in 8.08M  cached 7.70M  out 90.0k  i:o 89.8:1  $8.4500
      API rate: 380.0k input × $5/M  +  7.70M cached input × $0.5/M
                0 cache write × $6.25/M  +  90.0k output × $30/M
                =  $8.450000  ·  codex rate effective 2026-06-26

API-priced model rows show the uncached input, cached input, cache-write, and output quantities alongside the effective catalog rates used for each. If a window crosses a price change, Tokenhawk shows a separate rate breakdown for each effective period. Gemini reasoning tokens are included in its billed output quantity.

t cycles the built-in windows: last 24 hours, 7 days, 30 days, month to date, and all time. d accepts a typed window, and --since opens Tokenhawk directly on one:

tokenhawk --since 30d
tokenhawk --since 2026-07-01

Windows accept RFC 3339 timestamps, YYYY-MM-DD dates, relative offsets (90m, 24h, 7d, 2w, 3mo, 1y, or any Go duration), and the keywords today, yesterday, wtd, mtd, ytd, and all. Relative windows keep rolling while Tokenhawk stays open. The provider filter and the / search narrow the spend view and its exports too.

On the spend view, e and x export the displayed totals and provider, model, and day breakdowns rather than raw sessions. The export also includes one token-and-cost time-series point per UTC day, including zero-value days. Daily resolution is the finest available because provider stores expose running session totals rather than timestamped token events.

Provider stores record one running total per session rather than a timestamped ledger, so Tokenhawk maintains its own: each scan records how much every session grew on the current UTC day. A long-running session's usage is therefore spread across the days it was actually active while Tokenhawk was indexing. History discovered in a single pass — a first scan or a --rebuild — cannot be split retroactively and lands on the session's last-update day.

Headless export

tokenhawk export --format json --output usage.json
tokenhawk export --format csv --output usage.csv --provider codex --since 2026-07-01
tokenhawk export --format csv --output usage.csv --since mtd

Filters include --provider, --model, --project, --status, --since, and --until. Both dates accept every window form the spend view accepts; a bare YYYY-MM-DD in --until includes that whole day. JSON contains nested per-model and subagent usage. CSV contains tagged session/model and subagent/model rows, including costs and running status. Source paths are excluded unless --include-source is set.

Configuration

Tokenhawk loads tokenhawk/config.toml below the OS user-config directory. All fields are optional:

claude_dir = "~/.claude/projects"
codex_dir = "~/.codex"
gemini_dir = "~/.gemini/tmp"
agy_dir = "~/.gemini/antigravity-cli"
pi_dir = "~/.pi/agent/sessions"
opencode_db = "~/.local/share/opencode/opencode.db"
active_window = "5m"
refresh = "2s"
db_path = "~/.cache/tokenhawk/index.db"
pricing_file = "~/.config/tokenhawk/pricing.json"
anthropic_cost_lookback_days = 31
include_source = false

Equivalent CLI flags override the loaded values. Use --rebuild after changing source roots. Pricing catalog and override changes are fingerprinted and automatically trigger a one-time rebuild so stored API-rate costs cannot remain stale.

Pricing

Claude, Codex, Gemini, and recognized models used through AGY are priced from their exact recorded token counts at public API list rates. These API-rate costs do not represent subscription charges, invoices, free-tier consumption, discounts, credits, or taxes; subscription users can read them as the API value included with their plan. AGY model labels are normalized before exact lookup and use the underlying Gemini or Claude catalog rate. Unknown identifiers remain marked unpriced rather than inheriting a guessed family rate. Pi and nonzero costs recorded by OpenCode are labeled reported and preserved instead of being repriced. When OpenCode records zero cost for a recognized openai, anthropic, or google model, Tokenhawk applies the underlying model's public API list rate instead.

Anthropic-reported spend

Organization administrators can give Tokenhawk read access to Anthropic's Usage and Cost Admin API through an Admin API key:

export ANTHROPIC_ADMIN_KEY='sk-ant-admin...'
tokenhawk

Tokenhawk calls GET /v1/organizations/cost_report grouped by description, preserves the response's fractional-cent USD amounts, and stores a daily ledger of organization-wide costs by exact model identifier. The first interactive run imports 31 UTC days by default; anthropic_cost_lookback_days or --anthropic-cost-lookback-days can widen that bootstrap. While Tokenhawk remains open it refreshes the current and previous UTC day every five minutes. The key is read only from the environment and is never written to Tokenhawk's configuration or index.

The Spend view uses these rows as reported cost for covered UTC days and removes the overlapping Claude API-rate cost, while keeping local session tokens and API-rate costs for other providers. It displays reported and API-rate dollars separately when both occur in a window. Anthropic's report has no local session or project ID, so reported costs are not assigned to individual sessions and are excluded while a Spend search is active. Both the local usage ledger and the reported cost buckets use UTC days.

The Admin API is unavailable to individual accounts. For Pro and Max subscriptions, model use is included in the subscription and there is no authoritative per-model billed spend to import. Priority Tier charges and usage routed through Bedrock, Vertex, Foundry, or Claude Platform on AWS are also not reported by this endpoint; those remain API-rate costs unless their billing provider is integrated separately.

Session detail includes a copy-ready resume command. Tokenhawk changes to the recorded project directory first because resume behavior can be project-sensitive.

A pricing override file can add exact identifiers or replace a bundled rate:

{
  "version": "company-rates-1",
  "rates": [
    {
      "provider": "codex",
      "model": "my-exact-model-id",
      "effective_from": "2026-01-01",
      "input_per_million": 1.0,
      "cached_input_per_million": 0.1,
      "cache_creation_per_million": 1.0,
      "output_per_million": 8.0
    }
  ]
}

About

A live, local monitor for your AI coding sessions. See usage, cache efficiency, subagents, and cost across every tool, without your data leaving the machine.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages