Ligne d'état sous le prompt : modèle, dossier, branche, tokens, contexte et quotas 5 h / 7 j (barres colorées, reset).

Declarative macOS system configuration using Nix flakes
[]() [
]()
Single host: alex-mbp (aarch64-darwin). Everything below is declared in this repo — system settings, CLI tools, GUI apps, fonts, shell, editor, and the Claude Code setup.
# 1. Prerequisites (git + clone access)
xcode-select --install
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
brew install gh
gh auth login # authenticate with GitHub
# 2. Clone and run bootstrap (handles everything else)
git clone https://github.com/AlxWrtl/NixConfig.git ~/.config/nix-darwin
cd ~/.config/nix-darwin
./bootstrap.sh
bootstrap.sh runs twelve checkpointed steps and skips whatever is already done, so it is safe to re-run after an interruption. Once a run completes, later runs skip the app configs restore unless you pass ./bootstrap.sh --restore:
| # | Step | Notes |
|---|---|---|
| 1 | Xcode Command Line Tools | |
| 2 | Nix package manager | Determinate Systems installer |
| 3 | Homebrew | |
| 4 | 1Password | pauses — you retrieve SSH keys + git-crypt key from the vault |
| 5 | SSH key permissions | chmod 700 ~/.ssh, 600 on the private key |
| 6 | GitHub CLI authentication | gh auth login |
| 7 | Decrypt secrets | git-crypt unlock |
| 8 | App Store login | pauses — sign in for masApps |
| 9 | darwin-rebuild switch | the actual build |
| 10 | Switch git remote to SSH | |
| 11 | VS Code extensions | vscode-install-extensions |
| 12 | Restore app configs | Plex, Logitech, Raycast, Ice, Finder sidebar, Wi-Fi/BT |
Steps 4 and 8 block on a manual action; the rest are unattended. App logins (Discord, Figma, Teams, …) stay manual — see the checklist below.
# 1. Xcode Command Line Tools
xcode-select --install
# 2. Install Homebrew + GitHub CLI
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
brew install gh
gh auth login
# 3. Install Nix
curl --proto '=https' --tlsv1.2 -sSf -L https://install.determinate.systems/nix | sh
# 4. Clone
git clone https://github.com/AlxWrtl/NixConfig.git ~/.config/nix-darwin
cd ~/.config/nix-darwin
# 5. Install 1Password and retrieve keys
brew install --cask 1password
# Open 1Password → login → save SSH keys to ~/.ssh/ and git-crypt key to ~/git-crypt-key
# 6. Decrypt secrets
nix-shell -p git-crypt --run "git-crypt unlock ~/git-crypt-key"
rm ~/git-crypt-key
# 7. Login to App Store (for masApps)
# 8. Build & apply
sudo darwin-rebuild switch --flake .#alex-mbp
# 9. Post-install
git remote set-url origin git@github.com:AlxWrtl/NixConfig.git
~/.local/bin/vscode-install-extensions
flake.nix # inputs, checks, darwinConfigurations, devShell
├── hosts/alex-mbp/ # Host identity
│ ├── default.nix
│ └── configuration.nix
├── modules/ # System modules
│ ├── system.nix # Nix settings, env, firewall, shell
│ ├── packages.nix # CLI tools + shell aliases
│ ├── services.nix # launchd agents & daemons
│ ├── ui.nix # Fonts, Dock, Finder, macOS defaults, wallpaper
│ └── brew.nix # taps, brews, casks, masApps
├── home/ # User config (home-manager)
│ ├── default.nix # User packages & imports
│ ├── git.nix # Git + SSH signing
│ ├── ssh.nix # SSH hosts
│ ├── zsh.nix # Shell (zsh + fzf + zoxide + autosuggest + highlighting)
│ ├── starship.nix # Prompt
│ ├── direnv.nix # Directory environments
│ ├── ghostty.nix # Terminal (Catppuccin, quick terminal)
│ ├── vscode.nix # VS Code settings, keybindings, extensions
│ ├── claude-code.nix # Claude Code entrypoint — imports claude-code/
│ ├── claude-code/ # settings, hooks, agents, skills, commands, rules…
│ │ # incl. skills-manifest.nix (Claude skills)
│ │ # and mods/ (deck, status-bar) via mods.nix
│ │ # and apex-board/ (APEX run board page + serve.py
│ │ # + tui/, the same board in the terminal, in Go)
│ ├── codex.nix # Codex CLI entrypoint — imports codex/
│ ├── codex/ # hooks.json generator, activation, hook & merge scripts
│ └── colima.nix # Colima VMs: `ci` (k3s + ARC self-hosted CI runners),
│ # `default` (dev containers, active Docker context)
├── checks/ # Flake checks (see Quality Gates)
│ ├── agent-instructions.nix
│ ├── agent-pane.nix
│ ├── apex-board.nix
│ ├── apex-consistency.nix
│ ├── apex-health.nix
│ ├── apex-plan-provenance.nix
│ ├── apex-tier.nix
│ ├── audit-apex-needles.py # Advisory, not a flake check — needle shapes
│ ├── claude-config.nix
│ ├── claude-dispatch.nix
│ ├── claude-mods.nix
│ ├── codex-config.nix
│ ├── colima-ci.nix
│ ├── hook-wiring.nix
│ ├── js-lint.nix
│ ├── preprod-curl.nix
│ ├── readme-consistency.nix
│ └── trello-cli.nix
├── backups/ # 🔒 Encrypted app config exports (backup-apps.sh)
├── wallpapers/ # Desktop wallpaper
├── secrets.nix # 🔒 Encrypted (git-crypt) — emails, IPs, usernames
├── bootstrap.sh # Fresh-machine install
├── backup-apps.sh # Export app configs into backups/
└── .gitattributes # git-crypt filter rules
flake.nix inputs: nixpkgs (unstable), nix-darwin, home-manager (master), and determinate for the Nix daemon. awesome-design-md, claude-video, cloudflare-security-audit, brag and emil-skills are pinned non-flake sources for the design-md, watch, security-audit, brag and ui-expert skills.
Sensitive values live in secrets.nix, encrypted by git-crypt. The backups/ tree is encrypted by the same filter — app exports contain Wi-Fi networks and the Bluetooth device list.
git-crypt status # Check encryption status
git-crypt lock # Re-encrypt (rarely needed)
git-crypt unlock <key-file> # Decrypt after clone
Filter rules live in .gitattributes:
secrets.nix filter=git-crypt diff=git-crypt
backups/** filter=git-crypt diff=git-crypt
rebuild # alias: sudo darwin-rebuild switch --flake .#alex-mbp
nix flake check # Run all quality gates (see below)
nix flake update # Update inputs
nix develop # Dev shell: vulnix, nix-tree, nixfmt, nil
darwin-rebuild rollback # Rollback to previous generation
darwin-rebuild switch --flake .#alex-mbp --show-trace -v # Debug
nix-options (home/claude-code/scripts/nix-options.sh, packaged by home/claude-code/nix-options.nix) evaluates the options of the flake.lock-pinned nix-darwin, home-manager and determinate modules. "Declared in" maps to GitHub at the lock rev. Inside the Claude sandbox it falls back to a read-only store. Override with NIX_OPTIONS_FLAKE, --flake or --host.
nix-options show system.defaults.dock.autohide
nix-options show programs.git.settings
nix-options search dock
nix-options --json show system.defaults.dock.autohide
nix flake check runs every check below. They are the reason a broken module, a drifted Claude Code config or a stale README fails before it reaches the system.
| Check | What it enforces |
|---|---|
format-check | nixfmt --check over every tracked *.nix (find walk, no per-directory list) |
system-config | The whole alex-mbp darwin configuration actually builds |
agent-instructions | The shared instruction trunk actually reaches both rendered outputs: every shared section body present in CLAUDE.md and AGENTS.md, each heading exactly once, headings equal the declared trunk-plus-delta list in order, no mechanism Codex lacks named to Codex or smuggled through the trunk, the nix Docs Gate divergence pinned as Codex-inline only, each output under 110 lines, Project Map gone from both |
agent-pane | The agent-pane top pane (home/claude-code/agent-pane.nix) against a stub abduco: agent-pane pick <name> writes the name plus a nonce atomically into a 0700 state dir, and a name off claude-dispatch's rule (asserted equal at eval) or a wrong arity exits 2 with the target untouched and no temp file left; the pane, run headless and driven through pick, attaches with abduco -a <name> only to a listed session not marked +, lists the sessions with the state and intent of ~/.claude/session-state/<name>.json (? when missing or unparsable, control characters blanked, cut to the width), sends the attached client SIGTERM before attaching the next target, reattaches on a re-pick of the same name, does not restart a client that exited on its own until the next pick, and on SIGTERM detaches the client, exits 143 and ends with the terminal-restore sequence; agent-pane stop <name> TERMs the pid the list gives for exactly that name (two sleeps stand in for the servers: the named one dies, the other lives), a bad name or a wrong arity exits 2, an unlisted name or a prefix or suffix of a listed one exits 1 with nothing killed; abduco is never called with other arguments (stop calls only the bare list); the pane holds an flock on pane.lock that its client never inherits, and agent-pane alive exits 0 only while that lock is held (1 with no file, a free lock, an unopenable one or after the pane exits, even by SIGKILL with its client still running; 2 on an argument), printing nothing; abduco gets XDG_CACHE_HOME defaulted to ~/.cache (its socket dir) and a set one kept; --slot <id> puts target and lock under slots/<id>/ (0700): two slots' picks write two targets and leave the global one alone, a pick on one slot's pane TERMs only its client, alive --slot answers for that slot's lock only, stop ignores the slot, and a bad or missing id exits 2 with nothing created; --here is --slot with the id a stub osascript prints, lowercased (target and lock under slots/<lower id>/, osascript called once), and osascript failing or an id off the rule falls back to the global pane with a reason on stderr and under the idle header, no slot dir created; @osascript@ is /usr/bin/osascript in the real script. Canaries C1 (pick's name check dropped), C2 (no SIGTERM to the old client on a change), C4 (stop's exact match turned into a substring one), C5 (alive's conflict check dropped), C6 (the client inherits the lock fd), C7 (the XDG_CACHE_HOME default dropped), C8 (the slot ignored in the paths), C9 (the slot's name check dropped), C10 (--here's lowercasing dropped) and C11 (the fallback's line under the idle header dropped) must die at their case |
apex-board | The APEX run board (home/claude-code/apex-board.nix): node test.js passes on board.js (stage rules over the three real 00-context.md shapes and synthetic À-toi cases), then the built apex-board --dry-run against throwaway repos and HOMEs links runs to the repo's .claude/output/apex, budget to ~/.claude/apex-correction-budget or an empty dir, copies index.html and board.js from the store as regular files with a launch-time mtime (store files sit at 1970, which freezes Last-Modified and keeps the old page cached; no test.js), ships serve.py in the store but not in the root, writes meta.json with the repo name, defaults to the git toplevel, removes its temp root, exits 1 without runs and 2 on a bad port. serve.py's gates, imported: Host only 127.0.0.1:<port> or localhost:<port> (DNS rebinding), real path only under the root, runs/ or budget/ and no link loop. The built launcher then serves for real on loopback (__darwinAllowLocalNetworking): 403 on a foreign or missing Host, 404 on an escaping link and a loop, 405 on POST, 304 on If-Modified-Since, a directory listing, and a TERM leaves the port free. Statically: no http.server left, serve.py run once from the store, bound to the literal 127.0.0.1 with no bind argument. The terminal board is a Go module (apex-board/tui/, buildGoModule) whose go test runs in its build (disk reads, links out of the runs dir never read, render width, truecolor and Terminé cap, keys, mouse and wheel, markdown; the Agents tab over testdata/jobs/ fixtures: deck's bgKind columns, empty sessions hidden, stale after 15 min, links and oversized files under the jobs dir never read; a × only on the sessions abduco lists, x or a click on it arms, a second runs exactly agent-pane stop <name>, any other key or click disarms; n or a click on « + nouvel agent » runs exactly claude-dispatch --blank agent-HHMMSS in the board's repo off the UI goroutine, a suffix on a name abduco lists or a state file or worktree holds, then the show path below on it, a refused launch shows nothing; Enter, o, a card click or a launch that succeeded (n, N, c) first focuses a live pane already showing the agent (a slot named like a Ghostty terminal id, whose target is the card and whose alive answers 0: exactly one focus script, the id uppercased as its argv item; a hand-named slot, a dead pane or a linked target are passed over), else enters placement mode: each tick one osascript asks which terminal of the board's tab has the focus; the board itself → nothing run, another terminal whose pane runs → exactly agent-pane --slot <lower id> pick <name>, one with none → one split on its right running <store agent-pane> --here, then the pick on the new terminal's slot (no id back → no pick); Enter splits the board's own terminal, Échap, the 30 s timeout, a closed tab or a failed query end it with nothing run, any other key or click is ignored; ids and the command are osascript argv items, never script text; Ghostty not answering falls back to the old pick on the board's own pane: agent-pane alive, and only on its exit 1 exactly one /usr/bin/osascript with Ghostty's split script as -e lines and the store path as its argv item, never in the script text, a failure only in the footer; c on a closed agent only (abduco answered without it, a state file, cwd exactly <repo>/.claude/worktrees/<name>, a real dir) runs exactly env -u CLAUDE_CODE_CHILD_SESSION abduco -n <name> claude --continue --name <name> in that worktree, then the show path, without --continue when claude's project dir for it holds no *.jsonl (a blank agent never typed into); a listed, ended, unknown-liveness or stateless card, a gone or linked worktree launch nothing; a card is titled by its first prompt once known, by its name before; « ↻ actualiser » in both tabs' footers, drawn under its hit, polls as r; in that fallback the board's tty is its pane slot: pick, alive and the split's command carry --slot <tty>, stop does not, the composed command holds only path-safe characters; agents grouped by project from their cwd (a worktree as its repo, same-named repos kept apart), the tab's main repo first and open even when empty, « Génériques » last, p/P and a header click open another; N creates ~/agents/<name> (a linked root refused) and runs exactly env -u CLAUDE_CODE_CHILD_SESSION abduco -n <name> claude --name <name> there, and c resumes a closed generic in that dir; the Runs tab also lists the runs of <main repo>/.claude/worktrees/<name>/.claude/output/apex and ~/agents/<name>/.claude/output/apex, labelled « agent <name> » / « générique <name> », keyed apart from a main run of the same id, a link anywhere on that path or a source whose realpath leaves its parent never read, the drawer reading the card's own source re-checked, a board opened in a worktree not listing it twice, and --derive-json never reading them). Parity: on a copy of its testdata/ fixture runs, read as copied and then aged per mtimes.tsv, node parity.js (board.js's rules) and the built apex-board-tui --derive-json write byte-equal JSON. apex-board --tui --dry-run names the store Go binary, the runs dir and the budget dir or none, with no temp root and no tui.js shipped, and --tui with PATH=/var/empty and no terminal runs the binary and exits 1 with "needs a terminal". Canaries: M1 (board.js reading a failed step as done) must turn the failed-step run away from À toi; M2 (host_allowed always true) must fail the foreign-Host case; M3 (the Go module rebuilt with rules.go reading failed as done) must break the parity |
apex-consistency | The APEX skill keeps its critical clauses, flag casing, subagent isolation, and step-file references |
apex-health | The built apex-health report against a fake ~/.claude and a throwaway git repo, clock fixed: 6 APEX sessions each side with one correction round each is VERDICT: ok (exit 0), two rounds per AFTER session against none before is DÉRIVE (rounds / run) (exit 2), 2 AFTER sessions is insuffisant, a session under a scratchpad project dir changes nothing but the excluded count, a fix: touching the file of a feat: 2 days later scores fix-after 1/1, and one session with known usage (duplicate message.id, a subagent, a malformed line) prints the exact weighted mean. Canary M1 (the drift comparison returning False) must stop the drift case from saying DÉRIVE, proving that verdict rests on the comparison |
apex-plan-provenance | Every premise in an APEX plan carries [M] or [I] as its first token: the clause still stands in step-02-plan, and the line detector is run against two inline fixtures — one correctly tagged, one identical but for a stripped tag — so a detector that stopped detecting fails instead of passing. Presence is not truth: it proves the tag is THERE, never that it is earned; falsifying a tag is the examine reviewer's job and the Fable premises pass |
apex-tier | The built apex-tier classifier against throwaway git repos: a matcher added under hooks.Notification is direct, an entry added inside a deny = [ ... ] list is high, a permissionDecision branch in hooks/x.js is high, a 40-line README change is standard, a new .env.example is high. Canary M1 (the permission regex replaced by one that never matches) must turn the deny-list case away from high, proving that assertion rests on the permission class |
claude-config | Claude Code invariants: JSON parses, sandbox denies ~/.ssh and secrets, .env open to the sandbox and to the Read tool (neither denied nor asked, user decision 2026-10-19), agents declare a model, haiku only on read-only agents, rules declare paths, sandbox allowWrite never opens a path that runs outside it, allowUnixSockets only under the sandbox TMPDIR (never the nix daemon or docker socket), allowMachLookup = the measured list, nix shell/run/develop never excluded, claude-dispatch * excluded, no claude … entry and no entry for the retired claude-bg wrapper, Preliz pnpm run deploy / pnpm run deploy:prod excluded and allowed as exact entries only, autoMode naming them (prod after the user's explicit yes), disableAgentView true (Claude's background daemon off: daemon-hosted sessions lose the mic, anthropics/claude-code#86217) |
claude-dispatch | The claude-dispatch wrapper (home/claude-code/claude-dispatch.nix) against a stub abduco and a stub claude: abduco gets exactly -n <name> <claude> --worktree <name> --name <name> "[claude-dispatch] <brief>" (a detached abduco session, not Claude's daemon) and claude is never called directly, no --bg in the script; wrong arity, bad names, empty/one-word/dash-led/multi-line/oversize briefs exit 2 without calling abduco or claude; shell metacharacters pass literally; with the store abduco (socket in the build dir) and an argv-recording claude stub, abduco exits 0 and claude gets --worktree <name> …, so abduco's getopt stops at the name. claude-dispatch --blank <name> (the board's new agent) gives abduco the same argv with nothing after --name <name>, under the same name rule and the same CLAUDE_CODE_CHILD_SESSION unset, and the store-abduco probe sees claude get --worktree <name> --name <name> alone; a lone <name> still exits 2. Canaries C1-C8 (leading-dash rule, name regex, an extra claude flag, the dropped marker, a revert to claude --bg, an extra abduco flag, the kept CLAUDE_CODE_CHILD_SESSION, a prompt on the blank session) must die at their case |
claude-mods | Claude Code mods (home/claude-code/mods.nix), offline structure only: names equal the folders under home/claude-code/mods/ both ways, each plugin.json parses and names its folder, each hooks.json names one existing module, no .js there, no sound / host process (nor its aliases process.spawn, 'process', "process", a computed $[ or Reflect.get($) / network / file write / dynamic import / toast in any source and no refusal or rewrite token (deny, permissionDecision, decision:, updatedToolOutput, preventContinuation) nor the bare word process in a hooks module of any mod, except one host command: the exact agent-pane pick <name> call (the deck's « ↗ afficher »), exactly once in deck/hooks/pick.ts and that file's only $.process, settings env.CLAUDE_CODE_PLUGIN_DIRS equal to the ~/.claude/mods/<name> folders, activation copying them with the DRY_RUN skip and the engine's types excluded. Canaries: the scan must flag $.audio.speak, and a deny and a permissionDecision in the deck mod's hooks, the filter a .js name, the comparison an extra name; for the pick exception (C5-C10) the call in another file, a second call in pick.ts that survives the strip, another subcommand, and the $['process'], { process: p } = $ and Reflect.get($, 'pro' + 'cess') aliases, and pass the call alone in pick.ts. claude plugin validate --strict and claude plugin test on each mod folder are the code gate and run in the session (claude is not in the build sandbox) |
codex-config | Codex hook invariants: every command in the generated hooks.json names a script the module installs, both scripts pass node --check, hook order and matcher, registered timeouts above each script's own watchdog |
colima-ci | The Colima VMs (home/colima.nix), from the evaluated home-manager config: the profiles are exactly ci and default. ci (self-hosted CI runners) is never active (the dev VM keeps the Docker context) and never setDockerHost, started as a service, no host mount, no sshConfig, no autoActivate, k3s on; the provision script carries the ARC version, one HelmChart per runs-on label and no public repo; the launchd agent colima-ci passes --activate=false. default (dev containers) is active, a service, never setDockerHost, no k3s, no sshConfig, and its launchd agent colima-default passes --activate=true. Fails at evaluation (a throw), so --no-build sees it |
| hook-wiring | Claude Code hook wiring, from the evaluated module rather than from text: every hook file home/claude-code.nix installs is named by a command in home/claude-code/settings.nix and every such command names a file that exists, both senses reported apart; additionalContext emitted only inside hookSpecificOutput, the one shape the reference documents; the hookEventName a hook writes equal to the event registering
hooks/index.tsx 264 lines1// status-bar: the session's status under the prompt, in place of the
2// command status line: model, folder, git branch, the last response's
3// tokens in/out, the context bar (against the auto-compact window) and the 5h / 7d quota bars with their
4// reset countdowns. Drawn on the PromptHint line, one row when it fits the
5// width, else two; the engine's own hint line (`? for shortcuts`, `esc to
6// interrupt`, its pills) stays drawn beneath, live.
7// Observes only: turn.step, turn.complete and session.measure hooks return
8// next(e)'s result unchanged. Read-only: the branch is read from .git/HEAD.
9
10import { atom, read, update } from 'claude-code'
11import type { EngineInterface, Register, TextProps, Timer } from 'claude-code'
12
13import type { StatusBarLimit, StatusBarStep, StatusBarUsage } from '../types'
14import { contextFill, layout, parentDir, parseHead, pickModel, resolveGitdir } from './format.ts'
15import type { Seg } from './format.ts'
16
17// Reset countdowns move by the minute.
18const TICK_MS = 60_000
19// Folders walked up from the working directory to find `.git`.
20const MAX_DEPTH = 64
21
22const NO_USAGE: StatusBarUsage = { contextPercent: null, contextTokens: null, limits: [] }
23
24const usage = atom({ plugin: 'status-bar', key: 'usage' } as const, NO_USAGE)
25const step = atom({ plugin: 'status-bar', key: 'step' } as const, null)
26const model = atom({ plugin: 'status-bar', key: 'model' } as const, '')
27const cwd = atom({ plugin: 'status-bar', key: 'cwd' } as const, '')
28const branch = atom({ plugin: 'status-bar', key: 'branch' } as const, null)
29const now = atom({ plugin: 'status-bar', key: 'now' } as const, 0)
30
31// Module-level: a hot reload drops the environment and its timers with it.
32let timer: Timer | undefined
33
34// The engine's usage figures as the state keeps them (JSON values only:
35// no absent field, null instead).
36function toUsage(
37 context: { percent?: number; tokens?: number; window: number },
38 rateLimits: readonly { kind: string; percentUsed: number; resetsAt?: string }[],
39 raw: string | undefined,
40): StatusBarUsage {
41 const limits: StatusBarLimit[] = rateLimits.map(l => ({
42 kind: l.kind,
43 percentUsed: l.percentUsed,
44 resetsAt: l.resetsAt ?? null,
45 }))
46 return { contextPercent: contextFill(context, raw).pct, contextTokens: context.tokens ?? null, limits }
47}
48
49// Writes only on change, so readers redraw only when a figure moved (the
50// state library reads and writes named atoms only: one helper per atom).
51async function putUsage($: EngineInterface, value: StatusBarUsage): Promise<void> {
52 if (JSON.stringify(await read($, usage)) === JSON.stringify(value)) return
53 await update($, usage, () => value)
54}
55
56async function putStep($: EngineInterface, value: StatusBarStep | null): Promise<void> {
57 if (JSON.stringify(await read($, step)) === JSON.stringify(value)) return
58 await update($, step, () => value)
59}
60
61async function putModel($: EngineInterface, value: string): Promise<void> {
62 if ((await read($, model)) === value) return
63 await update($, model, () => value)
64}
65
66async function putCwd($: EngineInterface, value: string): Promise<void> {
67 if ((await read($, cwd)) === value) return
68 await update($, cwd, () => value)
69}
70
71async function putBranch($: EngineInterface, value: string | null): Promise<void> {
72 if ((await read($, branch)) === value) return
73 await update($, branch, () => value)
74}
75
76async function putNow($: EngineInterface, value: number): Promise<void> {
77 if ((await read($, now)) === value) return
78 await update($, now, () => value)
79}
80
81// The branch HEAD names at `path`; null when unreadable or detached.
82async function readHead($: EngineInterface, path: string): Promise<string | null> {
83 try {
84 return parseHead(await $.fs.read(path)) ?? null
85 } catch {
86 // No HEAD there (a broken worktree link): no branch shown.
87 return null
88 }
89}
90
91// The checked-out branch of the repository holding `dir`: the nearest
92// `.git` above it, a folder, or a worktree's file naming its git folder.
93async function findBranch($: EngineInterface, dir: string): Promise<string | null> {
94 let at = dir
95 for (let depth = 0; depth < MAX_DEPTH; depth += 1) {
96 const dotGit = `${at === '/' ? '' : at}/.git`
97 let kind: string | undefined
98 try {
99 kind = (await $.fs.stat(dotGit)).kind
100 } catch {
101 // No .git here: look one folder up.
102 kind = undefined
103 }
104 if (kind === 'dir') return readHead($, `${dotGit}/HEAD`)
105 if (kind === 'file') {
106 let text: string
107 try {
108 text = await $.fs.read(dotGit)
109 } catch {
110 // Unreadable .git file: branch unknown.
111 return null
112 }
113 const gitdir = resolveGitdir(text, at)
114 return gitdir === undefined ? null : readHead($, `${gitdir}/HEAD`)
115 }
116 const up = parentDir(at)
117 if (up === at) return null
118 at = up
119 }
120 return null
121}
122
123// Each figure on its own: one refused read leaves the others current.
124async function refresh($: EngineInterface): Promise<void> {
125 const jobs: Promise<void>[] = [
126 $.clock.now().then(at => putNow($, at)),
127 // A refused read measures against the model's window, as an unset variable does.
128 Promise.all([$.session.usage(), $.env.get('CLAUDE_CODE_AUTO_COMPACT_WINDOW').catch(() => undefined)]).then(([u, raw]) =>
129 putUsage($, toUsage(u.context, u.rateLimits, raw)),
130 ),
131 $.session.model().then(m => putModel($, m)),
132 $.session.cwd().then(async dir => {
133 await putCwd($, dir)
134 await putBranch($, await findBranch($, dir))
135 }),
136 ]
137 const results = await Promise.allSettled(jobs)
138 const failed = results.find(r => r.status === 'rejected')
139 if (failed !== undefined) throw failed.reason
140}
141
142function onTick($: EngineInterface): void {
143 refresh($).catch(() => {
144 // A refused read or write leaves that figure as drawn; the next tick
145 // (TICK_MS later), turn or measurement refreshes it again.
146 })
147}
148
149// Started from session.start and lazily from prompt.submit: session.start
150// does not fire again after a hot reload.
151function ensurePolling($: EngineInterface): void {
152 if (timer !== undefined) return
153 timer = $.clock.every(TICK_MS, () => onTick($))
154 $.clock.after(0, () => onTick($))
155}
156
157// Runs `write`; a refused state write leaves the bar as it was (an observer
158// never fails the event it watches).
159async function record(write: () => Promise<void>): Promise<void> {
160 try {
161 await write()
162 } catch {
163 // Display only: the next step, turn or tick writes again.
164 }
165}
166
167// A segment's Text props: only the styles it sets, never an undefined prop.
168function segProps(seg: Seg): TextProps {
169 return {
170 ...(seg.color === undefined ? {} : { color: seg.color }),
171 ...(seg.dim === true ? { dimColor: true } : {}),
172 }
173}
174
175export const register: Register = on => {
176 on('session.start', async ($, e, next) => {
177 ensurePolling($)
178 return next(e)
179 })
180
181 on('prompt.submit', ($, e, next) => {
182 ensurePolling($)
183 return next(e)
184 }).catch(($, e, next) => next(e))
185
186 // Pushed when the context fill or a quota window moves.
187 on('session.measure', async ($, e, next) => {
188 await record(async () => {
189 const raw = await $.env.get('CLAUDE_CODE_AUTO_COMPACT_WINDOW').catch(() => undefined)
190 await putUsage($, toUsage(e.context, e.rateLimits, raw))
191 })
192 return next(e)
193 }).catch(($, e, next) => next(e))
194
195 // Each main-loop response: its tokens in/out (the status line's
196 // total_input_tokens / total_output_tokens) and the model that answered.
197 on('turn.step', async function* ($, e, next) {
198 const result = yield* next(e)
199 const used = result.usage
200 if (e.agentId === undefined && used !== null) {
201 const tokensIn = used.input_tokens + used.cache_creation_input_tokens + used.cache_read_input_tokens
202 await record(() => putStep($, { tokensIn, tokensOut: used.output_tokens, model: used.model }))
203 }
204 return result
205 }).catch(async function* ($, e, next) {
206 return yield* next(e)
207 })
208
209 // A main-loop turn ended: the branch may have moved, the model changed.
210 on('turn.complete', async ($, e, next) => {
211 const done = await next(e)
212 if (e.agentId === undefined) await record(() => refresh($))
213 return done
214 }).catch(($, e, next) => next(e))
215
216 on('session.end', async ($, e, next) => {
217 if (e.reason === 'clear') {
218 // No session.start follows a /clear: the timer is kept, counts reset.
219 await record(() => putStep($, null))
220 await record(() => refresh($))
221 } else {
222 timer?.cancel()
223 timer = undefined
224 }
225 return next(e)
226 })
227
228 // Our rows, then the engine's own hint line (what next(e) answers: its
229 // drawing, pills live). Reads state only.
230 on('ui.render', { component: 'PromptHint' }, async ($, e, next) => {
231 const { Box, Text } = $.ui.resolve(e)
232 const last = await read($, step)
233 const figures = await read($, usage)
234 const lines = layout(
235 {
236 model: pickModel(await read($, model), last?.model),
237 cwd: await read($, cwd),
238 branch: await read($, branch),
239 tokensIn: last?.tokensIn ?? figures.contextTokens ?? 0,
240 tokensOut: last?.tokensOut ?? 0,
241 contextPercent: figures.contextPercent ?? 0,
242 limits: figures.limits,
243 now: await read($, now),
244 },
245 e.viewport?.columns,
246 )
247 const theirs = await next(e)
248 return (
249 <Box flexDirection="column">
250 {lines.map(line => (
251 <Box flexDirection="row">
252 {line.map(seg => (
253 <Text {...segProps(seg)} wrap="truncate-end">
254 {seg.text}
255 </Text>
256 ))}
257 </Box>
258 ))}
259 {theirs}
260 </Box>
261 )
262 })
263}
264hooks/format.ts 230 lines1// Pure logic of the status bar: model name, bars, reset countdowns,
2// thousands separators, git HEAD parsing and the one-or-two-line layout.
3// Same figures, colours, thresholds and formats as the former command
4// status line (statusline.sh). Widths are counted in terminal cells by an
5// approximation (cellWidth): the bar's emoji count 2, the rest 1.
6
7import type { Color } from 'claude-code'
8
9import type { StatusBarLimit } from '../types'
10
11// One run of text drawn with one style; index.tsx maps it to a Text.
12export type Seg = { text: string; color?: Color; dim?: boolean }
13
14// The script's ANSI colours as their xterm-256 hex, the same on every surface.
15export const PALETTE = {
16 red: '#ff5f5f',
17 orange: '#ff8700',
18 yellow: '#ffd75f',
19 green: '#5fd75f',
20 cyan: '#5fd7ff',
21 grey: '#6c6c6c',
22} as const
23
24export const BAR_CELLS = 10
25const FULL = '█'
26const EMPTY = '░'
27const SEP = ' | '
28// Cells left free at the row's end before the bar breaks onto two lines.
29const MARGIN = 4
30
31// `claude-opus-5-5[1m]` → `Opus 5.5`, `claude-3-5-sonnet-20241022` →
32// `Sonnet 3.5`, `opus` → `Opus`; a display name (`Opus 5.5 (1M context)`)
33// loses its parenthesis. The family is the first word that is no number.
34export function modelName(id: string): string {
35 const bare = id
36 .replace(/\[[^\]]*\]/g, '')
37 .replace(/\s*\([^)]*\)/g, '')
38 .trim()
39 if (bare === '') return ''
40 if (/\s/.test(bare)) return bare
41 const words = bare
42 .replace(/^claude-/i, '')
43 .replace(/-\d{8}$/, '')
44 .replace(/-latest$/i, '')
45 .split('-')
46 .filter(w => w !== '')
47 const family = words.find(w => !/^\d+$/.test(w))
48 const version = words.filter(w => /^\d+$/.test(w)).join('.')
49 if (family === undefined) return bare
50 const name = family.charAt(0).toUpperCase() + family.slice(1)
51 return version === '' ? name : `${name} ${version}`
52}
53
54// The session's model as /model has it; an alias without a version
55// (`opus[1m]`) takes the version of the API's model of the same family.
56export function pickModel(session: string, step: string | undefined): string {
57 const fromSession = modelName(session)
58 if (step === undefined) return fromSession
59 const fromStep = modelName(step)
60 if (fromSession === '') return fromStep
61 const isBare = !/\d/.test(fromSession)
62 const sameFamily = fromStep.split(' ')[0]?.toLowerCase() === fromSession.toLowerCase()
63 return isBare && sameFamily ? fromStep : fromSession
64}
65
66// A percentage as the script rounds it (jq round: half away from zero).
67export function roundPct(value: number): number {
68 return value < 0 ? -Math.round(-value) : Math.round(value)
69}
70
71// The window context fill is measured against: CLAUDE_CODE_AUTO_COMPACT_WINDOW read as the
72// engine reads it (leading integer, clamped to 100k–1M, capped at the model's window), else the
73// model's window. Same text in the status-bar and deck mods: keep them in step.
74export function compactWindow(modelWindow: number, raw: string | undefined): number {
75 const set = raw === undefined ? Number.NaN : Number.parseInt(raw, 10)
76 if (!Number.isFinite(set)) return modelWindow
77 const clamped = Math.min(Math.max(set, 100_000), 1_000_000)
78 return modelWindow > 0 ? Math.min(clamped, modelWindow) : clamped
79}
80
81// The context fill against that window, 0 to 100; the engine's own percent when no token count.
82export function contextFill(
83 context: { tokens?: number; window: number; percent?: number },
84 raw: string | undefined,
85): { window: number; pct: number | null } {
86 const window = compactWindow(context.window, raw)
87 if (context.tokens === undefined || window <= 0) return { window, pct: context.percent ?? null }
88 return { window, pct: Math.min(100, (context.tokens / window) * 100) }
89}
90
91// A 10-cell bar: filled cells from the whole tens of `pct` (clamped 0-100),
92// green under 60, orange under 85, red from 85; empty cells grey.
93export function bar(pct: number): Seg[] {
94 const clamped = Math.min(100, Math.max(0, Math.trunc(pct)))
95 const filled = Math.floor(clamped / 10)
96 const color = clamped >= 85 ? PALETTE.red : clamped >= 60 ? PALETTE.orange : PALETTE.green
97 const segs: Seg[] = []
98 if (filled > 0) segs.push({ text: FULL.repeat(filled), color })
99 if (filled < BAR_CELLS) segs.push({ text: EMPTY.repeat(BAR_CELLS - filled), color: PALETTE.grey })
100 return segs
101}
102
103// Time left until `resetMs`: under an hour `42min`, under a day `5.07h`
104// (the digits after the dot are minutes, 00-59), else `5j 0h`.
105export function fmtReset(resetMs: number, nowMs: number): string {
106 const seconds = Math.max(0, Math.floor((resetMs - nowMs) / 1000))
107 const mins = Math.floor(seconds / 60)
108 if (mins < 60) return `${mins}min`
109 if (mins < 1440) return `${Math.floor(mins / 60)}.${String(mins % 60).padStart(2, '0')}h`
110 return `${Math.floor(mins / 1440)}j ${Math.floor((mins % 1440) / 60)}h`
111}
112
113// 1234567 → `1,234,567` (the en_US grouping the script's printf used).
114export function thousands(value: number): string {
115 const whole = Math.trunc(value)
116 const sign = whole < 0 ? '-' : ''
117 return sign + String(Math.abs(whole)).replace(/\B(?=(\d{3})+(?!\d))/g, ',')
118}
119
120// The branch `.git/HEAD` names (`ref: refs/heads/feat/x` → `feat/x`); a
121// detached HEAD names none, as `git branch --show-current` prints nothing.
122export function parseHead(text: string): string | undefined {
123 const name = /^ref:\s*refs\/heads\/(\S+)\s*$/.exec(text.trim())?.[1]
124 return name === undefined || name === '' ? undefined : name
125}
126
127// The git directory a `.git` file points at (`gitdir: ../.git/worktrees/x`),
128// made absolute against the folder holding that file.
129export function resolveGitdir(text: string, dir: string): string | undefined {
130 const target = /^gitdir:\s*(.+?)\s*$/m.exec(text)?.[1]
131 if (target === undefined || target === '') return undefined
132 if (target.startsWith('/')) return target
133 return `${dir === '/' ? '' : dir}/${target}`
134}
135
136// The folder above `dir`; the root is its own parent.
137export function parentDir(dir: string): string {
138 const trimmed = dir.replace(/\/+$/, '')
139 const cut = trimmed.lastIndexOf('/')
140 return cut <= 0 ? '/' : trimmed.slice(0, cut)
141}
142
143// The last path component, trailing slashes ignored; the root reads `/`.
144export function basename(path: string): string {
145 const trimmed = path.replace(/\/+$/, '')
146 const name = trimmed.slice(trimmed.lastIndexOf('/') + 1)
147 return name === '' ? '/' : name
148}
149
150// Cells a code point takes: 2 for emoji and CJK, 0 for joiners, variation
151// selectors and combining marks, 1 otherwise.
152function pointWidth(code: number): number {
153 if (code === 0x200d || (code >= 0xfe00 && code <= 0xfe0f) || (code >= 0x0300 && code <= 0x036f)) return 0
154 if (
155 code === 0x23f3 ||
156 (code >= 0x1100 && code <= 0x115f) ||
157 (code >= 0x2e80 && code <= 0xa4cf) ||
158 (code >= 0xac00 && code <= 0xd7a3) ||
159 (code >= 0xf900 && code <= 0xfaff) ||
160 (code >= 0xff00 && code <= 0xff60) ||
161 (code >= 0x1f300 && code <= 0x1faff) ||
162 (code >= 0x20000 && code <= 0x3fffd)
163 ) {
164 return 2
165 }
166 return 1
167}
168
169export function cellWidth(text: string): number {
170 let width = 0
171 for (const point of text) width += pointWidth(point.codePointAt(0) ?? 0)
172 return width
173}
174
175const lineWidth = (line: readonly Seg[]): number => line.reduce((sum, seg) => sum + cellWidth(seg.text), 0)
176
177export type StatusData = {
178 model: string
179 cwd: string
180 branch: string | null
181 tokensIn: number
182 tokensOut: number
183 contextPercent: number
184 limits: readonly StatusBarLimit[]
185 now: number
186}
187
188const sep = (): Seg => ({ text: SEP, dim: true })
189
190// Group 1: model, folder, branch (when known), tokens in/out.
191export function sessionGroup(data: StatusData): Seg[] {
192 const segs: Seg[] = [
193 { text: `🤖 ${data.model === '' ? '?' : data.model}`, color: PALETTE.red },
194 sep(),
195 { text: `📁 ${basename(data.cwd)}`, color: PALETTE.orange },
196 ]
197 if (data.branch !== null && data.branch !== '') segs.push(sep(), { text: `⎇ ${data.branch}`, color: PALETTE.yellow })
198 segs.push(sep(), { text: `📊 ${thousands(data.tokensIn)}/${thousands(data.tokensOut)}`, color: PALETTE.green })
199 return segs
200}
201
202// One quota window: glyph, bar, percentage and the time to its reset.
203function limitSegs(glyph: string, limit: StatusBarLimit, now: number): Seg[] {
204 const pct = roundPct(limit.percentUsed)
205 const resetMs = limit.resetsAt === null ? Number.NaN : Date.parse(limit.resetsAt)
206 const reset = Number.isFinite(resetMs) ? ` · ${fmtReset(resetMs, now)}` : ''
207 return [sep(), { text: `${glyph} ` }, ...bar(pct), { text: ` ${pct}%${reset}`, color: PALETTE.cyan }]
208}
209
210// Group 2: context bar, then the 5h and 7d windows that have a reading.
211export function usageGroup(data: StatusData): Seg[] {
212 const ctx = roundPct(data.contextPercent)
213 const segs: Seg[] = [{ text: '🧠 ' }, ...bar(ctx), { text: ` ${ctx}%`, color: PALETTE.cyan }]
214 const five = data.limits.find(l => l.kind === 'five_hour')
215 const seven = data.limits.find(l => l.kind === 'seven_day')
216 if (five !== undefined) segs.push(...limitSegs('⏳', five, data.now))
217 if (seven !== undefined) segs.push(...limitSegs('📆', seven, data.now))
218 return segs
219}
220
221// One line when it fits `cols` (less a margin), else group 1 over group 2;
222// one line too when the width is unknown.
223export function layout(data: StatusData, cols: number | undefined): Seg[][] {
224 const first = sessionGroup(data)
225 const second = usageGroup(data)
226 const one = [...first, sep(), ...second]
227 if (cols === undefined || lineWidth(one) <= cols - MARGIN) return [one]
228 return [first, second]
229}
230types/index.d.ts 31 lines1// status-bar state contract: what the hooks module keeps in $.state.
2// Self-contained (no import), as the plugin-authoring reference asks.
3
4// One rate-limit window as $.session.usage() reports it (`five_hour`,
5// `seven_day`); `resetsAt` is an ISO 8601 timestamp, null when unknown.
6export type StatusBarLimit = { kind: string; percentUsed: number; resetsAt: string | null }
7
8// The figures of $.session.usage(); null where the engine has none yet.
9export type StatusBarUsage = {
10 contextPercent: number | null
11 contextTokens: number | null
12 limits: StatusBarLimit[]
13}
14
15// The main loop's last model response: input (uncached + cache write + cache
16// read) and output tokens, and the model id the API reported.
17export type StatusBarStep = { tokensIn: number; tokensOut: number; model: string }
18
19declare module 'claude-code' {
20 interface PluginState {
21 'status-bar': {
22 usage: StatusBarUsage
23 step: StatusBarStep | null
24 model: string
25 cwd: string
26 branch: string | null
27 now: number
28 }
29 }
30}
31