#!/usr/bin/env python3 """Ganivra seat check: what your Claude Code and Codex usage would cost at API prices, next to your plan. curl -fsSL https://ganivra.com/check.sh | sh python3 check.py [--days 30] [--claude-plan max] [--codex-plan plus --codex-price 20] [--json] Reads the logs Claude Code and Codex keep on this machine (~/.claude/projects, ~/.codex/sessions) and uses only their token counts, model names, times and folder names. It never prints, stores or sends prompt, response or code text. The only network request is downloading the public price list, unless you run it with --import, which sends those token counts to your Ganivra workspace. Standard library only, Python 3.8 or later. Source: https://ganivra.com/check.py """ from __future__ import annotations import argparse import json import math import os import re import sys import urllib.error import urllib.request from dataclasses import dataclass, field from datetime import datetime, timedelta, timezone from pathlib import Path VERSION = "1" HOME = Path.home() GV_HOME = Path(os.environ.get("GANIVRA_HOME") or HOME / ".ganivra") PRICE_URLS = [u for u in (os.environ.get("GANIVRA_PRICES_URL"), "https://raw.githubusercontent.com/ProdMoh/llm-prices/main/data/prices.json") if u] SIGNUP = "https://ganivra.com/signup?from=check" DAY = timedelta(days=1) # Monthly prices in USD, as each provider's pricing page showed them on the checked date. A plan with # no price is asked for: ChatGPT's page shows local prices only, so we don't guess its USD price. PLANS = { "claude": { "pro": ("Claude Pro", 20.0), "pro-annual": ("Claude Pro, billed yearly", 17.0), "max": ("Claude Max (5x Pro)", 100.0), "ultra": ("Claude Ultra", 200.0), "team-standard": ("Claude Team, Standard seat", 25.0), "team-standard-annual": ("Claude Team, Standard seat, billed yearly", 20.0), "team-premium": ("Claude Team, Premium seat", 125.0), "team-premium-annual": ("Claude Team, Premium seat, billed yearly", 100.0), "api": ("API key, pay per token", None), }, "codex": { "go": ("ChatGPT Go", None), "plus": ("ChatGPT Plus", None), "pro": ("ChatGPT Pro", None), "business": ("ChatGPT Business seat", 25.0), "business-annual": ("ChatGPT Business seat, billed yearly", 20.0), "api": ("API key, pay per token", None), }, } PLAN_SOURCES = { "claude": ("https://claude.com/pricing", "2026-11-21"), "codex": ("https://openai.com/business/chatgpt-pricing/", "2026-11-04"), } TOOL_NAMES = {"claude": "Claude Code", "codex": "Codex"} @dataclass class Call: tool: str id: str session: str time: datetime model: str project: str input: int = 0 # uncached input cached: int = 0 # cache reads write_5m: int = 0 # Claude cache writes, 5-minute write_1h: int = 0 # Claude cache writes, 1-hour output: int = 0 # includes reasoning fast: bool = False us_only: bool = False web_searches: int = 0 cost: float | None = None # ---------------------------------------------------------------- reading the logs def _time(value) -> datetime | None: if not isinstance(value, str): return None try: parsed = datetime.fromisoformat(value.replace("Z", "+00:00")) except ValueError: return None return parsed if parsed.tzinfo else parsed.replace(tzinfo=timezone.utc) def _int(value) -> int: try: return max(0, int(value or 0)) except (TypeError, ValueError): return 0 def _folder(path) -> str: """Only the last folder name is kept: full paths carry the user's home directory.""" if not isinstance(path, str) or not path.strip(): return "unknown" name = re.split(r"[\\/]", path.rstrip("/\\"))[-1].strip() return name or "unknown" def _recent(path: Path, since: datetime) -> bool: try: return path.stat().st_mtime >= since.timestamp() except OSError: return False def claude_calls(root: Path, since: datetime) -> list[Call]: """One Call per API response. Claude Code writes a response once per content block, and resumed sessions copy earlier lines into new files, so responses are de-duplicated across all files by message and request ID, keeping the line with the final (largest) output count.""" best: dict[tuple, Call] = {} if not root.is_dir(): return [] for path in root.rglob("*.jsonl"): if not _recent(path, since): continue try: handle = path.open(encoding="utf-8", errors="replace") except OSError: continue with handle: for line in handle: if '"assistant"' not in line or '"usage"' not in line: continue try: row = json.loads(line) except ValueError: continue if not isinstance(row, dict) or row.get("type") != "assistant": continue message = row.get("message") or {} usage = message.get("usage") if isinstance(message, dict) else None model = message.get("model") if isinstance(message, dict) else None if not isinstance(usage, dict) or not isinstance(model, str) or model.startswith("<"): continue when = _time(row.get("timestamp")) if not when or when < since: continue message_id, request_id = message.get("id") or row.get("uuid") or "", row.get("requestId") or "" if not message_id and not request_id: continue creation = usage.get("cache_creation") if isinstance(usage.get("cache_creation"), dict) else {} write_5m, write_1h = _int(creation.get("ephemeral_5m_input_tokens")), _int(creation.get("ephemeral_1h_input_tokens")) if not write_5m and not write_1h: write_5m = _int(usage.get("cache_creation_input_tokens")) # older logs: the default 5-minute cache tools = usage.get("server_tool_use") if isinstance(usage.get("server_tool_use"), dict) else {} call = Call( tool="claude", id=str(request_id or message_id), session=str(row.get("sessionId") or "session"), time=when, model=model, project=_folder(row.get("cwd")), input=_int(usage.get("input_tokens")), cached=_int(usage.get("cache_read_input_tokens")), write_5m=write_5m, write_1h=write_1h, output=_int(usage.get("output_tokens")), fast=str(usage.get("speed") or "").lower() == "fast", us_only=str(usage.get("inference_geo") or "").lower() == "us", web_searches=_int(tools.get("web_search_requests")), ) key = (message_id, request_id) if key not in best or call.output > best[key].output: best[key] = call return list(best.values()) _USAGE_KEYS = ("input_tokens", "cached_input_tokens", "output_tokens") def codex_calls(home: Path, since: datetime) -> list[Call]: """One Call per model response. Newer Codex logs write a token_usage_record with the response ID; older ones only a token_count event, which can repeat, so those use increments of the running total.""" files = [] for folder, pattern in ((home / "sessions", "**/*.jsonl"), (home / "archived_sessions", "*.jsonl")): if folder.is_dir(): files.extend(p for p in folder.glob(pattern) if _recent(p, since)) calls, seen = [], set() for path in files: try: lines = path.read_text(encoding="utf-8", errors="replace").splitlines() except OSError: continue records = any('"token_usage_record"' in line for line in lines) model = cwd = None session = path.stem previous: dict | None = None for line in lines: if not any(k in line for k in ('"token_usage_record"', '"token_count"', '"turn_context"', '"session_meta"')): continue try: row = json.loads(line) except ValueError: continue if not isinstance(row, dict): continue kind, payload = row.get("type"), row.get("payload") if isinstance(row.get("payload"), dict) else {} if kind == "session_meta": cwd = payload.get("cwd") or cwd session = str(payload.get("id") or payload.get("session_id") or session) continue if kind == "turn_context": model = payload.get("model") or model cwd = payload.get("cwd") or cwd continue if records and kind == "token_usage_record": usage = payload.get("usage") if isinstance(payload.get("usage"), dict) else None ident = payload.get("response_id") or f"{payload.get('turn_id')}:{row.get('ordinal')}" elif not records and kind == "event_msg" and payload.get("type") == "token_count": info = payload.get("info") if isinstance(payload.get("info"), dict) else {} total = info.get("total_token_usage") if isinstance(info.get("total_token_usage"), dict) else None if not total or total == previous: continue if previous and all(_int(total.get(k)) >= _int(previous.get(k)) for k in _USAGE_KEYS): usage = {k: _int(total.get(k)) - _int(previous.get(k)) for k in _USAGE_KEYS} else: usage = {k: _int(total.get(k)) for k in _USAGE_KEYS} previous = total ident = f"{session}:{_int(total.get('total_tokens'))}" else: continue when = _time(row.get("timestamp")) if not usage or not model or not when or when < since or ident in seen: continue seen.add(ident) raw_input = _int(usage.get("input_tokens")) cached = min(_int(usage.get("cached_input_tokens")), raw_input) # OpenAI counts cached inside input calls.append(Call(tool="codex", id=str(ident), session=session, time=when, model=str(model), project=_folder(cwd), input=raw_input - cached, cached=cached, output=_int(usage.get("output_tokens")))) # reasoning is inside output return calls # ---------------------------------------------------------------- prices class Prices: def __init__(self, data: dict, origin: str): self.origin = origin self.date = str(data.get("generated") or "unknown date") self.models: dict[str, dict] = {} for entry in data.get("models") or []: for name in [entry.get("model"), *(entry.get("aliases") or [])]: if isinstance(name, str): self.models.setdefault(name.lower(), entry) def find(self, model: str) -> dict | None: name = model.lower().split("/")[-1] for candidate in (name, re.sub(r"-\d{8}$", "", name), re.sub(r"-(latest|preview)$", "", name)): if candidate in self.models: return self.models[candidate] return None def load_prices() -> Prices: cache = GV_HOME / "prices.json" for url in PRICE_URLS: try: with urllib.request.urlopen(urllib.request.Request(url, headers={"User-Agent": f"ganivra-check/{VERSION}"}), timeout=15) as response: data = json.loads(response.read().decode("utf-8")) if data.get("models"): try: GV_HOME.mkdir(parents=True, exist_ok=True) cache.write_text(json.dumps(data)) except OSError: pass return Prices(data, url) except (OSError, ValueError, urllib.error.URLError): continue if cache.is_file(): try: return Prices(json.loads(cache.read_text()), f"{cache} (saved copy; couldn't download a newer one)") except ValueError: pass raise SystemExit("ganivra check: couldn't download the price list. Check your connection and try again.") def price(call: Call, entry: dict) -> float | None: """List price of one call, using the same rules as Ganivra's dashboard.""" rates = entry.get("price_per_million_tokens") or {} if "input" not in rates or "output" not in rates: return None input_rate, output_rate = float(rates["input"]), float(rates["output"]) cached_rate = float(rates.get("cached_input", input_rate * 0.1)) long_prompt = entry.get("long_prompt") if isinstance(entry.get("long_prompt"), dict) else None if entry.get("provider") == "anthropic": read_share = cached_rate / input_rate if input_rate else 0.1 write_5m_rate = float(rates.get("cache_write_5m", input_rate * 1.25)) write_1h_rate = float(rates.get("cache_write_1h", input_rate * 2)) prompt = call.input + call.cached + call.write_5m + call.write_1h override = False if call.fast: fast = entry.get("fast_mode_price_per_million_tokens") if not fast: return None input_rate, output_rate, override = float(fast["input"]), float(fast["output"]), True elif long_prompt and prompt > _int(long_prompt.get("over_input_tokens")): input_rate, output_rate, override = float(long_prompt["input"]), float(long_prompt["output"]), True if override: # Cache prices follow the overriding input price. cached_rate, write_5m_rate, write_1h_rate = input_rate * read_share, input_rate * 1.25, input_rate * 2 total = (call.input * input_rate + call.cached * cached_rate + call.output * output_rate + call.write_5m * write_5m_rate + call.write_1h * write_1h_rate) / 1e6 if call.us_only: total *= 1.1 return total + call.web_searches * 0.01 if long_prompt and call.input + call.cached > _int(long_prompt.get("over_input_tokens")): share = cached_rate / input_rate if input_rate else 0.1 input_rate, output_rate = float(long_prompt["input"]), float(long_prompt["output"]) cached_rate = float(long_prompt.get("cached_input", input_rate * share)) return (call.input * input_rate + call.cached * cached_rate + call.output * output_rate) / 1e6 # ---------------------------------------------------------------- summary @dataclass class ToolSummary: tool: str calls: int = 0 cost: float = 0.0 unpriced: dict = field(default_factory=dict) # model -> calls models: dict = field(default_factory=dict) # model -> {cost, input, cached, writes, output} projects: dict = field(default_factory=dict) # folder -> cost days: set = field(default_factory=set) first: datetime | None = None busiest_5h: tuple = (0.0, None) # (cost, start) monthly: float = 0.0 span_days: int = 0 def summarize(calls: list[Call], prices: Prices, days: int, now: datetime) -> dict[str, ToolSummary]: out: dict[str, ToolSummary] = {} for call in calls: entry = prices.find(call.model) call.cost = price(call, entry) if entry else None s = out.setdefault(call.tool, ToolSummary(call.tool)) s.calls += 1 s.days.add(call.time.astimezone().date()) s.first = min(s.first, call.time) if s.first else call.time m = s.models.setdefault(call.model, {"cost": 0.0, "input": 0, "cached": 0, "writes": 0, "output": 0, "unpriced": 0}) m["input"] += call.input m["cached"] += call.cached m["writes"] += call.write_5m + call.write_1h m["output"] += call.output if call.cost is None: s.unpriced[call.model] = s.unpriced.get(call.model, 0) + 1 m["unpriced"] += 1 continue s.cost += call.cost m["cost"] += call.cost s.projects[call.project] = s.projects.get(call.project, 0.0) + call.cost for tool, s in out.items(): priced = sorted((c for c in calls if c.tool == tool and c.cost is not None), key=lambda c: c.time) best, start, running = (0.0, None), 0, 0.0 for end, call in enumerate(priced): running += call.cost while call.time - priced[start].time >= timedelta(hours=5): running -= priced[start].cost start += 1 if running > best[0]: best = (running, priced[start].time) s.busiest_5h = best # Logs may cover less than the window (new install, or Claude Code's 30-day log cleanup). s.span_days = max(1, min(days, math.ceil((now - s.first).total_seconds() / 86400))) if s.first else days s.monthly = s.cost * 30 / s.span_days return out def verdict(summary: ToolSummary, plan_price: float | None, plan_key: str | None) -> tuple[str, str]: """(code, sentence) comparing a month of usage at API prices with the plan's monthly price.""" usage = summary.monthly if plan_key == "api": return "api", f"You already pay per token; about ${usage:,.2f} a month at list prices." if plan_price is None: return "no_plan", "Tell the check your plan and its monthly price to compare (--claude-plan / --codex-price)." if len(summary.days) < 5: return "too_little", f"Only {len(summary.days)} active days in the logs: too few to judge the plan." ratio = usage / plan_price if plan_price else math.inf if ratio < 0.5: return "api_cheaper", f"API billing would have cost less: about ${usage:,.2f} a month against ${plan_price:,.0f}. The plan also covers the chat app." if ratio <= 1.5: return "break_even", f"About break-even: ${usage:,.2f} a month at API prices against ${plan_price:,.0f}." return "keep", f"Your plan covered {ratio:.1f}x its price in usage. Keep it." # ---------------------------------------------------------------- plans def saved_settings() -> dict: try: return json.loads((GV_HOME / "check.json").read_text()) except (OSError, ValueError): return {} def save_settings(settings: dict) -> None: if not settings: return try: GV_HOME.mkdir(parents=True, exist_ok=True) (GV_HOME / "check.json").write_text(json.dumps(settings, indent=2) + "\n") except OSError: pass def _tty(): try: return open("/dev/tty", "r+", encoding="utf-8") except OSError: return None def ask_plan(tool: str, tty) -> tuple[str | None, float | None]: options = list(PLANS[tool].items()) tty.write(f"\nWhich plan do you use {TOOL_NAMES[tool]} with?\n") for n, (key, (label, cost)) in enumerate(options, 1): tty.write(f" {n}. {label}" + (f", ${cost:,.0f} a month" if cost else "") + "\n") tty.write(" Enter a number, or press Enter to skip: ") tty.flush() answer = tty.readline().strip() if not answer.isdigit() or not 1 <= int(answer) <= len(options): return None, None key, (label, cost) = options[int(answer) - 1] if cost is None and key != "api": tty.write(f" What do you pay for {label} a month, in US dollars? ") tty.flush() try: cost = float(tty.readline().strip().lstrip("$").replace(",", "")) except ValueError: cost = None return key, cost def resolve_plans(args, tools: list[str]) -> dict[str, tuple[str | None, float | None]]: settings = saved_settings() plans, tty = {}, None for tool in tools: key = getattr(args, f"{tool}_plan") cost = getattr(args, f"{tool}_price") if key and key not in PLANS[tool]: raise SystemExit(f"ganivra check: unknown {tool} plan {key!r}. Choose from: {', '.join(PLANS[tool])}") saved = settings.get(tool) or {} if not key and cost is None and saved: key, cost = saved.get("plan"), saved.get("price") if key and cost is None: cost = PLANS[tool][key][1] if not key and cost is None and not args.json and not args.no_input: tty = tty or _tty() if tty: key, cost = ask_plan(tool, tty) if key or cost is not None: settings[tool] = {"plan": key, "price": cost} plans[tool] = (key, cost) save_settings(settings) if tty: tty.close() return plans # ---------------------------------------------------------------- output def money(value: float) -> str: return f"${value:,.2f}" def tokens(value: int) -> str: for size, unit in ((1e9, "B"), (1e6, "M"), (1e3, "k")): if value >= size: return f"{value / size:.1f}{unit}" return str(value) def report(summaries: dict, plans: dict, prices: Prices, days: int) -> dict: tools = {} for tool, s in summaries.items(): key, cost = plans.get(tool, (None, None)) code, sentence = verdict(s, cost, key) tools[tool] = { "tool": TOOL_NAMES[tool], "calls": s.calls, "active_days": len(s.days), "days_covered": s.span_days, "cost_usd": round(s.cost, 2), "monthly_usd": round(s.monthly, 2), "busiest_5h_usd": round(s.busiest_5h[0], 2), "busiest_5h_start": s.busiest_5h[1].isoformat() if s.busiest_5h[1] else None, "models": {m: {**v, "cost": round(v["cost"], 2)} for m, v in sorted(s.models.items(), key=lambda kv: -kv[1]["cost"])}, "projects": {p: round(c, 2) for p, c in sorted(s.projects.items(), key=lambda kv: -kv[1])}, "unpriced_calls": s.unpriced, "plan": {"key": key, "label": PLANS[tool][key][0] if key else None, "monthly_usd": cost, "source": PLAN_SOURCES[tool][0], "checked": PLAN_SOURCES[tool][1]}, "verdict": code, "summary": sentence, } return {"version": VERSION, "days": days, "prices": {"source": prices.origin, "date": prices.date}, "tools": tools} def print_report(data: dict, importing: bool = False) -> None: if not data["tools"]: print("No Claude Code or Codex usage found in the last %d days on this machine." % data["days"]) print("They keep their logs in ~/.claude/projects and ~/.codex/sessions.") return projects: dict[str, float] = {} for t in data["tools"].values(): print(f"\n{t['tool']} · last {data['days']} days · {t['active_days']} active days") if t["days_covered"] < data["days"]: print(f" (the logs cover {t['days_covered']} days; figures are scaled to a month)") print(f" Usage at API prices {money(t['cost_usd']):>12}" + (f" about {money(t['monthly_usd'])} a month" if t["days_covered"] < data["days"] else "")) for name, m in list(t["models"].items())[:4]: detail = f"{tokens(m['input'] + m['writes'])} input · {tokens(m['cached'])} cache reads · {tokens(m['output'])} output" label = money(m["cost"]) if not m["unpriced"] else "unpriced" print(f" {name[:22]:<22} {label:>10} {detail}") if t["busiest_5h_start"]: start = datetime.fromisoformat(t["busiest_5h_start"]).astimezone() print(f" Busiest 5 hours {money(t['busiest_5h_usd']):>12} from {start:%a %d %b %H:%M}") plan = t["plan"] if plan["label"] or plan["monthly_usd"] is not None: price_text = f", ${plan['monthly_usd']:,.0f} a month" if plan["monthly_usd"] else "" print(f" Your plan {(plan['label'] or 'custom')}{price_text}") print(f" → {t['summary']}") if t["unpriced_calls"]: print(f" Not priced (no list price): {', '.join(sorted(t['unpriced_calls']))}") for name, cost in t["projects"].items(): projects[name] = projects.get(name, 0.0) + cost top = sorted(projects.items(), key=lambda kv: -kv[1]) if top: shown = " · ".join(f"{name} {money(cost)}" for name, cost in top[:3]) rest = sum(cost for _, cost in top[3:]) print(f"\nTop projects: {shown}" + (f" · other {money(rest)}" if rest else "")) print(f"\nNothing was sent anywhere. Prices: {data['prices']['source']} ({data['prices']['date']}).") connected = any(export_start(tool)[0] for tool in data["tools"]) for line in closing(data, len(projects), importing, connected): print(line) HEAVY_MONTHLY_USD = 100 # a month of usage at API prices that makes team tracking worth raising HEAVY_PROJECTS = 3 def closing(data: dict, project_count: int, importing: bool = False, connected: bool = False) -> list[str]: """The next step, matched to what the check found. Light users get one line; heavy users and people working across several projects get the team pitch with the --import hook.""" if importing: return [] if connected: return ["", "This machine already sends usage to Ganivra. To add the days before it was connected: ganivra check --import"] monthly = sum(t["monthly_usd"] for t in data["tools"].values()) if monthly < HEAVY_MONTHLY_USD and project_count < HEAVY_PROJECTS: return [f"Tracking a team? {SIGNUP}"] reason = (f"Your usage spans {project_count} projects and comes to about {money(monthly)} a month at API prices." if project_count >= HEAVY_PROJECTS else f"That's about {money(monthly)} a month at API prices on one machine.") return [ "", reason, "Running a team on Claude Code or Codex? Ganivra shows this for every developer, every month,", "by developer, team, project and client. 14-day free trial, no card:", f" {SIGNUP}", f"Sign up, run the one-line setup, then `ganivra check --import`: your dashboard starts with these {data['days']} days.", ] # ---------------------------------------------------------------- import def _ident(value: str, prefix: str, limit: int = 80) -> str: clean = re.sub(r"[^A-Za-z0-9._:-]", "-", value).strip("-.:_") or "x" return (prefix + clean)[:limit] def _read_json(path: Path) -> dict: try: data = json.loads(path.read_text()) return data if isinstance(data, dict) else {} except (OSError, ValueError): return {} def export_start(tool: str) -> tuple[bool, datetime | None]: """Whether this machine already sends the tool's usage to Ganivra, and since when. Imported history stops there, so nothing is counted twice.""" if tool == "claude": config = HOME / ".claude" / "settings.json" env = _read_json(config).get("env") or {} connected = "ganivra" in str(env.get("OTEL_EXPORTER_OTLP_ENDPOINT", "")).lower() else: config = Path(os.environ.get("CODEX_HOME") or HOME / ".codex") / "config.toml" try: connected = "ganivra" in config.read_text().lower() except OSError: connected = False if not connected: return False, None for marker in (config.with_name(config.name + ".bak-ganivra"), GV_HOME / "config"): if marker.exists(): return True, datetime.fromtimestamp(marker.stat().st_mtime, timezone.utc) return True, None def find_key(explicit: str | None) -> tuple[str | None, str]: api = os.environ.get("GANIVRA_API_URL", "").rstrip("/") key = explicit or os.environ.get("GANIVRA_API_KEY") env = _read_json(HOME / ".claude" / "settings.json").get("env") or {} if not key: found = re.search(r"Bearer\s+([A-Za-z0-9_\-.]+)", str(env.get("OTEL_EXPORTER_OTLP_HEADERS", ""))) key = found.group(1) if found else None if not api: endpoint = str(env.get("OTEL_EXPORTER_OTLP_ENDPOINT", "")) api = endpoint.split("/v1/otlp")[0].rstrip("/") if "ganivra" in endpoint else "https://api.ganivra.com" return key, api def git_email() -> str | None: try: import subprocess result = subprocess.run(["git", "config", "--global", "user.email"], capture_output=True, text=True, timeout=5) return result.stdout.strip() or None except (OSError, ValueError): return None def to_event(call: Call, user: str | None) -> dict: if call.tool == "claude": event_id = _ident(call.id, "cc-") # the same ID Ganivra's live export gives this request usage_details: dict = {"cache_creation_5m_input_tokens": call.write_5m, "cache_creation_1h_input_tokens": call.write_1h} if call.fast: usage_details["speed_fast"] = 1 if call.us_only: usage_details["inference_geo_us"] = 1 if call.web_searches: usage_details["web_search_requests"] = call.web_searches provider, operation, execution = "anthropic", "messages", _ident(call.session, "cc-", 63) total = call.input + call.output + call.cached + call.write_5m + call.write_1h input_tokens = call.input else: event_id = _ident(call.id, "cx-") usage_details, provider, operation = {}, "openai", "responses" execution = _ident(call.session, "cx-", 63) input_tokens = call.input + call.cached # OpenAI counts cached input inside input total = input_tokens + call.output attributes = {"source": "claude_code" if call.tool == "claude" else "codex", "workflow": call.project, "conversation_id": call.session[:200], "imported": "local_logs"} if user: attributes["user_id"] = user return { "event_id": event_id, "execution_id": execution, "step_id": event_id, "timestamp": call.time.isoformat(), "provider": provider, "model": call.model, "operation": operation, "input_tokens": input_tokens, "output_tokens": call.output, "cached_tokens": call.cached, "total_tokens": total, "usage_details": usage_details, "latency_ms": 0.0, "status": "success", "environment": "production", # what the live export records when no environment is set "attributes": attributes, } def import_calls(calls: list[Call], args) -> int: key, api = find_key(args.key) if not key: raise SystemExit("ganivra check: --import needs your workspace key. Pass --key, set GANIVRA_API_KEY, or run ganivra setup first.") user = args.user or git_email() chosen = [] for tool in ("claude", "codex"): connected, since = export_start(tool) tool_calls = [c for c in calls if c.tool == tool] if connected and since is None: print(f"Skipping {TOOL_NAMES[tool]}: it already sends usage to Ganivra and the start date is unknown, so history could be counted twice.") continue if since: tool_calls = [c for c in tool_calls if c.time < since] print(f"{TOOL_NAMES[tool]}: importing usage before {since.astimezone():%d %b %Y %H:%M}, when this machine started sending it live.") chosen.extend(tool_calls) if not chosen: print("Nothing to import.") return 0 print(f"Sending {len(chosen)} calls to {api}: token counts, model, time, folder name" + (f" and {user} as the developer" if user else "") + ". No prompt, response or code text.") events = [to_event(c, user) for c in sorted(chosen, key=lambda c: c.time)] accepted = 0 for start in range(0, len(events), 100): body = json.dumps({"events": events[start:start + 100]}).encode() request = urllib.request.Request(f"{api}/v1/events", data=body, method="POST", headers={ "Authorization": f"Bearer {key}", "Content-Type": "application/json", "User-Agent": f"ganivra-check/{VERSION}"}) try: with urllib.request.urlopen(request, timeout=30) as response: result = json.loads(response.read().decode() or "{}") except urllib.error.HTTPError as error: hint = "the key is invalid" if error.code == 401 else f"HTTP {error.code}" raise SystemExit(f"ganivra check: import stopped after {accepted} calls ({hint}). Run it again to continue; sent calls are not duplicated.") except (OSError, urllib.error.URLError) as error: raise SystemExit(f"ganivra check: import stopped after {accepted} calls ({error}). Run it again to continue.") accepted += int(result.get("accepted", 0)) + int(result.get("duplicates", 0)) print(f"Imported {accepted} calls. Open Ganivra → Dashboard → Coding agents.") return accepted # ---------------------------------------------------------------- main def main(argv: list[str] | None = None) -> int: parser = argparse.ArgumentParser(prog="ganivra check", description="What your Claude Code and Codex usage would cost at API prices, next to your plan. Reads local logs only.") parser.add_argument("--days", type=int, default=30, help="days to look back, 1 to 90 (default 30)") parser.add_argument("--tool", choices=["claude", "codex"], help="check one tool only") parser.add_argument("--claude-plan", choices=list(PLANS["claude"])) parser.add_argument("--claude-price", type=float, help="what you pay a month, USD, if not a listed plan") parser.add_argument("--codex-plan", choices=list(PLANS["codex"])) parser.add_argument("--codex-price", type=float, help="what you pay a month, USD (needed for Plus, Pro, Go)") parser.add_argument("--json", action="store_true", help="print JSON instead of text") parser.add_argument("--no-input", action="store_true", help="never ask questions") parser.add_argument("--import", dest="do_import", action="store_true", help="send the usage to your Ganivra workspace") parser.add_argument("--key", help="workspace API key for --import") parser.add_argument("--user", help="developer name or email for --import (default: git user.email)") parser.add_argument("--version", action="version", version=f"ganivra check {VERSION}") args = parser.parse_args(argv) if not 1 <= args.days <= 90: parser.error("--days must be between 1 and 90") now = datetime.now(timezone.utc) since = now - args.days * DAY calls = [] if args.tool in (None, "claude"): calls += claude_calls(Path(os.environ.get("CLAUDE_CONFIG_DIR") or HOME / ".claude") / "projects", since) if args.tool in (None, "codex"): calls += codex_calls(Path(os.environ.get("CODEX_HOME") or HOME / ".codex"), since) prices = load_prices() summaries = summarize(calls, prices, args.days, now) plans = resolve_plans(args, list(summaries)) if summaries else {} data = report(summaries, plans, prices, args.days) if args.json: print(json.dumps(data, indent=2)) else: print_report(data, importing=args.do_import) if args.do_import: import_calls(calls, args) return 0 if __name__ == "__main__": try: sys.exit(main()) except KeyboardInterrupt: sys.exit(130)