Last active
November 8, 2026 21:14
-
-
Save vanshb03/49791364fe9bdab2f7caac4f17099a90 to your computer and use it in GitHub Desktop.
Claude Code Statusline
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| """Claude Code status line - original from Graham (https://grahamhelton.com/) | |
| Displays: cwd | model | effort | context% | cost(session/today) | rate-limits | |
| e.g. ~/projects/myapp | Opus 5.5 xhigh | ctx 42% | $0.03/$0.11 | 5h 18% | |
| Setup: save as ~/.claude/statusline.py, then in ~/.claude/settings.json add | |
| "statusLine": {"type": "command", "command": "python3 ~/.claude/statusline.py"} | |
| Claude Code pipes a JSON blob to stdin; fields are read defensively since any | |
| may be absent depending on session state / CC version. | |
| The "today" cost is computed from the transcripts under ~/.claude/projects | |
| (including subagent transcripts), de-duplicated by API message id, and cached | |
| incrementally in ~/.claude/.statusline-cost-cache.json so each refresh only | |
| parses newly appended lines. | |
| """ | |
| import datetime as dt | |
| import glob | |
| import json | |
| import os | |
| import re | |
| import sys | |
| import tempfile | |
| # USD per 1M tokens: (input, output, cache_write_5m, cache_write_1h, cache_read) | |
| # Source: platform.claude.com/docs/en/about-claude/pricing (verified 2026-11-08) | |
| PRICES = { | |
| "fable-5-1": (10.0, 50.0, 12.50, 20.0, 0.25), # Fable 5.1 / Mythos 5.1 | |
| "fable-5": (10.0, 50.0, 12.50, 20.0, 1.00), # Fable 5 / Mythos 5 | |
| "opus-5-5": (4.0, 20.0, 5.00, 8.0, 0.20), # Opus 5.5 | |
| "opus-5": (5.0, 25.0, 6.25, 10.0, 0.50), # Opus 5 | |
| "opus-4-5": (5.0, 25.0, 6.25, 10.0, 0.50), # Opus 4.5 - 4.8 | |
| "opus-legacy": (15.0, 75.0, 18.75, 30.0, 1.50), # Opus 4 / 4.1 / 3 | |
| "sonnet-5-5": (2.0, 10.0, 2.50, 4.0, 0.10), # Sonnet 5.5 | |
| "sonnet-5": (2.0, 10.0, 2.50, 4.0, 0.20), # Sonnet 5 | |
| "sonnet-4": (3.0, 15.0, 3.75, 6.0, 0.30), # Sonnet 3.x / 4 / 4.5 / 4.6 | |
| "haiku-5-5": (0.10, 0.50, 0.125, 0.20, 0.01), # Haiku 5.5, prompt <= 100K | |
| "haiku-5-5-long": (0.50, 2.50, 0.625, 1.0, 0.05), # Haiku 5.5, prompt > 100K | |
| "haiku-4-5": (1.0, 5.0, 1.25, 2.0, 0.10), # Haiku 4.5 | |
| "haiku-3-5": (0.80, 4.0, 1.00, 1.6, 0.08), # Haiku 3.5 | |
| "haiku-3": (0.25, 1.25, 0.30, 0.50, 0.03), # Haiku 3 | |
| } | |
| HAIKU_55_LONG_PROMPT = 100_000 | |
| # Fast mode multiplies every category (cache multipliers stack on the fast rate). | |
| # Opus 5.5 $8/$40, Opus 5 and 4.8 $10/$50 -> 2x; Opus 4.6 was 6x. | |
| FAST_MULT = {(5, 5): 2.0, (5, 0): 2.0, (4, 8): 2.0, (4, 6): 6.0} | |
| # inference_geo "us": 1.1x on all categories, Claude 4.6 and later. | |
| US_RESIDENCY_MULT = 1.1 | |
| CACHE_PATH = os.path.expanduser("~/.claude/.statusline-cost-cache.json") | |
| # "claude-opus-5-5", "claude-opus-4-20250514", "claude-fable-5-1[1m]", ... | |
| _NEW_ID = re.compile(r"(fable|mythos|opus|sonnet|haiku)-(\d)(?:-(\d{1,2}))?(?!\d)") | |
| # "claude-3-5-haiku-20241022", "claude-3-opus-..." | |
| _OLD_ID = re.compile(r"claude-(\d)(?:-(\d))?-(opus|sonnet|haiku)") | |
| def parse_model(model): | |
| """Return (family, major, minor) or None.""" | |
| if not model: | |
| return None | |
| m = model.lower() | |
| hit = _NEW_ID.search(m) | |
| if hit: | |
| fam, major, minor = hit.group(1), int(hit.group(2)), int(hit.group(3) or 0) | |
| if fam == "mythos": | |
| fam = "fable" # same pricing tier | |
| return fam, major, minor | |
| hit = _OLD_ID.search(m) | |
| if hit: | |
| return hit.group(3), int(hit.group(1)), int(hit.group(2) or 0) | |
| return None | |
| def price_key(fam, ver, prompt_tokens): | |
| if fam == "fable": | |
| return "fable-5-1" if ver >= (5, 1) else "fable-5" | |
| if fam == "opus": | |
| if ver >= (5, 5): | |
| return "opus-5-5" | |
| if ver >= (5, 0): | |
| return "opus-5" | |
| if ver >= (4, 5): | |
| return "opus-4-5" | |
| return "opus-legacy" | |
| if fam == "sonnet": | |
| if ver >= (5, 5): | |
| return "sonnet-5-5" | |
| if ver >= (5, 0): | |
| return "sonnet-5" | |
| return "sonnet-4" | |
| if fam == "haiku": | |
| if ver >= (5, 5): | |
| return "haiku-5-5-long" if prompt_tokens > HAIKU_55_LONG_PROMPT else "haiku-5-5" | |
| if ver >= (4, 5): | |
| return "haiku-4-5" | |
| if ver >= (3, 5): | |
| return "haiku-3-5" | |
| return "haiku-3" | |
| return None | |
| def cost_of(usage: dict, model: str) -> float: | |
| parsed = parse_model(model) | |
| if not parsed: | |
| return 0.0 | |
| fam, major, minor = parsed | |
| ver = (major, minor) | |
| inp = usage.get("input_tokens", 0) or 0 | |
| out = usage.get("output_tokens", 0) or 0 | |
| cr = usage.get("cache_read_input_tokens", 0) or 0 | |
| cc = usage.get("cache_creation") | |
| if isinstance(cc, dict): | |
| cw5 = cc.get("ephemeral_5m_input_tokens", 0) or 0 | |
| cw1h = cc.get("ephemeral_1h_input_tokens", 0) or 0 | |
| else: | |
| cw5 = usage.get("cache_creation_input_tokens", 0) or 0 | |
| cw1h = 0 | |
| key = price_key(fam, ver, inp + cr + cw5 + cw1h) | |
| if not key: | |
| return 0.0 | |
| pin, pout, pcw5, pcw1h, pcr = PRICES[key] | |
| cost = (inp * pin + out * pout + cw5 * pcw5 + cw1h * pcw1h + cr * pcr) / 1_000_000.0 | |
| speed = (usage.get("speed") or usage.get("service_tier") or "").lower() | |
| if speed in ("fast", "priority_fast") and fam == "opus": | |
| cost *= FAST_MULT.get(ver, 1.0) | |
| if (usage.get("inference_geo") or "").lower() == "us" and ver >= (4, 6): | |
| cost *= US_RESIDENCY_MULT | |
| return cost | |
| def _entry(line, day): | |
| """Parse one transcript line -> (dedup_key or None, cost) or None.""" | |
| if '"usage"' not in line: | |
| return None | |
| try: | |
| obj = json.loads(line) | |
| except Exception: | |
| return None | |
| msg = obj.get("message") or {} | |
| usage = msg.get("usage") or obj.get("usage") | |
| model = msg.get("model") or obj.get("model") | |
| if not usage or not model: | |
| return None | |
| if day is not None: | |
| ts = obj.get("timestamp") or msg.get("timestamp") | |
| if not ts: | |
| return None | |
| try: | |
| t = dt.datetime.fromisoformat(ts.replace("Z", "+00:00")) | |
| if t.astimezone().date() != day: | |
| return None | |
| except Exception: | |
| return None | |
| # Claude Code writes one line per content block, each repeating the same | |
| # usage; key on the API message id (+ request id) so it counts once. | |
| mid = msg.get("id") | |
| key = f"{mid}:{obj.get('requestId') or ''}" if mid else None | |
| return key, cost_of(usage, model) | |
| def session_cost_from_transcript(path: str) -> float: | |
| seen, total = set(), 0.0 | |
| try: | |
| with open(path, "r", encoding="utf-8", errors="replace") as f: | |
| for line in f: | |
| e = _entry(line, None) | |
| if not e: | |
| continue | |
| key, c = e | |
| if key: | |
| if key in seen: | |
| continue | |
| seen.add(key) | |
| total += c | |
| except OSError: | |
| pass | |
| return total | |
| def _load_cache(today_s): | |
| try: | |
| with open(CACHE_PATH, "r", encoding="utf-8") as f: | |
| cache = json.load(f) | |
| if cache.get("day") == today_s and isinstance(cache.get("files"), dict): | |
| return cache | |
| except Exception: | |
| pass | |
| return {"day": today_s, "files": {}} | |
| def _save_cache(cache): | |
| tmp = None | |
| try: | |
| d = os.path.dirname(CACHE_PATH) | |
| fd, tmp = tempfile.mkstemp(dir=d, prefix=".statusline-cache-") | |
| with os.fdopen(fd, "w", encoding="utf-8") as f: | |
| json.dump(cache, f, separators=(",", ":")) | |
| os.replace(tmp, CACHE_PATH) | |
| except Exception: | |
| try: | |
| os.unlink(tmp) | |
| except Exception: | |
| pass | |
| def today_cost() -> float: | |
| """Sum today's cost across every transcript, incl. subagents, de-duplicated.""" | |
| today = dt.date.today() | |
| today_s = today.isoformat() | |
| midnight = dt.datetime.combine(today, dt.time.min).timestamp() | |
| root = os.path.expanduser("~/.claude/projects") | |
| cache = _load_cache(today_s) | |
| old_files = cache["files"] | |
| files = {} | |
| for path in glob.glob(os.path.join(root, "**", "*.jsonl"), recursive=True): | |
| try: | |
| st = os.stat(path) | |
| except OSError: | |
| continue | |
| if st.st_mtime < midnight: | |
| continue | |
| rec = old_files.get(path) | |
| if not rec or rec.get("ino") != st.st_ino or st.st_size < rec.get("off", 0): | |
| rec = {"ino": st.st_ino, "off": 0, "costs": {}} | |
| if st.st_size > rec["off"]: | |
| try: | |
| with open(path, "rb") as f: | |
| f.seek(rec["off"]) | |
| chunk = f.read() | |
| except OSError: | |
| chunk = b"" | |
| end = chunk.rfind(b"\n") + 1 # only consume complete lines | |
| base = rec["off"] | |
| pos = 0 | |
| for raw in chunk[:end].split(b"\n"): | |
| line_off = base + pos | |
| pos += len(raw) + 1 | |
| e = _entry(raw.decode("utf-8", "replace"), today) | |
| if e: | |
| key, c = e | |
| rec["costs"][key or f"{path}@{line_off}"] = round(c, 8) | |
| rec["off"] = base + end | |
| files[path] = rec | |
| cache["files"] = files | |
| _save_cache(cache) | |
| merged = {} | |
| for rec in files.values(): | |
| merged.update(rec["costs"]) # same message id in a forked session counts once | |
| return sum(merged.values()) | |
| def shorten_path(p: str) -> str: | |
| """Shorten a path for display: replace home dir with ~, keep last 2 parts if long.""" | |
| if not p: | |
| return "?" | |
| home = os.path.expanduser("~") | |
| p_norm = p.replace("\\", "/") | |
| home_norm = home.replace("\\", "/") | |
| if p_norm.lower().startswith(home_norm.lower()): | |
| p_norm = "~" + p_norm[len(home_norm):] | |
| parts = p_norm.rstrip("/").split("/") | |
| if len(parts) > 4: | |
| p_norm = parts[0] + "/.../" + "/".join(parts[-2:]) | |
| return p_norm | |
| def main(): | |
| try: | |
| raw = sys.stdin.read() | |
| info = json.loads(raw) if raw.strip() else {} | |
| # --- current-working-directory --------------------------------------- | |
| ws = info.get("workspace") or {} | |
| cwd = ws.get("current_dir") or info.get("cwd") or os.getcwd() | |
| cwd_str = shorten_path(cwd) | |
| wt = ws.get("git_worktree") or (info.get("worktree") or {}).get("branch") | |
| if wt: | |
| cwd_str += f" ({wt})" | |
| # --- model (+ effort / thinking / fast) ------------------------------ | |
| model_obj = info.get("model") or {} | |
| model_id = model_obj.get("id") or "" | |
| model_display = model_obj.get("display_name") or model_id or "?" | |
| model_str = model_display | |
| effort = (info.get("effort") or {}).get("level") | |
| if effort: | |
| model_str += f" {effort}" | |
| if info.get("fast_mode"): | |
| model_str += " ⚡" | |
| if (info.get("thinking") or {}).get("enabled"): | |
| model_str += " 🧠" | |
| # --- context-window-usage -------------------------------------------- | |
| ctx = info.get("context_window") or {} | |
| used_pct = ctx.get("used_percentage") | |
| ctx_str = None | |
| if used_pct is not None: | |
| ctx_str = f"ctx {used_pct:.0f}%" | |
| size = ctx.get("context_window_size") | |
| if size and size >= 1_000_000 and "1m" not in model_display.lower(): | |
| ctx_str += " (1M)" | |
| if used_pct >= 90: | |
| ctx_str += " !" | |
| # --- cost ------------------------------------------------------------ | |
| # Prefer Claude Code's own session cost; fall back to the transcript. | |
| cost_obj = info.get("cost") or {} | |
| sess_cost = cost_obj.get("total_cost_usd") | |
| if sess_cost is None: | |
| transcript = info.get("transcript_path") or "" | |
| sess_cost = session_cost_from_transcript(transcript) if transcript else 0.0 | |
| try: | |
| daily = today_cost() | |
| cost_str = f"${sess_cost:.2f}/${daily:.2f}" | |
| except Exception: | |
| cost_str = f"${sess_cost:.2f}" | |
| # --- rate limits (Pro/Max plans only) -------------------------------- | |
| rl = info.get("rate_limits") or {} | |
| rl_parts = [] | |
| five = (rl.get("five_hour") or {}).get("used_percentage") | |
| if five is not None: | |
| rl_parts.append(f"5h {five:.0f}%") | |
| seven = (rl.get("seven_day") or {}).get("used_percentage") | |
| if seven is not None: | |
| rl_parts.append(f"7d {seven:.0f}%") | |
| rl_str = " ".join(rl_parts) if rl_parts else None | |
| # --- assemble -------------------------------------------------------- | |
| parts = [cwd_str, model_str] | |
| if ctx_str: | |
| parts.append(ctx_str) | |
| parts.append(cost_str) | |
| if rl_str: | |
| parts.append(rl_str) | |
| print(" | ".join(parts)) | |
| except Exception: | |
| try: | |
| print(os.getcwd()) | |
| except Exception: | |
| print("?") | |
| if __name__ == "__main__": | |
| main() |
vanshb03
commented
Apr 26, 2026
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment