agy-token-stats
Zero-dependency CLI and Python library for analyzing token usage, prompt cache efficiency, thinking token decomposition, model breakdowns, context growth, and subagent trees across Antigravity (agy) CLI and IDE sessions.
Overview
Antigravity records structured per-step execution transcripts for every root session and spawned subagent conversation across two local brain directories:
- CLI brain:
~/.gemini/antigravity-cli/brain/<conversation-id>/ - IDE brain:
~/.gemini/antigravity/brain/<conversation-id>/
Within each conversation directory:
.system_generated/logs/transcript.jsonlstores chronological step records (USER_INPUT,PLANNER_RESPONSE,SYSTEM_MESSAGE, etc.), including native token counters (input_tokens,cache_read_tokens,output_tokens),thinkingtext,content, and tool call payloads..system_generated/subagents/<child-id>.jsonstores explicit parent-to-child subagent descriptors (typeName,role,spawnStepIndex,workspaceUris).~/.gemini/antigravity-cli/history.jsonl(optional) stores workspace paths and user prompt history for CLI sessions.
agy-token-stats discovers all sessions across CLI and IDE brains, reconstructs multi-level subagent trees (root -> implementer / oracle / reviewer / bash-executor), tracks and propagates model selections across steps and subagents, filters by local-time windows or --model, and produces human-readable tables or structured JSON reports without double counting.
Token Metrics, Thinking Decomposition & Subagent Tree Rollups
Token Metric Definitions
| Metric | Formula / Meaning |
|---|---|
uncached_input |
Sum of native input_tokens across PLANNER_RESPONSE steps (prompt tokens not served from cache). |
cache_read |
Sum of native cache_read_tokens across PLANNER_RESPONSE steps. |
gross_input |
uncached_input + cache_read — total prompt context processed by the model across all calls. |
cache_hit_pct |
cache_read / gross_input * 100 (0.0% when gross_input == 0). |
output_tokens |
Sum of native output_tokens generated across PLANNER_RESPONSE steps (includes thinking + visible content + tool calls). |
thinking_tokens |
Estimated portion of output_tokens spent on thinking text (0 <= thinking_tokens <= output_tokens). |
response_tokens |
max(0, output_tokens - thinking_tokens) — estimated non-thinking output tokens (visible content + tool calls). |
thinking_pct |
thinking_tokens / output_tokens * 100 (0.0% when output_tokens == 0). |
thinking_steps |
Number of PLANNER_RESPONSE steps with non-empty thinking text. |
net_tokens |
uncached_input + output_tokens — non-cached tokens processed plus output generated. (thinking_tokens is a decomposition of output_tokens and is never double-counted.) |
total_tokens |
gross_input + output_tokens — total tokens processed including prompt cache reads. |
initial_context |
gross_input of the first PLANNER_RESPONSE step in the session/window. |
peak_context |
Maximum single-step context (input_tokens + cache_read_tokens + output_tokens) across included PLANNER_RESPONSE steps. |
approx_cost_usd |
Approximate Gemini API Paid Tier USD cost (input_cost_usd + cache_cost_usd + output_cost_usd) across priced calls. |
cache_savings_usd |
Approximate USD saved by prompt cache hits vs. uncached input pricing. |
Approximate Gemini Pricing
When steps map to a Gemini model (including Gemini 4 Hydrogen/Neon/Argon/Carbon, Gemini 3.x Pro/Flash/Flash-Lite, and Gemini 2.x), agy-token-stats computes approximate costs using Google AI Studio Gemini API Paid Tier rates (USD / 1M tokens):
uncached_inputis billed at the model's standard (or>200klong-context) input rate.cache_readis billed at the model's context-caching read rate, andcache_savings_usdtracks the discount relative to uncached input.output_tokens(which already includes thinking tokens) is billed at the model's combined output rate.- Non-Gemini or
Unknownmodel calls are excluded from cost totals (shown as—, with partial aggregates marked*).
Thinking Token Estimation
Native Antigravity PLANNER_RESPONSE entries emit a single combined output_tokens counter covering internal reasoning (thinking), visible response text (content), and serialized tool invocations (tool_calls).
For each PLANNER_RESPONSE step with non-empty thinking:
- Untruncated text sizes (
thinking_len,content_len,tool_calls_len) are computed, expanding any<truncated N bytes>markers recorded intranscript.jsonl. - When
output_tokens > 0:- If
content_len + tool_calls_len == 0,thinking_tokens = output_tokens. - Otherwise,
thinking_tokens = min(output_tokens, max(1, round(output_tokens * (thinking_len / (thinking_len + content_len + tool_calls_len))))).
- If
response_tokens = output_tokens - thinking_tokens, preserving the exact invariantthinking_tokens + response_tokens == output_tokens.
Fallback character estimation: If a legacy or truncated
PLANNER_RESPONSEstep omits bothinput_tokensandoutput_tokens,agy-token-statsestimatesinput_tokens = ceil(accumulated_context_chars / 4)andoutput_tokens = ceil(step_text_chars / 4), setsis_estimated = True, and reports the exact count of estimated steps in the header.
Model Attribution & Subagent Inheritance
- Sequential step tracking:
<USER_SETTINGS_CHANGE>model tags (changed setting Model Selection from ... to <Model>.) are tracked chronologically acrossUSER_INPUTsteps. If a user switches models mid-session, steps before and after the switch are attributed to their respective models inby_model. - Subagent inheritance: Subagent transcripts begin with
SYSTEM_MESSAGE(step_index: 0) and omit<USER_SETTINGS_CHANGE>. During discovery, models are propagated top-down from parent sessions to child and grandchild subagents using the parent's active model atspawnStepIndex(or any explicitinvoke_subagentModeloverride).
Subagent Tree Rollup vs. Flat Mode
- Parent-Child Linking:
- Primary: Explicit descriptor files in
<parent>/.system_generated/subagents/<child>.jsonprovideparent_id,typeName(oracle,implementer,reviewer,bash-executor, etc.),role,spawnStepIndex, and workspace fallback. - Fallback: If a descriptor file is missing, an initial
SYSTEM_MESSAGEstep containingsender=<parent-uuid>links the subagent to its parent session (with cycle prevention).
- Primary: Explicit descriptor files in
- No Double Counting:
overall,by_source,by_role,by_model, anddailyaggregate each active step exactly once.- In tree mode (default), the
Sessionstable displays top-level root sessions withtree_metrics(parentself_metrics+ all descendant subagents'self_metrics). Passing--show-subagents(or--session <id>) expands an indented breakdown showing├─ <id> (self)and each active child/grandchild subagent row. - In flat mode (
--flat), every conversation UUID is listed independently withtree_metrics == self_metrics.
Installation
agy-token-stats requires Python 3.9+ and has zero third-party runtime dependencies.
# Install from PyPI
pip install agy-token-stats
# or isolated CLI via uv / pipx
uv tool install agy-token-stats
pipx install agy-token-stats
# Or install directly from GitHub
uv tool install git+https://github.com/vikrant82/agy-token-stats.git
CLI Options
| Flag | Description |
|---|---|
--source {all,cli,ide} |
Brain source(s) to scan when --brain-dir is not specified (default: all). |
--brain-dir [LABEL=]PATH |
Override brain root directory to scan (repeatable, e.g. --brain-dir cli=/path/to/brain). |
--history-file PATH |
Path to CLI history.jsonl for workspace/title enrichment. |
--today |
Include activity from today 00:00:00 local time to now. |
--yesterday |
Include activity from yesterday 00:00:00 to 23:59:59.999999 local time. |
--last-n-days N, --days N |
Include activity from the last N calendar days in local time including today (N=1 equals --today; N=7 covers today + 6 preceding days). |
--last-n-hours H, --hours H |
Include activity from the rolling last H hours up to now. |
--since DATE_OR_ISO |
Lower bound in local time (YYYY-MM-DD at 00:00:00 or ISO-8601 timestamp). |
--until DATE_OR_ISO |
Upper bound in local time (YYYY-MM-DD at 23:59:59.999999 or ISO-8601 timestamp). |
--quota |
Show the weekly Antigravity quota countdown and a forecast based on local usage. |
--quota-reset WHEN |
With --quota, save a reset timestamp with an explicit UTC offset, a fresh countdown, or the full weekly-limit notice. |
--quota-blocked |
With --quota, record that Antigravity is currently blocking usage until the registered reset. If the saved reset has passed or is unknown, also provide a fresh --quota-reset. |
--quota-limit USD |
With --quota, set the budget for this report (default: $200). |
--quota-file PATH |
With --quota, override the reset state file. |
--by-session |
Filter whole sessions by session start time instead of individual step timestamps. |
--session ID_OR_PREFIX |
Filter to a conversation UUID (or prefix) and expand its subagent tree. |
--model PATTERN |
Filter steps/sessions by model name using a case-insensitive substring match (e.g. --model claude, --model flash). |
--flat |
Treat every conversation UUID independently without rolling subagents into parent roots. |
--show-subagents |
Display indented child subagent rows beneath each parent session in the sessions table. |
--top N |
Number of sessions to show in the sessions table (0 for all; default: 20). |
--daily / --no-daily |
Force-enable or hide the local-date daily breakdown table. |
--color {auto,always,never} |
Colorize human-readable terminal output (auto uses TTY + NO_COLOR/FORCE_COLOR; default: auto). |
--no-color |
Disable ANSI color codes in human-readable output (alias for --color never). |
--json |
Emit structured JSON output instead of the human-readable report. |
Usage Examples
# Today's token usage across both CLI and IDE brains
agy-token-stats --today
# Filter to a specific model family over the last 7 calendar days
agy-token-stats --days 7 --model claude
# Last 7 calendar days with daily breakdown and expanded subagent trees
agy-token-stats --days 7 --daily --show-subagents
# Rolling last 4 hours for IDE sessions only
agy-token-stats --source ide --hours 4
# Drill into a specific root or subagent session by UUID prefix
agy-token-stats --session 179c4f24
# Export JSON report for a custom date range
agy-token-stats --since 2026-04-01 --until 2026-04-19 --json
Weekly quota
# Show the current cycle, or the last 7 days of local usage if the reset is unknown
agy-token-stats --quota
# Save an observation (use your reset time / fresh countdown)
agy-token-stats --quota --quota-reset '2026-11-27T20:15:00+05:30'
agy-token-stats --quota --quota-reset '1h30m19s'
# Antigravity has blocked usage and the saved reset is still in the future
agy-token-stats --quota --quota-blocked
# Machine-readable report, using a different budget for this run
agy-token-stats --quota --quota-limit 250 --json
The tool does not fetch your quota status or reset from Google or detect it from transcripts. Pasting the full “You've reached your individual weekly usage limit…” notice records both the block and the reset; entering a countdown or timestamp by itself only records the reset. Use --quota-blocked to mark an existing future reset as blocked without re-entering its time. A reported block suppresses remaining-budget and pace estimates until the observed reset. After the reset, quota status is unverified. Use a countdown only while it is fresh: it is added to the time you enter it. To record an older observation, enter the exact reset timestamp instead. The observation is saved to ${XDG_CONFIG_HOME:-~/.config}/agy-token-stats/quota.json by default. JSON and noninteractive runs never prompt; provide --quota-reset to register a reset in those runs.
Without a saved reset, the report shows estimated spend and a daily average for the last 168 hours. That period is not your Google quota window, so the report does not show budget remaining or a forecast. In a terminal, you can register a reset after seeing the estimate or press Enter to leave the reset unknown.
The report counts usage from the start of the current cycle, not the last seven calendar days. It projects future resets in fixed 168-hour intervals from the saved observation; re-register if Antigravity shows a different reset. Quiet days in the transcript are not evidence of a reset. Quota mode does not accept time, model, or session filters.
The $200 is a configurable planning budget, not a limit fetched from Google. Spend and forecasts use approximate Gemini API rates for calls found in local transcripts; unpriced calls and activity on other machines are not counted. The report identifies unavailable transcript sources and does not report a spend estimate if none are accessible. When quota status is unverified, the local usage table shows the estimated dollars left until reset and when the current pace would hit the budget, if before reset. The daily averages table compares average recorded spend so far with the budget divided by seven days. If at least 24 hours remain and a spend rate is available, it also shows the estimated remaining budget per day until reset. Projected total spend at reset remains available in --json; the human tables follow the CLI's usual --color setting.
Package Architecture
agy-token-stats/
├── LICENSE
├── pyproject.toml
├── README.md
├── src/agy_token_stats/
│ ├── __init__.py # Public package API and version metadata
│ ├── __main__.py # `python3 -m agy_token_stats` entry point
│ ├── models.py # Dataclasses: StepRecord, SessionRecord, TokenMetrics, StatsReport, etc.
│ ├── time_window.py # Timezone resolution, ISO-8601 parsing, calendar/rolling window bounds
│ ├── parser.py # Transcript JSONL step parsing, thinking split, model tracking, char/4 fallback
│ ├── discovery.py # Brain directory scanning, history.jsonl enrichment, subagent model inheritance
│ ├── aggregator.py # Step/session/model filtering and tree/flat rollup aggregation
│ ├── pricing.py # Approximate Gemini API Paid Tier rate catalog and per-step cost estimation
│ ├── formatters.py # Colorized/plain human-readable CLI tables and JSON report serialization
│ └── cli.py # Argument parser, source path resolution, and CLI main()
└── tests/
├── helpers.py
├── test_time_window.py
├── test_parser_and_discovery.py
├── test_aggregator_and_cli.py
└── test_pricing_and_formatting.py
Running Tests
python3 -m unittest discover -s tests -t . -v
Metadata
Release files for agy-token-stats 0.3.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| agy_token_stats-0.3.0.tar.gz | 71.4 kB | With provenance | Details for agy_token_stats-0.3.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| agy_token_stats-0.3.0-py3-none-any.whl | Python 3 | none | any | Details for agy_token_stats-0.3.0-py3-none-any.whl |
Total release size: 123.4 kB
Release files / agy_token_stats-0.3.0.tar.gz
| Download URL | agy_token_stats-0.3.0.tar.gz |
|---|---|
| Size | 71.4 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
eb5afe8f14d0efa91d38a0eb8024d4f0fdaaf0b8426d9866e50c73d75ad7ac10
|
|
BLAKE2b-256 checksum How to use checksums |
a87aca66be70535833d88c57efc50abff7bb785515dd6bbf387f2dd789960c6c
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 27, 2026.
Transparency logRelease files / agy_token_stats-0.3.0-py3-none-any.whl
| Download URL | agy_token_stats-0.3.0-py3-none-any.whl |
|---|---|
| Size | 52.0 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
046bd0dc4e9c048638e5c3c2f323adccf58f0f240e84c6514988930fb0ab1070
|
|
BLAKE2b-256 checksum How to use checksums |
e8e359c1482bd52bfd48f469644843ffe4ae3903e35771884e7a5d1a06200175
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 27, 2026.
Transparency logSecurity for agy-token-stats 0.3.0
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
Full provenance
Both files in this release have been uploaded with provenance metadata.
Attestation for agy_token_stats-0.3.0.tar.gz
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 27, 2026.
Transparency logA note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.