Skip to content

Instantly share code, notes, and snippets.

@42LM
Last active August 17, 2026 12:06
Show Gist options
  • Select an option

  • Save 42LM/bf775c195416b4e007d57a0d48c9db3b to your computer and use it in GitHub Desktop.

Select an option

Save 42LM/bf775c195416b4e007d57a0d48c9db3b to your computer and use it in GitHub Desktop.
claude cli status line
#!/usr/bin/env bash
# Claude Code statusLine command
#
# - in = fresh input tokens (session total, summed from the main transcript;
# subagent spend shows on the agents line, not here)
# - out = output tokens (session total)
# - cr = cache read tokens (session total)
# - cw = cache write tokens (session total)
# -> monotonically rising; summed from the transcript ONLY (never from the
# request JSON — that would render a fake session line)
# - last in/cw = fresh input + cache write of the LAST request (cache health:
# "last in" should be ~0; yellow >= 1k, red >= 10k signals a cache miss)
# - /N = context window size (shortened: 1000000 -> 1m, 900000 -> 900k)
# - ctx% = usage % (color coded)
#
# GENERAL RULE: a line with no data is HIDDEN, never rendered empty. When the
# cause of the missing data is known, a single dim (note) line states it
# instead of the hidden line(s).
#
# Aligned, table-like layout (fixed label column, right-aligned numbers,
# uniform bar width):
#
# Numbers sit directly after their colon; alignment is done purely with
# spaces between the fields. Lines 1+2 are laid out to LINE_W (80) columns.
# Big numbers get _ thousand separators (3820023 -> 3_820_023).
#
# All lines are exactly LINE_W (80) columns; suffixes are right-aligned.
#
# Line 1: ~/path git:branch Model
# Line 2: in:N out:N cr:N cw:N (session)
# Line 3: in:N out:N cr:N cw:N (request)
# -> same columns as line 2; in+out+cr+cw of the request line = total
# on the ctx line
# Line 4: ctx: N% ⛁ ⛁ ⛁ ⛁ ⛶ ⛶ … total:N /N
# Line 5: session: N% カタカナ… R:13.08.26T05:20pm
# Line 6: week: N% カタカナ… R:14.08.26T02:00am
# Line 7: week_fable_5: N% カタカナ… R:14.08.26T02:00am
# -> lines 5-7 are hidden while their usage is at 0% (nothing to show,
# /usage omits the reset clause there anyway)
# Line 8: credits: N (only if present)
# Line 9+: agents: (subagents/workflows of THIS session, one
# * name:1.5m bullet line per agent with its token
# * name:3k usage; hidden when none were spawned)
input=$(cat)
cwd=$(echo "$input" | jq -r '.workspace.current_dir // .cwd // ""')
branch=$(git -C "$cwd" rev-parse --abbrev-ref HEAD 2>/dev/null)
[ "$branch" = "HEAD" ] && branch=$(git -C "$cwd" rev-parse --short HEAD 2>/dev/null)
[ -n "$branch" ] && branch="git:${branch}"
cwd="${cwd/#$HOME/~}"
model=$(echo "$input" | jq -r '.model.display_name // ""')
used=$(echo "$input" | jq -r '.context_window.used_percentage // empty')
ctx_size=$(echo "$input" | jq -r '.context_window.context_window_size // empty')
total_tok=$(echo "$input" | jq -r '.context_window.total_input_tokens // empty')
in_tok=$(echo "$input" | jq -r '.context_window.current_usage.input_tokens // empty')
out_tok=$(echo "$input" | jq -r '.context_window.current_usage.output_tokens // empty')
cache_write=$(echo "$input" | jq -r '.context_window.current_usage.cache_creation_input_tokens // empty')
cache_read=$(echo "$input" | jq -r '.context_window.current_usage.cache_read_input_tokens // empty')
transcript=$(echo "$input" | jq -r '.transcript_path // empty')
# Last request's values from the JSON (absent while subagents run).
last_in="$in_tok"
last_out="$out_tok"
last_cr="$cache_read"
last_cw="$cache_write"
# Session totals come ONLY from the transcript (dedup by message.id — one
# assistant message spans several transcript lines repeating the same usage);
# the request JSON must not leak in here, it would render as a fake session
# line. tr_reason records why the sums are missing (shown as a dim note).
in_tok=""; out_tok=""; cache_read=""; cache_write=""
tr_reason=""
u_count=0
if [ -z "$transcript" ]; then
tr_reason="no transcript path"
elif [ ! -r "$transcript" ]; then
tr_reason="transcript not readable"
else
# -R + try fromjson: the transcript is appended live, a half-written last
# line must not kill the whole parse
sums=$(jq -rRn '
[ inputs | try fromjson | .message? | select(.usage != null) | {id: (.id // "noid"), u: .usage} ] as $all
| (reduce $all[] as $m ({}; .[$m.id] = $m.u) | [.[]]) as $uniq
| (($all | last | .u) // {}) as $last
| "\($uniq | map(.input_tokens // 0) | add // 0) \($uniq | map(.output_tokens // 0) | add // 0) \($uniq | map(.cache_read_input_tokens // 0) | add // 0) \($uniq | map(.cache_creation_input_tokens // 0) | add // 0) \($all | length) \($last.input_tokens // 0) \($last.output_tokens // 0) \($last.cache_read_input_tokens // 0) \($last.cache_creation_input_tokens // 0)"
' "$transcript" 2>/dev/null)
if [ -z "$sums" ]; then
tr_reason="transcript parse failed"
else
read -r in_tok out_tok cache_read cache_write u_count t_in t_out t_cr t_cw <<< "$sums"
if [ "${u_count:-0}" -eq 0 ]; then
in_tok=""; out_tok=""; cache_read=""; cache_write=""
tr_reason="no requests in transcript yet"
elif [ -z "$last_in" ]; then
# subagents running (/code-review, Task tool, ...): the JSON has
# no current_usage — freeze the (request) line at the
# transcript's last main-loop request instead of hiding it
last_in=$t_in; last_out=$t_out; last_cr=$t_cr; last_cw=$t_cw
fi
fi
fi
# Subagent renders also drop total_input_tokens / used_percentage /
# context_window_size — rebuild them: the context snapshot is the last
# request's in + cr + cw; the window size comes from a per-session cache
# written back while the main loop still reported it.
[ -z "$total_tok" ] && [ -n "$last_in" ] && total_tok=$(( last_in + ${last_cr:-0} + ${last_cw:-0} ))
if [ -n "$transcript" ]; then
size_state="/tmp/claude_ctx_size_$(basename "$transcript" .jsonl)"
if [ -n "$ctx_size" ]; then
[ "$(cat "$size_state" 2>/dev/null)" = "$ctx_size" ] || printf '%s' "$ctx_size" > "$size_state"
else
ctx_size=$(cat "$size_state" 2>/dev/null)
case "$ctx_size" in *[!0-9]*|"") ctx_size="";; esac
fi
fi
if [ -z "$used" ] && [ -n "$total_tok" ] && [ "${ctx_size:-0}" -gt 0 ] 2>/dev/null; then
used=$(( total_tok * 100 / ctx_size ))
fi
# ── Subagent usage scan: one row per agent, for the agents line ───────────────
# Agent transcripts live in <transcript-minus-.jsonl>/subagents/agent-*.jsonl
# with the same usage lines as the main transcript (same message.id dedupe).
# Deliberately NOT merged into the (session) sums — the grid stays main-loop
# only (user's call 2026-08-17: mixing was more confusing than valuable);
# agent spend is visible in the agents line instead.
agent_entries=""
subdir="${transcript%.jsonl}/subagents"
if [ -n "$transcript" ] && [ -d "$subdir" ]; then
agent_entries=$(jq -rRn '
[ inputs as $l | {f: input_filename, j: ($l | try fromjson)} | select(.j != null) ]
| group_by(.f)
| map({
f: .[0].f,
name: ([ .[].j | select(.type? == "user") | .message.content
| if type == "string" then . elif type == "array" then (map(.text? // empty) | first // "") else "" end
]
| map(select(. != "" and (startswith("<") | not))) | first // "agent"
| gsub("\\s+"; " ") | gsub("^[Yy]ou are an? "; "")
# a leading parenthetical is the distinguishing part
# ("code-review finder agent (Simplification angle) ...")
| (try (.[0:80] | capture("\\((?<p>[^)]{3,40})\\)").p) // .)
| if length > 40 then .[0:39] + "…" else . end),
u: ([ .[].j.message? | objects | select(.usage != null) | {id: (.id // "noid"), u: .usage} ]
| (reduce .[] as $m ({}; .[$m.id] = $m.u)) | [.[]]
| { i: (map(.input_tokens // 0) | add // 0),
o: (map(.output_tokens // 0) | add // 0),
cr: (map(.cache_read_input_tokens // 0) | add // 0),
cw: (map(.cache_creation_input_tokens // 0) | add // 0) })
})
| map(.tot = (.u.i + .u.o + .u.cw)) | sort_by(-.tot)
| .[] | "\(.f)\t\(.tot)\t\(.name)"
' "$subdir"/agent-*.jsonl 2>/dev/null)
fi
RESET="\033[0m"
BOLD="\033[1m"
BLUE="\033[34m"
MAGENTA="\033[35m"
PURPLE="\033[95m" # bright magenta — the terminal theme's purple slot
WHITE="\033[97m"
GREEN="\033[32m"
DIM="\033[2m"
CYAN="\033[36m"
YELLOW="\033[33m"
CTX_GREEN="\033[32m"
CTX_YELLOW="\033[33m"
CTX_RED="\033[31m"
BAR_WIDTH=10 # fallback bar width (make_bar default)
LABEL_W=13 # widest label: "week_fable_5:"
LINE_W=80 # target width for all lines
SUFFIX_W=19 # reserved suffix column — sized for the widest realistic
# suffix ("total:260_001 /200k", 19 cols; R:-timestamps are
# 18); keeps all bars the same length, shorter suffixes get
# extra padding
month_num() {
case "$1" in
Jan) echo 01;; Feb) echo 02;; Mar) echo 03;; Apr) echo 04;;
May) echo 05;; Jun) echo 06;; Jul) echo 07;; Aug) echo 08;;
Sep) echo 09;; Oct) echo 10;; Nov) echo 11;; Dec) echo 12;;
esac
}
# parse_reset "Aug 13 at 5:20pm" -> sets P_M P_DAY P_HH P_MM P_AP P_YY
# (year inferred: dates already past roll over into the next year)
parse_reset() {
local s=$1 mon time t
P_M=""
mon=$(echo "$s" | awk '{print $1}')
P_DAY=$(echo "$s" | awk '{print $2}')
time=$(echo "$s" | awk '{print $4}')
P_M=$(month_num "$mon")
[ -n "$P_M" ] || return 1
P_AP="${time: -2}"
t="${time%??}"
P_HH="${t%%:*}"
P_MM="${t#*:}"
[ "$P_MM" = "$t" ] && P_MM=00
P_YY=$(date +%y)
if [ "$P_M$( printf '%02d' "$P_DAY" )" -lt "$(date +%m%d)" ]; then
P_YY=$(printf '%02d' $(( 10#$P_YY + 1 )))
fi
}
# "Aug 13 at 5:20pm" -> "13.08.26T05:20pm"
fmt_reset() {
parse_reset "$1" || { echo "$1"; return; }
printf '%02d.%s.%sT%02d:%s%s' "$P_DAY" "$P_M" "$P_YY" "$P_HH" "$P_MM" "$P_AP"
}
# "Aug 13 at 5:20pm" -> unix epoch (empty on parse failure)
reset_epoch() {
parse_reset "$1" || return
date -j -f '%y-%m-%d %I:%M %p' \
"${P_YY}-${P_M}-$(printf '%02d' "$P_DAY") $(printf '%02d' "$P_HH"):${P_MM} $(printf '%s' "$P_AP" | tr 'apm' 'APM')" \
+%s 2>/dev/null
}
# Color for the R:<date> suffix by how much of the limit window still lies
# ahead: > 2/3 remaining -> red (budget must survive nearly the whole window),
# > 1/3 -> yellow, else dim (reset is near).
reset_color() {
local src=$1 window=$2 epoch rem
epoch=$(reset_epoch "$src")
[ -n "$epoch" ] || { echo "$DIM"; return; }
rem=$(( epoch - $(date +%s) ))
if [ "$rem" -gt $(( window * 2 / 3 )) ]; then echo "$CTX_RED"
elif [ "$rem" -gt $(( window / 3 )) ]; then echo "$CTX_YELLOW"
else echo "$DIM"
fi
}
# 3820023 -> 3_820_023 (thousand separators)
sep_num() {
printf '%s' "$1" | rev | sed 's/[0-9]\{3\}/&_/g' | rev | sed 's/^_//'
}
# 1000000 -> 1m, 1500000 -> 1.5m, 900000 -> 900k, 500 -> 500
fmt_num() {
local n=$1
if [ "$n" -ge 1000000 ]; then
awk -v n="$n" 'BEGIN{v=n/1000000; printf (v==int(v)) ? "%dm" : "%.1fm", v}'
elif [ "$n" -ge 1000 ]; then
awk -v n="$n" 'BEGIN{v=n/1000; printf (v==int(v)) ? "%dk" : "%.1fk", v}'
else
printf '%s' "$n"
fi
}
# Matrix-style bars: random halfwidth katakana (single-column glyphs), the
# filled part in the row color, the empty remainder dimmed.
KATA=(ヲ ァ ィ ゥ ェ ォ ャ ュ ョ ッ ア イ ウ エ オ カ キ ク ケ コ サ シ ス セ ソ タ チ ツ テ ト ナ ニ ヌ ネ ノ ハ ヒ フ ヘ ホ マ ミ ム メ モ ヤ ユ ヨ ラ リ ル レ ロ ワ ン)
make_bar() {
local pct=$1 width=${2:-$BAR_WIDTH}
local filled=$(( pct * width / 100 ))
[ "$filled" -gt "$width" ] && filled=$width # pct can exceed 100
[ "$filled" -lt 0 ] && filled=0
local empty=$(( width - filled ))
local bar="" i
for ((i=0; i<filled; i++)); do bar+="${KATA[RANDOM % ${#KATA[@]}]}"; done
bar+="$DIM"
for ((i=0; i<empty; i++)); do bar+="${KATA[RANDOM % ${#KATA[@]}]}"; done
echo "$bar"
}
# /context-style disc bar: "⛁ ⛁ ⛶ ⛶ …" — spaced cells, 2 display columns each
# (fills the same span as a katakana bar of the given width; threshold color
# stays, the empty part is dimmed)
make_disc_bar() {
local pct=$1 width=$2
local cells=$(( (width + 1) / 2 )) # spaces only BETWEEN cells: 2*cells-1 cols
local filled=$(( pct * cells / 100 ))
[ "$filled" -gt "$cells" ] && filled=$cells # pct can exceed 100
[ "$filled" -lt 0 ] && filled=0
local empty=$(( cells - filled ))
local bar="" i
for ((i=0; i<filled; i++)); do bar+="⛁ "; done
bar+="$DIM"
for ((i=0; i<empty; i++)); do bar+="⛶ "; done
# drop the trailing space when the span is odd, so the bar ends on a glyph
# at the same column where the katakana bars end
[ $(( cells * 2 )) -gt "$width" ] && bar="${bar% }"
echo "$bar"
}
# pct_color <pct> [yellow_at] [red_at] (defaults: 60/80)
pct_color() {
local pct=$1 yellow_at=${2:-60} red_at=${3:-80}
if [ "$pct" -ge "$red_at" ]; then echo "$CTX_RED"
elif [ "$pct" -ge "$yellow_at" ]; then echo "$CTX_YELLOW"
else echo "$CTX_GREEN"
fi
}
# row <color> <label> <pct> [suffix]
# -> "label: N% ████████░░░░░░░░… <suffix>"
# All bars share one width (suffix column reserved at SUFFIX_W); the suffix is
# right-aligned so the line is exactly LINE_W wide. Widths are computed
# arithmetically (the bar's █/░ are multibyte, ${#} would miscount under a
# non-UTF8 locale).
row() {
local color=$1 label=$2 pct=$3 suffix=$4 sfx_color=${5:-$DIM} bar_style=${6:-kata} prefix_w bar_w bar cell pad
prefix_w=$(( LABEL_W + 1 + 4 + 1 )) # label column, space, " N%", space
# always reserve the suffix column so bars stay uniform even when a row
# has no suffix (e.g. /usage omits "resets ..." while usage is at 0%)
bar_w=$(( LINE_W - prefix_w - 2 - SUFFIX_W ))
[ "$bar_w" -lt 5 ] && bar_w=5
if [ "$bar_style" = "disc" ]; then
bar=$(make_disc_bar "$pct" "$bar_w")
else
bar=$(make_bar "$pct" "$bar_w")
fi
cell=$(printf '%-*s %3s%% %s' "$LABEL_W" "${label}:" "$pct" "$bar")
if [ -n "$suffix" ]; then
pad=$(( LINE_W - prefix_w - bar_w - ${#suffix} ))
[ "$pad" -lt 1 ] && pad=1
printf '%s' "${color}${cell}${RESET}$(printf '%*s' "$pad" '')${sfx_color}${suffix}${RESET}"
else
printf '%s' "${color}${cell}${RESET}"
fi
}
# ── Line 1: path + git branch left, model right-aligned at LINE_W ─────────────
line1="${BLUE}${cwd}${RESET}"
line1_w=${#cwd}
if [ -n "$branch" ]; then
# truncate the branch so path + branch + model still fit into LINE_W
reserve=0
[ -n "$model" ] && reserve=$(( ${#model} + 2 ))
max_b=$(( LINE_W - ${#cwd} - 2 - reserve ))
branch_w=${#branch}
if [ "$branch_w" -gt "$max_b" ]; then
if [ "$max_b" -ge 2 ]; then
branch="${branch:0:$(( max_b - 1 ))}…"
branch_w=$max_b # "…" is multibyte; count its width, not its bytes
else
branch="" # no room at all
fi
fi
if [ -n "$branch" ]; then
line1="${line1} ${CYAN}${branch}${RESET}"
line1_w=$(( line1_w + 2 + branch_w ))
fi
fi
if [ -n "$model" ]; then
pad1=$(( LINE_W - line1_w - ${#model} ))
[ "$pad1" -lt 2 ] && pad1=2
line1="${line1}$(printf '%*s' "$pad1" '')${BOLD}${PURPLE}${model}${RESET}"
fi
# ── Lines 2+3: session totals / last request as one column grid ───────────────
# Both lines share identical columns (each column as wide as the wider of its
# two cells); a field missing on one line leaves blank space in its column.
# Numbers sit directly after the colon; the gaps carry the alignment.
# spreads the collected cells_plain/cells_color across LINE_W and echoes the line
spread_cells() {
local n=${#cells_plain[@]} line="" cells_w=0 gap=2 rem=0 i g c
[ "$n" -eq 0 ] && { echo ""; return; }
for c in "${cells_plain[@]}"; do cells_w=$(( cells_w + ${#c} )); done
if [ "$n" -gt 1 ] && [ "$LINE_W" -gt "$cells_w" ]; then
gap=$(( (LINE_W - cells_w) / (n - 1) ))
[ "$gap" -lt 2 ] && gap=2
rem=$(( LINE_W - cells_w - gap * (n - 1) ))
[ "$rem" -lt 0 ] && rem=0
fi
for i in $(seq 0 $(( n - 1 ))); do
if [ "$i" -gt 0 ]; then
g=$gap
[ "$i" -le "$rem" ] && g=$(( g + 1 ))
line="${line}$(printf '%*s' "$g" '')"
fi
line="${line}${cells_color[$i]}"
done
echo "$line"
}
# session cells (flow — only rises) / request cells (snapshot; on the request
# line in+out+cr+cw = total on the ctx line, and "in" is the cache-health alarm)
s_in=""; s_out=""; s_cr=""; s_cw=""; s_tag=""
r_in=""; r_out=""; r_cr=""; r_cw=""; r_tag=""
last_color="$DIM"
[ -n "$in_tok" ] && s_in="in:$(sep_num "$in_tok")"
[ -n "$out_tok" ] && s_out="out:$(sep_num "$out_tok")"
[ -n "$cache_read" ] && s_cr="cr:$(sep_num "$cache_read")"
[ -n "$cache_write" ] && s_cw="cw:$(sep_num "$cache_write")"
[ -n "${s_in}${s_out}${s_cr}${s_cw}" ] && s_tag="(session)"
if [ -n "$last_in" ]; then
if [ "$last_in" -ge 10000 ]; then last_color="$CTX_RED"
elif [ "$last_in" -ge 1000 ]; then last_color="$CTX_YELLOW"
fi
r_in="in:$(sep_num "$last_in")"
[ -n "$last_out" ] && r_out="out:$(sep_num "$last_out")"
[ -n "$last_cr" ] && r_cr="cr:$(sep_num "$last_cr")"
[ -n "$last_cw" ] && r_cw="cw:$(sep_num "$last_cw")"
r_tag="(request)"
fi
l2_plain=(); l2_color=(); l3_plain=(); l3_color=()
add_col() { # add_col <session-cell> <request-cell> <request-color>
local s=$1 r=$2 rcol=$3 w sp rp
[ -z "$s" ] && [ -z "$r" ] && return
w=${#s}; [ ${#r} -gt "$w" ] && w=${#r}
sp=$(printf '%-*s' "$w" "$s")
rp=$(printf '%-*s' "$w" "$r")
l2_plain+=("$sp")
if [ -n "$s" ]; then l2_color+=("${DIM}${sp}${RESET}"); else l2_color+=("$sp"); fi
l3_plain+=("$rp")
if [ -n "$r" ]; then l3_color+=("${rcol}${rp}${RESET}"); else l3_color+=("$rp"); fi
}
add_col "$s_in" "$r_in" "$last_color"
add_col "$s_out" "$r_out" "$DIM"
add_col "$s_cr" "$r_cr" "$DIM"
add_col "$s_cw" "$r_cw" "$DIM"
add_col "$s_tag" "$r_tag" "$DIM"
# identical column widths + identical column count -> spread_cells produces
# identical gaps, so the two lines align perfectly
# the grid may hold columns where only the request cell is filled — a session
# line of blank-padded cells is whitespace, not "empty", so gate on s_tag
line2=""
if [ -n "$s_tag" ]; then
cells_plain=("${l2_plain[@]}")
cells_color=("${l2_color[@]}")
line2=$(spread_cells)
fi
line2b=""
if [ -n "$r_tag" ]; then
cells_plain=("${l3_plain[@]}")
cells_color=("${l3_color[@]}")
line2b=$(spread_cells)
fi
# ── Line 3: context bar + current context size ────────────────────────────────
line3=""
if [ -n "$used" ]; then
used_int=$(printf '%.0f' "$used")
ctx_color=$(pct_color "$used_int" 45 65) # ctx warns earlier than the usage limits
ctx_suffix=""
# last response's output joins the context on the next request; adding it
# matches the live token counter in the Claude Code UI
[ -n "$total_tok" ] && ctx_suffix="total:$(sep_num $(( total_tok + ${last_out:-0} )))"
[ -n "$ctx_size" ] && ctx_suffix="${ctx_suffix} /$(fmt_num "$ctx_size")"
ctx_suffix="${ctx_suffix# }"
line3=$(row "$ctx_color" "ctx" "$used_int" "$ctx_suffix" "$DIM" "disc")
fi
# ── Lines 4-7: /usage (cached, background-refresh when stale) ──────────────────
USAGE_CACHE="/tmp/claude_usage_cache"
line4=""
line5=""
line6=""
line7=""
# The refresh writes to a temp file and only replaces the cache when the new
# content is non-empty — `claude /usage` is flaky when spawned from inside a
# statusline render, and a failed run must never truncate a good cache
# (empty cache = usage lines vanish). Always backgrounded (a sync call blocks
# the render for seconds); the marker file keeps it to one refresh in flight
# even though renders keep coming while the cache is still stale.
refresh_usage() {
local marker="${USAGE_CACHE}.refreshing"
find "$marker" -mmin -2 -print -quit 2>/dev/null | grep -q . && return
touch "$marker"
( { claude /usage > "${USAGE_CACHE}.$$" 2>/dev/null
if [ -s "${USAGE_CACHE}.$$" ]; then
mv "${USAGE_CACHE}.$$" "$USAGE_CACHE"
else
rm -f "${USAGE_CACHE}.$$"
fi
rm -f "$marker"; } & )
}
usage_note=""
if [ -s "$USAGE_CACHE" ]; then
if ! find "$USAGE_CACHE" -mmin -5 -print -quit 2>/dev/null | grep -q .; then
refresh_usage
# a cache far beyond its 5-min refresh window means the refreshes
# keep failing — say so instead of silently showing old numbers
age=$(( ( $(date +%s) - $(stat -f %m "$USAGE_CACHE" 2>/dev/null || date +%s) ) / 60 ))
[ "$age" -ge 15 ] && usage_note="usage data ${age}m old — claude /usage refresh failing?"
fi
usage_data=$(cat "$USAGE_CACHE")
else
refresh_usage
usage_data=""
usage_note="usage limits: first refresh running..."
fi
# usage_line <line> <label> <window-seconds> -> aligned row via row(), or ""
usage_line() {
local src=$1 label=$2 window=$3 pct reset color
[ -n "$src" ] || { echo ""; return; }
pct=$(echo "$src" | grep -oE '[0-9]+' | head -1)
[ -n "$pct" ] || { echo ""; return; }
# at 0% the row carries no information (no reset time either) — hide it,
# like the ctx line at session start; also covers /usage dropping the
# "(all models)"/"(Fable)" qualifiers at 0%
[ "$pct" -eq 0 ] && { echo ""; return; }
color=$(pct_color "$pct")
# at 0% usage /usage omits the "· resets ..." clause — no suffix then,
# instead of leaking the rest of the line into it
reset=""
case "$src" in
*"resets "*) reset=$(echo "$src" | sed 's/.*resets //' | sed 's/ (.*)//');;
esac
if [ -n "$reset" ]; then
row "$color" "$label" "$pct" "R:$(fmt_reset "$reset")" "$(reset_color "$reset" "$window")"
else
row "$color" "$label" "$pct"
fi
}
if [ -n "$usage_data" ]; then
session_line=$(echo "$usage_data" | grep -i "current session:")
week_all_line=$(echo "$usage_data" | grep -i "current week (all models)")
week_fable_line=$(echo "$usage_data" | grep -i "current week (fable)")
credits_line=$(echo "$usage_data" | grep -i "credit")
line4=$(usage_line "$session_line" "session" 18000) # 5h window
line5=$(usage_line "$week_all_line" "week" 604800) # 7d window
line6=$(usage_line "$week_fable_line" "week_fable_5" 604800) # 7d window
if [ -n "$credits_line" ]; then
credits=$(echo "$credits_line" | grep -oE '\$?[0-9]+(\.[0-9]+)?' | head -1)
[ -n "$credits" ] && line7="${CYAN}$(printf '%-*s %s' "$LABEL_W" "credits:" "$credits")${RESET}"
fi
fi
# ── Agents block: header + one bullet line per agent ──────────────────────────
# The name lives in the sibling agent-<id>.meta.json (.name, e.g.
# "code-review" — same label as Claude Code's agent picker); transcripts of
# older sessions have no meta file, there the scan's cleaned task-prompt
# snippet serves as the name — the transcript itself has no type field and
# the main transcript never references the agentIds.
# One number per agent: in + out + cw — the same metric as the "↓ N tokens"
# counter Claude Code shows per agent (cache READS are excluded there; a
# cr-inclusive total reads ~20x higher and never matches the UI). Biggest
# spender first, one line each (capped at LINE_W).
agents_line=""
if [ -n "$agent_entries" ]; then
while IFS=$'\t' read -r a_f a_tot a_name; do
[ -n "$a_name" ] || continue
# the meta file's .name beats the prompt snippet when present
# (.agentType is deliberately NOT used — workflow agents all say
# "general-purpose" there, the snippet is more distinct)
meta="${a_f%.jsonl}.meta.json"
if [ -s "$meta" ]; then
m_name=$(jq -r '.name // empty' "$meta" 2>/dev/null)
[ -n "$m_name" ] && a_name="$m_name"
fi
entry=" * ${a_name}:$(fmt_num "${a_tot:-0}")"
[ ${#entry} -gt "$LINE_W" ] && entry="${entry:0:$(( LINE_W - 1 ))}…"
agents_line="${agents_line}"$'\n'"${DIM}${entry}${RESET}"
done <<< "$agent_entries"
[ -n "$agents_line" ] && agents_line="${CYAN}agents:${RESET}${agents_line}"
fi
# ── Diagnostics: hidden lines with a KNOWN cause get one dim note instead ─────
# (a brand-new session with no requests yet is normal — silence, not a note)
note=""
benign="no requests in transcript yet"
if [ -z "$line2b" ]; then
# neither JSON current_usage nor a transcript request to freeze on:
# the whole token grid (and with it the ctx line) is gone
if [ "$tr_reason" = "$benign" ]; then
# a transcript with no usage but spawned subagents = agents are doing
# the work right now; a truly fresh session stays quiet
[ -n "$agents_line" ] && note="subagents running — main loop has no usage in the transcript yet"
else
note="no token data — current_usage missing, ${tr_reason:-transcript had no usable request}"
fi
elif [ -z "$line2" ] && [ -n "$tr_reason" ] && [ "$tr_reason" != "$benign" ]; then
note="no session totals — ${tr_reason}"
fi
if [ -z "$line3" ] && [ -n "$line2b" ]; then
note="${note:+${note} · }ctx hidden — window size unknown (no full render seen yet)"
fi
[ -n "$note" ] && note="${DIM}(${note})${RESET}"
[ -n "$usage_note" ] && usage_note="${DIM}(${usage_note})${RESET}"
# ── Assembly: only lines that actually carry data ─────────────────────────────
# the note stands in for the hidden grid lines, so it takes their slot (above
# the ctx line)
out="$line1"
for l in "$line2" "$line2b" "$note" "$line3" "$line4" "$line5" "$line6" "$line7" "$agents_line" "$usage_note"; do
[ -n "$l" ] && out="${out}\n${l}"
done
printf '%b\n' "$out"
#!/usr/bin/env bash
# Frozen example renders of statusline-command.sh — for eyeballing colors and
# layout in the terminal. Pure prints, touches nothing, exercises nothing.
# Generated 2026-08-17 by rendering the real script against fixtures.
# Covers: ctx disc bar green (<45%) / yellow (>=45%) / red (>=65%)
# · usage bars green/yellow/red (60/80) · request-in alarm dim/yellow/red
# · reset-time colors red (fresh window) / yellow (mid) / dim (near)
# · agents block (meta.json name vs task-prompt-snippet name)
# · dim (note) lines: subagents running · no token data
# · hide rule: grid lines hidden when their data is missing — the ctx
# line effectively always shows (Claude Code always sends
# context_window, zeros in fresh sessions)
p() { printf '%b\n' "$1"; }
echo
echo "1) all healthy — green bars · request in:2 dim · fresh resets (red R:) · agents"
p '\033[34m/Users/Username/repo/rgs\033[0m \033[1m\033[95mFable 5\033[0m'
p '\033[2min:265\033[0m \033[2mout:141_037\033[0m \033[2mcr:17_126_650\033[0m \033[2mcw:531_960\033[0m \033[2m(session)\033[0m'
p '\033[2min:2 \033[0m \033[2mout:261 \033[0m \033[2mcr:212_949 \033[0m \033[2mcw:482 \033[0m \033[2m(request)\033[0m'
p '\033[32mctx: 21% ⛁ ⛁ ⛁ ⛁ \033[2m⛶ ⛶ ⛶ ⛶ ⛶ ⛶ ⛶ ⛶ ⛶ ⛶ ⛶ ⛶ ⛶ ⛶ ⛶ ⛶ \033[0m \033[2mtotal:213_955 /1m\033[0m'
p '\033[32msession: 28% スラウチオワユオヘルァ\033[2mャヤォッムョニキリスワタタルニタホラシイシコメコルクサォッ\033[0m \033[31mR:17.08.26T05:45pm\033[0m'
p '\033[32mweek: 31% ユヤコネラルラタイョネリ\033[2mリカッッルイィリラママャリリメノレイセヒチィルロチヨキユ\033[0m \033[31mR:22.08.26T11:00pm\033[0m'
p '\033[32mweek_fable_5: 56% カサリスオレノナィヒイニトトセヌンセセサヤッ\033[2mサュナュヌメレケスネフウニヘツホユテ\033[0m \033[33mR:20.08.26T11:00pm\033[0m'
p '\033[36magents:\033[0m'
p '\033[2m * code-review:154.3k\033[0m'
p '\033[2m * Angle A: line-by-line diff scan:88.0k\033[0m'
echo
echo "2) mid — ctx 55% yellow · in:1_500 yellow · mid-window resets (yellow R:) · credits"
p '\033[34m/Users/Username/repo/rgs\033[0m \033[1m\033[95mFable 5\033[0m'
p '\033[2min:265 \033[0m \033[2mout:141_037\033[0m \033[2mcr:17_126_650\033[0m \033[2mcw:531_960\033[0m \033[2m(session)\033[0m'
p '\033[33min:1_500\033[0m \033[2mout:4_200 \033[0m \033[2mcr:540_000 \033[0m \033[2mcw:8_500 \033[0m \033[2m(request)\033[0m'
p '\033[33mctx: 55% ⛁ ⛁ ⛁ ⛁ ⛁ ⛁ ⛁ ⛁ ⛁ ⛁ ⛁ \033[2m⛶ ⛶ ⛶ ⛶ ⛶ ⛶ ⛶ ⛶ ⛶ \033[0m \033[2mtotal:554_200 /1m\033[0m'
p '\033[32msession: 45% ナニメトシクェロフナェェァメサアキム\033[2mヲキゥテュオマヤケサオイヘコゥルワンォヌリキ\033[0m \033[33mR:17.08.26T04:15pm\033[0m'
p '\033[33mweek: 62% ケアョネムナマッラヌゥホハレケスヘサレセネヌユオ\033[2mュエェチヘオコメワヘモソクユヨニ\033[0m \033[33mR:20.08.26T01:00am\033[0m'
p '\033[33mweek_fable_5: 71% ッラハカエニテュキミホショメイツィュソアホレソエフォルレ\033[2mヲカンノクァクサッワトュ\033[0m \033[2mR:19.08.26T01:00pm\033[0m'
p '\033[36mcredits: $12.50\033[0m'
p '\033[36magents:\033[0m'
p '\033[2m * code-review:154.3k\033[0m'
p '\033[2m * Angle A: line-by-line diff scan:88.0k\033[0m'
echo
echo "3) alarm — ctx 87% red · in:45_000 red (full re-send) · resets imminent (dim R:)"
p '\033[34m/Users/Username/repo/rgs\033[0m \033[1m\033[95mFable 5\033[0m'
p '\033[2min:265 \033[0m \033[2mout:141_037\033[0m \033[2mcr:17_126_650\033[0m \033[2mcw:531_960\033[0m \033[2m(session)\033[0m'
p '\033[31min:45_000\033[0m \033[2mout:950 \033[0m \033[2mcr:820_000 \033[0m \033[2mcw:120_000\033[0m \033[2m(request)\033[0m'
p '\033[31mctx: 87% ⛁ ⛁ ⛁ ⛁ ⛁ ⛁ ⛁ ⛁ ⛁ ⛁ ⛁ ⛁ ⛁ ⛁ ⛁ ⛁ ⛁ \033[2m⛶ ⛶ ⛶ \033[0m \033[2mtotal:870_950 /1m\033[0m'
p '\033[31msession: 85% ナホイュキヌロャノコャイヒレニノェマコクゥフトハハトオァノンヘツテツ\033[2mヌツイマレエ\033[0m \033[2mR:17.08.26T01:30pm\033[0m'
p '\033[31mweek: 91% ョコャヨワァサセンェスノケヌソミアマレツラァチョミネイェリィシカソァヨシ\033[2mウキスュ\033[0m \033[2mR:18.08.26T11:00am\033[0m'
p '\033[31mweek_fable_5: 97% ェトテハネヒモヲテシタホマオワケョタハュヲァトテフファツヲムトンフスィィヤホ\033[2mミュ\033[0m \033[2mR:18.08.26T11:00am\033[0m'
p '\033[36magents:\033[0m'
p '\033[2m * code-review:154.3k\033[0m'
p '\033[2m * Angle A: line-by-line diff scan:88.0k\033[0m'
echo
echo "4) subagents running — grid hidden, note explains, ctx 0%, agents live"
p '\033[34m/Users/Username/repo/rgs\033[0m \033[1m\033[95mOpus 5\033[0m'
p '\033[2m(subagents running — main loop has no usage in the transcript yet)\033[0m'
p '\033[32mctx: 0% \033[2m⛶ ⛶ ⛶ ⛶ ⛶ ⛶ ⛶ ⛶ ⛶ ⛶ ⛶ ⛶ ⛶ ⛶ ⛶ ⛶ ⛶ ⛶ ⛶ ⛶ \033[0m \033[2mtotal:0 /1m\033[0m'
p '\033[32msession: 28% クンムミトヘエナョンッ\033[2mミネヒスカアウェミキィゥソェトョスンラェラキワゥアュソレツ\033[0m \033[31mR:17.08.26T05:45pm\033[0m'
p '\033[32mweek: 31% カャユニレユルタュフマレ\033[2mメチウサマャサソケッレナヌッホキソェオケヲヌネヒエムスフ\033[0m \033[31mR:22.08.26T11:00pm\033[0m'
p '\033[32mweek_fable_5: 56% ャエゥチエリテネャユモニロョロォェヤステクル\033[2mミトャェニチユスメィトレルヘミクラト\033[0m \033[33mR:20.08.26T11:00pm\033[0m'
p '\033[36magents:\033[0m'
p '\033[2m * code-review:154.3k\033[0m'
p '\033[2m * Angle A: line-by-line diff scan:88.0k\033[0m'
echo
echo "5) diagnostics — transcript not readable: grid hidden, note says why, ctx 0%"
p '\033[34m/Users/Username/repo/rgs\033[0m \033[1m\033[95mFable 5\033[0m'
p '\033[2m(no token data — current_usage missing, transcript not readable)\033[0m'
p '\033[32mctx: 0% \033[2m⛶ ⛶ ⛶ ⛶ ⛶ ⛶ ⛶ ⛶ ⛶ ⛶ ⛶ ⛶ ⛶ ⛶ ⛶ ⛶ ⛶ ⛶ ⛶ ⛶ \033[0m \033[2mtotal:0 /1m\033[0m'
p '\033[32msession: 28% ラササナメオクノントコ\033[2mュクテテオヘヨカンシォカトルマニタコサナハワセッコツヘレユ\033[0m \033[31mR:17.08.26T05:45pm\033[0m'
p '\033[32mweek: 31% ュマィヘハョロクネネゥサ\033[2mホエラキセヌホョヲトキキトナフルィシコュヒリモヤタィタオ\033[0m \033[31mR:22.08.26T11:00pm\033[0m'
p '\033[32mweek_fable_5: 56% ノセスンチセウヌモニラツラカネヒェノケモャニ\033[2mフゥフイゥヤワウゥヲォフャソュレエワ\033[0m \033[33mR:20.08.26T11:00pm\033[0m'
echo
{
"statusLine": {
"type": "command",
"command": "bash /Users/Username/.claude/statusline-command.sh"
}
}
#!/usr/bin/env bash
# Claude Code statusLine command
#
# - in = fresh input tokens (session total, summed from the transcript)
# - out = output tokens (session total)
# - cr = cache read tokens (session total)
# - cw = cache write tokens (session total)
# -> monotonically rising; falls back to the last request's usage if the
# transcript is unavailable
# - last in/cw = fresh input + cache write of the LAST request (cache health:
# "last in" should be ~0; yellow >= 1k, red >= 10k signals a cache miss)
# - /N = context window size (shortened: 1000000 -> 1m, 900000 -> 900k)
# - ctx% = usage % (color coded)[9:04 PM]
#
# Aligned, table-like layout (fixed label column, right-aligned numbers,
# uniform bar width):
#
# Numbers sit directly after their colon; alignment is done purely with
# spaces between the fields. Lines 1+2 are laid out to LINE_W (80) columns.
# Big numbers get _ thousand separators (3820023 -> 3_820_023).
#
# All lines are exactly LINE_W (80) columns; suffixes are right-aligned.
#
# Line 1: ~/path git:branch Model
# Line 2: in:N out:N cr:N cw:N (session)
# Line 3: in:N out:N cr:N cw:N (request)
# -> same columns as line 2; in+out+cr+cw of the request line = total
# on the ctx line
# Line 4: ctx: N% ⛁ ⛁ ⛁ ⛁ ⛶ ⛶ … total:N /N
# Line 5: session: N% カタカナ… R:13.08.26T05:20pm
# Line 6: week: N% カタカナ… R:14.08.26T02:00am
# Line 7: week_fable_5: N% カタカナ… R:14.08.26T02:00am
# -> lines 5-7 are hidden while their usage is at 0% (nothing to show,
# /usage omits the reset clause there anyway)
# Line 8: credits: N (only if present)
input=$(cat)
cwd=$(echo "$input" | jq -r '.workspace.current_dir // .cwd // ""')
branch=$(git -C "$cwd" rev-parse --abbrev-ref HEAD 2>/dev/null)
[ "$branch" = "HEAD" ] && branch=$(git -C "$cwd" rev-parse --short HEAD 2>/dev/null)
[ -n "$branch" ] && branch="git:${branch}"
cwd="${cwd/#$HOME/~}"
model=$(echo "$input" | jq -r '.model.display_name // ""')
used=$(echo "$input" | jq -r '.context_window.used_percentage // empty')
ctx_size=$(echo "$input" | jq -r '.context_window.context_window_size // empty')
total_tok=$(echo "$input" | jq -r '.context_window.total_input_tokens // empty')
in_tok=$(echo "$input" | jq -r '.context_window.current_usage.input_tokens // empty')
out_tok=$(echo "$input" | jq -r '.context_window.current_usage.output_tokens // empty')
cache_write=$(echo "$input" | jq -r '.context_window.current_usage.cache_creation_input_tokens // empty')
cache_read=$(echo "$input" | jq -r '.context_window.current_usage.cache_read_input_tokens // empty')
transcript=$(echo "$input" | jq -r '.transcript_path // empty')
# Last request's values (kept before the transcript sums overwrite them).
last_in="$in_tok"
last_out="$out_tok"
last_cr="$cache_read"
last_cw="$cache_write"
# Session totals from the transcript (dedup by message.id — one assistant
# message spans several transcript lines repeating the same usage).
if [ -n "$transcript" ] && [ -r "$transcript" ]; then
sums=$(jq -rn '
reduce (inputs | .message? | select(.usage != null) | {id: (.id // "noid"), u: .usage}) as $m
({}; .[$m.id] = $m.u)
| [.[]]
| "\(map(.input_tokens // 0) | add // 0) \(map(.output_tokens // 0) | add // 0) \(map(.cache_read_input_tokens // 0) | add // 0) \(map(.cache_creation_input_tokens // 0) | add // 0)"
' "$transcript" 2>/dev/null)
if [ -n "$sums" ]; then
read -r in_tok out_tok cache_read cache_write <<< "$sums"
fi
fi
RESET="\033[0m"
BOLD="\033[1m"
BLUE="\033[34m"
MAGENTA="\033[35m"
PURPLE="\033[95m" # bright magenta — the terminal theme's purple slot
WHITE="\033[97m"
GREEN="\033[32m"
DIM="\033[2m"
CYAN="\033[36m"
YELLOW="\033[33m"
CTX_GREEN="\033[32m"
CTX_YELLOW="\033[33m"
CTX_RED="\033[31m"
BAR_WIDTH=10 # fallback bar width (make_bar default)
LABEL_W=13 # widest label: "week_fable_5:"
LINE_W=80 # target width for all lines
SUFFIX_W=18 # reserved suffix column ("R:13.08.26T05:20pm"), keeps all
# bars the same length; shorter suffixes get extra padding
month_num() {
case "$1" in
Jan) echo 01;; Feb) echo 02;; Mar) echo 03;; Apr) echo 04;;
May) echo 05;; Jun) echo 06;; Jul) echo 07;; Aug) echo 08;;
Sep) echo 09;; Oct) echo 10;; Nov) echo 11;; Dec) echo 12;;
esac
}
# parse_reset "Aug 13 at 5:20pm" -> sets P_M P_DAY P_HH P_MM P_AP P_YY
# (year inferred: dates already past roll over into the next year)
parse_reset() {
local s=$1 mon time t
P_M=""
mon=$(echo "$s" | awk '{print $1}')
P_DAY=$(echo "$s" | awk '{print $2}')
time=$(echo "$s" | awk '{print $4}')
P_M=$(month_num "$mon")
[ -n "$P_M" ] || return 1
P_AP="${time: -2}"
t="${time%??}"
P_HH="${t%%:*}"
P_MM="${t#*:}"
[ "$P_MM" = "$t" ] && P_MM=00
P_YY=$(date +%y)
if [ "$P_M$( printf '%02d' "$P_DAY" )" -lt "$(date +%m%d)" ]; then
P_YY=$(printf '%02d' $(( 10#$P_YY + 1 )))
fi
}
# "Aug 13 at 5:20pm" -> "13.08.26T05:20pm"
fmt_reset() {
parse_reset "$1" || { echo "$1"; return; }
printf '%02d.%s.%sT%02d:%s%s' "$P_DAY" "$P_M" "$P_YY" "$P_HH" "$P_MM" "$P_AP"
}
# "Aug 13 at 5:20pm" -> unix epoch (empty on parse failure)
reset_epoch() {
parse_reset "$1" || return
date -j -f '%y-%m-%d %I:%M %p' \
"${P_YY}-${P_M}-$(printf '%02d' "$P_DAY") $(printf '%02d' "$P_HH"):${P_MM} $(printf '%s' "$P_AP" | tr 'apm' 'APM')" \
+%s 2>/dev/null
}
# Color for the R:<date> suffix by how much of the limit window still lies
# ahead: > 2/3 remaining -> red (budget must survive nearly the whole window),
# > 1/3 -> yellow, else dim (reset is near).
reset_color() {
local src=$1 window=$2 epoch rem
epoch=$(reset_epoch "$src")
[ -n "$epoch" ] || { echo "$DIM"; return; }
rem=$(( epoch - $(date +%s) ))
if [ "$rem" -gt $(( window * 2 / 3 )) ]; then echo "$CTX_RED"
elif [ "$rem" -gt $(( window / 3 )) ]; then echo "$CTX_YELLOW"
else echo "$DIM"
fi
}
# 3820023 -> 3_820_023 (thousand separators)
sep_num() {
printf '%s' "$1" | rev | sed 's/[0-9]\{3\}/&_/g' | rev | sed 's/^_//'
}
# 1000000 -> 1m, 1500000 -> 1.5m, 900000 -> 900k, 500 -> 500
fmt_num() {
local n=$1
if [ "$n" -ge 1000000 ]; then
awk -v n="$n" 'BEGIN{v=n/1000000; printf (v==int(v)) ? "%dm" : "%.1fm", v}'
elif [ "$n" -ge 1000 ]; then
awk -v n="$n" 'BEGIN{v=n/1000; printf (v==int(v)) ? "%dk" : "%.1fk", v}'
else
printf '%s' "$n"
fi
}
# Matrix-style bars: random halfwidth katakana (single-column glyphs), the
# filled part in the row color, the empty remainder dimmed.
KATA=(ヲ ァ ィ ゥ ェ ォ ャ ュ ョ ッ ア イ ウ エ オ カ キ ク ケ コ サ シ ス セ ソ タ チ ツ テ ト ナ ニ ヌ ネ ノ ハ ヒ フ ヘ ホ マ ミ ム メ モ ヤ ユ ヨ ラ リ ル レ ロ ワ ン)
make_bar() {
local pct=$1 width=${2:-$BAR_WIDTH}
local filled=$(( pct * width / 100 ))
local empty=$(( width - filled ))
local bar="" i
for ((i=0; i<filled; i++)); do bar+="${KATA[RANDOM % ${#KATA[@]}]}"; done
bar+="$DIM"
for ((i=0; i<empty; i++)); do bar+="${KATA[RANDOM % ${#KATA[@]}]}"; done
echo "$bar"
}
# /context-style disc bar: "⛁ ⛁ ⛶ ⛶ …" — spaced cells, 2 display columns each
# (fills the same span as a katakana bar of the given width; threshold color
# stays, the empty part is dimmed)
make_disc_bar() {
local pct=$1 width=$2
local cells=$(( (width + 1) / 2 )) # spaces only BETWEEN cells: 2*cells-1 cols
local filled=$(( pct * cells / 100 ))
local empty=$(( cells - filled ))
local bar="" i
for ((i=0; i<filled; i++)); do bar+="⛁ "; done
bar+="$DIM"
for ((i=0; i<empty; i++)); do bar+="⛶ "; done
# drop the trailing space when the span is odd, so the bar ends on a glyph
# at the same column where the katakana bars end
[ $(( cells * 2 )) -gt "$width" ] && bar="${bar% }"
echo "$bar"
}
# pct_color <pct> [yellow_at] [red_at] (defaults: 60/80)
pct_color() {
local pct=$1 yellow_at=${2:-60} red_at=${3:-80}
if [ "$pct" -ge "$red_at" ]; then echo "$CTX_RED"
elif [ "$pct" -ge "$yellow_at" ]; then echo "$CTX_YELLOW"
else echo "$CTX_GREEN"
fi
}
# row <color> <label> <pct> [suffix]
# -> "label: N% ████████░░░░░░░░… <suffix>"
# All bars share one width (suffix column reserved at SUFFIX_W); the suffix is
# right-aligned so the line is exactly LINE_W wide. Widths are computed
# arithmetically (the bar's █/░ are multibyte, ${#} would miscount under a
# non-UTF8 locale).
row() {
local color=$1 label=$2 pct=$3 suffix=$4 sfx_color=${5:-$DIM} bar_style=${6:-kata} prefix_w bar_w bar cell pad
prefix_w=$(( LABEL_W + 1 + 4 + 1 )) # label column, space, " N%", space
# always reserve the suffix column so bars stay uniform even when a row
# has no suffix (e.g. /usage omits "resets ..." while usage is at 0%)
bar_w=$(( LINE_W - prefix_w - 2 - SUFFIX_W ))
[ "$bar_w" -lt 5 ] && bar_w=5
if [ "$bar_style" = "disc" ]; then
bar=$(make_disc_bar "$pct" "$bar_w")
else
bar=$(make_bar "$pct" "$bar_w")
fi
cell=$(printf '%-*s %3s%% %s' "$LABEL_W" "${label}:" "$pct" "$bar")
if [ -n "$suffix" ]; then
pad=$(( LINE_W - prefix_w - bar_w - ${#suffix} ))
[ "$pad" -lt 1 ] && pad=1
printf '%s' "${color}${cell}${RESET}$(printf '%*s' "$pad" '')${sfx_color}${suffix}${RESET}"
else
printf '%s' "${color}${cell}${RESET}"
fi
}
# ── Line 1: path + git branch left, model right-aligned at LINE_W ─────────────
line1="${BLUE}${cwd}${RESET}"
line1_w=${#cwd}
if [ -n "$branch" ]; then
# truncate the branch so path + branch + model still fit into LINE_W
reserve=0
[ -n "$model" ] && reserve=$(( ${#model} + 2 ))
max_b=$(( LINE_W - ${#cwd} - 2 - reserve ))
branch_w=${#branch}
if [ "$branch_w" -gt "$max_b" ]; then
if [ "$max_b" -ge 2 ]; then
branch="${branch:0:$(( max_b - 1 ))}…"
branch_w=$max_b # "…" is multibyte; count its width, not its bytes
else
branch="" # no room at all
fi
fi
if [ -n "$branch" ]; then
line1="${line1} ${CYAN}${branch}${RESET}"
line1_w=$(( line1_w + 2 + branch_w ))
fi
fi
if [ -n "$model" ]; then
pad1=$(( LINE_W - line1_w - ${#model} ))
[ "$pad1" -lt 2 ] && pad1=2
line1="${line1}$(printf '%*s' "$pad1" '')${BOLD}${PURPLE}${model}${RESET}"
fi
# ── Lines 2+3: session totals / last request as one column grid ───────────────
# Both lines share identical columns (each column as wide as the wider of its
# two cells); a field missing on one line leaves blank space in its column.
# Numbers sit directly after the colon; the gaps carry the alignment.
# spreads the collected cells_plain/cells_color across LINE_W and echoes the line
spread_cells() {
local n=${#cells_plain[@]} line="" cells_w=0 gap=2 rem=0 i g c
[ "$n" -eq 0 ] && { echo ""; return; }
for c in "${cells_plain[@]}"; do cells_w=$(( cells_w + ${#c} )); done
if [ "$n" -gt 1 ] && [ "$LINE_W" -gt "$cells_w" ]; then
gap=$(( (LINE_W - cells_w) / (n - 1) ))
[ "$gap" -lt 2 ] && gap=2
rem=$(( LINE_W - cells_w - gap * (n - 1) ))
[ "$rem" -lt 0 ] && rem=0
fi
for i in $(seq 0 $(( n - 1 ))); do
if [ "$i" -gt 0 ]; then
g=$gap
[ "$i" -le "$rem" ] && g=$(( g + 1 ))
line="${line}$(printf '%*s' "$g" '')"
fi
line="${line}${cells_color[$i]}"
done
echo "$line"
}
# session cells (flow — only rises) / request cells (snapshot; on the request
# line in+out+cr+cw = total on the ctx line, and "in" is the cache-health alarm)
s_in=""; s_out=""; s_cr=""; s_cw=""; s_tag=""
r_in=""; r_out=""; r_cr=""; r_cw=""; r_tag=""
last_color="$DIM"
[ -n "$in_tok" ] && s_in="in:$(sep_num "$in_tok")"
[ -n "$out_tok" ] && s_out="out:$(sep_num "$out_tok")"
[ -n "$cache_read" ] && s_cr="cr:$(sep_num "$cache_read")"
[ -n "$cache_write" ] && s_cw="cw:$(sep_num "$cache_write")"
[ -n "${s_in}${s_out}${s_cr}${s_cw}" ] && s_tag="(session)"
if [ -n "$last_in" ]; then
if [ "$last_in" -ge 10000 ]; then last_color="$CTX_RED"
elif [ "$last_in" -ge 1000 ]; then last_color="$CTX_YELLOW"
fi
r_in="in:$(sep_num "$last_in")"
[ -n "$last_out" ] && r_out="out:$(sep_num "$last_out")"
[ -n "$last_cr" ] && r_cr="cr:$(sep_num "$last_cr")"
[ -n "$last_cw" ] && r_cw="cw:$(sep_num "$last_cw")"
r_tag="(request)"
fi
l2_plain=(); l2_color=(); l3_plain=(); l3_color=()
add_col() { # add_col <session-cell> <request-cell> <request-color>
local s=$1 r=$2 rcol=$3 w sp rp
[ -z "$s" ] && [ -z "$r" ] && return
w=${#s}; [ ${#r} -gt "$w" ] && w=${#r}
sp=$(printf '%-*s' "$w" "$s")
rp=$(printf '%-*s' "$w" "$r")
l2_plain+=("$sp")
if [ -n "$s" ]; then l2_color+=("${DIM}${sp}${RESET}"); else l2_color+=("$sp"); fi
l3_plain+=("$rp")
if [ -n "$r" ]; then l3_color+=("${rcol}${rp}${RESET}"); else l3_color+=("$rp"); fi
}
add_col "$s_in" "$r_in" "$last_color"
add_col "$s_out" "$r_out" "$DIM"
add_col "$s_cr" "$r_cr" "$DIM"
add_col "$s_cw" "$r_cw" "$DIM"
add_col "$s_tag" "$r_tag" "$DIM"
# identical column widths + identical column count -> spread_cells produces
# identical gaps, so the two lines align perfectly
line2=""
if [ "${#l2_plain[@]}" -gt 0 ]; then
cells_plain=("${l2_plain[@]}")
cells_color=("${l2_color[@]}")
line2=$(spread_cells)
fi
line2b=""
if [ -n "$r_tag" ]; then
cells_plain=("${l3_plain[@]}")
cells_color=("${l3_color[@]}")
line2b=$(spread_cells)
fi
# ── Line 3: context bar + current context size ────────────────────────────────
line3=""
if [ -n "$used" ]; then
used_int=$(printf '%.0f' "$used")
ctx_color=$(pct_color "$used_int" 45 65) # ctx warns earlier than the usage limits
ctx_suffix=""
# last response's output joins the context on the next request; adding it
# matches the live token counter in the Claude Code UI
[ -n "$total_tok" ] && ctx_suffix="total:$(sep_num $(( total_tok + ${last_out:-0} )))"
[ -n "$ctx_size" ] && ctx_suffix="${ctx_suffix} /$(fmt_num "$ctx_size")"
ctx_suffix="${ctx_suffix# }"
line3=$(row "$ctx_color" "ctx" "$used_int" "$ctx_suffix" "$DIM" "disc")
fi
# ── Lines 4-7: /usage (cached, background-refresh when stale) ──────────────────
USAGE_CACHE="/tmp/claude_usage_cache"
line4=""
line5=""
line6=""
line7=""
# The refresh writes to a temp file and only replaces the cache when the new
# content is non-empty — `claude /usage` is flaky when spawned from inside a
# statusline render, and a failed run must never truncate a good cache
# (empty cache = usage lines vanish).
if [ -s "$USAGE_CACHE" ]; then
if ! find "$USAGE_CACHE" -mmin -5 -print -quit 2>/dev/null | grep -q .; then
( { claude /usage > "${USAGE_CACHE}.$$" 2>/dev/null
if [ -s "${USAGE_CACHE}.$$" ]; then
mv "${USAGE_CACHE}.$$" "$USAGE_CACHE"
else
rm -f "${USAGE_CACHE}.$$"
fi; } & )
fi
usage_data=$(cat "$USAGE_CACHE")
else
usage_data=$(claude /usage 2>/dev/null)
[ -n "$usage_data" ] && printf '%s' "$usage_data" > "$USAGE_CACHE"
fi
# usage_line <line> <label> <window-seconds> -> aligned row via row(), or ""
usage_line() {
local src=$1 label=$2 window=$3 pct reset color
[ -n "$src" ] || { echo ""; return; }
pct=$(echo "$src" | grep -oE '[0-9]+' | head -1)
[ -n "$pct" ] || { echo ""; return; }
# at 0% the row carries no information (no reset time either) — hide it,
# like the ctx line at session start; also covers /usage dropping the
# "(all models)"/"(Fable)" qualifiers at 0%
[ "$pct" -eq 0 ] && { echo ""; return; }
color=$(pct_color "$pct")
# at 0% usage /usage omits the "· resets ..." clause — no suffix then,
# instead of leaking the rest of the line into it
reset=""
case "$src" in
*"resets "*) reset=$(echo "$src" | sed 's/.*resets //' | sed 's/ (.*)//');;
esac
if [ -n "$reset" ]; then
row "$color" "$label" "$pct" "R:$(fmt_reset "$reset")" "$(reset_color "$reset" "$window")"
else
row "$color" "$label" "$pct"
fi
}
if [ -n "$usage_data" ]; then
session_line=$(echo "$usage_data" | grep -i "current session:")
week_all_line=$(echo "$usage_data" | grep -i "current week (all models)")
week_fable_line=$(echo "$usage_data" | grep -i "current week (fable)")
credits_line=$(echo "$usage_data" | grep -i "credit")
line4=$(usage_line "$session_line" "session" 18000) # 5h window
line5=$(usage_line "$week_all_line" "week" 604800) # 7d window
line6=$(usage_line "$week_fable_line" "week_fable_5" 604800) # 7d window
if [ -n "$credits_line" ]; then
credits=$(echo "$credits_line" | grep -oE '\$?[0-9]+(\.[0-9]+)?' | head -1)
[ -n "$credits" ] && line7="${CYAN}$(printf '%-*s %s' "$LABEL_W" "credits:" "$credits")${RESET}"
fi
fi
out="${line1}\n${line2}"
[ -n "$line2b" ] && out="${out}\n${line2b}"
out="${out}\n${line3}"
[ -n "$line4" ] && out="${out}\n${line4}"
[ -n "$line5" ] && out="${out}\n${line5}"
[ -n "$line6" ] && out="${out}\n${line6}"
[ -n "$line7" ] && out="${out}\n${line7}"
printf '%b\n' "$out"
#!/usr/bin/env bash
# Frozen example renders of statusline-command.sh — for eyeballing colors and
# layout in the terminal. Pure prints, touches nothing, exercises nothing.
# Regenerate by re-rendering through statusline-command.sh if the layout changes.
# Covers: ctx disc bar green (<45%) / yellow (>=45%) / red (>=65%)
# · usage bars green/yellow/red (60/80) · request-in alarm dim/yellow/red
# · reset-time colors red (fresh window) / yellow (mid) / dim (near)
p() { printf '%b\n' "$1"; }
echo
echo "1) all healthy — green bars · request in:2 dim · fresh resets (red R:)"
p '\033[34m/Users/Username/repo/rgs\033[0m \033[36mgit:main\033[0m \033[1m\033[95mFable 5\033[0m'
p '\033[2min:265\033[0m \033[2mout:141_037\033[0m \033[2mcr:17_126_650\033[0m \033[2mcw:531_960\033[0m \033[2m(session)\033[0m'
p '\033[2min:2 \033[0m \033[2mout:261 \033[0m \033[2mcr:212_949 \033[0m \033[2mcw:482 \033[0m \033[2m(request)\033[0m'
p '\033[32mctx: 21% ⛁ ⛁ ⛁ ⛁ \033[2m⛶ ⛶ ⛶ ⛶ ⛶ ⛶ ⛶ ⛶ ⛶ ⛶ ⛶ ⛶ ⛶ ⛶ ⛶ ⛶ ⛶\033[0m \033[2mtotal:213_955 /1m\033[0m'
p '\033[32msession: 28% ヨヤラノファァテメワヘ\033[2mロラスツヌワイツミオキトムルキヲキヒハヌツニモサトゥカミシァ\033[0m \033[31mR:14.08.26T03:57am\033[0m'
p '\033[32mweek: 31% セウレッミウワヘムリムニ\033[2mヤマルモクセゥソテフレウョクルォソナサュュアキヌコョメマニ\033[0m \033[31mR:19.08.26T11:27pm\033[0m'
p '\033[32mweek_fable_5: 56% ナワマウムトスルヘャアヌオョロロアチマンュァ\033[2mイホヌホヒコフオレホッリヲンムュラェム\033[0m \033[33mR:16.08.26T11:27pm\033[0m'
echo
echo "2) mid — ctx 55% yellow · in:1_500 yellow · mid-window resets (yellow R:) · credits"
p '\033[34m/Users/Username/repo/rgs\033[0m \033[36mgit:main\033[0m \033[1m\033[95mFable 5\033[0m'
p '\033[2min:265 \033[0m \033[2mout:141_037\033[0m \033[2mcr:17_126_650\033[0m \033[2mcw:531_960\033[0m \033[2m(session)\033[0m'
p '\033[33min:1_500\033[0m \033[2mout:4_200 \033[0m \033[2mcr:540_000 \033[0m \033[2mcw:8_500 \033[0m \033[2m(request)\033[0m'
p '\033[33mctx: 55% ⛁ ⛁ ⛁ ⛁ ⛁ ⛁ ⛁ ⛁ ⛁ ⛁ ⛁ \033[2m⛶ ⛶ ⛶ ⛶ ⛶ ⛶ ⛶ ⛶ ⛶ ⛶\033[0m \033[2mtotal:554_200 /1m\033[0m'
p '\033[32msession: 45% メヨニタラソャヨオウァキゥヲルエモオ\033[2mフンキシュホハシッマルッァチメゥヲユイオクヌソ\033[0m \033[33mR:14.08.26T01:47am\033[0m'
p '\033[33mweek: 62% ョハルィクハミウウラフェコレァスヌワョネヒソゥロハ\033[2mヘコハユヤサモミコルゥマアコヲシ\033[0m \033[33mR:17.08.26T11:27am\033[0m'
p '\033[33mweek_fable_5: 71% レタナアエウヌオォネワムョネヤァウモヒヌモレアラロヌワルチ\033[2mサァナスメカユサィォハフ\033[0m \033[2mR:14.08.26T11:27pm\033[0m'
p '\033[36mcredits: $12.50\033[0m'
echo
echo "3) alarm — ctx 87% red · in:45_000 red (full re-send) · resets imminent (dim R:)"
p '\033[34m/Users/Username/repo/rgs\033[0m \033[36mgit:main\033[0m \033[1m\033[95mFable 5\033[0m'
p '\033[2min:265 \033[0m \033[2mout:141_037\033[0m \033[2mcr:17_126_650\033[0m \033[2mcw:531_960\033[0m \033[2m(session)\033[0m'
p '\033[31min:45_000\033[0m \033[2mout:950 \033[0m \033[2mcr:820_000 \033[0m \033[2mcw:120_000\033[0m \033[2m(request)\033[0m'
p '\033[31mctx: 87% ⛁ ⛁ ⛁ ⛁ ⛁ ⛁ ⛁ ⛁ ⛁ ⛁ ⛁ ⛁ ⛁ ⛁ ⛁ ⛁ ⛁ ⛁ \033[2m⛶ ⛶ ⛶\033[0m \033[2mtotal:870_950 /1m\033[0m'
p '\033[31msession: 85% ハサヌイノヲイュイゥヤテハニコヤンアヌハヘミュョテハテロュヘモクセス\033[2mセノアナヲネノ\033[0m \033[2mR:13.08.26T11:57pm\033[0m'
p '\033[31mweek: 91% ソエャウイマッスノツゥァセンヤホエコナゥオァョエャネホヒトァネヲミエヨルラ\033[2mヨウタォ\033[0m \033[2mR:14.08.26T11:27am\033[0m'
p '\033[31mweek_fable_5: 97% ェスヤヌヲメアユォォニメソチモサナウカァネカニヘョスイヤワィミクハヌカォムェゥ\033[2mソモ\033[0m \033[2mR:14.08.26T11:27am\033[0m'
echo
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment