Skip to content

Instantly share code, notes, and snippets.

@panicoenlaxbox
Last active September 5, 2026 18:20
Show Gist options
  • Select an option

  • Save panicoenlaxbox/826f0c5af67ebd06771afbbc9fad4733 to your computer and use it in GitHub Desktop.

Select an option

Save panicoenlaxbox/826f0c5af67ebd06771afbbc9fad4733 to your computer and use it in GitHub Desktop.
Claude statusline
import hashlib, json, os, subprocess, sys
from pathlib import Path
from datetime import datetime, timezone
from urllib.parse import quote, urlsplit, urlunsplit
GREEN = "\x1b[32m"
YELLOW = "\x1b[33m"
ORANGE = "\x1b[38;5;208m"
CYAN = "\x1b[36m"
GRAY = "\x1b[90m"
VSCODE_BLUE = "\x1b[38;2;35;129;204m"
ITALIC = "\x1b[3m"
RESET = "\x1b[0m"
CONTEXT_WARN_THRESHOLD = 60
BRANCH_ICON = "" # nf-cod-git_branch
WORKTREE_ICON = "" # nf-cod-worktree
WARNING_ICON = "" # nf-cod-warning
# BRANCH_ICON = "⎇"
# WORKTREE_ICON = "⑂"
# WARNING_ICON = "⚠"
VSCODE_ICON = "󰨞" # nf-md-microsoft_visual_studio_code
SHORTCUT_DIR = Path.home() / ".claude" / "statusline-links"
BRANCH_PATHS = {
"github.com": "/tree/{branch}",
"dev.azure.com": "?version=GB{branch}",
}
def hyperlink(uri, text):
return f"\x1b]8;;{uri}\x1b\\{text}\x1b]8;;\x1b\\"
def remote_uri(cwd):
try:
result = subprocess.run(
["git", "config", "--get", "remote.origin.url"],
capture_output=True,
text=True,
cwd=cwd,
timeout=2,
)
except Exception:
return None
remote = result.stdout.strip() if result.returncode == 0 else ""
remote = remote.removesuffix(".git")
if not remote:
return None
if "://" not in remote:
host, _, path = remote.partition(":")
if not path:
return None
return f"https://{host.rpartition('@')[2]}/{path.lstrip('/')}"
split = urlsplit(remote)
if not split.netloc:
return None
return urlunsplit(("https", split.netloc.rpartition("@")[2], split.path, "", ""))
def branch_uri(cwd, branch):
base = remote_uri(cwd)
if not base:
return None
host = urlsplit(base).netloc
if host.startswith("ssh."):
return None
template = BRANCH_PATHS.get(host)
if not template:
return base
safe = "" if template.startswith("?") else "/"
return base + template.format(branch=quote(branch, safe=safe))
def abbreviate_home(path_text):
home = str(Path.home()).rstrip(os.sep)
if path_text.lower() == home.lower():
return "~"
if path_text.lower().startswith(home.lower() + os.sep):
return "~" + path_text[len(home) :]
return path_text
def vscode_shortcut_uri(path_text):
if os.name != "nt":
return None
# Windows Terminal only shell-executes http, https and file URIs, so the
# vscode:// URL travels inside an Internet Shortcut that file: can point at.
target = "vscode://file/" + quote(path_text.replace(os.sep, "/"), safe="/:")
body = "[InternetShortcut]\nURL=" + target + "\n"
digest = hashlib.sha1(path_text.lower().encode("utf-8")).hexdigest()[:12]
shortcut = SHORTCUT_DIR / f"{digest}.url"
try:
if not shortcut.exists() or shortcut.read_text(encoding="utf-8") != body:
SHORTCUT_DIR.mkdir(parents=True, exist_ok=True)
shortcut.write_text(body, encoding="utf-8")
return shortcut.as_uri()
except OSError:
return None
data = json.loads(sys.stdin.read())
# with open(Path.home() / ".claude" / "statusline.json", "w") as f:
# json.dump(data, f, indent=2)
model = data.get("model", {}).get("display_name", "Unknown")
context_window_size = data.get("context_window", {}).get("context_window_size", 0)
used_percentage = data.get("context_window", {}).get("used_percentage")
current_usage = data.get("context_window", {}).get("current_usage") or {}
total_tokens = (
current_usage.get("input_tokens", 0)
+ current_usage.get("cache_creation_input_tokens", 0)
+ current_usage.get("cache_read_input_tokens", 0)
)
effort_level = (data.get("effort") or {}).get("level")
total_cost_usd = data.get("cost", {}).get("total_cost_usd")
rate_limits = data.get("rate_limits", {})
five_hour = rate_limits.get("five_hour", {})
seven_day = rate_limits.get("seven_day", {})
cwd = data.get("cwd")
in_worktree = "git_worktree" in (data.get("workspace") or {})
git_branch = None
branch_pushed = False
try:
result = subprocess.run(
[
"git",
"for-each-ref",
"--format=%(HEAD)|%(refname:short)",
"refs/heads",
"refs/remotes/origin",
],
capture_output=True,
text=True,
cwd=cwd,
timeout=2,
)
if result.returncode == 0:
refs = [line.split("|", 1) for line in result.stdout.splitlines() if "|" in line]
git_branch = next((name for head, name in refs if head == "*"), None)
if git_branch:
branch_pushed = f"origin/{git_branch}" in {name for _, name in refs}
except Exception:
pass
if context_window_size >= 1_000_000:
context_window_label = f"{context_window_size // 1_000_000}M context"
elif context_window_size >= 1_000:
context_window_label = f"{context_window_size // 1_000}K context"
else:
context_window_label = f"{context_window_size} context"
branch_line = ""
if git_branch:
branch_target = branch_uri(cwd, git_branch) if branch_pushed else None
branch_text = hyperlink(branch_target, git_branch) if branch_target else git_branch
if in_worktree:
branch_text += f" {CYAN}{WORKTREE_ICON}"
branch_line = f"{GREEN}{BRANCH_ICON} {branch_text}{RESET}\n"
model_label = (
model
if context_window_label.lower() in model.lower()
else f"{model} ({context_window_label})"
)
if effort_level:
model_label += f" with {effort_level} effort"
status_line = f"{branch_line}{YELLOW}{ITALIC}{model_label}{RESET}"
if used_percentage is not None:
over_threshold = used_percentage > CONTEXT_WARN_THRESHOLD
percentage_color = ORANGE if over_threshold else ""
warning_icon = f"{WARNING_ICON} " if over_threshold else ""
status_line += f" | {percentage_color}{warning_icon}{round(used_percentage)}% used{RESET if percentage_color else ''}"
if total_tokens:
if total_tokens >= 1_000:
status_line += f" | {total_tokens / 1_000:.1f}k tokens"
else:
status_line += f" | {total_tokens} tokens"
if total_cost_usd is not None:
status_line += f" | ${total_cost_usd:.2f} cost"
if five_hour:
five_hour_percentage = five_hour.get("used_percentage", 0)
resets_at = five_hour.get("resets_at")
if resets_at:
resets_dt = datetime.fromtimestamp(resets_at, tz=timezone.utc).astimezone()
now = datetime.now(tz=timezone.utc).astimezone()
diff_minutes = max(0, int((resets_dt - now).total_seconds() / 60))
if diff_minutes >= 60:
resets_label = f"{diff_minutes // 60}h{diff_minutes % 60:02d}m"
else:
resets_label = f"{diff_minutes}m"
status_line += (
f" | 5h: {round(five_hour_percentage)}% (reset in {resets_label})"
)
else:
status_line += f" | 5h: {round(five_hour_percentage)}%"
if seven_day:
seven_day_percentage = seven_day.get("used_percentage", 0)
status_line += f" | 7d: {round(seven_day_percentage)}%"
if cwd:
cwd_label = abbreviate_home(cwd)
try:
cwd_label = hyperlink(Path(cwd).as_uri(), cwd_label)
except ValueError:
pass
editor_target = vscode_shortcut_uri(cwd)
if editor_target:
cwd_label += f" {VSCODE_BLUE}{hyperlink(editor_target, VSCODE_ICON)}"
status_line += f"\n{GRAY}{cwd_label}{RESET}"
sys.stdout.buffer.write((status_line + "\n").encode("utf-8"))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment