A row under the prompt: context, 5-hour, weekly and model-scoped weekly usage; in Nx repos also memory, the session's nx serve projects and the branch's…

Personal Claude Code mods: plugins of function hooks that restyle the transcript, add rows around the prompt and react to tool calls. Built and used on Claude Code 2.1.287+, Linux.
| Mod | What it does | Commands | Needs | |||
|---|---|---|---|---|---|---|
| quiet-bash | One-line tool rows (✓ <description>, red ✗ exit N on failure, +N −M on edits, duration for calls ≥10 s). Hides every tool's result block (Bash output, Edit diffs, WebFetch, MCP and Agent results; interactive tools, SendUserFile and image Reads keep theirs), finished read-only rows (Read/Grep/Glob, and calls the engine ran read-only like ls or git status, and every Claude in Chrome step but navigate), collapsed tool groups unless one failed, and timed-out GitLab pipeline-wait notices. Inline PNG thumbnails under rows that read, sent or wrote a PNG (at most 3 written ones per call), relative paths included; a group holding a thumbnail stays open, even under /quiet | /quiet brings it all back; /thumb [big] <path> shows a PNG (relative to the session's directory) as thumb #N: <path> | ImageMagick (magick) for thumbnails; a terminal with kitty graphics (see herdr) | |||
| quiet-spinner | Plain spinner words (thinking, writing, running, waiting, preparing) and Took 1m 4s instead of the whimsical ones | – | – | |||
| usage-percent | Row under the prompt: `ctx ▰▱▱▱ 34% \ | 5h ▰▰▱▱ 41% \ | wk ▰▰▰▱ 86% \ | fable ▰▰▱▱ 28% (four-cell bars; the fourth is the plan's model-scoped week, from the usage endpoint with the session's login) and resets 1d5h a gap after them for the weekly reset, yellow from 80 %, red from 95 %. Memory (claude.slice usage as a ten-cell bar of its limit + app.slice pressure, yellow from 20 %, red from 50 %) is sampled every 10 s and drawn by TamaGoxtix's band. In Nx repos also, on the right, the session's own nx serve projects (▶ admin api; a bare nx serve or run-many -t serve shows ▶ serve) and the branch's pipeline (ci ⏳ test, ⏸` when it waits on a manual job or an approval; none for Azure remotes) | – | gh / glab logged in for the pipeline; systemd claude.slice for memory |
| reminder-log | Tallies the reminders Claude Code injects for the model, per session; drops the token counter and repeated commit attribution blocks (sent again after a compaction) | /reminders prints the tally of the last 30 days | – | |||
| mr-banner | Colored card with a link under each MR/PR created, merged, approved or reviewed | – | GitLab MCP server named gitlab, or glab / gh | |||
| coderabbit-band | Band above the prompt with the open CodeRabbit threads (by severity) and nitpicks of the current branch's GitLab MR, with a link. Shows only when something is open | /coderabbit hides it until the counts change | glab logged in; GitLab remote | |||
| redact | Secrets in prompts and tool output reach the model as ‹secret:…› tokens; only Write/Edit turn them back into the real value. See redact | – | betterleaks on PATH | |||
| mem-guard | Bash commands that run Node tools go into a memory-capped claude-cmd.slice scope. Refused, with the fix in the message: nx affected/run-many without --parallel=1, a pnpm script that has a :lite twin, jest without a worker cap (--maxWorkers=N, -w N or --runInBand; a percentage doesn't count), pkill -f/pgrep -f with an unbracketed pattern, ci:local, heavy runs and dev-server starts while the slice is above 75 % or under pressure, a third heavy command or a third dev server at once, and writes by a check-runner subagent. See mem-guard | – | Linux with systemd: a user claude-cmd.slice, ps; see mem-guard | |||
| handover | Skill plus mod: the handover skill writes a one-sentence handover for a cold session to ~/.claude/handover.md; the mod files it per session under ~/.claude/handovers/<session id>.md, so parallel sessions in one repo never overwrite each other. A band above the prompt shows it; after /clear that session's sentence waits in the prompt (Tab takes it) and the next prompt spends it. A new terminal suggests nothing but lists the open sentences of the repo it started in (newest first, 14 days); a sentence belongs to the repo of the file its session wrote last, else to the folder the session started in | /handover-copy copies it and hides the band; /handover lists, /handover N puts one in the prompt, /handover drop N removes it; a sentence pasted by hand leaves the list too | – | |||
| herdr-notify | GNOME popup when Claude waits for a permission, an answer or a new prompt (a Notification hook, not a plugin). Skipped while that pane is the focused one in herdr. Clicking it raises Ghostty and focuses that session's herdr pane. Hook: `"Notification": [{"matcher": "permission_prompt\ | idle_prompt\ | elicitation_dialog", "hooks": [{"type": "command", "command": "bash \"$HOME/.claude/skills/herdr-notify/notify.sh\""}]}]` | – | herdr, Ghostty, notify-send, jq | |
| stack-down | On /clear and exit (also logout, a finished -p run, SIGINT/SIGTERM/SIGHUP), stops what the session left running in its repo: the nx processes it started (with their workers), and the repo's Docker Compose projects (compose down, volumes kept) unless another Claude session works in the same repo. Only for a session at a repo's top level (git rev-parse --show-toplevel); one started above the repos, such as ~/Dev, stops nothing | – | docker compose, git | |||
| review-walk | Skill plus mod: /review-walk takes the findings of the reviews already run in the conversation (/code-review, a repo's own review skill, CodeRabbit threads, MR comments), merges and ranks them, and asks fix / issue / skip one finding at a time; fixes wait until every finding is decided. The mod puts Finding N/M, a progress bar and the decisions so far over each question, and a band above the prompt between them. Decisions you authorised up front ("apply every Fix") are recorded through its ReviewWalkDecide tool instead of a question. The walk starts only after the skill runs, so a review on its own draws no band | /review-walk | A review run first: it walks findings, it never reviews. Any review skill or source works | |||
| tamagoxtix | Third line beside the monster, idle and while Claude works: usage-percent's memory bar. A fork of fabandrade88/tamagoxtix (MIT): a pixel monster in place of the spinner that acts out what Claude does, a band above the prompt between turns, cheer scenes while you type, twelve palettes, an optional powerline status line. The fork drops the band's usage column and repo column (repo-line shows repo and branch), the spinner's token line (usage-percent has the limits), pads the effects column so the text beside the monster stays put, adds /tamagoxtix animate off for still scenes, and puts the other mods' bands under the monster's caption instead of replacing them. With quiet-spinner the monster's line shows the plain word when quiet-spinner sits outer in the chain, else the whimsical one. The herdr half is herdr-tamagoxtix (sidebar faces, a usage popup, a tab-bar status area) | /tamagoxtix help, `… pet on\ | off hides the band, … palette <name>, … statusline on\ | off (writes statusLine into settings.json, backup kept), … theme on\ | off, … reroll` | Node.js 18+, a Nerd Font (or /tamagoxtix icons plain); git for the status line |
| task-meter | Band above the prompt with one row per running task: background shells, foreground shells after 5 s, subagents (their shells as └ child rows, tool count ⚒ N), workflows, monitors. Per row a ten-cell bar (filled where the output shows [N/M], a percentage or an nx task count, else one cell walking), the process tree's memory (yellow from 2 GB, red from 4 GB) and the running time, in aligned columns. Rows end with the task | – | Linux: ps, /proc/<pid>/fd, tail | |||
| repo-line | A line right above the prompt: the repository's name as a badge on the repository's own colour (a golden-angle hue per new repository, kept in the store), the branch (@abc1234 when detached) and (wt: name) in a linked worktree, so a prompt does not go to the wrong session. `/repo-line color <hue | #rrggbb> overrides, color reset` drops it | /repo-line | git | ||
| needs-you | Asks that wait on you stand out. Adds a system-prompt section: yes/no approvals and choices go through AskUserQuestion; anything else Claude waits on you for goes on its own line ⏸ Needs you: …. Those lines are drawn bold in the theme's warning colour (as plain text: links and code spans inside them are not formatted), pinned in a band above the prompt until your next message (or Clear), and in herdr shown as a ⏸ in the session's sidebar row; a ? there while an AskUserQuestion picker is open. See herdr for the sidebar row | – | herdr ≥ 0.9.5 for the sidebar icons, with { token = "$ask" } and { token = "$pick" } in ui.sidebar.agents.rows | |||
| ask-guard | When a reply asks a yes/no question in prose (shall I…?, want me to…?, ok to push…?, should I…? and similar), a Stop hook sends Claude back to ask it with AskUserQuestion, once per reply. Skips code blocks, > quotes, quoted text and ⏸ Needs you lines; a hook that fails lets the reply through | – | – | |||
| pii-guard | Asks before a tool call would send your personal data off the machine: WebFetch, WebSearch, every MCP tool (Claude in Chrome form fills included) and network Bash commands (curl, wget, urllib, requests, gh, git push …) whose input holds one of your identifiers, plain or URL-encoded, case-insensitive. Calls only to localhost pass. Born from a session that put the user's email into a third-party API's User-Agent because the API's policy asked for contact details. Does not see inside script files a command runs | – | pluginConfigs.pii-guard.options.identifiers in ~/.claude/settings.json: comma-separated emails and names (empty = off) |
The model sees exactly what it would without them: the mods change what is drawn, except reminder-log, which drops two kinds of injected reminders, redact, which hides secrets, mem-guard, which runs Node commands inside a systemd scope and refuses some with a mem-guard: … error, and stack-down, which stops the session's own servers and, when no other session is in the repo, its Compose stacks when the session ends.
Four mods call out on their own:
get_merge_request on the gitlab MCP server for the link and title. gh/glab commands cost nothing extra.glab for GitLab origin remotes: a 60 s timer checks the branch, and a fetch (glab mr view plus all pages of the MR's discussions) runs every minute for 15 min after a git push, every 5 min while the band shows something, every 15 min otherwise, and once 5 s after a thread is resolved.node on its usage script at session start and after each turn, and contacts no host. The mod's own README lists every call.ps and pwdx for nx serve processes, and docker inspect once per container a server runs in, to read its compose project directory. The pipeline (gh run list / glab ci get) is fetched when HEAD moves, 15 s after a git push, every minute while it runs and every 5 min otherwise.From the marketplace (gets updates; herdr-notify and herdr-link-toast are not in it):
claude plugin marketplace add schreibse/claude-code-mods
claude plugin install quiet-bash@schreibse-mods # per mod
Then turn on updates: /plugin → Marketplaces → schreibse-mods → Enable auto-update. See Updates.
From a clone, to adapt a mod or work on it. Claude Code loads every plugin folder under ~/.claude/skills/ at session start. Don't install the same mod from the marketplace too: the installed copy silently replaces the folder.
~/.claude/skills: clone straight into it: ``sh git clone https://github.com/schreibse/claude-code-mods ~/.claude/skills ``sh git clone https://github.com/schreibse/claude-code-mods ~/src/claude-code-mods ln -s ~/src/claude-code-mods/quiet-bash ~/.claude/skills/quiet-bash # per mod ``New sessions pick them up; a running one needs /exit and claude --continue.
Leave a mod out: claude plugin uninstall <mod>@schreibse-mods, or delete or unlink its folder. Try one for a single session: claude --plugin-dir ~/src/claude-code-mods/<mod>.
Where they run. Built and used only in the terminal CLI on Fedora (Linux, systemd, cgroup v2). The engine also loads user-scope mods in the local session the desktop app starts for its Code tab, and draws them there (desktop surface); untested here. See Setting up for what each mod needs.
This repo is the skills folder itself, so .gitignore ignores everything and re-includes each mod: a new mod needs a !/<name>/ line or git won't see it. .claude-plugin/types/ is generated by the engine and stays untracked.
Each mod has its own version (plugin.json) and a CHANGELOG.md in its folder; each release is a git tag <mod>--v<version>.
Plugin updated: <mod> · Run /reload-plugins to apply. Without it nothing tells you; check by hand: ``sh claude plugin marketplace update schreibse-mods claude plugin update quiet-bash@schreibse-mods # per mod; "already at the latest version" if none ``CHANGELOG.md. Read every version you skipped: a major version means you have to act (a new hook in settings.json, a new dependency, a removed command).git -C ~/.claude/skills pull --ff-only, then read the changelogs of the mods whose version moved (git -C ~/.claude/skills diff ORIG_HEAD -- '*/.claude-plugin/plugin.json').betterleaks scans every prompt and tool result before it reaches the model. Each value it flags becomes ‹secret:xxxxxxxx› and stays hidden wherever it appears later, even where the scanner would not recognise it again.
| The model's call | What happens |
|---|---|
| Write, Edit, NotebookEdit with a token | the real value is written to the file |
| Write that would drop a secret the file holds | refused: use Edit |
| Agent, SendMessage, TodoWrite with a token | passed on as the token |
| Any other tool with a token (Bash, WebFetch, MCP …) | refused, so the value never leaves |
| A token the mod no longer knows (after a restart) | refused, never restored wrongly |
Cut-short output. Before Bash or any tool with a file_path/path (Read, Grep, Edit …) runs, every file the call names (Bash: the first 10 words that could be paths, files up to 1 MB) is scanned whole, so cut -c1-60 .env, cut -d= -f2 or a Read of a few lines from a PEM key still come back as tokens. Multi-line secrets are hidden line by line. Bash words resolve against the directory each segment runs in (cd sub && cut -c1-40 .env), and ~/, $HOME/ and ${HOME}/ expand to the home directory.
Rules. betterleaks' defaults plus redact/betterleaks.toml: Sentry DSN keys, and client secrets too short for the generic rules. A client secret containing dev, local, test, example, changeme or placeholder stays visible, so local dev clients keep working in commands.
Not covered:
git show HEAD:.env | cut …, printenv | cut …); the transcript file's structured tool records, which keep real values (the model does not read them).cut -c1-40 *.env), quoted paths with spaces and a cd inside a subshell ((cd sub && cut -c1-40 .env)).client-secret rule needs some entropy (≥ 3.0), so short, repetitive client secrets stay visible.base64, rev, xxd) or sent (curl -T file). redact keeps secrets out of the model's context by accident; it is not a sandbox against a model trying to get them.‹secret:…› token is refused like any other tool call carrying one.The vault lives in session memory: /exit forgets it.
The status line shows redacted N once a value is hidden: N counts vault entries, so a PEM key counts once per line. A toast per call names the rules that hid new values. Without betterleaks the status line says off (no betterleaks) and nothing is hidden. A betterleaks run that fails leaves that call unredacted (values already in the vault stay hidden): one toast per failure streak, the status says off (betterleaks), and the next call scans again.
Every Bash command that names a Node tool (node, npx, pnpm, npm, npm exec, yarn, nx, jest, vitest, playwright, tsc, ngc) runs as systemd-run --user --scope --slice=claude-cmd.slice -p MemoryMax=30% -p MemorySwapMax=4% -- bash -c '…', so an overrun dies with exit 137 instead of taking the desktop down. Leading cd … && stay outside the wrapper, so the shell's directory still moves.
The rules read what each part of a command runs (after &&, |, ;, &, $( ), inside bash -c '…', following cd), never words it only mentions, so a commit message saying pkill -f passes. Not looked into: xargs, make, eval, scripts.
At once, counted per scope or service anywhere in claude.slice from one ps scan (skipped when ps fails):
node script that imports Playwright, tsc, ngc, an nx task), a running dev server included; the nx daemon doesn't count;nx serve, nx run x:serve, a serve* script): the API and one app.A command counts as heavy for these checks when it runs one of those tools, docker compose up, or a test, build, lint, typecheck, e2e or serve* script.
check-runner subagents (an agent type of the owner's) only run checks: git commands that change the tree or history, sed -i, --write/--fix, starting or stopping servers or processes, and writes outside /tmp are refused with "Report the failure instead of fixing it".
Assumes this setup; the messages name it:
claude-cmd.slice user unit. Without it systemd makes the slice with no limit of its own: each command is still capped at 30 % of RAM, but the headroom check has nothing to measure and stays off: ``ini # ~/.config/systemd/user/claude-cmd.slice [Slice] MemoryMax=30% MemorySwapMax=4% ` A full slice can livelock without ever reaching the OOM killer, so let systemd-oomd kill a scope in it under sustained pressure: systemctl --user set-property claude-cmd.slice ManagedOOMMemoryPressure=kill ManagedOOMMemoryPressureLimit=50%. systemd turns a percentage into bytes of the machine's RAM (on 27 GiB: 8.2G and 1.1G), so the same unit fits any machine. Check what a machine gets: systemd-run --user --scope -q -p MemoryMax=30% -- sh -c 'cat /sys/fs/cgroup$(cut -d: -f3 /proc/self/cgroup)/memory.max'`fuser -k 4700/tcp.:lite twin (lint:affected:lite, typecheck:lite, test:affected:lite) and a slow ci:local script.git@work:org/repo) reads as ci no login (work) though you are logged in.Under herdr (here inside Ghostty), quiet-bash's thumbnails draw only their alt text, and links in mr-banner, coderabbit-band and Claude's own output aren't clickable.
Cause: Claude Code turns on kitty graphics only for terminals whose XTVERSION answer is kitty (≥ 0.28) or starts with ghostty, and hyperlinks only for terminals it recognises. herdr forwards both, but answers with its own name, so Claude Code turns both off.
Fix: force both on, inside herdr only, before Claude Code starts (it reads them at startup):
# ~/.bashrc.d/herdr-terminal.sh
if [ -n "$HERDR_ENV" ]; then
export CLAUDE_CODE_FORCE_TERMINAL_IMAGES=1
export FORCE_HYPERLINK=1
fi
The herdr client forks its server into the client's own cgroup, so a server started inside a Ghostty window dies with that window and takes every pane with it. A wrapper in ~/.bashrc.d starts the first server in its own scope under app.slice instead; every other call, herdr plugin … included, goes straight through:
# ~/.bashrc.d/herdr-scope.sh
herdr() {
if [ $# -eq 0 ] && [ -z "$HERDR_ENV" ] && ! command herdr status server 2>/dev/null | grep -q '^status: running'; then
systemd-run --user --scope -q --slice=app.slice --unit="herdr-$(date +%s)" "$HOME/.local/bin/herdr"
else
command herdr "$@"
fi
}
Also turn on herdr's kitty graphics passthrough (off by default) in ~/.config/herdr/config.toml:
[experimental]
kitty_graphics = true
Then herdr server reload-config, open a new herdr pane (old panes keep the old environment) and start Claude Code there. Check it: /thumb /path/to/some.png should draw the picture.
herdr opens a ctrl+clicked link in the background with no feedback, and ignores file:// links altogether. herdr-link-toast opens http(s) links with xdg-open and shows a toast. It also opens the path in quiet-bash's thumbnail captions, which link to http://localhost/open-file/<path> because file:// isn't clickable in herdr. Such a link opens only when the path ends in .png; any other gets a "Could not open link" toast. Needs python3 ≥ 3.9. Install:
herdr plugin link ~/.claude/skills/herdr-link-toast
needs-you reports two tokens on its own pane (herdr pane report-metadata): $ask (⏸) while a ⏸ Needs you line is open, $pick (?) while an AskUserQuestion picker is open. herdr draws them only where the agent row names them, in ~/.config/herdr/config.toml:
[ui.sidebar.agents]
rows = [["state_icon", { token = "$ask", fg = "#f5a623", bold = true }, { token = "$pick", fg = "#f5a623", bold = true }, "machine", "workspace", "tab"], ["agent"]]
fg takes hex only. The row layout is the client's: after editing, choose reload config in herdr's menu (herdr server reload-config does not reload it).
The herdr half of tamagoxtix, unchanged from upstream: the monster's face in the sidebar, a usage popup (herdr plugin action invoke tamagoxtix.stats) and, on request, a status area right of the tabs and herdr colors f
hooks/register.tsx 273 lines1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, Register, SessionContextUsage, SessionRateLimit, Timer } from 'claude-code'
3
4import { containerOf, directoriesOf, isUnder, memory, pressureAvg10, servedIn, serveProcesses } from './machine'
5import type { ServeProcess } from './machine'
6import { bar, dim, joined, toneOf } from './pieces'
7import { forgeOf, hostOf, githubPipeline, gitlabPipeline, pipeline } from './pipeline'
8import type { Pipeline } from './pipeline'
9import { scopedWindows, USAGE_URL } from './scoped'
10import type { ScopedWindow } from './scoped'
11import type { Piece } from '../types'
12
13const WINDOWS: Record<string, string> = { five_hour: '5h', seven_day: 'wk' }
14const TICK_MS = 10_000
15const PIPELINE_RUNNING_MS = 60_000
16const PIPELINE_IDLE_MS = 300_000
17const AFTER_PUSH_MS = 15_000
18const SCOPED_MS = 60_000
19const RESET_GAP = ' '.repeat(8)
20
21const usageLine = atom({ plugin: 'usage-percent', key: 'line' } as const, null)
22const nxLine = atom({ plugin: 'usage-percent', key: 'nx' } as const, null)
23const memoryLine = atom({ plugin: 'usage-percent', key: 'memory' } as const, null)
24
25type Poll = { root: string; isNx: boolean; uid: string; head: string; pipelineAt: number; pushedAt: number; pipe: Pipeline | null; composeDirs: Map<string, string>; isBusy: boolean }
26
27const BAR_CELLS = 4
28
29// Time until a window resets, in its two largest units: 1d5h, 3h12m, 45m.
30export function resetIn(iso: string | undefined, now: number): string {
31 const ms = iso ? Date.parse(iso) - now : NaN
32 if (!Number.isFinite(ms) || ms <= 0) {
33 return ''
34 }
35 const minutes = Math.floor(ms / 60_000)
36 const days = Math.floor(minutes / 1440)
37 const hours = Math.floor((minutes % 1440) / 60)
38 const rest = minutes % 60
39 if (days >= 1) {
40 return hours > 0 ? `${days}d${hours}h` : `${days}d`
41 }
42 if (hours >= 1) {
43 return rest > 0 ? `${hours}h${rest}m` : `${hours}h`
44 }
45 return `${Math.max(1, rest)}m`
46}
47
48function figure(label: string, percent: number): Piece[] {
49 return [dim(`${label} `), { text: `${bar(percent, BAR_CELLS)} ${Math.round(percent)}%`, tone: toneOf(percent) }]
50}
51
52export function isGitPush(command: string): boolean {
53 return /\bgit(?:\s+-[Cc]\s+\S+)*\s+push\b/.test(command)
54}
55
56// The weekly windows share one reset, drawn once a gap after the bars; the 5h reset is left out.
57export function line(context: SessionContextUsage, rateLimits: readonly SessionRateLimit[], now = Date.now(), scoped: readonly ScopedWindow[] = []): Piece[] {
58 const limits = rateLimits.flatMap(limit => {
59 const label = WINDOWS[limit.kind]
60 return label === undefined ? [] : [{ label, percentUsed: limit.percentUsed, resetsAt: limit.resetsAt }]
61 })
62 const windows = [...limits, ...scoped]
63 const left = joined([figure('ctx', context.percent ?? 0), ...windows.map(w => figure(w.label, w.percentUsed))], ' | ')
64 const week = resetIn(windows.find(w => w.label === 'wk')?.resetsAt ?? scoped[0]?.resetsAt, now)
65 return week === '' ? left : [...left, dim(`${RESET_GAP}resets ${week}`)]
66}
67
68type Usage = { context: SessionContextUsage; rateLimits: readonly SessionRateLimit[]; scoped: ScopedWindow[]; scopedAt: number; isFetching: boolean }
69
70async function redraw($: EngineInterface, usage: Usage): Promise<void> {
71 const now = await $.clock.now()
72 await update($, usageLine, () => line(usage.context, usage.rateLimits, now, usage.scoped))
73}
74
75// The model-scoped week comes from the usage endpoint, at most once a minute; a failed fetch keeps the last reading.
76async function refreshScoped($: EngineInterface, usage: Usage): Promise<void> {
77 const now = await $.clock.now()
78 if (usage.isFetching || now - usage.scopedAt < SCOPED_MS) {
79 return
80 }
81 usage.isFetching = true
82 try {
83 const auth = (await $.session.authorize())?.handle
84 if (auth === undefined) {
85 return
86 }
87 const response = await $.http.fetch(USAGE_URL, { auth, headers: { 'anthropic-beta': 'oauth-2025-04-20' } })
88 if (response.ok) {
89 usage.scoped = scopedWindows(response.text)
90 await redraw($, usage)
91 }
92 } finally {
93 usage.scopedAt = now
94 usage.isFetching = false
95 }
96}
97
98function startRefresh($: EngineInterface, usage: Usage): void {
99 void refreshScoped($, usage).catch((error: unknown) => $.ui.log(`usage-percent: ${String(error)}`, { to: 'debug' }))
100}
101
102async function memoryPieces($: EngineInterface, uid: string): Promise<Piece[]> {
103 const service = `/sys/fs/cgroup/user.slice/user-${uid}.slice/user@${uid}.service`
104 const files = ['claude.slice/memory.current', 'claude.slice/memory.max', 'app.slice/memory.pressure']
105 const contents = await Promise.all(files.map(file => $.fs.read(`${service}/${file}`))).catch(() => null)
106 if (contents === null) {
107 return []
108 }
109 const [current = '', max = '', pressure = ''] = contents
110 return memory(Number(current), Number(max), pressureAvg10(pressure))
111}
112
113async function fetchPipeline($: EngineInterface, root: string): Promise<Pipeline | null> {
114 const git = (...args: string[]) => $.process.run(['git', ...args], { cwd: root }).then(r => r.stdout.trim())
115 const [remote, branch] = await Promise.all([git('remote', 'get-url', 'origin'), git('branch', '--show-current')])
116 const forge = forgeOf(remote)
117 if (forge === null || branch === '') {
118 return null
119 }
120 const argv = forge === 'github'
121 ? ['gh', 'run', 'list', '--branch', branch, '--limit', '1', '--json', 'status,conclusion,workflowName']
122 : ['glab', 'ci', 'get', '--branch', branch, '--output', 'json']
123 const run = await $.process.run(argv, { cwd: root, timeoutMs: 20_000 })
124 if (run.exitCode !== 0) {
125 // A failure is either no pipeline for the branch (show nothing) or a host the CLI is not logged in to.
126 const host = hostOf(remote)
127 const auth = await $.process.run([forge === 'github' ? 'gh' : 'glab', 'auth', 'status', '--hostname', host], { timeoutMs: 10_000 })
128 return auth.exitCode === 0 ? null : { state: 'no-login', detail: host }
129 }
130 return forge === 'github' ? githubPipeline(run.stdout) : gitlabPipeline(run.stdout)
131}
132
133// A server counts when it runs in the session's tree; one in a container counts when its compose project lives there.
134async function servedHere($: EngineInterface, poll: Poll, processes: readonly ServeProcess[]): Promise<string[]> {
135 if (processes.length === 0) {
136 return []
137 }
138 const pwdx = await $.process.run(['pwdx', ...processes.map(p => p.pid)])
139 const dirOf = directoriesOf(pwdx.stdout)
140 for (const { pid } of processes) {
141 if (isUnder(dirOf.get(pid) ?? '', poll.root)) {
142 continue
143 }
144 const container = containerOf(await $.fs.read(`/proc/${pid}/cgroup`).catch(() => ''))
145 if (container !== null) {
146 dirOf.set(pid, await composeDir($, poll, container))
147 }
148 }
149 return servedIn(poll.root, processes, dirOf)
150}
151
152async function composeDir($: EngineInterface, poll: Poll, container: string): Promise<string> {
153 if (!poll.composeDirs.has(container)) {
154 const label = '{{index .Config.Labels "com.docker.compose.project.working_dir"}}'
155 const run = await $.process.run(['docker', 'inspect', '--format', label, container], { timeoutMs: 10_000 }).catch(() => null)
156 poll.composeDirs.set(container, run?.exitCode === 0 ? run.stdout.trim() : '')
157 }
158 return poll.composeDirs.get(container) ?? ''
159}
160
161// Memory every tick, in every session; in an Nx repo also the servers, and the pipeline only when HEAD
162// moved, after a push, or when its interval is up.
163async function tick($: EngineInterface, poll: Poll) {
164 if (poll.isBusy) {
165 return
166 }
167 poll.isBusy = true
168 try {
169 const memoryNow = await memoryPieces($, poll.uid)
170 await update($, memoryLine, () => (memoryNow.length > 0 ? memoryNow : null))
171 if (!poll.isNx) {
172 return
173 }
174 const [ps, head] = await Promise.all([
175 $.process.run(['ps', '-eo', 'pid,args']),
176 $.process.run(['git', 'rev-parse', 'HEAD'], { cwd: poll.root }).then(r => r.stdout.trim()),
177 ])
178 const now = await $.clock.now()
179 const interval = poll.pipe?.state === 'running' ? PIPELINE_RUNNING_MS : PIPELINE_IDLE_MS
180 const isPushSettled = poll.pushedAt > 0 && now - poll.pushedAt >= AFTER_PUSH_MS
181 if (head !== poll.head || isPushSettled || now - poll.pipelineAt >= interval) {
182 poll.head = head
183 poll.pipelineAt = now
184 poll.pushedAt = 0
185 poll.pipe = await fetchPipeline($, poll.root).catch(() => null)
186 }
187 const served = await servedHere($, poll, serveProcesses(ps.stdout)).catch(() => [])
188 const right = joined([served.length > 0 ? [dim(`▶ ${served.join(' ')}`)] : [], poll.pipe ? pipeline(poll.pipe) : []], ' · ')
189 await update($, nxLine, () => (right.length > 0 ? right : null))
190 } finally {
191 poll.isBusy = false
192 }
193}
194
195function startTick($: EngineInterface, poll: Poll): void {
196 void tick($, poll).catch((error: unknown) => $.ui.log(`usage-percent: ${String(error)}`, { to: 'debug' }))
197}
198
199type Sampler = { poll: Poll | null; timer: Timer | null }
200
201async function startPolling($: EngineInterface, sampler: Sampler) {
202 sampler.timer?.cancel()
203 sampler.timer = null
204 sampler.poll = null
205 const root = await $.session.root()
206 const isNx = await $.fs.exists(`${root}/nx.json`)
207 const uid = (await $.process.run(['id', '-u'])).stdout.trim()
208 const current: Poll = { root, isNx, uid, head: '', pipelineAt: 0, pushedAt: 0, pipe: null, composeDirs: new Map(), isBusy: false }
209 sampler.poll = current
210 startTick($, current)
211 sampler.timer = $.clock.every(TICK_MS, () => startTick($, current))
212}
213
214export const register: Register = on => {
215 const sampler: Sampler = { poll: null, timer: null }
216 const usage: Usage = { context: {} as SessionContextUsage, rateLimits: [], scoped: [], scopedAt: 0, isFetching: false }
217
218 on('session.start', async ($, e, next) => {
219 const result = await next(e)
220 const { context, rateLimits } = await $.session.usage()
221 Object.assign(usage, { context, rateLimits })
222 await redraw($, usage)
223 startRefresh($, usage)
224 await startPolling($, sampler)
225 return result
226 })
227
228 // a hot reload of the skills dir re-runs register without a session.start, so the first measure re-arms the timer
229 on('session.measure', async ($, e, next) => {
230 Object.assign(usage, { context: e.context, rateLimits: e.rateLimits })
231 await redraw($, usage)
232 startRefresh($, usage)
233 if (sampler.timer === null) {
234 await startPolling($, sampler)
235 }
236 return next(e)
237 })
238
239 on('tool.call', { tool: 'Bash' }, async ($, e, next) => {
240 const result = await next(e)
241 if (sampler.poll?.isNx && isGitPush(e.command)) {
242 sampler.poll.pushedAt = await $.clock.now()
243 }
244 return result
245 })
246
247 on('ui.render', { component: 'PromptHint' }, async ($, e, next) => {
248 const left = (await read($, usageLine)) ?? []
249 const right = (await read($, nxLine)) ?? []
250 const hint = await next(e)
251 if (left.length === 0 && right.length === 0) {
252 return hint
253 }
254
255 const { Box, Text } = $.ui.resolve(e)
256 const draw = (pieces: readonly Piece[]) => (
257 <Text>
258 {pieces.map(piece => (piece.tone === 'dim' ? <Text dimColor>{piece.text}</Text> : <Text color={piece.tone}>{piece.text}</Text>))}
259 </Text>
260 )
261
262 return (
263 <Box flexDirection="column">
264 {hint}
265 <Box>
266 <Box width={0} flexGrow={1}>{draw(left)}</Box>
267 <Box width={0} flexGrow={1} justifyContent="flex-end">{draw(right)}</Box>
268 </Box>
269 </Box>
270 )
271 })
272}
273hooks/machine.ts 68 lines1import { bar, dim, toneOf } from './pieces'
2import type { Piece } from '../types'
3
4const GIB = 1024 ** 3
5
6export type ServeProcess = { pid: string; project: string }
7
8const MEMORY_CELLS = 10
9
10// The slice's usage as a bar of its limit; without a limit the figure alone.
11export function memory(current: number, max: number, pressureAvg10: number): Piece[] {
12 const percent = Number.isFinite(max) ? (current / max) * 100 : NaN
13 const figure = `${(current / GIB).toFixed(1)}G`
14 const used = Number.isFinite(percent) ? { text: `${bar(percent, MEMORY_CELLS)} ${figure}`, tone: toneOf(percent) } : dim(figure)
15 if (pressureAvg10 <= 0) {
16 return [dim('RAM '), used]
17 }
18 return [dim('RAM '), used, dim(' · psi '), { text: `${Math.round(pressureAvg10)}%`, tone: toneOf(pressureAvg10, 20, 50) }]
19}
20
21export function pressureAvg10(pressureFile: string): number {
22 return Number(/^some avg10=([\d.]+)/m.exec(pressureFile)?.[1] ?? 0)
23}
24
25// From `ps -eo pid,args`. A server of nx's default project, or of every project, shows as plain `serve`.
26export function serveProcesses(ps: string): ServeProcess[] {
27 return [...ps.matchAll(/^\s*(\d+)\s.*?\bnx (.*)$/gm)].flatMap(m => servedProjects(m[2] ?? '').map(project => ({ pid: m[1] ?? '', project })))
28}
29
30function servedProjects(args: string): string[] {
31 const run = /^run ([\w.-]+):serve(?=[:\s]|$)/.exec(args)
32 if (run) {
33 return [run[1] ?? '']
34 }
35 const serve = /^serve(?=\s|$)(.*)/.exec(args)
36 if (serve) {
37 return [optionOf(serve[1] ?? '', 'project', 'p') ?? /^\s+(\w[\w.-]*)/.exec(serve[1] ?? '')?.[1] ?? 'serve']
38 }
39 if (/^run-many\b/.test(args) && /(?:^|,)serve(?:,|$)/.test(optionOf(args, 'targets', 't') ?? optionOf(args, 'target') ?? '')) {
40 return (optionOf(args, 'projects', 'p') ?? 'serve').split(',')
41 }
42 return []
43}
44
45function optionOf(args: string, name: string, short?: string): string | null {
46 const flag = short === undefined ? `--${name}` : `(?:--${name}|-${short})`
47 return new RegExp(`(?:^|\\s)${flag}(?:=|\\s+)([^\\s-][^\\s]*)`).exec(args)?.[1] ?? null
48}
49
50// From `pwdx <pid>...`: `1234: /dir` per line.
51export function directoriesOf(pwdx: string): Map<string, string> {
52 return new Map([...pwdx.matchAll(/^(\d+): (.+)$/gm)].map(m => [m[1] ?? '', m[2] ?? '']))
53}
54
55// From `/proc/<pid>/cgroup`: the Docker container the process runs in, if any.
56export function containerOf(cgroup: string): string | null {
57 return /\/docker-([0-9a-f]+)\.scope/.exec(cgroup)?.[1] ?? null
58}
59
60export function isUnder(dir: string, root: string): boolean {
61 return dir === root || dir.startsWith(`${root}/`)
62}
63
64export function servedIn(root: string, processes: readonly ServeProcess[], dirOf: ReadonlyMap<string, string>): string[] {
65 const names = processes.filter(p => isUnder(dirOf.get(p.pid) ?? '', root)).map(p => p.project)
66 return [...new Set(names)].sort()
67}
68hooks/pieces.ts 19 lines1import type { Piece, Tone } from '../types'
2
3export function toneOf(percent: number, warn = 80, alarm = 95): Tone {
4 return percent >= alarm ? 'red' : percent >= warn ? 'yellow' : 'dim'
5}
6
7export function bar(percent: number, cells: number): string {
8 const filled = Math.round((Math.max(0, Math.min(100, percent)) / 100) * cells)
9 return '▰'.repeat(filled) + '▱'.repeat(cells - filled)
10}
11
12export function dim(text: string): Piece {
13 return { text, tone: 'dim' }
14}
15
16export function joined(groups: readonly Piece[][], gap: string): Piece[] {
17 return groups.filter(group => group.length > 0).flatMap((group, i) => (i === 0 ? group : [dim(gap), ...group]))
18}
19hooks/pipeline.ts 74 lines1import { dim } from './pieces'
2import type { Piece } from '../types'
3
4export type Pipeline = { state: 'running' | 'passed' | 'manual' | 'failed' | 'no-login'; detail: string }
5export type Forge = 'github' | 'gitlab'
6
7export function hostOf(remoteUrl: string): string {
8 return /^(?:[a-z+]+:\/\/)?(?:[^@/]+@)?([^/:]+)/i.exec(remoteUrl.trim())?.[1] ?? ''
9}
10
11export function forgeOf(remoteUrl: string): Forge | null {
12 if (remoteUrl.trim() === '') {
13 return null
14 }
15 if (/(^|[@/.])(dev\.azure|visualstudio)\.com[:/]/.test(remoteUrl)) {
16 return null
17 }
18 return /(^|[@/])github\.com[:/]/.test(remoteUrl) ? 'github' : 'gitlab'
19}
20
21type GitlabJob = { name?: string; status?: string; stage?: string }
22
23export function gitlabPipeline(json: string): Pipeline | null {
24 const p = JSON.parse(json) as { status?: string; jobs?: GitlabJob[] }
25 const jobs = p.jobs ?? []
26 switch (p.status) {
27 case 'running':
28 case 'pending':
29 case 'created':
30 case 'preparing':
31 case 'waiting_for_resource':
32 return { state: 'running', detail: jobs.find(job => job.status === 'running')?.stage ?? '' }
33 case 'failed':
34 return { state: 'failed', detail: jobs.filter(job => job.status === 'failed').map(job => job.name ?? '').join(' ') }
35 case 'canceled':
36 return { state: 'failed', detail: '' }
37 case 'success':
38 return { state: 'passed', detail: '' }
39 case 'manual':
40 return { state: 'manual', detail: '' }
41 default:
42 return null
43 }
44}
45
46type GithubRun = { status?: string; conclusion?: string; workflowName?: string }
47
48export function githubPipeline(json: string): Pipeline | null {
49 const run = (JSON.parse(json) as GithubRun[])[0]
50 if (run === undefined) {
51 return null
52 }
53 if (run.status === 'waiting' || run.status === 'pending' || run.status === 'action_required' || run.conclusion === 'action_required') {
54 return { state: 'manual', detail: run.workflowName ?? '' }
55 }
56 if (run.status !== 'completed') {
57 return { state: 'running', detail: run.workflowName ?? '' }
58 }
59 if (run.conclusion === 'success' || run.conclusion === 'skipped' || run.conclusion === 'neutral') {
60 return { state: 'passed', detail: '' }
61 }
62 return { state: 'failed', detail: run.workflowName ?? '' }
63}
64
65export function pipeline(p: Pipeline): Piece[] {
66 if (p.state === 'no-login') {
67 return [dim(`ci no login (${p.detail})`)]
68 }
69 const glyph = { running: '⏳', passed: '✓', manual: '⏸', failed: '✗' }[p.state]
70 const tone = p.state === 'failed' ? 'red' : p.state === 'passed' ? 'green' : 'dim'
71 const detail = p.detail.toLowerCase() === 'ci' ? '' : p.detail
72 return [dim('ci '), { text: detail === '' ? glyph : `${glyph} ${detail}`, tone }]
73}
74hooks/scoped.ts 26 lines1// A weekly window the usage endpoint scopes to one model, which the API's rate-limit headers never carry.
2export type ScopedWindow = { label: string; percentUsed: number; resetsAt?: string }
3
4export const USAGE_URL = 'https://api.anthropic.com/api/oauth/usage?skip_spend=1'
5
6type Limit = { kind?: string; percent?: number; resets_at?: string; scope?: { model?: { display_name?: string } | null } | null }
7
8export function scopedWindows(text: string): ScopedWindow[] {
9 let limits: unknown
10 try {
11 limits = (JSON.parse(text) as { limits?: unknown }).limits
12 } catch {
13 return []
14 }
15 if (!Array.isArray(limits)) {
16 return []
17 }
18 return (limits as Limit[]).flatMap(limit => {
19 const model = limit.scope?.model?.display_name
20 if (limit.kind !== 'weekly_scoped' || typeof model !== 'string' || typeof limit.percent !== 'number') {
21 return []
22 }
23 return [{ label: model.toLowerCase(), percentUsed: limit.percent, resetsAt: limit.resets_at }]
24 })
25}
26types/index.d.ts 12 lines1export type Tone = 'dim' | 'yellow' | 'red' | 'green'
2export type Piece = { text: string; tone: Tone }
3export type UsageLine = Piece[] | null
4export type NxLine = Piece[] | null
5export type MemoryLine = Piece[] | null
6
7declare module 'claude-code' {
8 interface PluginState {
9 'usage-percent': { line: UsageLine; nx: NxLine; memory: MemoryLine }
10 }
11}
12