Band above the prompt: stacked context bar, rate limits, last-turn stats, cache countdown and threshold toasts.

A macOS-focused developer workstation built around Zsh, Powerlevel10k, modern CLI tools, and battle-tested automation. Everything is wired together with bestow (a Go-based GNU Stow successor), encrypted secrets, and a centralized package manifest so each new machine behaves exactly like the last one.
z command), Atuin history (Ctrl+R and up-arrow), and Ghostty compatible key bindingsgw), uv (Python packages and projects), and curated helper aliases/functions (take, kill_by_port, show_tools, etc.)<leader>d… plus F5/F10/F11) shared by every language. Go (delve) supports debugging the test under the cursor, launching the program with arguments, and attaching to a remote dlv --headless; Python, Java, and Ballerina are wired in too. Adding another debugger is a single drop-in file: a module at nvim/.config/nvim/lua/thisarug/dap/<lang>.lua exporting setup(dap) is picked up automatically by lua/plugins/dap.lua<leader>G… for code generation (if err != nil guards, struct tags, interface stubs, test and doc-comment generation), and <leader>T… to run tests from the buffer with a summary tree and watch mode (Go, plus pytest and Vitest via neotest adapters)<leader>qs, or s on the dashboard), and diffview.nvim reviews a branch against the default branch (<leader>gv) or walks a file's history (<leader>gh)v for nvim, g for ripgrep, f for fd, z for zoxide) while keeping original commands for scripts.md → mdcat, .json/.yaml → jless, .py/.bash/.zsh/.bal → $EDITOR)pam-reattach)ControlEscape.spoon: tap Caps Lock for Escape, hold for Control — a Karabiner alternative that needs only Accessibility/Input Monitoring permissions, no blockable system extensionccp (personal) and cce (enterprise) run Claude Code against separate config dirs, with TypeScript mods for a status band, risk previews, secret redaction and a subagent pane (see Claude Code); tmux shows which windows are waiting on Claudeprefix + f opens a project with three windows ([Claude], [Nvim], [Shell])edit_secrets workflow, and automatic .env handling inside init.shBrewfile with optional category files in packages/ for modular installationbin/lint (shellcheck, shfmt, zsh -n, stylua, mod tests; also run by CI), test-zsh integration tests, dotdoctor health check, profile_startup quick timing, and bin/profile-zsh-startup for deep divesgit --version /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
brew install --cask font-fira-code-nerd-font
Set the font once inside your terminal profile (Appearance/Text settings).
init.sh)git clone https://github.com/ThisaruGuruge/dotfiles.git ~/dotfiles
cd ~/dotfiles
./init.sh
The checkout can live anywhere (the script finds the repo from its own path). The rest of the setup hard-codes ~/dotfiles, so when the checkout is elsewhere init.sh creates a ~/dotfiles symlink pointing at it (and stops with a clear message if ~/dotfiles is already something else). ./init.sh --dry-run is a preflight only: it checks the checkout and ~/dotfiles and changes nothing; ./init.sh --help lists the steps.
The script is interactive; it will:
bestow)Brewfile with Brewpam-reattach, loaded from a root-owned copy in /opt/pam).env with SOPS + age (keys stored at ~/.config/sops/age/keys.txt, per-machine ~/.sops.yaml)bestowdotdoctor for a full health check; the final output also lists the manual steps: the Hammerspoon spoon and permissions, the ~/.claude symlink, tmux plugins)git clone https://github.com/ThisaruGuruge/dotfiles.git ~/dotfiles
cd ~/dotfiles
# Install everything that is currently enabled in Brewfile
brew bundle --file=Brewfile
# Install bestow (requires Go)
go install github.com/redpierrot/bestow@latest
# Bootstrap bestow's own config (source: this repo, destination: $HOME)
bestow init --source ~/dotfiles --destination ~/
# Symlink the packages you need (add/remove as desired)
bestow stow zsh git tmux direnv bash
bestow stow bin -d ~/bin # bin links into ~/bin, not ~
# Secrets: an age key and this machine's own sops config (not tracked)
mkdir -p ~/.config/sops/age && age-keygen -o ~/.config/sops/age/keys.txt
sed "s/AGE_PUBLIC_KEY/$(grep '^# public key:' ~/.config/sops/age/keys.txt | cut -d' ' -f4)/g" \
bash/.sops.yaml.example > ~/.sops.yaml
# Reload configuration, then create the encrypted ~/.env
source ~/.zshrc
edit_secrets
Git signs every commit with SSH (gpgSign = true), so set user.signingkey in ~/.gitconfig.local (see git/.gitconfig.local.example) and create the key it names (ssh-keygen -t ed25519 -f ~/.ssh/id_ed25519_signing) before your first commit.
Edit the Brewfile directly or use category Brewfiles in packages/ before running brew bundle if you want to customize packages.
Already have a preferred dotfiles strategy but want the curated tools? Run brew bundle --file=Brewfile and manually pick pieces (aliases, functions, etc.). Edit the Brewfile directly or use the category files in packages/ to customize your installation.
The main Brewfile contains core packages that are always installed. Optional packages are organized into category files in packages/:
packages/
├── cloud.brewfile # aws-vault, gcloud CLI
├── containers.brewfile # colima, Docker CLI + Compose + credential helper
├── development.brewfile # pyenv, rbenv, nvm, flutter
├── editors.brewfile # VS Code
├── productivity.brewfile # Raycast, Rectangle, Alfred, Caffeine, etc.
└── terminals.brewfile # iTerm2
brew bundle --file=Brewfile # Core packages
brew bundle --file=packages/development.brewfile # Add dev tools
brew bundle --file=packages/editors.brewfile # Add editors
core – powerlevel10k, zoxide, eza, bat, ripgrep, lazygit, lazydocker, tmux, direnv, atuin, gh, etc.security – sops + age for encrypted secrets (always enabled)development – pyenv, rbenv, nvm, flutter (optional)cloud – aws-vault and the gcloud CLIeditors – VS Codeterminals – iTerm2 (casks)containers – colima (container runtime), Docker CLI + Compose + credential helperproductivity – Raycast, Rectangle, TablePlus, Alfred, Postman, CaffeineComment out what you do not need in the Brewfile, then rerun brew bundle.
brew-sync (or ./bin/sync-brewfile) is a read-only drift report: it lists formulae and casks that are installed but in no Brewfile, and declared packages that are not installed. It never rewrites a Brewfile; add or remove lines by hand. brew-check verifies the core Brewfile is satisfied.
| Path | Notes |
|---|---|
zsh/ | .zshrc, .zshrc.d/ (modular shell config), .functions.d/ (modular functions), aliases, paths |
zsh/.zshrc.d/ | 6 modules: plugins, completion, keybindings, history, integrations, environment |
zsh/.functions.d/ | 9 modules: colors, core, navigation, archives, git, system, dotfiles, docs, packages |
<tool>/.config/<tool>/ | XDG configs, one stow package per tool (ghostty, lazygit, nvim, yazi, ripgrep, typos) |
zsh/.p10k.zsh | Powerlevel10k prompt config (Catppuccin Mocha, stowed to ~/.p10k.zsh) |
git/ | .gitconfig, ignore rules, delta settings |
tmux/ | Modern tmux config + keybinds, project session layout, Claude state in status bar |
claude/ | Per-account Claude Code settings.json and status line, stowed to ~/.claude-personal and ~/.claude-enterprise |
claude-mods/ | Claude Code mods (not a stow package; loaded through CLAUDE_CODE_PLUGIN_DIRS) |
tests/ | Golden-output and behaviour tests for the Claude Code helpers (tests/claude/check.sh, run by test-zsh) |
direnv/ | Project-specific environment automation |
packages/ | Optional category Brewfiles (cloud, containers, development, etc.) |
bin/ | Helper scripts (lint, dotdoctor, test-zsh-config, profile-zsh-startup, audit-configs, adopt-config; see bin/README.md) |
docs/ | Additional documentation (prompt guide, tmux keybindings, config management) |
Ghostty is configured with:
ESC [ H / ESC [ F), which 03-keybindings.zsh binds to start/end of line (a raw Ctrl+a would be eaten as the tmux prefix)Ctrl+a; test-zsh fails if the prefix changes)The optional containers category (packages/containers.brewfile) installs colima as the local container runtime, paired with the plain docker, docker-compose, and docker-credential-helper CLI formulae — no Docker Desktop app/VM required.
brew bundle --file=packages/containers.brewfile # colima + docker CLI + compose + credential helper
colima-start # boots the VM, sets the `colima` docker context
docker ps # talks to colima automatically
lzd # lazydocker also works unchanged — it just follows the active docker context
Colima lifecycle aliases (zsh/.aliases.sh, only defined if colima is installed):
| Alias | Command |
|---|---|
colima-start | colima start |
colima-stop | colima stop |
colima-restart | colima restart |
colima-status | colima status |
colima-list | colima list |
colima-ssh | colima ssh |
Homebrew's docker-compose formula installs as a CLI plugin, and docker-credential-helper installs docker-credential-osxkeychain to store registry credentials in the macOS Keychain instead of plaintext — but Docker only picks either up if ~/.docker/config.json says so:
{
"cliPluginsExtraDirs": ["/opt/homebrew/lib/docker/cli-plugins"],
"credsStore": "osxkeychain"
}
init.sh does not currently write these keys automatically — add them by hand (or merge into an existing ~/.docker/config.json) after installing docker-compose / docker-credential-helper.
Day-to-day package management (adding/removing symlinks after the initial install) uses bestow — a Go-based successor to GNU Stow — instead of stow directly. It replicates stow --no-folding behavior (always on, no flag needed) but is idempotent and conflict-safe with pre-existing absolute symlinks.
bestow stow zsh # Shell config (includes .p10k.zsh)
bestow stow nvim ghostty lazygit ripgrep yazi typos # Per-tool packages
bestow stow git tmux direnv # Git/Tmux/Direnv packages
# Remove a package
bestow unstow zsh
init.sh (the fresh-machine installer) installs bestow with go install github.com/redpierrot/bestow@latest and runs the same bestow stow commands per package. @latest resolves to bestow's newest tagged release once it publishes tags (until then, the newest commit on its default branch).
binis the exception: it links into~/bin, so always stow it asbestow stow bin -d ~/bin. Don't run a barebestow stowacross every package — with the single$HOMEdestination in bestow's config it would linkbin/*straight into~.
test-zsh # Full validation (tools, PATH, runtimes)
./bin/lint # Lint everything, as CI does (./bin/lint --file <path> for one file)
./bin/profile-zsh-startup # Deep component timing (zinit plugins, SDKMAN, p10k, etc.)
help # Alias documentation entry point
docs # Interactive alias browser (alias_docs)
show_tools # Overview of installed CLI upgrades
alias_search git # Search for aliases by keyword
edit_secrets # Safely edit encrypted ~/.env via SOPS
take my-service && code . # Smart project bootstrap / clone helper
kill_by_port 3000 # Stop the process LISTENING on port 3000 (TERM, then KILL); clients are left alone
awake # Keep the Mac from idle-sleeping (awake stop | status | for 2h | screen | ac)
dotdoctor # Health check (changes nothing): unlinked files, dangling links, secrets, mods (--full adds brew + plugin validation)
prs # Browse PRs with fzf: enter=checkout, ctrl-o=browser, ctrl-d=diff via delta
prw # Watch the current PR's checks, then notify with the result
envrc work|personal|status|off # Pin the Claude Code + gws account for this directory via direnv
lg # Launch lazygit with our config (arguments are forwarded, e.g. lg log)
lzd # Launch lazydocker for Docker management
gw build # Run Gradle build from any subdirectory
gwt # Alias for: gw test
gwc # Alias for: gw clean
gwcb # Alias for: gw clean build
Ctrl+R # Atuin search UI (fuzzy search all history; Ctrl+R again narrows the filter)
Up arrow # Atuin prefix search (as you type)
Ctrl+T / Alt+C # fzf file / directory picker with a preview (Ctrl+/ toggles it)
Two accounts, each with its own config directory (claude/ is the stow package that links settings.json and statusline-command.sh into both; history, sessions and auth stay local, auth in the macOS Keychain):
| Command | Account | Config dir |
|---|---|---|
ccp, ccpr, ccpc | personal: start, --resume, --continue | ~/.claude-personal |
cce, ccer, ccec | enterprise: start, --resume, --continue | ~/.claude-enterprise |
~/.claude must be a symlink to ~/.claude-personal (ln -s ~/.claude-personal ~/.claude), so plain claude outside a pinned directory is the personal account. dotdoctor checks it.ccp/ccpr/ccpc also load ~/.claude-personal/projects.d/<repo>.json with --settings when the current git repo has one. That is where a project's own autoMode rules go, since Claude Code ignores autoMode in a project's .claude/settings*.json and they must not live in this public repo. <repo> is the main checkout's directory name, so linked worktrees share it.claude-mods/ (statusbar, blast-radius, redact, agents, rabe, session-wrapped, conventions) load straight from the repo via CLAUDE_CODE_PLUGIN_DIRS in both settings.json files, with nothing to link. The band above the prompt (context bar, rate limits) is the statusbar mod, the line below it is bin/claude-statusline, and conventions runs bin/lint --file after each edit Claude makes in this repo. See claude-mods/README.md.bin/claude-tmux-state, so tmux windows show when Claude is working, waiting or done (prefix + A jumps to the next waiting window).bin/claude-notify, which shows a macOS notification when a session finishes (Stop), asks you something (AskUserQuestion) or needs you (permission prompt, idle: Notification). It stays quiet while the terminal and the tmux window are in view. CLAUDE_NOTIFY=0 turns it off, CLAUDE_NOTIFY_SUBAGENTS=1 adds subagent completions, CLAUDE_NOTIFY_ALWAYS=1 disables the in-view suppression, CLAUDE_NOTIFY_SOUND=<name> changes the sound. One-time setup: allow banners and sounds for Script Editor under System Settings > Notifications (osascript notifications are attributed to it); Focus modes silence them. Details in bin/README.md.envrc (below).prefix + f (sessionizer) and prefix + S (new session) create a session with three windows: [Claude] (runs claude with the directory's .envrc applied), [Nvim] (nvim over a small shell, the window the session opens on) and [Shell] (plain shell). SESSIONIZER_LAYOUT=bare gives a single shell instead. After pulling, run bestow stow tmux if a new helper script is missing. Key reference: docs/TMUX_KEYBINDINGS.md.
envrc)envrc work (enterprise) or envrc personal writes a .envrc in the current directory that pins CLAUDE_CONFIG_DIR and GOOGLE_WORKSPACE_CLI_CONFIG_DIR (plus the gws file keyring backend), creates the account's gws directory with mode 700, runs direnv allow and applies the pin to the current shell straight away. Plain claude and gws then use the right account anywhere under that directory, including subdirectories and new shells or tmux panes opened inside the tree (direnv stays lazy-loaded: it is only loaded once a .envrc exists in the current directory or any parent). The file is added to the repo's local exclude (info/exclude, also from a linked worktree; envrc confirms with git check-ignore) and inherits parent pins through source_up_if_exists.
envrc status shows which pin applies (and whether it is inherited from a parent directory)envrc off removes a pin written by envrc (it never touches a .envrc it did not write).envrc (not written by envrc, or edited by hand since) asks first and keeps a copy as .envrc.bak; a symlinked .envrc is refused rather than written throughWhat overrides what
| Command | CLAUDE_CONFIG_DIR | GOOGLE_WORKSPACE_CLI_CONFIG_DIR |
|---|---|---|
plain claude in a pinned tree | pinned account | pinned account (inherited) |
ccp/ccpr/ccpc, cce/ccer/ccec | the account you typed | blanked for that claude, so a pin never leaks the other account's gws into it |
gwsp/gwse | unchanged | the account you typed |
bare gws in a pinned tree | unchanged | pinned account: the bin/gws guard lets it through because the pin supplies the account context |
bare gws anywhere else | unchanged | blocked (exit 64) |
Inside a pinned tree a bare gws therefore acts on the pinned account instead of being refused; that is the point of the pin. Plain claude outside any pinned directory uses ~/.claude, which should be a symlink to ~/.claude-personal (dotdoctor checks this: ln -s ~/.claude-personal ~/.claude).
prs, prw)prs [gh pr list flags] – fzf over the repo's PRs with a gh pr view preview. enter checks the PR out, ctrl-o opens it in the browser, ctrl-d shows the full diff through delta. Example: prs --author @meprw [pr] – gh pr checks --watch for the current branch's PR (or the given number/URL), then a macOS notification with the result; the exit status mirrors gh pr checksBoth need gh and jq; prs also needs fzf. PR titles are untrusted text: control characters (including ESC) are replaced with spaces before they are shown, and prw prints titles verbatim (no backslash interpretation). prw says whether the checks failed, were cancelled or are still pending, or that gh reported no result (no checks, or gh could not be reached), instead of calling every non-zero exit "failed".
cp / mv are small functions, not aliases: they prompt before overwriting (-i, verbose) only when a human is at the terminal, and run the plain command otherwise (scripts, agents, pipes). They do not force -r; copy directories with cp -R. sudo cp / sudo mv run the plain commands (sudo runs the binary, not the shell function), so pass -i yourself there.awake keeps the Mac from idle-sleeping in the background (caffeinate -i: the display may still sleep or lock, and it works on AC and battery). awake screen also keeps the display on, awake ac hooks/register.tsx 463 lines1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, Register } from 'claude-code'
3
4import type { Last, Limit, Row, Snap } from '../types'
5
6const snap = atom({ plugin: 'statusbar', key: 'snap' } as const, null)
7const rows = atom({ plugin: 'statusbar', key: 'rows' } as const, null)
8const history = atom({ plugin: 'statusbar', key: 'history' } as const, [])
9const last = atom({ plugin: 'statusbar', key: 'last' } as const, null)
10const isHidden = atom({ plugin: 'statusbar', key: 'isHidden' } as const, false)
11const isLegend = atom({ plugin: 'statusbar', key: 'isLegend' } as const, true)
12const warned = atom({ plugin: 'statusbar', key: 'warned' } as const, [])
13const now = atom({ plugin: 'statusbar', key: 'now' } as const, 0)
14const compactAt = atom({ plugin: 'statusbar', key: 'compactAt' } as const, null)
15
16const AMBER = '#c98500'
17const RED = '#e66767'
18const FREE = '#45475a'
19const RESERVE = '#6c7086'
20const OTHER = '#9399b2'
21
22// Category colors validated for a dark surface (lightness band, CVD separation)
23const PALETTE: [RegExp, string, string, string][] = [
24 [/system prompt/i, '#e66767', 'system', 'sys'],
25 [/tools/i, '#9085e9', 'tools', 'tools'],
26 [/mcp/i, '#d55181', 'MCP', 'mcp'],
27 [/agent/i, '#c98500', 'agents', 'agents'],
28 [/memory/i, '#199e70', 'memory', 'mem'],
29 [/skill/i, '#d95926', 'skills', 'skills'],
30 [/messages/i, '#3987e5', 'messages', 'msg'],
31]
32
33export const fmt = (n: number): string => {
34 if (n >= 1e6) return `${(n / 1e6).toFixed(1)}M`
35 if (n >= 1e4) return `${Math.round(n / 1e3)}k`
36 if (n >= 1e3) return `${(n / 1e3).toFixed(1)}k`
37 return String(n)
38}
39
40export const eta = (resetsAt: string | undefined, at: number): string => {
41 if (!resetsAt) return ''
42 const s = Math.floor((Date.parse(resetsAt) - at) / 1000)
43 if (!Number.isFinite(s)) return ''
44 if (s <= 0) return 'now'
45 const h = Math.floor(s / 3600)
46 const m = Math.floor((s % 3600) / 60)
47 if (h >= 24) return `${Math.floor(h / 24)}d${h % 24}h`
48 if (h > 0) return `${h}h${m}m`
49 return `${m}m`
50}
51
52export const paint = (r: Row): { color: string; name: string; short: string } => {
53 if (r.kind === 'free') return { color: FREE, name: 'free', short: 'free' }
54 if (r.kind === 'buffer') return { color: RESERVE, name: 'reserve', short: 'reserve' }
55 for (const [re, color, name, short] of PALETTE) {
56 if (re.test(r.name)) return { color, name, short }
57 }
58 return { color: OTHER, name: r.name.toLowerCase(), short: r.name.toLowerCase() }
59}
60
61type Cell = { ch: string; color: string; dim: boolean }
62
63export const barCells = (list: Row[], width: number, markerAt: number): Cell[] => {
64 const shown = list.filter(r => r.kind !== 'deferred')
65 const total = shown.reduce((a, r) => a + r.tokens, 0) || 1
66 const cells: Cell[] = []
67 const counts = new Map<Row, number>()
68 for (const r of shown.filter(x => x.kind !== 'free')) {
69 counts.set(r, r.tokens > 0 ? Math.max(1, Math.round((r.tokens / total) * width)) : 0)
70 }
71 const used = [...counts.values()].reduce((a, n) => a + n, 0)
72 for (const r of shown.filter(x => x.kind === 'free')) counts.set(r, Math.max(0, width - used))
73 for (const r of shown) {
74 const n = counts.get(r) ?? 0
75 const ch = r.kind === 'free' ? '░' : r.kind === 'buffer' ? '▒' : '█'
76 for (let i = 0; i < n && cells.length < width; i++) {
77 cells.push({ ch, color: paint(r).color, dim: false })
78 }
79 }
80 while (cells.length < width) cells.push({ ch: '░', color: FREE, dim: false })
81 if (markerAt >= 0 && markerAt < width) cells[markerAt] = { ch: '┃', color: '#cdd6f4', dim: false }
82 return cells
83}
84
85const runs = (cells: Cell[]): { text: string; color: string }[] => {
86 const out: { text: string; color: string }[] = []
87 for (const c of cells) {
88 const p = out[out.length - 1]
89 if (p && p.color === c.color && !(c.ch === '┃')) p.text += c.ch
90 else out.push({ text: c.ch, color: c.color })
91 }
92 return out
93}
94
95export type LegendItem = { key: string; swatch: string; color: string; text: string }
96
97export const legendItems = (
98 list: Row[],
99 window: number,
100 isNarrow: boolean,
101 minShare = 0.005,
102): LegendItem[] => {
103 const used = list.filter(r => r.kind === 'used' && r.tokens > 0).sort((a, b) => b.tokens - a.tokens)
104 const big = used.filter(r => r.tokens / window >= minShare)
105 const small = used.filter(r => r.tokens / window < minShare)
106 const out: LegendItem[] = big.map(r => {
107 const p = paint(r)
108 const label = isNarrow ? p.short : p.name
109 return { key: p.name, swatch: '■', color: p.color, text: `${label} ${fmt(r.tokens)}` }
110 })
111 if (small.length > 0) {
112 const t = small.reduce((a, r) => a + r.tokens, 0)
113 out.push({ key: 'other', swatch: '■', color: OTHER, text: `other ${fmt(t)}` })
114 }
115 for (const r of list) {
116 if (r.kind === 'buffer' || r.kind === 'free') {
117 const p = paint(r)
118 out.push({
119 key: p.name,
120 swatch: r.kind === 'free' ? '░' : '▒',
121 color: p.color,
122 text: `${isNarrow ? p.short : p.name} ${fmt(r.tokens)}`,
123 })
124 }
125 }
126 return out
127}
128
129// One ladder for context and limits, always on what is left
130export const leftColor = (leftPercent: number): string =>
131 leftPercent >= 50 ? 'text' : leftPercent >= 20 ? AMBER : RED
132
133export const hitColor = (hit: number): string => (hit >= 90 ? 'text' : hit >= 50 ? AMBER : RED)
134
135export const limitBar = (left: number, cells: number): string => {
136 const filled = Math.max(0, Math.min(cells, Math.round((left / 100) * cells)))
137 return '▰'.repeat(filled) + '▱'.repeat(cells - filled)
138}
139
140export const cacheState = (
141 left: number | null,
142): { glyph: string; color: string; text: string } | null => {
143 if (left === null) return null
144 if (left <= 0) return { glyph: '○', color: RED, text: 'cold' }
145 const t = `${Math.floor(left / 60)}:${String(left % 60).padStart(2, '0')}`
146 return left < 60 ? { glyph: '◐', color: AMBER, text: t } : { glyph: '●', color: '#199e70', text: t }
147}
148
149// Turns until the context reaches the compact point, from the last 6 turns' growth.
150// Null when there is too little data, the growth is noise (under 200 tokens a turn),
151// or the answer is too far off to mean anything (over 60 turns).
152export const turnsLeft = (used: number[], threshold: number): number | null => {
153 const pts = used.slice(-6)
154 if (pts.length < 3) return null
155 const growth = (pts[pts.length - 1] - pts[0]) / (pts.length - 1)
156 if (growth < 200) return null
157 const remaining = threshold - pts[pts.length - 1]
158 if (remaining <= 0) return 0
159 const n = Math.ceil(remaining / growth)
160 return n > 60 ? null : n
161}
162
163export const tier = (cols: number): 'wide' | 'mid' | 'narrow' =>
164 cols >= 150 ? 'wide' : cols >= 130 ? 'mid' : 'narrow'
165
166export type CompactInfo = {
167 categories: Row[]
168 autoCompactThreshold?: number
169 isAutoCompactEnabled?: boolean
170}
171
172/**
173 * The token count at which Claude Code compacts, on the same scale as the
174 * breakdown's rows (which add up to the compaction window, so an
175 * `autoCompactWindow` setting is already in them). Claude's own
176 * `autoCompactThreshold` first; when that is missing or does not fit inside
177 * the rows, the window less its compaction reserve; then `fallbackPercent`
178 * of the window. Null when auto-compaction is off.
179 */
180export const compactPoint = (b: CompactInfo, fallbackPercent: number): number | null => {
181 if (b.isAutoCompactEnabled === false) return null
182 const shown = b.categories.filter(r => r.kind !== 'deferred')
183 const total = shown.reduce((a, r) => a + r.tokens, 0)
184 const t = b.autoCompactThreshold
185 if (t !== undefined && t > 0 && (total === 0 || t <= total)) return t
186 const reserve = shown.filter(r => r.kind === 'buffer').reduce((a, r) => a + r.tokens, 0)
187 if (reserve > 0 && reserve < total) return total - reserve
188 return (total * fallbackPercent) / 100
189}
190
191async function refreshUsage($: EngineInterface, fallbackPercent: number): Promise<Snap> {
192 const u = await $.session.usage({ breakdown: 'summary' })
193 const s: Snap = {
194 tokens: u.context.tokens,
195 window: u.context.window,
196 percent: u.context.percent,
197 limits: u.rateLimits,
198 usd: u.cost?.usd,
199 }
200 await update($, snap, () => s)
201 const b = u.context.breakdown
202 const list: Row[] | null = b
203 ? b.categories.map(c => ({ name: c.name, tokens: c.tokens, color: c.color, kind: c.kind }))
204 : null
205 await update($, rows, () => list)
206 if (b && list) {
207 const at = compactPoint(
208 { categories: list, autoCompactThreshold: b.autoCompactThreshold, isAutoCompactEnabled: b.isAutoCompactEnabled },
209 fallbackPercent,
210 )
211 await update($, compactAt, () => at)
212 }
213 return s
214}
215
216export const register: Register = (on, options) => {
217 const autocompact = Number(options.autocompactPercent ?? 75)
218 const ttl = Number(options.cacheTtlSeconds ?? 3600)
219 let tools = 0
220 let prevUsd = 0
221
222 on('session.start', async ($, e, next) => {
223 await $.command.register({
224 name: 'statusbar',
225 description: 'Show or hide the status band above the prompt',
226 })
227 await $.command.register({
228 name: 'context-bar',
229 description: 'Toggle the legend under the context bar',
230 })
231 const started = await next(e)
232 await refreshUsage($, autocompact)
233 $.clock.every(10000, async () => {
234 const l = await read($, last)
235 if (l) {
236 const t = await $.clock.now()
237 await update($, now, () => t)
238 }
239 })
240 return started
241 })
242
243 on('command.run', { command: 'statusbar' }, async $ => {
244 const hidden = await read($, isHidden)
245 await update($, isHidden, () => !hidden)
246 return { text: hidden ? 'Status band shown.' : 'Status band hidden.' }
247 })
248
249 on('command.run', { command: 'context-bar' }, async $ => {
250 const shown = await read($, isLegend)
251 await update($, isLegend, () => !shown)
252 return { text: shown ? 'Legend hidden.' : 'Legend shown.' }
253 })
254
255 on('prompt.submit', async ($, e, next) => {
256 tools = 0
257 return next(e)
258 })
259
260 on('tool.call', async ($, e, next) => {
261 tools += 1
262 return next(e)
263 })
264
265 on('turn.complete', async ($, e, next) => {
266 if (e.agentId) return next(e)
267 const s = await refreshUsage($, autocompact)
268 const at = await $.clock.now()
269 const usd = s.usd ?? 0
270 const u = e.usage
271 const inTok = u ? u.input_tokens + u.cache_read_input_tokens + u.cache_creation_input_tokens : 0
272 const entry: Last = {
273 seconds: Math.round(e.durationMs / 1000),
274 tools,
275 usd: Math.max(0, usd - prevUsd),
276 outTokens: u?.output_tokens ?? 0,
277 cacheHitPercent: inTok > 0 && u ? Math.round((u.cache_read_input_tokens / inTok) * 100) : 0,
278 endedAt: at,
279 }
280 prevUsd = usd
281 await update($, last, () => entry)
282 if (s.tokens !== undefined) {
283 const tokensNow = s.tokens
284 await update($, history, h => [...h, tokensNow].slice(-6))
285 }
286 await update($, now, () => at)
287 return next(e)
288 })
289
290 on('session.measure', async ($, e, next) => {
291 const active: Record<string, string> = {}
292 const pct = e.context.percent ?? 0
293 // Close: within 10% of Claude's own compaction point once the breakdown was read, else the fallback percent
294 const [at, known] = await Promise.all([read($, compactAt), read($, rows)])
295 const tokens = e.context.tokens
296 const isNear = known ? at !== null && tokens !== undefined && tokens >= at * 0.9 : pct >= autocompact
297 if (pct >= 90) active.ctx90 = `Context at ${Math.round(pct)}%`
298 else if (isNear) active.ctx75 = `Context at ${Math.round(pct)}%: compaction is close`
299 for (const l of e.rateLimits as Limit[]) {
300 const name = l.kind === 'five_hour' ? '5h' : l.kind === 'seven_day' ? '7d' : l.kind
301 if (l.percentUsed >= 95) active[`${name}95`] = `${name} limit ${Math.round(l.percentUsed)}% used`
302 else if (l.percentUsed >= 80) active[`${name}80`] = `${name} limit ${Math.round(l.percentUsed)}% used`
303 }
304 const before = await read($, warned)
305 for (const k of Object.keys(active).filter(k => !before.includes(k))) $.ui.toast(active[k])
306 await update($, warned, () => Object.keys(active))
307 await update($, snap, s => ({
308 tokens: e.context.tokens,
309 window: e.context.window,
310 percent: e.context.percent,
311 limits: e.rateLimits as Limit[],
312 usd: e.cost?.usd ?? s?.usd,
313 }))
314 return next(e)
315 })
316
317 on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
318 if (e.props.hasSurvey || (await read($, isHidden))) return next(e)
319 const s = await read($, snap)
320 if (!s) return next(e)
321
322 const { Box, Text } = $.ui.resolve(e)
323 const [list, l, legend, hist, at] = await Promise.all([
324 read($, rows),
325 read($, last),
326 read($, isLegend),
327 read($, history),
328 read($, compactAt),
329 ])
330 await read($, now)
331 const wall = await $.clock.now()
332 const cols = e.props.bodyColumns
333 const t = tier(cols)
334 const isNarrow = t === 'narrow'
335 const isTiny = cols < 120
336 const pct = Math.round(s.percent ?? 0)
337 const shown = (list ?? []).filter(r => r.kind !== 'deferred')
338 const total = shown.reduce((a, r) => a + r.tokens, 0)
339 // Claude's own compaction point when the breakdown was read (null: auto-compaction is off)
340 const threshold = list ? at : null
341 const left = threshold !== null ? turnsLeft(hist, threshold) : null
342 const leftText =
343 left === null ? '' : left === 0 ? 'compact due' : left < 3 ? `${left} turns left` : `~${left} turns left`
344 const width = Math.max(10, cols - 3 - leftText.length - 6)
345 const markerAt = list
346 ? threshold !== null && total > 0
347 ? Math.floor((threshold / total) * width)
348 : -1
349 : Math.floor((autocompact / 100) * width)
350 const cells = list
351 ? barCells(list, width, markerAt)
352 : barCells(
353 [
354 { name: 'messages', tokens: pct, color: '', kind: 'used' },
355 { name: 'free', tokens: 100 - pct, color: '', kind: 'free' },
356 ],
357 width,
358 markerAt,
359 )
360 const items = list ? legendItems(list, total || 1, isTiny, isTiny ? 0.01 : 0.005) : []
361 if (threshold !== null) {
362 items.push({ key: 'compact', swatch: '┃', color: '#cdd6f4', text: `compact ${fmt(Math.round(threshold))}` })
363 }
364 const cacheLeft = l ? Math.round(ttl - (wall - l.endedAt) / 1000) : null
365 const cache = cacheState(cacheLeft)
366 // Each limit line is about 15 columns of text around its bar; the two bars share what is left, up to 40 cells
367 const limitCells = Math.max(6, Math.min(40, Math.floor((cols - 3 - 9 - 30) / 2)))
368 const gap = isNarrow ? 2 : 3
369 const rowGap = isNarrow ? 3 : 4
370 const blank = 0
371
372 const limitNodes = s.limits.map(x => {
373 const name = x.kind === 'five_hour' ? '5h' : x.kind === 'seven_day' ? '7d' : x.kind
374 const left = Math.max(0, 100 - Math.round(x.percentUsed))
375 const color = leftColor(left)
376 return (
377 <Text key={x.kind}>
378 {name} <Text color={color}>{limitBar(left, limitCells)}</Text>{' '}
379 <Text color={color}>{left}%</Text> <Text dimColor>{eta(x.resetsAt, wall)}</Text>
380 </Text>
381 )
382 })
383
384 const turnNodes = l
385 ? [
386 <Text key="s">{l.seconds}s</Text>,
387 <Text key="t">{l.tools} {l.tools === 1 ? 'tool' : 'tools'}</Text>,
388 <Text key="c">${l.usd.toFixed(2)}</Text>,
389 <Text key="o">↑{fmt(l.outTokens)}</Text>,
390 <Text key="h" color={l.cacheHitPercent >= 90 ? undefined : hitColor(l.cacheHitPercent)} dimColor={l.cacheHitPercent >= 90}>⚡ {l.cacheHitPercent}% cache</Text>,
391 cache ? (
392 <Text key="k">
393 <Text color={cache.color}>{cache.glyph}</Text>{' '}
394 <Text color={cache.glyph === '○' ? RED : undefined} dimColor={cache.glyph === '●'}>{cache.text}</Text>
395 {cache.glyph === '○' && !isNarrow && <Text color={RED}> ⚠ next re-reads full</Text>}
396 </Text>
397 ) : (
398 <Text key="k"> </Text>
399 ),
400 ]
401 : []
402
403 const lane = (nodes: unknown[]) =>
404 nodes.map((n, i) => <Box key={String(i)}>{n as never}</Box>)
405
406 // Other mods draw here too (agents, rabe): keep what they draw instead of replacing it
407 const below = await next(e)
408
409 return (
410 <Box flexDirection="column">
411 {below}
412 <Box flexDirection="column" marginTop={1}>
413 <Box flexDirection="row">
414 <Box width={3}><Text dimColor>◔</Text></Box>
415 <Box flexDirection="row" columnGap={2}>
416 <Box flexDirection="row">
417 {runs(cells).map((r, i) => (
418 <Text key={String(i)} color={r.color}>{r.text}</Text>
419 ))}
420 </Box>
421 {leftText !== '' && (
422 <Text color={left !== null && left < 3 ? RED : undefined} dimColor={left !== null && left >= 3}>
423 {leftText}
424 </Text>
425 )}
426 </Box>
427 </Box>
428 {legend && cols >= 80 && items.length > 0 && (
429 <Box flexDirection="row">
430 <Box width={3}><Text> </Text></Box>
431 <Box flexDirection="row" flexWrap="wrap" columnGap={gap}>
432 {lane(
433 items.map(it => (
434 <Text key={it.key}>
435 <Text color={it.color}>{it.swatch}</Text> <Text dimColor>{it.text}</Text>
436 </Text>
437 )),
438 )}
439 </Box>
440 </Box>
441 )}
442 <Box flexDirection="row" marginTop={blank}>
443 <Box width={3}><Text dimColor>⏱</Text></Box>
444 <Box flexDirection="row" columnGap={rowGap}>
445 {lane(
446 limitNodes.flatMap((n, i) => (i === 0 ? [n] : [<Text key={`d${i}`} dimColor>·</Text>, n])),
447 )}
448 </Box>
449 </Box>
450 {l && (
451 <Box flexDirection="row" marginTop={blank}>
452 <Box width={3}><Text dimColor>↻</Text></Box>
453 <Box flexDirection="row" columnGap={rowGap}>
454 {lane(turnNodes)}
455 </Box>
456 </Box>
457 )}
458 </Box>
459 </Box>
460 )
461 })
462}
463types/index.d.ts 43 lines1export type Row = {
2 name: string
3 tokens: number
4 color: string
5 kind: 'used' | 'free' | 'buffer' | 'deferred'
6}
7
8export type Limit = { kind: string; percentUsed: number; resetsAt?: string }
9
10export type Snap = {
11 tokens?: number
12 window: number
13 percent?: number
14 limits: Limit[]
15 usd?: number
16}
17
18export type Last = {
19 seconds: number
20 tools: number
21 usd: number
22 outTokens: number
23 cacheHitPercent: number
24 endedAt: number
25}
26
27declare module 'claude-code' {
28 interface PluginState {
29 statusbar: {
30 snap: Snap | null
31 rows: Row[] | null
32 history: number[]
33 last: Last | null
34 isHidden: boolean
35 isLegend: boolean
36 warned: string[]
37 now: number
38 /** Tokens at which auto-compaction runs, from Claude Code's breakdown; null when off or not yet read. */
39 compactAt: number | null
40 }
41 }
42}
43