#!/usr/bin/env python3 """Token usage and API-equivalent cost of the agent's work in a time window, for the dev log. Not part of the Deverenz product. Reads Claude Code's session transcripts for this project and sums the token usage of every model response between --since and --until. Cost is what the same usage would cost at Anthropic API list prices, converted to EUR with the ECB reference rate; on a subscription it is not what was actually paid. Usage: .claude/scripts/ticket-cost.py --since 2026-11-15T10:00:00Z [--until 2026-11-15T14:00:00Z] .claude/scripts/ticket-cost.py --since ... --usd-eur 0.86 # skip the ECB lookup """ # pyright: strict import argparse import json import re import sys import urllib.request from datetime import UTC, datetime from pathlib import Path # USD per million tokens: input, output, cache read, cache write 5m, cache write 1h. # Source: Anthropic pricing as of 2026-11-03. Update when prices change. PRICES: dict[str, tuple[float, float, float, float, float]] = { "claude-opus-5-5": (4.00, 20.00, 0.20, 5.00, 8.00), "claude-sonnet-5-5": (2.00, 10.00, 0.10, 2.50, 4.00), "claude-haiku-5-5": (0.10, 0.50, 0.01, 0.125, 0.20), # prompts <= 100K tokens "claude-fable-5-2": (8.00, 40.00, 0.20, 10.00, 16.00), } FAST_MODE_FACTOR = 2.0 ECB_URL = "https://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml" def transcript_dir() -> Path: repo = Path(__file__).resolve().parents[2] return Path.home() / ".claude" / "projects" / re.sub(r"[^A-Za-z0-9]", "-", str(repo)) def parse_time(value: str) -> datetime: parsed = datetime.fromisoformat(value) return parsed if parsed.tzinfo else parsed.astimezone() # naive input = local time def usd_to_eur() -> float: with urllib.request.urlopen(ECB_URL, timeout=10) as response: xml = response.read().decode() match = re.search(r"currency='USD' rate='([0-9.]+)'", xml) if not match: raise RuntimeError("USD rate not found in ECB feed") return 1 / float(match.group(1)) # ECB quotes USD per EUR Counts = tuple[int, int, int, int, int] # same order as PRICES def parse_response(line: str) -> tuple[str, str, datetime, Counts, bool] | None: """(response id, model, time, token counts, fast mode) of one transcript line, or None.""" entry = json.loads(line) message = entry.get("message") if entry.get("type") != "assistant" or not isinstance(message, dict): return None usage = message.get("usage") if not message.get("id") or not usage or not entry.get("timestamp"): return None cache_write = usage.get("cache_creation") or {} write_5m = cache_write.get("ephemeral_5m_input_tokens", 0) write_1h = cache_write.get("ephemeral_1h_input_tokens", 0) if not cache_write: # older entries without the TTL breakdown write_5m = usage.get("cache_creation_input_tokens", 0) counts: Counts = ( usage.get("input_tokens", 0), usage.get("output_tokens", 0), usage.get("cache_read_input_tokens", 0), write_5m, write_1h, ) time = parse_time(entry["timestamp"]) return message["id"], message.get("model", ""), time, counts, usage.get("speed") == "fast" def main() -> int: parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) parser.add_argument("--since", required=True, help="ISO time, e.g. 2026-11-15T10:00:00Z") parser.add_argument("--until", help="ISO time (default: now)") parser.add_argument("--usd-eur", type=float, help="fixed USD->EUR rate instead of the ECB lookup") args = parser.parse_args() since = parse_time(args.since) until = parse_time(args.until) if args.until else datetime.now(UTC) seen: set[str] = set() tokens = {"input": 0, "output": 0, "cache_read": 0, "cache_write": 0} cost_usd = 0.0 sessions: set[str] = set() unpriced: set[str] = set() # Subagent transcripts live in subdirectories, hence rglob. for path in sorted(transcript_dir().rglob("*.jsonl")): for line in path.open(encoding="utf-8"): parsed = parse_response(line) # One response is split over several lines that repeat the same usage. if parsed is None or parsed[0] in seen or not since <= parsed[2] <= until: continue msg_id, model, _, counts, fast = parsed seen.add(msg_id) sessions.add(path.stem) tokens["input"] += counts[0] tokens["output"] += counts[1] tokens["cache_read"] += counts[2] tokens["cache_write"] += counts[3] + counts[4] if model in PRICES: factor = FAST_MODE_FACTOR if fast else 1.0 cost_usd += factor * sum(n * p for n, p in zip(counts, PRICES[model], strict=True)) / 1e6 elif sum(counts): unpriced.add(model) rate = args.usd_eur if args.usd_eur is not None else usd_to_eur() total = sum(tokens.values()) print(f"Window: {since.isoformat()} .. {until.isoformat()}") print(f"Sessions: {len(sessions)}, responses: {len(seen)}") print( f"Tokens: {total:,} (input {tokens['input']:,}, output {tokens['output']:,}, " f"cache read {tokens['cache_read']:,}, cache write {tokens['cache_write']:,})" ) print(f"Cost: ~EUR {cost_usd * rate:.2f} API-equivalent (USD {cost_usd:.2f} at {rate:.4f} EUR/USD)") if unpriced: print(f"Warning: no price for {', '.join(sorted(unpriced))}; not included in cost", file=sys.stderr) return 0 if __name__ == "__main__": sys.exit(main())