#!/usr/bin/env python3 import dataclasses import datetime import json import math import os import subprocess import sys CYAN = "\033[36m" DIM = "\033[2m" GREEN = "\033[32m" RED = "\033[31m" RESET = "\033[0m" YELLOW = "\033[33m" @dataclasses.dataclass(frozen=True) class Limit: percent: float resets_at: datetime.datetime | None @dataclasses.dataclass(frozen=True) class Status: context_percent: float | None context_size: float | None context_used: float | None directory: str five_hour: Limit | None model: str seven_day: Limit | None def field(raw: object, *path: str) -> object: for key in path: if not isinstance(raw, dict): return None raw = raw.get(key) return raw def number(raw: object, *path: str) -> float | None: found = field(raw, *path) if isinstance(found, bool) or not isinstance(found, (int, float)): return None return found if isinstance(found, int) or math.isfinite(found) else None def text(raw: object, *path: str) -> str: found = field(raw, *path) return found if isinstance(found, str) else "" def instant(epoch: float | None, zone: datetime.tzinfo | None) -> datetime.datetime | None: if epoch is None: return None try: return datetime.datetime.fromtimestamp(round(epoch), datetime.timezone.utc).astimezone(zone) except (OSError, OverflowError, ValueError): return None def limit(raw: dict[str, object], window: str, zone: datetime.tzinfo | None) -> Limit | None: percent = number(raw, "rate_limits", window, "used_percentage") return None if percent is None else Limit(percent, instant(number(raw, "rate_limits", window, "resets_at"), zone)) # The input's fields: https://code.claude.com/docs/en/statusline # Leave out a field absent, null or of the wrong type without a warning: many are absent in normal use (no rate_limits for API users), so drift shows only as absence. def parse(raw: dict[str, object], zone: datetime.tzinfo | None) -> Status: return Status( context_percent=number(raw, "context_window", "used_percentage"), context_size=number(raw, "context_window", "context_window_size"), context_used=number(raw, "context_window", "total_input_tokens"), directory=text(raw, "workspace", "current_dir") or text(raw, "cwd"), five_hour=limit(raw, "five_hour", zone), model=text(raw, "model", "display_name"), seven_day=limit(raw, "seven_day", zone), ) def usage_color(percent: int) -> str: return RED if percent >= 80 else YELLOW if percent >= 50 else GREEN def humanize_tokens(count: int) -> str: if count >= 1_000_000: return f"{count // 1_000_000}.{count % 1_000_000 // 100_000}M" if count >= 1000: return f"{count // 1000}k" return str(count) def reset_suffix(at: datetime.datetime, now: datetime.datetime) -> str: seconds = max(0, int((at - now).total_seconds())) if seconds >= 86400: left = f"{seconds // 86400}d{seconds % 86400 // 3600}h" elif seconds >= 3600: left = f"{seconds // 3600}h{seconds % 3600 // 60}m" else: left = f"{seconds // 60}m" # %a stays English on every machine; setlocale would make this read process-wide state. clock = at.strftime("%H:%M" if at.date() == now.date() else "%a %H:%M") return f" {DIM}{left} left ({clock}){RESET}" def usage_segment(label: str, percent: float, suffix: str) -> str: rounded = round(percent) return f"{DIM}{label}{RESET} {usage_color(rounded)}{rounded}%{RESET}{suffix}" def limit_segment(label: str, window: Limit | None, now: datetime.datetime) -> list[str]: if window is None: return [] return [usage_segment(label, window.percent, "" if window.resets_at is None else reset_suffix(window.resets_at, now))] def render(status: Status, branch: str, home: str, now: datetime.datetime) -> str: where = [] if status.directory: shown = status.directory if home and (shown == home or shown.startswith(home + "/")): shown = "~" + shown[len(home):] where.append(f"{CYAN}{shown}{RESET}") if branch: where.append(f"{DIM}{branch}{RESET}") if status.model: where.append(f"{DIM}{status.model}{RESET}") load = [] if status.context_percent is not None: used, size = status.context_used, status.context_size tokens = "" if used is None or size is None else f" {DIM}{humanize_tokens(int(used))}/{humanize_tokens(int(size))}{RESET}" load.append(usage_segment("ctx", status.context_percent, tokens)) load += limit_segment("5h", status.five_hour, now) + limit_segment("7d", status.seven_day, now) return "\n".join(f"{DIM} | {RESET}".join(row) for row in (where, load) if row) def current_branch(where: str) -> str: if not where: return "" try: found = subprocess.run(["git", "-C", where, "branch", "--show-current"], errors="replace", stderr=subprocess.DEVNULL, stdout=subprocess.PIPE, text=True) except OSError: return "" return found.stdout.strip() if found.returncode == 0 else "" def main() -> str: try: raw = json.load(sys.stdin) except ValueError: raw = None if not isinstance(raw, dict): return f"{RED}warning: statusline.py's input is not a JSON object{RESET}" # Zone None: astimezone converts to the machine's own zone, daylight saving included. status = parse(raw, None) return render(status, current_branch(status.directory), os.environ.get("HOME", ""), datetime.datetime.now().astimezone()) if __name__ == "__main__": sys.stdout.write(main())