Skip to content

About

Zero-dependency local token usage, cache analytics, and multi-provider official API cost tracker for Antigravity, Claude Code, and Codex

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

AgentTokenMeter Logo

AgentTokenMeter

Zero-dependency local token usage, prompt cache hit/write analytics, and multi-provider official API cost tracker for Antigravity, Claude Code, Codex, and PI Desktop — one repository, one persistent ledger, native host plugins + live web dashboard.

Changelog · MIT License

Inspiration & Credit: The architecture and design philosophy of this project (zero-dependency Node.js ESM, incremental Stop hook archiving, late-binding pricing, and a live local dashboard) were directly inspired by NianJiuZst/antigravity-token-meter and generalized here to work natively across Antigravity, Claude Code, Codex, and PI Desktop.


Highlights

  • Single Repo, Multi-Agent Native: Coexisting manifests and hooks for Antigravity (plugin.json), Claude Code (.claude-plugin/), Codex (.codex-plugin/), and PI Desktop (manifest.json) with zero configuration conflicts.
  • Host-Scoped by Default, Combined on Demand:
    • Inside Antigravity, the side pane defaults to showing Antigravity alone (automatically revealing a switcher only when logs from additional agents exist).
    • Inside PI Desktop, the docked right work-panel view (Token Meter) and detached window default to showing PI Desktop alone, follow your active conversation and light/dark appearance automatically, and auto-refresh when each turn ends.
    • Inside Claude Code, install statusline defaults to --agent claude-code (pass --all for combined totals).
    • The shared agent skill defaults to querying the current host agent and switches to --agent all when asked for combined totals.
    • Set TOKEN_METER_AGENTS=<agent> or serve --agent <agent> --only for strict single-agent isolation across scanning, hooks, API, and CSV export.
  • Exact Per-Agent Accounting (No Double-Counting):
    • Antigravity: Disjoint input_tokens / cache_read_tokens, torn-line protection, terminal billed step recovery, Swarm/Subagent titles, parent model inheritance, and one-time read-only archive import from legacy ~/.gemini/token-meter.
    • Claude Code: Streaming (message.id, requestId) last-write-wins deduplication, recursive subagents/ & workflows/ isolation (up to depth 8), usage.iterations[] compaction & thinking_tokens accounting, 5-minute (1.25x) vs 1-hour (2.0x) cache_creation tiers, and speed: fast (2x) / inference_geo: us (1.1x) pricing.
    • Codex: Cumulative total_token_usage delta & token_usage_record accounting (preventing duplicate/delayed-replay inflation), forked/subagent session_meta isolation, revert rollout disambiguation, .jsonl.zst compressed & archived_sessions/ scanning, service_tier (priority/fast 2x, flex 0.5x) tracking, inclusive-to-disjoint cached_input_tokens / cache_write_input_tokens normalization, reasoning_output_tokens subset tracking, and turn_context model lookahead.
    • PI Desktop: Strictly read-only node:sqlite (readOnly: true + PRAGMA query_only = ON) sync of pi.sqlite turns and per-request usage_json.operations[] (attributing parent, retry, compaction, and subagent requests to their true physical models with zero double-counting of imported Codex / Claude Code history), plus automatic detection of optional sibling Ecosystem isolated-agent ledgers (lyra/ledger/, jobs/*/receipts.jsonl, institution/runs/*/advance.json, github-daily/state/*/events.jsonl).
  • Zero Dependencies & 100% Local: Pure Node.js ESM (>=22.15.0, using built-in node:zlib zstd and node:sqlite). No npm install, no telemetry, no external network calls. Only normalized numeric metrics and short session titles are persisted under ~/.agent-token-meter/ (never raw message bodies).
  • Persistent Archive Ledger: Monthly NDJSON ledger (events/YYYY-MM.jsonl) with cross-process file locking and Windows-safe atomic rewrites. Historical usage survives even if original transcripts are later cleaned up.
  • Multi-Provider Official Pricing + Custom Overrides: Declarative official rate cards for Google Gemini, Anthropic Claude, OpenAI GPT / Codex, and xAI Grok (including >200K Gemini/Claude/Grok and >272K OpenAI long-context tiers; official 1.25x/2.5x cache-write tiers on GPT-6.x/GPT-5.6 with estimated 2x long-context scaling, and 1.0x input rate for models without published cache-write pricing) in core/rate-card.mjs, strict suffix matching (preventing mispricing of future minor versions/tiers), honest unpriced marking for unknown models, and optional <dataDir>/pricing.override.json for custom models or channel multipliers.

Installation

1. Antigravity

Clone directly into your global Antigravity plugins directory:

git clone https://github.com/KennyMcSimpson/AgentTokenMeter.git ~/.gemini/config/plugins/agent-token-meter

Antigravity automatically discovers plugin.json, activates the root Stop hook, loads the agent-token-meter skill, and launches the live side-pane dashboard (sidecar://agent-token-meter/dashboard/).

2. Claude Code

Option A — Native Plugin Marketplace:

/plugin marketplace add KennyMcSimpson/AgentTokenMeter
/plugin install agent-token-meter@agent-token-meter-marketplace

Option B — Local Clone + Non-Destructive Hook & StatusLine Setup:

git clone https://github.com/KennyMcSimpson/AgentTokenMeter.git ~/AgentTokenMeter
cd ~/AgentTokenMeter

# Preview changes safely with --dry-run first
node bin/token-meter.mjs install claude --dry-run
node bin/token-meter.mjs install claude

# Optional: add a compact live statusLine HUD (defaults to Claude Code only; pass --all for combined totals)
node bin/token-meter.mjs install statusline

3. Codex

Clone the repository and optionally wire the non-destructive Stop hook (strictly compliant with Codex hooks.json schema, preserving any existing description and third-party hooks):

git clone https://github.com/KennyMcSimpson/AgentTokenMeter.git ~/AgentTokenMeter
cd ~/AgentTokenMeter

# Preview first, then install Stop hook into $CODEX_HOME/hooks.json
node bin/token-meter.mjs install codex --dry-run
node bin/token-meter.mjs install codex

Codex 0.171+ Hook Trust Requirement: Codex treats newly added user hooks as untrusted until you explicitly approve them. Open /hooks in Codex TUI (or the Hooks settings panel in Codex Desktop) and trust the AgentTokenMeter Stop hook so it runs automatically at the end of each turn. The installer deliberately never auto-writes trust hashes. Even before approving the hook, summary and serve perform fast incremental scans across both $CODEX_HOME/sessions/ and $CODEX_HOME/archived_sessions/ (including .jsonl.zst archives).

4. PI Desktop

  1. Clone or keep the repository locally (zero build step, zero symlinks).
  2. In PI Desktop, open Extensions (plug icon in the bottom-left sidebar) → ... → Load local plugin and select the AgentTokenMeter directory (PI automatically loads root manifest.json).
  3. Open Token Meter in the right work panel (or run Open Token Meter Dashboard / Open Token Meter Window from the command palette).
  4. Loading the plugin automatically registers PI's active <dataDir> into ~/.agent-token-meter/sources.json so Antigravity, Claude Code, Codex, and standalone CLI/Web views see PI usage automatically too. You can also register a custom PI profile directory manually via CLI:
node bin/token-meter.mjs install pi --data-dir /path/to/pi/desktop

5. Standalone Local Web Dashboard (Single-Agent or Combined)

# Combined dashboard across all detected agents (auto-hides switcher if only 1 agent has data)
node bin/token-meter.mjs serve --port 3456

# Strict single-agent dashboard (scans and displays only one agent)
node bin/token-meter.mjs serve --port 3456 --agent claude-code --only
node bin/token-meter.mjs serve --port 3456 --agent codex --only
node bin/token-meter.mjs serve --port 3456 --agent pi --only
# Open http://127.0.0.1:3456

CLI Reference

# 7-day cross-agent summary (auto-syncs new logs first)
node bin/token-meter.mjs summary --days 7

# Filter by agent: all | antigravity | claude-code | codex | pi
node bin/token-meter.mjs summary --days 7 --agent claude-code
node bin/token-meter.mjs summary --days 7 --agent codex
node bin/token-meter.mjs summary --days 7 --agent pi
node bin/token-meter.mjs summary --days 1 --agent antigravity

# All-time JSON report
node bin/token-meter.mjs summary --days 0 --json

# Launch local web dashboard (loopback only, DNS-rebinding protected)
node bin/token-meter.mjs serve --port 3456

# Compact one-line output for Claude Code statusLine
node bin/token-meter.mjs statusline --agent claude-code

# View built-in Google / Anthropic / OpenAI / xAI rate card
node bin/token-meter.mjs pricing

# Switch display currency (USD / CNY)
node bin/token-meter.mjs set-currency CNY --rate 7.25

# Export daily breakdown to CSV
node bin/token-meter.mjs export --days 30 --agent all --out usage.csv

# Full rescan & compaction (preserves archived records from deleted logs)
node bin/token-meter.mjs sync --full

# Cleanly remove installed hooks or statusLine (preserves third-party entries)
node bin/token-meter.mjs uninstall claude
node bin/token-meter.mjs uninstall statusline
node bin/token-meter.mjs uninstall codex

Environment Variables & Custom Pricing

Variable Purpose
AGENT_TOKEN_METER_DATA_DIR Dedicated ledger directory override (takes precedence over TOKEN_METER_DATA_DIR; recommended if legacy v1 token-meter is still installed)
TOKEN_METER_DATA_DIR Override ledger directory (default: ~/.agent-token-meter)
TOKEN_METER_AGENTS Comma-separated allowlist of enabled agents (e.g. claude-code or antigravity,codex) enforced end-to-end
TOKEN_METER_DEFAULT_AGENT Override default initial view in the Antigravity sidecar (antigravity by default)
TOKEN_METER_BRAIN_ROOTS Override Antigravity brain roots (: / ; separated; empty string disables scan)
TOKEN_METER_CLAUDE_ROOTS Override Claude Code project roots (defaults to $CLAUDE_CONFIG_DIR/projects or ~/.claude/projects)
TOKEN_METER_CODEX_ROOTS Override Codex session roots (defaults to $CODEX_HOME/sessions and $CODEX_HOME/archived_sessions)
TOKEN_METER_PI_ROOTS Override PI Desktop data/state roots (; / : separated; empty string disables scan; auto-discovers PI_DESKTOP_DATA_DIR, PI_ECOSYSTEM_PROFILE_FILE, <dataDir>/sources.json, storage-location.json, and ~/.pi-desktop)
TOKEN_METER_MAX_ZSTD_BYTES Override per-archive .jsonl.zst decompression safety limit in bytes (default: 2 GiB)

Create <dataDir>/pricing.override.json to add custom models or apply channel/proxy multipliers:

{
  "multipliers": {
    "antigravity": 1.0,
    "claude-code": 1.0,
    "codex": 1.0
  },
  "models": {
    "my-internal-model": {
      "provider": "custom",
      "input": 1.5,
      "cacheRead": 0.15,
      "cacheWrite5m": 1.875,
      "cacheWrite1h": 3.0,
      "output": 7.5
    }
  }
}

Architecture

AgentTokenMeter/
├── plugin.json                     # Antigravity root plugin manifest
├── hooks.json                      # Antigravity root Stop hook
├── manifest.json                   # PI Desktop native plugin manifest (zero conflict with plugin.json)
├── .claude-plugin/
│   ├── plugin.json                 # Claude Code plugin manifest
│   └── marketplace.json            # Claude Code marketplace catalog
├── .codex-plugin/
│   └── plugin.json                 # Codex plugin manifest
├── hooks/
│   ├── hooks.json                  # Claude Code Stop & SubagentStop hooks
│   └── record.mjs                  # Universal cross-host Stop hook entrypoint
├── pi/
│   └── main.mjs                    # Thin PI Desktop plugin host (onPanelInvoke + turn-end sync + API fallback)
├── core/
│   ├── fs-utils.mjs                # Cross-process lock + Windows-safe atomic writes + JSONL collector
│   ├── jsonl-reader.mjs            # Shared offset/inode delta reader (torn-line & shrink safe)
│   ├── rate-card.mjs               # Declarative official Google / Anthropic / OpenAI / xAI rate table
│   ├── pricing.mjs                 # Pricing engine + strict suffix guard + overrides + prefs + local sources
│   ├── store.mjs                   # Unified v2 ledger (v1 backward compatible) + cache
│   ├── sync.mjs                    # Multi-adapter & multi-session sync orchestration
│   └── report.mjs                  # Cross-agent aggregation, ETag & CSV export
├── adapters/
│   ├── index.mjs                   # Adapter registry, allowlist & path/content auto-detection
│   ├── antigravity.mjs             # ~/.gemini/*/brain adapter
│   ├── claude-code.mjs             # ~/.claude/projects adapter (LWW + subagents + 5m/1h CW)
│   ├── codex.mjs                   # $CODEX_HOME/sessions adapter (cumulative delta + inclusive fix)
│   └── pi.mjs                      # PI Desktop read-only SQLite + optional companion ledger adapter
├── server/
│   ├── api.mjs                     # Transport-agnostic API controller
│   └── http.mjs                    # Zero-dep loopback HTTP server (Host/Origin validated)
├── sidecars/dashboard/             # Thin Antigravity SidecarApp wrapper
├── ui/                             # Single shared frontend (HTML / CSS / SVG JS + HostBridge)
├── bin/
│   ├── token-meter.mjs             # Unified CLI & Claude Code statusLine
│   └── installer.mjs               # Non-destructive config merger (--dry-run supported)
├── skills/agent-token-meter/
│   └── SKILL.md                    # Shared agent skill instructions (host-scoped by default)
└── test/                           # Unit, adapter, concurrency, security, HTTP/CLI & manifest tests

Testing

npm test
# or
node --test test/*.test.mjs

Credits & License

About

Zero-dependency local token usage, cache analytics, and multi-provider official API cost tracker for Antigravity, Claude Code, and Codex

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages