Skip to content

Instantly share code, notes, and snippets.

@asdf8675309
Created August 20, 2026 19:08
Show Gist options
  • Select an option

  • Save asdf8675309/e55d55b15dcb1339d84be3fbf4156bc5 to your computer and use it in GitHub Desktop.

Select an option

Save asdf8675309/e55d55b15dcb1339d84be3fbf4156bc5 to your computer and use it in GitHub Desktop.
Standalone script to inspect Google Antigravity (agy) session token usage from local SQLite databases
#!/usr/bin/env python3
"""
Antigravity CLI (agy) Token Usage Analyzer
Inspects and aggregates token telemetry (input, output, reasoning/thinking, cached context)
from SQLite conversation databases in ~/.gemini/antigravity-cli/conversations/
"""
import sys
import os
import glob
import sqlite3
import io
import json
import argparse
def decode_varint(stream):
res, shift = 0, 0
while True:
b = stream.read(1)
if not b:
return None
byte = b[0]
res |= (byte & 0x7f) << shift
if not (byte & 0x80):
break
shift += 7
return res
def parse_proto(data):
if not data or not isinstance(data, (bytes, bytearray)):
return []
stream = io.BytesIO(data)
fields = []
while True:
tag = decode_varint(stream)
if tag is None:
break
field_num, wire_type = tag >> 3, tag & 0x07
if wire_type == 0:
fields.append((field_num, decode_varint(stream)))
elif wire_type == 2:
length = decode_varint(stream)
fields.append((field_num, stream.read(length)))
elif wire_type == 1:
fields.append((field_num, stream.read(8)))
elif wire_type == 5:
fields.append((field_num, stream.read(4)))
else:
break
return fields
def extract_tokens(val):
if not isinstance(val, bytes):
return None
parsed = dict(parse_proto(val))
if 2 in parsed and isinstance(parsed[2], bytes):
parsed = dict(parse_proto(parsed[2]))
in_tok = parsed.get(2, 0)
out_tok = parsed.get(3, 0)
cache_tok = parsed.get(5, 0)
think_tok = parsed.get(9, 0)
in_tok = in_tok if isinstance(in_tok, int) else 0
out_tok = out_tok if isinstance(out_tok, int) else 0
cache_tok = cache_tok if isinstance(cache_tok, int) else 0
think_tok = think_tok if isinstance(think_tok, int) else 0
if in_tok or out_tok or cache_tok or think_tok:
return in_tok, out_tok, cache_tok, think_tok
return None
def analyze_session(db_path):
conn = sqlite3.connect(db_path)
c = conn.cursor()
c.execute("SELECT idx, metadata FROM steps WHERE metadata IS NOT NULL")
total_in, total_out, total_cache, total_think = 0, 0, 0, 0
turns = 0
for idx, meta in c.fetchall():
for fnum, val in parse_proto(meta):
if fnum in (9, 28) and isinstance(val, bytes):
res = extract_tokens(val)
if res:
in_tok, out_tok, cache_tok, think_tok = res
total_in += in_tok
total_out += out_tok
total_cache += cache_tok
total_think += think_tok
turns += 1
return {
"turns": turns,
"input_tokens": total_in,
"output_tokens": total_out,
"thinking_tokens": total_think,
"cached_tokens": total_cache,
"total_processed": total_in + total_out + total_cache
}
def get_session_titles(app_dir):
titles = {}
summaries_db = os.path.join(app_dir, "conversation_summaries.db")
if os.path.exists(summaries_db):
try:
conn = sqlite3.connect(summaries_db)
for cid, title, modified in conn.cursor().execute(
"SELECT conversation_id, title, last_modified_time FROM conversation_summaries"
):
titles[cid] = {"title": title, "last_modified": modified}
except Exception:
pass
return titles
def main():
parser = argparse.ArgumentParser(description="Antigravity CLI (agy) Token Usage Analyzer")
parser.add_argument("session_id", nargs="?", default=None, help="Optional conversation ID to inspect")
parser.add_argument("--json", action="store_true", help="Output results in JSON format")
parser.add_argument("--latest", action="store_true", help="Inspect only the most recent session")
args = parser.parse_args()
app_dir = os.path.expanduser("~/.gemini/antigravity-cli")
conv_base = os.path.join(app_dir, "conversations")
titles = get_session_titles(app_dir)
dbs = sorted(glob.glob(os.path.join(conv_base, "*.db")), key=os.path.getmtime, reverse=True)
if not dbs:
print(f"No conversation databases found in {conv_base}")
sys.exit(1)
# 1. Single session or Latest session
if args.session_id or args.latest:
if args.latest:
target_db = dbs[0]
cid = os.path.basename(target_db)[:-3]
else:
cid = args.session_id.replace(".db", "")
target_db = os.path.join(conv_base, f"{cid}.db")
if not os.path.exists(target_db):
print(f"Error: Session database not found: {target_db}", file=sys.stderr)
sys.exit(1)
stats = analyze_session(target_db)
title_info = titles.get(cid, {})
stats["session_id"] = cid
stats["title"] = title_info.get("title", "(Untitled)")
stats["last_modified"] = title_info.get("last_modified", "")
if args.json:
print(json.dumps(stats, indent=2))
else:
print(f"=== Session: {cid} ===")
if stats["title"]:
print(f"Title: {stats['title']}")
print(f"Turns: {stats['turns']}")
print(f"Input Context: {stats['input_tokens']:,} tokens")
print(f"Output Tokens: {stats['output_tokens']:,} tokens (Thinking: {stats['thinking_tokens']:,})")
print(f"Cached Context: {stats['cached_tokens']:,} tokens")
print(f"Total Processed: {stats['total_processed']:,} tokens")
return
# 2. All sessions breakdown mode
results = []
grand = {"turns": 0, "input_tokens": 0, "output_tokens": 0, "thinking_tokens": 0, "cached_tokens": 0, "total_processed": 0}
for db in dbs:
cid = os.path.basename(db)[:-3]
stats = analyze_session(db)
if stats["turns"] == 0:
continue
title_info = titles.get(cid, {})
stats["session_id"] = cid
stats["title"] = title_info.get("title", "(Untitled)")
stats["last_modified"] = title_info.get("last_modified", "")
results.append(stats)
for k in grand:
grand[k] += stats[k]
if args.json:
print(json.dumps({"sessions": results, "grand_total": grand}, indent=2))
else:
print(f"{'Session ID':<38} | {'Turns':<5} | {'Input':<11} | {'Output':<10} | {'Thinking':<10} | {'Cached':<12}")
print("-" * 100)
for s in results:
print(f"{s['session_id']:<38} | {s['turns']:<5} | {s['input_tokens']:<11,d} | {s['output_tokens']:<10,d} | {s['thinking_tokens']:<10,d} | {s['cached_tokens']:<12,d}")
print("-" * 100)
print(f"{'GRAND TOTAL':<38} | {grand['turns']:<5} | {grand['input_tokens']:<11,d} | {grand['output_tokens']:<10,d} | {grand['thinking_tokens']:<10,d} | {grand['cached_tokens']:<12,d}")
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment