Files
claude-config/bin/statusline.py
T

123 lines
3.7 KiB
Python
Executable File

#!/usr/bin/env python3
import datetime
import json
import math
import os
import subprocess
import sys
import time
import typing
CYAN = "\033[36m"
DIM = "\033[2m"
GREEN = "\033[32m"
RED = "\033[31m"
RESET = "\033[0m"
YELLOW = "\033[33m"
def field(status: object, *path: str) -> object:
for key in path:
if not isinstance(status, dict):
return None
status = status.get(key)
return status
def number(status: object, *path: str) -> float | None:
found = field(status, *path)
return found if isinstance(found, (int, float)) and not isinstance(found, bool) and math.isfinite(found) else None
def text(status: object, *path: str) -> str:
found = field(status, *path)
return found if isinstance(found, str) else ""
def directory(status: object) -> str:
return text(status, "workspace", "current_dir") or text(status, "cwd")
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(epoch: float, now: int, zone: datetime.tzinfo | None) -> str:
at = datetime.datetime.fromtimestamp(round(epoch), zone)
seconds = max(0, round(epoch) - now)
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"
clock = at.strftime("%H:%M" if at.date() == datetime.datetime.fromtimestamp(now, zone).date() else "%a %H:%M")
return f" {DIM}{left} left ({clock}){RESET}"
def usage(label: str, percent: float, suffix: str) -> str:
rounded = round(percent)
return f"{DIM}{label}{RESET} {usage_color(rounded)}{rounded}%{RESET}{suffix}"
def limit(status: object, label: str, window: str, now: int, zone: datetime.tzinfo | None) -> list[str]:
percent = number(status, "rate_limits", window, "used_percentage")
if percent is None:
return []
resets = number(status, "rate_limits", window, "resets_at")
return [usage(label, percent, "" if resets is None else reset_suffix(resets, now, zone))]
def render(status: object, branch: str, home: str, now: int, zone: datetime.tzinfo | None) -> str:
where = []
shown = directory(status)
if shown:
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}")
model = text(status, "model", "display_name")
if model:
where.append(f"{DIM}{model}{RESET}")
load = []
context = number(status, "context_window", "used_percentage")
if context is not None:
used, size = number(status, "context_window", "total_input_tokens"), number(status, "context_window", "context_window_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("ctx", context, tokens))
load += limit(status, "5h", "five_hour", now, zone) + limit(status, "7d", "seven_day", now, zone)
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"], capture_output=True, text=True)
except OSError:
return ""
return found.stdout.strip() if found.returncode == 0 else ""
def main(stdin: typing.TextIO, env: typing.Mapping[str, str]) -> str:
try:
status = json.load(stdin)
except ValueError:
status = None
return render(status, current_branch(directory(status)), env.get("HOME", ""), int(time.time()), None)
if __name__ == "__main__":
sys.stdout.write(main(sys.stdin, os.environ))