Skip to content

Instantly share code, notes, and snippets.

@dmd
Created March 19, 2026 23:59
Show Gist options
  • Select an option

  • Save dmd/99d0e056a9d7c7b3e4b97fabd083efd2 to your computer and use it in GitHub Desktop.

Select an option

Save dmd/99d0e056a9d7c7b3e4b97fabd083efd2 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python3
import json, subprocess, sys, time
from datetime import datetime, timezone
from pathlib import Path
from urllib.request import Request, urlopen
CACHE = Path("/tmp/claude-usage-cache.json")
inp = json.load(sys.stdin)
cwd = inp.get("workspace", {}).get("current_dir", "")
cc_version = inp.get("version", "2.1.72")
model_info = inp.get("model", {})
ctx_info = inp.get("context_window", {})
# Colors
GRN = "\033[32m"
YEL = "\033[33m"
RED = "\033[31m"
BCYN = "\033[1;36m"
WHT = "\033[97m"
DIM = "\033[90m"
RST = "\033[0m"
def get_token():
try:
raw = subprocess.check_output(
["security", "find-generic-password", "-s", "Claude Code-credentials", "-w"],
stderr=subprocess.DEVNULL, text=True,
)
return json.loads(raw).get("claudeAiOauth", {}).get("accessToken")
except Exception:
pass
creds = Path.home() / ".claude" / ".credentials.json"
if creds.exists():
return json.loads(creds.read_text()).get("claudeAiOauth", {}).get("accessToken")
return None
def update_cache():
if CACHE.exists() and time.time() - CACHE.stat().st_mtime < 300:
return
token = get_token()
if not token:
return
try:
req = Request(
"https://api.anthropic.com/api/oauth/usage",
headers={
"Authorization": f"Bearer {token}",
"anthropic-beta": "oauth-2025-04-20",
"User-Agent": f"claude-code/{cc_version}",
},
)
resp = json.loads(urlopen(req, timeout=5).read())
if "five_hour" in resp:
CACHE.write_text(json.dumps(resp))
except Exception:
pass
def pct_color(pct):
if pct >= 80:
return RED
if pct >= 50:
return YEL
return GRN
def progress_bar(pct, width=10):
pct = max(0, min(100, pct))
filled = round(pct / 100 * width)
empty = width - filled
color = pct_color(pct)
return f"{color}{'█' * filled}{DIM}{'░' * empty}{RST}"
def get_session_info():
if not CACHE.exists():
return None, None
try:
data = json.loads(CACHE.read_text())
pct = int(data["five_hour"]["utilization"])
resets_at = data["five_hour"].get("resets_at")
reset_str = None
if resets_at:
reset_time = datetime.fromisoformat(resets_at.replace("Z", "+00:00"))
diff = int((reset_time - datetime.now(timezone.utc)).total_seconds())
if diff > 0:
h, m = diff // 3600, (diff % 3600) // 60
reset_str = f"{h}:{m:02d}"
return pct, reset_str
except Exception:
return None, None
def short_model(info):
name = info.get("display_name", "") if isinstance(info, dict) else ""
if name:
return name
mid = info.get("id", "") if isinstance(info, dict) else str(info)
if mid.startswith("claude-"):
mid = mid[7:]
return mid or "?"
update_cache()
dirname = Path(cwd).name if cwd else "~"
ses_pct, ses_reset = get_session_info()
ctx_pct = ctx_info.get("used_percentage") if isinstance(ctx_info, dict) else None
SEP = f" {DIM}│{RST} "
parts = []
# Directory name
parts.append(f"{BCYN}{dirname}{RST}")
# Session usage
if ses_pct is not None:
bar = progress_bar(ses_pct)
color = pct_color(ses_pct)
s = f"Ses {bar} {color}{ses_pct}%{RST}"
if ses_reset:
s += f" ⏱ {color}{ses_reset}{RST}"
parts.append(s)
# Context window usage
if ctx_pct is not None:
bar = progress_bar(ctx_pct)
color = pct_color(ctx_pct)
parts.append(f"Ctx {bar} {color}{ctx_pct}%{RST}")
# Model
parts.append(f"{WHT}{short_model(model_info)}{RST}")
print(SEP.join(parts), end="")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment