SLOPSHOPPER

usage-percent

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

newspinnerguardprocesstimer
★ 2v0.2.0no licenseupdated 2026-10-08schreibse/claude-code-mods/usage-percent
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · usage-percent
› fix the failing auth test and add an audit log call ⏺ Read(src/auth.ts) ⎿ Read 6 lines ⏺ Update(src/auth.ts) ⎿ Added 2 lines, removed 1 line ⏺ Bash(bun test) ⎿ 3 pass, 1 fail ● Done. refresh now rejects expired claims and logs an audit event. ✻ Worked for 42s · done 4:20 PM ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ⟨Claude Code's own drawing⟩ c t x 4 9 % | 5 h 3 1 %

Draws

Prompt hint
⟨Claude Code's own drawing⟩ c t x 4 9 % | 5 h 3 1 %
README

claude-code-mods

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.

Mods

ModWhat it doesCommandsNeeds
quiet-bashOne-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-spinnerPlain spinner words (thinking, writing, running, waiting, preparing) and Took 1m 4s instead of the whimsical ones––
usage-percentRow under the prompt: `ctx 34% \5h 41% \wk 86%, yellow from 80 %, red from 95 %. In Nx repos also memory in the middle (claude.slice usage + app.slice pressure, yellow from 20 %, red from 50 %) and 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-logTallies 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-bannerColored card with a link under each MR/PR created, merged, approved or reviewed–GitLab MCP server named gitlab, or glab / gh
coderabbit-bandBand 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 changeglab logged in; GitLab remote
redactSecrets 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-guardBash 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
handoverSkill 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 repo's open sentences (newest first, 14 days)/handover-copy copies it and hides the band; /handover lists, /handover N puts one in the prompt–
herdr-notifyGNOME 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-downOn /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-walkSkill 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-walkA review run first: it walks findings, it never reviews. Any review skill or source works

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.

Three mods call out on their own:

  • mr-banner, when a GitLab MCP note or approval answers without the MR's link, calls get_merge_request on the gitlab MCP server for the link and title. gh/glab commands cost nothing extra.
  • coderabbit-band polls 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.
  • usage-percent, in Nx repos, polls every 10 s: 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.

Install

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.

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.

Updates

Each mod has its own version (plugin.json) and a CHANGELOG.md in its folder; each release is a git tag <mod>--v<version>.

  • Get them: with auto-update on, Claude Code updates the mods after a session's first message and says 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 ``
  • What changed: the mod's 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).
  • Notified outside Claude Code: on GitHub, Watch → Custom → Releases. Each release carries the mod's changelog entry.
  • From a clone: 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').

redact: secrets as tokens

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 callWhat happens
Write, Edit, NotebookEdit with a tokenthe real value is written to the file
Write that would drop a secret the file holdsrefused: use Edit
Agent, SendMessage, TodoWrite with a tokenpassed 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:

  • images; output with no file behind it, cut short (git show HEAD:.env | cut …, printenv | cut …); the transcript file's structured tool records, which keep real values (the model does not read them).
  • the cut-short pre-scan misses globs (cut -c1-40 *.env), quoted paths with spaces and a cd inside a subshell ((cd sub && cut -c1-40 .env)).
  • betterleaks' client-secret rule needs some entropy (≥ 3.0), so short, repetitive client secrets stay visible.
  • values shorter than 8 characters are never hidden.
  • a value restored into a file by Write/Edit can be read back transformed (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.
  • a subagent's report that quotes a ‹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.

mem-guard: memory rules for Bash

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 in claude-cmd.slice from one ps scan (skipped when ps fails):

  • at most 2 heavy commands (jest, vitest, Playwright, tsc, ngc, an nx task); the nx daemon and dev servers don't count;
  • at most 2 dev servers (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:

  • a 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'`
  • a dev API served on port 4700: the refusal messages say fuser -k 4700/tcp.
  • repos whose heavy scripts have a :lite twin (lint:affected:lite, typecheck:lite, test:affected:lite) and a slow ci:local script.

usage-percent: not covered

  • On GitHub only the newest workflow run of the branch is shown.
  • A remote using an SSH host alias (git@work:org/repo) reads as ci no login (work) though you are logged in.
  • A server counts as the session's when it runs inside the session's root, or in a container whose compose project lives there. Two sessions on one checkout both see its servers.

herdr: images and links

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

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-link-toast (a herdr plugin, not a Claude Code mod)

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

Without herdr, in plain kitty or Ghostty, none of this is needed. Terminals without the kitty graphics protocol show the thumbnail's alt text (its path).

Setting up on another machine (for AI agents)

Read before installing for someone. The mods were written for one machine; several carry its names and need Linux.

1. Check the host. Mods need Claude Code 2.1.287+. They load in the terminal CLI and, from ~/.claude/skills, in a desktop app's local Code-tab session. A desktop-app session can also be given a folder through CLAUDE_CODE_PLUGIN_DIRS in the env block of ~/.claude/settings.json. Nothing here has been tried in the desktop app, VS Code, JetBrains, macOS, WSL or native Windows: say so to the person instead of promising it works.

2. Pick mods by platform.

Works anywhereNeeds LinuxNever on macOS or Windows
quiet-spinner, reminder-log, mr-banner, coderabbit-band, redact (with betterleaks), handover, review-walk; usage-percent's ctx/5h/wk and pipeline partsusage-percent's memory and dev-server parts (cgroup v2, /proc, pwdx; they stay empty elsewhere); stack-down (ps, /proc/<pid>/cwd, setsid)mem-guard: it wraps every Node command in systemd-run, so without systemd every node/pnpm/nx call fails. Leave it out. herdr-notify, herdr-link-toast: Linux, herdr, Ghostty, GNOME
  • Windows: quiet-bash, redact and handover read POSIX paths (/, ~). There, quiet-bash thumbnails and redact's Bash pre-scan find nothing, and handover leaves spent files behind.
  • Surfaces: quiet-bash thumbnails draw only in a terminal with kitty graphics (kitty, Ghostty). Bands and the usage row show in the terminal and the desktop app, not in VS Code or on mobile. /handover-copy can't copy from the desktop app.

3. Adapt to the OS you are on. The mods do not detect the OS; you are running on it, so adapt the person's copy and test it there. The plugin API has no OS call: on Windows $.env.get('OS') is Windows_NT, elsewhere uname -s says Darwin or Linux. Known gaps:

  • mem-guard off Linux: leave it out. To keep its command-only rules (jest worker cap, :lite, pkill -f, ci:local), skip scoped() and the ps/cgroup checks when systemd-run is missing.
  • handover on Windows: HOME may be unset (USERPROFILE), and spent sentences are removed with rm.
  • quiet-bash, redact on Windows: path parsing knows / and ~ only, not C:\….
  • usage-percent on macOS: no pwdx (lsof -a -d cwd -p <pid> instead); the memory zone needs cgroup v2 and stays empty.
  • herdr-notify, herdr-link-toast: Linux, herdr and GNOME only; another OS needs its own notifier, not a port.

Write each OS change as its own commit with a test, so it can come back upstream.

4. Replace the owner's names. Names in this README and in the messages are examples from the owner's repos; use the person's own. The API project there is ec-api, not api, and the dev-server rules only work with the real project names: read them from the repo (npx nx show projects).

ModOwner-specificWhere
mem-guardclaude-cmd.slice and its 30 % / 4 % limits; port 4700; :lite scripts; ci:local "~45 min"; the check-runner agent type; 2 heavy commands, 2 dev servershooks/rules.ts, hooks/register.ts
usage-percentclaude.slice (usage) and app.slice (pressure) under the user manager; Nx repos only (nx.json)hooks/register.tsx
stack-downanother session is a process whose command is claude (native install); an npm install runs as node …/cli.js, goes unseen, and its repo's Compose stacks go down anywayhooks/targets.ts
mr-banner, coderabbit-band, quiet-bashthe GitLab MCP server named gitlab (mcp__gitlab__…)hooks/*.ts(x)
coderabbit-band, usage-percentany remote that isn't GitHub (or Azure) is taken for GitLabhooks/register.tsx
herdr-notifyGhostty's desktop entry com.mitchellh.ghosttynotify.sh

5. Install and check. Install as above (from a clone when you adapted a mod: an update replaces a marketplace copy), then run claude plugin validate <mod> and claude plugin test <mod> for each mod you install. Start a new session and check what the person should now see: the usage row, a tool row with ✓, and for redact, nothing until it hides a value, then redacted N in the status line.

Developing

Each mod is .claude-plugin/plugin.json, hooks/hooks.json and hooks/register.ts(x), plus types/index.d.ts when it keeps session state. Per mod:

claude plugin validate <mod>   # what it hooks and calls, and what the engine would refuse
claude plugin test <mod>       # its *.test.ts(x)
tsc -p <mod>                   # once the engine has laid .claude-plugin/types/

Edits in ~/.claude/skills hot-reload into running sessions that loaded the mod.

Releasing a mod

Marketplace users only get a change once the mod's version moves, so a change meant for them bumps it in the same commit:

  1. Bump version in <mod>/.claude-plugin/plugin.json: major when users must act, minor for a feature, patch for a fix.
  2. Add ## <version> — <date> to <mod>/CHANGELOG.md, with an Action needed line on a major.
  3. claude plugin validate --strict . (the marketplace) and claude plugin validate --strict <mod>.
  4. Commit and push, then claude plugin tag --push <mod>.
  5. gh release create <mod>--v<version> --verify-tag --title "<mod> <version>" --notes-file <entry>, with the new changelog entry as the notes; links in it must be absolute.
Source 5 files
hooks/register.tsx 194 lines
1import { 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 { dim, joined, toneOf } from './pieces'
7import { forgeOf, hostOf, githubPipeline, gitlabPipeline, pipeline } from './pipeline'
8import type { Pipeline } from './pipeline'
9import type { Piece } from '../types'
10
11const WINDOWS: Record<string, string> = { five_hour: '5h', seven_day: 'wk' }
12const TICK_MS = 10_000
13const PIPELINE_RUNNING_MS = 60_000
14const PIPELINE_IDLE_MS = 300_000
15const AFTER_PUSH_MS = 15_000
16
17const usageLine = atom({ plugin: 'usage-percent', key: 'line' } as const, null)
18const nxLine = atom({ plugin: 'usage-percent', key: 'nx' } as const, null)
19
20type Poll = { root: string; uid: string; head: string; pipelineAt: number; pushedAt: number; pipe: Pipeline | null; composeDirs: Map<string, string>; isBusy: boolean }
21
22function figure(label: string, percent: number): Piece[] {
23  return [dim(`${label} `), { text: `${Math.round(percent)}%`, tone: toneOf(percent) }]
24}
25
26export function isGitPush(command: string): boolean {
27  return /\bgit(?:\s+-[Cc]\s+\S+)*\s+push\b/.test(command)
28}
29
30export function line(context: SessionContextUsage, rateLimits: readonly SessionRateLimit[]): Piece[] {
31  const limits = rateLimits.flatMap(limit => {
32    const label = WINDOWS[limit.kind]
33    return label === undefined ? [] : [figure(label, limit.percentUsed)]
34  })
35  return joined([figure('ctx', context.percent ?? 0), ...limits], ' | ')
36}
37
38async function memoryPieces($: EngineInterface, uid: string): Promise<Piece[]> {
39  const service = `/sys/fs/cgroup/user.slice/user-${uid}.slice/user@${uid}.service`
40  const files = ['claude.slice/memory.current', 'claude.slice/memory.max', 'app.slice/memory.pressure']
41  const contents = await Promise.all(files.map(file => $.fs.read(`${service}/${file}`))).catch(() => null)
42  if (contents === null) {
43    return []
44  }
45  const [current = '', max = '', pressure = ''] = contents
46  return memory(Number(current), Number(max), pressureAvg10(pressure))
47}
48
49async function fetchPipeline($: EngineInterface, root: string): Promise<Pipeline | null> {
50  const git = (...args: string[]) => $.process.run(['git', ...args], { cwd: root }).then(r => r.stdout.trim())
51  const [remote, branch] = await Promise.all([git('remote', 'get-url', 'origin'), git('branch', '--show-current')])
52  const forge = forgeOf(remote)
53  if (forge === null || branch === '') {
54    return null
55  }
56  const argv = forge === 'github'
57    ? ['gh', 'run', 'list', '--branch', branch, '--limit', '1', '--json', 'status,conclusion,workflowName']
58    : ['glab', 'ci', 'get', '--branch', branch, '--output', 'json']
59  const run = await $.process.run(argv, { cwd: root, timeoutMs: 20_000 })
60  if (run.exitCode !== 0) {
61    // A failure is either no pipeline for the branch (show nothing) or a host the CLI is not logged in to.
62    const host = hostOf(remote)
63    const auth = await $.process.run([forge === 'github' ? 'gh' : 'glab', 'auth', 'status', '--hostname', host], { timeoutMs: 10_000 })
64    return auth.exitCode === 0 ? null : { state: 'no-login', detail: host }
65  }
66  return forge === 'github' ? githubPipeline(run.stdout) : gitlabPipeline(run.stdout)
67}
68
69// A server counts when it runs in the session's tree; one in a container counts when its compose project lives there.
70async function servedHere($: EngineInterface, poll: Poll, processes: readonly ServeProcess[]): Promise<string[]> {
71  if (processes.length === 0) {
72    return []
73  }
74  const pwdx = await $.process.run(['pwdx', ...processes.map(p => p.pid)])
75  const dirOf = directoriesOf(pwdx.stdout)
76  for (const { pid } of processes) {
77    if (isUnder(dirOf.get(pid) ?? '', poll.root)) {
78      continue
79    }
80    const container = containerOf(await $.fs.read(`/proc/${pid}/cgroup`).catch(() => ''))
81    if (container !== null) {
82      dirOf.set(pid, await composeDir($, poll, container))
83    }
84  }
85  return servedIn(poll.root, processes, dirOf)
86}
87
88async function composeDir($: EngineInterface, poll: Poll, container: string): Promise<string> {
89  if (!poll.composeDirs.has(container)) {
90    const label = '{{index .Config.Labels "com.docker.compose.project.working_dir"}}'
91    const run = await $.process.run(['docker', 'inspect', '--format', label, container], { timeoutMs: 10_000 }).catch(() => null)
92    poll.composeDirs.set(container, run?.exitCode === 0 ? run.stdout.trim() : '')
93  }
94  return poll.composeDirs.get(container) ?? ''
95}
96
97// Memory and servers every tick; the pipeline only when HEAD moved, after a push, or when its interval is up.
98async function tick($: EngineInterface, poll: Poll) {
99  if (poll.isBusy) {
100    return
101  }
102  poll.isBusy = true
103  try {
104    const [middle, ps, head] = await Promise.all([
105      memoryPieces($, poll.uid),
106      $.process.run(['ps', '-eo', 'pid,args']),
107      $.process.run(['git', 'rev-parse', 'HEAD'], { cwd: poll.root }).then(r => r.stdout.trim()),
108    ])
109    const now = await $.clock.now()
110    const interval = poll.pipe?.state === 'running' ? PIPELINE_RUNNING_MS : PIPELINE_IDLE_MS
111    const isPushSettled = poll.pushedAt > 0 && now - poll.pushedAt >= AFTER_PUSH_MS
112    if (head !== poll.head || isPushSettled || now - poll.pipelineAt >= interval) {
113      poll.head = head
114      poll.pipelineAt = now
115      poll.pushedAt = 0
116      poll.pipe = await fetchPipeline($, poll.root).catch(() => null)
117    }
118    const served = await servedHere($, poll, serveProcesses(ps.stdout)).catch(() => [])
119    const right = joined([served.length > 0 ? [dim(`▶ ${served.join(' ')}`)] : [], poll.pipe ? pipeline(poll.pipe) : []], ' · ')
120    await update($, nxLine, () => (middle.length > 0 || right.length > 0 ? { middle, right } : null))
121  } finally {
122    poll.isBusy = false
123  }
124}
125
126function startTick($: EngineInterface, poll: Poll): void {
127  void tick($, poll).catch((error: unknown) => $.ui.log(`usage-percent: ${String(error)}`, { to: 'debug' }))
128}
129
130export const register: Register = on => {
131  let poll: Poll | null = null
132  let timer: Timer | null = null
133
134  on('session.start', async ($, e, next) => {
135    const result = await next(e)
136    const { context, rateLimits } = await $.session.usage()
137    await update($, usageLine, () => line(context, rateLimits))
138
139    timer?.cancel()
140    timer = null
141    poll = null
142    const root = await $.session.root()
143    if (await $.fs.exists(`${root}/nx.json`)) {
144      const uid = (await $.process.run(['id', '-u'])).stdout.trim()
145      const current: Poll = { root, uid, head: '', pipelineAt: 0, pushedAt: 0, pipe: null, composeDirs: new Map(), isBusy: false }
146      poll = current
147      startTick($, current)
148      timer = $.clock.every(TICK_MS, () => startTick($, current))
149    }
150    return result
151  })
152
153  on('session.measure', async ($, e, next) => {
154    await update($, usageLine, () => line(e.context, e.rateLimits))
155    return next(e)
156  })
157
158  on('tool.call', { tool: 'Bash' }, async ($, e, next) => {
159    const result = await next(e)
160    if (poll !== null && isGitPush(e.command)) {
161      poll.pushedAt = await $.clock.now()
162    }
163    return result
164  })
165
166  on('ui.render', { component: 'PromptHint' }, async ($, e, next) => {
167    const left = (await read($, usageLine)) ?? []
168    const nx = await read($, nxLine)
169    const hint = await next(e)
170    if (left.length === 0 && nx === null) {
171      return hint
172    }
173
174    const { Box, Text } = $.ui.resolve(e)
175    const draw = (pieces: readonly Piece[]) => (
176      <Text>
177        {pieces.map(piece => (piece.tone === 'dim' ? <Text dimColor>{piece.text}</Text> : <Text color={piece.tone}>{piece.text}</Text>))}
178      </Text>
179    )
180
181    // Equal-width outer zones keep the memory zone centred.
182    return (
183      <Box flexDirection="column">
184        {hint}
185        <Box>
186          <Box width={0} flexGrow={1}>{draw(left)}</Box>
187          {nx && nx.middle.length > 0 ? <Box>{draw(nx.middle)}</Box> : null}
188          <Box width={0} flexGrow={1} justifyContent="flex-end">{draw(nx?.right ?? [])}</Box>
189        </Box>
190      </Box>
191    )
192  })
193}
194
hooks/machine.ts 63 lines
1import { dim, toneOf } from './pieces'
2import type { Piece } from '../types'
3
4const GIB = 1024 ** 3
5
6export type ServeProcess = { pid: string; project: string }
7
8export function memory(current: number, max: number, pressureAvg10: number): Piece[] {
9  const used = { text: `${(current / GIB).toFixed(1)}G`, tone: Number.isFinite(max) ? toneOf((current / max) * 100) : 'dim' } as const
10  if (pressureAvg10 <= 0) {
11    return [dim('mem '), used]
12  }
13  return [dim('mem '), used, dim(' psi '), { text: `${Math.round(pressureAvg10)}%`, tone: toneOf(pressureAvg10, 20, 50) }]
14}
15
16export function pressureAvg10(pressureFile: string): number {
17  return Number(/^some avg10=([\d.]+)/m.exec(pressureFile)?.[1] ?? 0)
18}
19
20// From `ps -eo pid,args`. A server of nx's default project, or of every project, shows as plain `serve`.
21export function serveProcesses(ps: string): ServeProcess[] {
22  return [...ps.matchAll(/^\s*(\d+)\s.*?\bnx (.*)$/gm)].flatMap(m => servedProjects(m[2] ?? '').map(project => ({ pid: m[1] ?? '', project })))
23}
24
25function servedProjects(args: string): string[] {
26  const run = /^run ([\w.-]+):serve(?=[:\s]|$)/.exec(args)
27  if (run) {
28    return [run[1] ?? '']
29  }
30  const serve = /^serve(?=\s|$)(.*)/.exec(args)
31  if (serve) {
32    return [optionOf(serve[1] ?? '', 'project', 'p') ?? /^\s+(\w[\w.-]*)/.exec(serve[1] ?? '')?.[1] ?? 'serve']
33  }
34  if (/^run-many\b/.test(args) && /(?:^|,)serve(?:,|$)/.test(optionOf(args, 'targets', 't') ?? optionOf(args, 'target') ?? '')) {
35    return (optionOf(args, 'projects', 'p') ?? 'serve').split(',')
36  }
37  return []
38}
39
40function optionOf(args: string, name: string, short?: string): string | null {
41  const flag = short === undefined ? `--${name}` : `(?:--${name}|-${short})`
42  return new RegExp(`(?:^|\\s)${flag}(?:=|\\s+)([^\\s-][^\\s]*)`).exec(args)?.[1] ?? null
43}
44
45// From `pwdx <pid>...`: `1234: /dir` per line.
46export function directoriesOf(pwdx: string): Map<string, string> {
47  return new Map([...pwdx.matchAll(/^(\d+): (.+)$/gm)].map(m => [m[1] ?? '', m[2] ?? '']))
48}
49
50// From `/proc/<pid>/cgroup`: the Docker container the process runs in, if any.
51export function containerOf(cgroup: string): string | null {
52  return /\/docker-([0-9a-f]+)\.scope/.exec(cgroup)?.[1] ?? null
53}
54
55export function isUnder(dir: string, root: string): boolean {
56  return dir === root || dir.startsWith(`${root}/`)
57}
58
59export function servedIn(root: string, processes: readonly ServeProcess[], dirOf: ReadonlyMap<string, string>): string[] {
60  const names = processes.filter(p => isUnder(dirOf.get(p.pid) ?? '', root)).map(p => p.project)
61  return [...new Set(names)].sort()
62}
63
hooks/pieces.ts 14 lines
1import 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 dim(text: string): Piece {
8  return { text, tone: 'dim' }
9}
10
11export function joined(groups: readonly Piece[][], gap: string): Piece[] {
12  return groups.filter(group => group.length > 0).flatMap((group, i) => (i === 0 ? group : [dim(gap), ...group]))
13}
14
hooks/pipeline.ts 74 lines
1import { 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}
74
types/index.d.ts 11 lines
1export type Tone = 'dim' | 'yellow' | 'red' | 'green'
2export type Piece = { text: string; tone: Tone }
3export type UsageLine = Piece[] | null
4export type NxLine = { middle: Piece[]; right: Piece[] } | null
5
6declare module 'claude-code' {
7  interface PluginState {
8    'usage-percent': { line: UsageLine; nx: NxLine }
9  }
10}
11