SLOPSHOPPER

band-pack

The first six Baselane band meters in one row above the prompt: session cost, lattes, context bar, today's spend, the focus timer and the mood ring.

newbandguardcommandtoasttimer
★ 1v0.5.1MITupdated 2026-10-06baselane-sh/mods/plugins/band-pack
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · band-pack
› 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 › /pomodoro ⎿ band-pack: Pomodoro started: 25 minutes of focus. Run /pomodoro again to stop it. $0.42 +$0.00 0.1 lattes [####------] 49% focus 25:00 ● tense ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Band
$0.42 +$0.00 0.1 lattes [####------] 49% focus 25:00 ● tense
README

Baselane mods

Small mods for Claude Code. Pick the ones you want and combine them.

Baselane mods are Claude Code plugins made of function hooks. Each mod does one thing: a guard that asks before rm -rf, a band with the session cost, a side pane with your git status, a sound when tests pass, a pirate voice for Claude's prose. There are 100+ mods in families such as guards, panes, meters, sounds and stats. Install one, or stack ten. They do not need each other.

Quick start (30 seconds)

You need Claude Code 2.1.288 or later, with mods.

claude plugin marketplace add baselane-sh/mods-catalog
claude plugin install guard-essentials@baselane-mods
claude plugin install receipt@baselane-mods

Start Claude Code. Now it asks before harsh commands, and /receipt prints a receipt of the session.

Browse every mod at https://baselane-sh.github.io/mods-catalog/. The gallery (baselane-mods) pins each mod to a reviewed commit, so a new mod reaches the gallery a short time after it reaches this repo. For update, uninstall, options and starter sets, read docs/INSTALL.md.

This repo also has a development marketplace, baselane-mods-dev, that tracks main. Use it only to try changes that are not released yet:

claude plugin marketplace add baselane-sh/mods
claude plugin install <name>@baselane-mods-dev

Each mod is released with a git tag <name>--v<version>.

How packs work

Most mods have one rule. A pack is one mod with several rules from the same family. For example, guard-essentials holds several guards and band-pack puts several meters in one band.

  • Install a pack when you want the whole set with one command.
  • Install single mods when you want only some of the rules.
  • Install a pack or its single mods, not both. Each mod has its own copy of its engine, so a rule in two installed mods runs two times. For example, with guard-pack and infra-guard installed, the terraform destroy check runs two times, and you can see two questions.
  • Mods from different families combine with no conflict. guard-essentials, cost-meter and git-pane work well together.

The catalog below marks each pack with "pack".

Beads mods

Beads (bd) is an issue tracker that lives in your repo. 19 mods show your beads in Claude Code: bars above the prompt, panes, slash commands, a guard and reminders. They need bd 1.2 or later and a repo with a .beads folder. Without these, they do nothing.

The core set in one go (the bars, the panes, /ready and the guard):

claude plugin install beads-bars@baselane-mods
claude plugin install beads-pane@baselane-mods
claude plugin install epics-pane@baselane-mods
claude plugin install ready@baselane-mods
claude plugin install beads-guard@baselane-mods

Each beads mod is also in the catalog below, in its family.

Safety

  • Guards ask. They do not block. A guard stops a harsh command and asks you first. You decide. If a guard check fails, it asks you. It does not let the call through without a question.
  • Your data stays on your machine. No mod sends data out unless you set a destination yourself, such as an ntfy topic for ntfy-notify or long-run-notify, or a webhook URL for slack-notify or discord-notify. With a destination set, those mods send a short message only: a generic "needs input" text with the project folder name, or the project name and the seconds. One exception needs no setup: ci-band and ops-band ask GitHub, through your own gh login, for the latest Actions run of your branch every 2 minutes, sending the repository and branch name. Without gh, or with gh not logged in, they do nothing.
  • One mod can make a model call, and it is off by default. sports-narrator makes one small model call at the end of a turn that used tools. It sends tool names, file names and the first two words of each shell command, never file contents. It spends tokens, so you must turn it on.
  • Beads mods only read your beads. They run read commands of your own bd on your machine, such as bd status --json and bd ready --json. No beads mod creates, changes or closes a bead. beads-guard asks before a bd command that deletes or rewrites beads.
  • Display mods do not change what Claude reads. The mods in "Display and render" change only how rows and replies look on your screen. Other families can add text for Claude: prompt styles change how Claude writes, secret-output-guard tells Claude not to repeat a credential, auto-format and auto-lint tell Claude to read a file again, beads-prime adds the workflow text that bd prime prints from your repo's .beads files, and bead-claim-nudge and bead-commit-nudge add a one-line reminder at your next prompt.
  • Stats stay local. Streaks, achievements and /wrapped read records that the mods keep on your machine.
  • Mods that write files say so. /handoff writes .claude/handoff.md and never overwrites it. session-journal appends to ~/.claude/journal.log. auto-format and auto-lint run your project's own formatter or linter fix, which can rewrite files. The descriptions say what each mod writes.

Requirements

  • Claude Code 2.1.288 or later, with mods (the plugin function-hook API, in early access). Read the Claude Code mods docs.
  • Some mods use local tools: git for the git pane, the git band and most commands, lsof for port-watch, gh for ci-band, bd 1.2 or later for the beads mods, ps for process-pane, and on macOS pmset for battery-band and pgrep with osascript for now-playing.
  • To build from source: Node.js.

Build and check from source

plugins/ and .claude-plugin/marketplace.json are generated. Do not edit them by hand.

node scripts/build.mjs          # build one plugin folder per catalog entry
bash scripts/check.sh           # rebuild, then validate, test and type-check every mod
bash scripts/check.sh git-pane  # check only the mods you name
node scripts/gen-docs.mjs       # rewrite the catalog in this README
node --test 'scripts/*.test.mjs'  # test the docs generator

A change is done when check.sh prints check: 0 failure(s). Read AGENTS.md for the layout and the API facts.

Contributing

To add a mod:

  1. Add a rule to an engine: engines/<engine>/hooks/rules/<id>.ts, with a test in engines/<engine>/tests/<id>.test.ts.
  2. Add a catalog entry in catalog/<name>.json: { "name", "description", "rules": ["<id>"] }. Give the description the slash command, if the mod has one (for example "Open it with /git"). The catalog table reads it from there.
  3. Run node scripts/build.mjs, then bash scripts/check.sh <mod>, then node scripts/gen-docs.mjs.

A new engine needs a family in scripts/gen-docs.mjs. Keep files small, do not change inputs in place, and do not use the em-dash character.

Licence

MIT. Copyright (c) 2026 Baselane, LLC. Read LICENSE.

Catalog

<!-- catalog:start -->

199 mods in 10 families.

"needs setup" means the mod has options that you set with claude plugin configure <mod>. Its description tells you if it works before you set them. "pack" means one mod with several rules.

Guards (36)

Ask you before a harsh or risky command runs.

ModWhat it doesCommandNotes
beads-guardAsks before bd commands that delete data or rewrite history: delete, purge, prune, gc, sql, admin, import, rename, forget, restore, migrate and more. Reads only the command text, runs no bd.
secret-filename-guardAsks before a Bash command touches a secret-looking file (.env, private keys, credentials).
secret-guardAsks before a live API key, token or private key is written, edited or run.
env-exfil-guardAsks before a command prints your environment, echoes a secret variable or sends local data to a remote host.
infra-guardAsks before terraform destroy, kubectl delete, force-push, DROP TABLE or rm -rf.
secret-commit-guardAsks before a git commit that would record a credential or a secret-named file. Reads the staged diff with git.
protect-mainAsks before a commit, push or merge while you are on main or master. Reads the branch with git.
gitignore-checkAsks before git add or commit when secret-looking files are not ignored or are already tracked. Checks with git ls-files.
secret-output-guardTells Claude not to repeat a credential that showed up in command or file output, and names the source to rotate.
curl-pipe-guardAsks before a download is piped into a shell or interpreter (curl \sh, wget -O- \bash, bash <(curl ...)).
sudo-guardAsks before sudo, doas or su -c runs a command with elevated rights.
no-verify-guardAsks before git hooks are skipped (--no-verify, commit -n, HUSKY=0, core.hooksPath=/dev/null).
lockfile-guardAsks before a lockfile is written or edited by hand; the package manager should change it.
package-guardAsks before a new dependency is installed (npm, pnpm, yarn, bun, pip, uv, poetry, cargo, go, gem) and names the packages.
prod-db-guardAsks before destructive SQL runs in a command: TRUNCATE, DELETE or UPDATE with no WHERE.
path-jailAsks before Write, Edit or NotebookEdit changes a file outside the working directory, by real path.
docker-guardAsks before Docker commands that delete data: system, volume or image prune, rm -f, volume rm and compose down -v.
k8s-guardAsks before kubectl apply or replace with --force, kubectl drain, helm uninstall, and kubectl delete behind global flags (plain kubectl delete is infra-guard's).
migration-guardAsks before Write or Edit changes a migration that already exists; new migration files pass.
ci-config-guardAsks before Write or Edit changes CI config: .github/workflows, .gitlab-ci.yml or .circleci/config.yml.
chmod-guardAsks before chmod makes files world-writable (777, a+w, o+w) or chmod or chown runs recursively on a broad path (/, a system folder, a home folder).
git-history-guardAsks before git commands that throw away work or rewrite history: reset --hard, clean, rebase, filter-branch, filter-repo, push --delete, branch -D and stash clear.
big-file-guardAsks before a Write creates content over 1 MB, or git add names a file over 5 MB. Measures the files with find.
publish-guardAsks before a package is published: npm, pnpm, yarn or bun publish, cargo publish, twine upload, gem push, poetry or uv publish. Dry runs pass.
tag-guardAsks before release tags go to a remote: git push --tags, --follow-tags or --mirror, a push of a tag ref, and a push that deletes a remote tag. Dry runs pass. Reads tags with git.
deploy-guardAsks before a production deploy: vercel --prod, netlify deploy --prod, firebase deploy, fly deploy, gcloud app deploy, eb deploy, heroku rollback, serverless deploy to prod.
db-reset-guardAsks before a framework wipes a database: prisma migrate reset, rails or rake db:drop and db:reset, alembic downgrade, django flush, supabase db reset, knex rollback --all.
ssh-guardAsks before a private key in .ssh is read, authorized_keys or the SSH config is changed, or ssh-keygen would overwrite a key. Public keys and ssh -i pass. Reads HOME with printenv.
cron-guardAsks before scheduled jobs or services are wiped or stopped: crontab -r, crontab replaced from stdin or a file, launchctl unload or bootout, systemctl stop, disable or mask.
upload-guardAsks before local files go to a remote host: scp or rsync to host:path, piped input to nc, curl -T, sftp put. Local copies, downloads and localhost pass.
registry-push-guardAsks before an image or chart is pushed to a registry: docker push, docker buildx --push, podman push, helm push, gcloud artifacts docker push. Local registries pass.
guard-essentialsAsks only before harsh or disaster commands: destructive infra, git and SQL, piping downloads into a shell, sudo, leaking or committing secrets. Reads git. The quiet choice for daily work.pack
guard-packThe 15 core Baselane guards in one mod (secrets, git, infra, packages, path jail). Some read git, measure files with find, read HOME with printenv, or check where a path really lands.pack
guard-devopsAsks before harsh DevOps commands: destructive Docker, Kubernetes and Helm calls, CI config edits, broad chmod and chown, and git commands that lose work. Add infra-guard for plain kubectl delete.pack
release-packAsks before a release leaves your machine: package publish, tag push, production deploy and registry push guards in one mod. The tag guard reads tags with git.pack
ship-safe-packThe release-pack guards plus db-reset-guard and upload-guard: asks before publish, tag push, production deploy, registry push, database wipes and file uploads. Reads tags with git.pack

Reminders (19)

One quiet toast at turn end when something needs your attention.

ModWhat it doesCommandNotes
bead-claim-nudgeAt turn end, if Claude edited a file and no bead is in progress, shows a toast and reminds Claude at your next prompt, once per session. Reads with bd count; quiet without bd.
bead-commit-nudgeAt turn end, if a git commit named no bead id while a bead is in progress, shows a toast and reminds Claude at your next prompt. Reads with bd count and bd where; quiet without bd.
test-reminderReminds you at turn end when source files changed but no test command ran since.
ctx-nudgeReminds you to /clear or /compact when the context window passes 75 percent.
clippyOne helpful toast per session per trigger, in the classic paperclip voice: when you edit a migrations folder, a Dockerfile or a GitHub workflow, or run rm -rf. At most one toast per turn.
sports-narratorOne line of sports play-by-play at turn end. OFF by default: one haiku call per turn with tools. Turn on the enabled option. Sends tool names, file names and the first two words of each command.needs setup
commit-nudgeSuggests a commit at turn end after 8 or more file edits since the last git commit. One toast per batch of edits; a successful git commit resets the count.
todo-nudgeAt turn end, one toast with the count of TODO, FIXME and HACK lines your edits added this turn. Quiet when none were added.
break-nudgeSuggests a short break once the session has run 90 minutes, and again every 90 minutes after that.
docs-nudgeAt turn end, one toast when edits added exported code (an export statement in .ts or .js, or a public function signature) and no README or docs file was edited this session.
debug-print-nudgeAt turn end, one toast naming the count of console.log, print(, debugger and dbg! lines your edits added this turn. Only code files count.
typecheck-nudgeAt turn end, one toast when .ts or .tsx files were edited and no type check (tsc, vue-tsc, a typecheck script or a build) ran since the last edit.
lockfile-nudgeAt turn end, one toast when dependencies in package.json, pyproject.toml, Cargo.toml or go.mod changed and neither the matching lockfile was edited nor an install command ran.
big-diff-nudgeSuggests splitting the change once your edits added or removed more than 500 lines since the last git commit. A successful commit resets the count.
migration-nudgeAt turn end, one toast when a schema file changed (schema.prisma, models.py, SQL under schema/, a drizzle schema) and no migration file was created this session.
env-example-nudgeAt turn end, one toast when edits add a reference to an environment variable (process.env, os.environ, os.getenv, Deno.env) that .env.example does not list. Reads only .env.example names, never .env.
nudge-packTwo turn-end reminders in one mod: test-reminder and ctx-nudge.pack
focus-packThree quiet nudges in one mod: commit after 8 edits, TODO/FIXME/HACK lines added, and debug prints added.pack
quality-packThree quiet nudges in one mod: type check after TypeScript edits, lockfile after dependency edits, and a split suggestion past 500 changed lines.pack

Commands (31)

Slash commands that print a result and, where it helps, copy it.

ModWhat it doesCommandNotes
readyAdds /ready: the 20 top ready beads, one line each, and the total. Read with bd, the beads tracker. Read-only. Prints only, copies nothing./ready
beadAdds /bead <id>: one bead with status, priority, labels, description, blockers and children. Read with bd, the beads tracker. Read-only. Prints only, copies nothing./bead
beads-standupAdds /beads-standup: beads closed since yesterday, in progress, and the next 5 ready. Read with bd, the beads tracker. Read-only. Prints only, copies nothing./beads-standup
receiptAdds /receipt: a shareable receipt of the session (tools, files, commands, blocks, context, cost), printed and copied./receipt
standupAdds /standup: Yesterday, Today and Blockers from your git log and this session's record, printed and copied./standup
changelogAdds /changelog: commits since the last tag (or the last 30), read with git log and grouped by conventional-commit type, as Markdown. Copies the result to your clipboard./changelog
pr-descriptionAdds /pr-description: title, summary, diff totals and a test plan stub for the current branch against main or master, read with git. Copies the result to your clipboard./pr-description
handoffAdds /handoff: writes a session summary with the git status to .claude/handoff.md (never overwriting) and answers with the path. Copies the result to your clipboard./handoff
todosAdds /todos: TODO, FIXME and HACK lines in tracked files, found with git grep, grouped by file (50 lines at most). Read-only. Copies the result to your clipboard./todos
locAdds /loc: lines of tracked text files by language, read with git, sorted, with a total. Skips lockfiles and binaries. Read-only. Copies the result to your clipboard./loc
hotspotsAdds /hotspots: the 10 files changed most often in the last 90 days, from git log, with change counts. Read-only. Copies the result to your clipboard./hotspots
commit-msgAdds /commit-msg: a Conventional Commits message proposed from the staged diff, read with git. Heuristic, no model call, writes nothing. Copies the result to your clipboard./commit-msg
branchesAdds /branches: local branches merged into the default branch or idle for 30 days, as a cleanup list, read with git. Never deletes. Copies the result to your clipboard./branches
treeAdds /tree: tracked files (git ls-files) as a tree, 2 levels deep, folders with file counts (80 lines at most). Read-only. Copies the result to your clipboard./tree
depsAdds /deps: direct dependencies with versions from package.json, pyproject.toml, requirements.txt, go.mod and Cargo.toml at the repo root. No network. Read-only. Copies the result to your clipboard./deps
authorsAdds /authors: the top 15 contributors by commit count with their last commit date, from git log. Names only, never email addresses. Read-only. Copies the result to your clipboard./authors
scriptsAdds /scripts: runnable tasks from package.json scripts, Makefile targets, justfile recipes and pyproject scripts at the git repo root. Read-only. Copies the result to your clipboard./scripts
env-checkAdds /env-check: variable names in .env.example against .env at the git repo root, listing missing and extra names. Reads names only, never a value. Read-only. Copies the result to your clipboard./env-check
sizeAdds /size: the 15 largest tracked files and the total tracked size at HEAD, read with git. Read-only. Copies the result to your clipboard./size
licensesAdds /licenses: the licence of each direct dependency, from node_modules and Python dist-info at the git repo root. Shows unknown when it cannot tell. Read-only. Copies the result to your clipboard./licenses
conflictsAdds /conflicts: tracked files that still hold merge conflict markers, with line numbers, found with git grep. Read-only. Copies the result to your clipboard./conflicts
secret-scanAdds /secret-scan: tracked files and line numbers that hold secret-shaped text, found with git grep. Never prints a matched value. Read-only. Copies the result to your clipboard./secret-scan
envinfoAdds /envinfo: versions of git, node, npm, python3, go, rustc and docker if installed, by running each (2 s limit), and the OS. Read-only. Copies the result to your clipboard./envinfo
stashesAdds /stashes: git stashes with their age and the branch each was made on. Read-only, never applies or drops. Copies the result to your clipboard./stashes
recentAdds /recent: your last 15 commits across all local branches (author is git user.name), with branch and date. Read-only. Copies the result to your clipboard./recent
file-ownersAdds /owners <path>: the top 5 authors of a file or folder by lines, from git blame. Names only, never addresses. Read-only. Copies the result to your clipboard./owners
readme-checkAdds /readme-check: missing README sections (install, usage, licence, contributing) and broken relative links, at the git repo root. Read-only. Copies the result to your clipboard./readme-check
command-packThe five original slash commands in one mod: /receipt, /standup, /changelog, /pr-description and /handoff. They read git; /handoff also writes .claude/handoff.md. They copy results to the clipboard./receipt, /standup, /changelog, /pr-description, /handoffpack
repo-packFive read-only repo commands in one mod: /todos, /loc, /hotspots, /commit-msg and /branches. They read git. They copy results to the clipboard./todos, /loc, /hotspots, /commit-msg, /branchespack
explore-packFive read-only repo exploration commands in one mod: /tree, /deps, /authors, /scripts and /env-check. They read git and project files. They copy results to the clipboard./tree, /deps, /authors, /scripts, /env-checkpack
audit-packThree read-only audit commands in one mod: /secret-scan, /conflicts and /licenses. They read git, project files and dependency folders. They copy results to the clipboard./secret-scan, /conflicts, /licensespack

Band meters (30)

A one-line band above the prompt.

ModWhat it doesCommandNotes
cost-meterA band above the prompt with the session cost so far and what the last turn cost.
latte-meterA band above the prompt that counts the session cost in lattes. Set the latte price in the plugin options.needs setup
context-meterA band above the prompt with a 10 cell bar of the context window used, yellow from 60 percent, red from 80.
daily-spendA band above the prompt with today's total cost across all your sessions.

| pomodoro | A band above the prompt with a 25/5 focus timer (focus 18:42, break 03:10). Start and stop it with /pomodoro; a to

Source 21 files
hooks/register.ts 23 lines
1import type { Register } from 'claude-code'
2
3import { registerBand } from './engine'
4import { watchCalls } from './hosts/calls'
5import { watchTickers } from './hosts/tickers'
6import { startSession } from './hosts/start'
7import { endTurnsWithStore } from './hosts/turn-end-store'
8import { rule as costMeter } from './rules/cost-meter'
9import { rule as latteMeter } from './rules/latte-meter'
10import { rule as contextMeter } from './rules/context-meter'
11import { rule as dailySpend } from './rules/daily-spend'
12import { rule as pomodoro } from './rules/pomodoro'
13import { rule as moodRing } from './rules/mood-ring'
14
15export const register: Register = (on, options) => {
16  const rules = [costMeter, latteMeter, contextMeter, dailySpend, pomodoro, moodRing]
17  registerBand(on, rules, options)
18  watchCalls(on, rules)
19  watchTickers(on, rules)
20  startSession(on, rules)
21  endTurnsWithStore(on, rules)
22}
23
hooks/engine.tsx 231 lines
1import { atom, read, update } from 'claude-code'
2import type { Frozen, On, PluginOptions, SessionUsage, TurnCompleteInput } from 'claude-code'
3
4import type { Fetched, GitState, Outcome, Pomodoro, Reading, Tally } from '../types'
5import { localDate } from './date'
6import { hasFetchers } from './fetch'
7import { syncMinuteTick } from './minute'
8import type { MinuteDeps } from './minute'
9import type { BandRule, Segment, Ticker, TurnEnd, TurnTokens } from './rule'
10import { startTurnTimer, stopTurnTimer } from './turn'
11import { bandTree, fitSegments } from './view'
12
13// The build writes the mod's own name in place of the token: `$.state` is
14// written only by the plugin that owns it, and the scan wants the atoms here.
15const reading = atom({ plugin: 'band-pack', key: 'reading' } as const, null)
16const turnStartUsd = atom({ plugin: 'band-pack', key: 'turnStartUsd' } as const, null)
17// The state scan wants each atom spelled in the file that reads or writes it,
18// so watch.ts spells the same two. A turn end replaces `reading` whole, which
19// is why these live apart from it.
20const outcomes = atom({ plugin: 'band-pack', key: 'outcomes' } as const, [] as readonly Outcome[])
21const pomodoro = atom({ plugin: 'band-pack', key: 'pomodoro' } as const, null as Pomodoro | null)
22// Written by tally.ts and git.ts, which spell the same atoms; read here to draw.
23const tally = atom({ plugin: 'band-pack', key: 'tally' } as const, { calls: {}, failures: 0 } as Tally)
24const git = atom({ plugin: 'band-pack', key: 'git' } as const, null as GitState | null)
25// Written by the minute tick and read to draw, so the write redraws the band.
26const minute = atom({ plugin: 'band-pack', key: 'minute' } as const, 0)
27// Written by fetch.ts and turn.ts, which spell the same atoms; read here to draw.
28const fetched = atom({ plugin: 'band-pack', key: 'fetched' } as const, {} as Readonly<Record<string, Fetched | null>>)
29const turnStartedAt = atom({ plugin: 'band-pack', key: 'turnStartedAt' } as const, null as number | null)
30
31export const failed = (where: string, error: unknown): string =>
32  `band: ${where} skipped, ${error instanceof Error ? error.message : String(error)}`
33
34export const tickersOf = (rules: readonly BandRule[]): Ticker[] =>
35  rules.flatMap(rule => (rule.ticker === undefined ? [] : [rule.ticker]))
36
37const segmentsOf = (rules: readonly BandRule[], draw: Parameters<BandRule['segment']>[0]): Segment[] =>
38  rules.flatMap(rule => {
39    try {
40      const segment = rule.segment(draw)
41      return segment === undefined ? [] : [segment]
42    } catch {
43      // A rule that throws leaves its segment out and the rest draw.
44      return []
45    }
46  })
47
48// The turn's cache tokens as the rules read them, or none when it had no usage.
49const tokensOf = (usage: { input_tokens: number; cache_read_input_tokens: number; cache_creation_input_tokens: number } | undefined): TurnTokens | undefined =>
50  usage === undefined ? undefined : { input: usage.input_tokens, cacheRead: usage.cache_read_input_tokens, cacheWrite: usage.cache_creation_input_tokens }
51
52const clampPercent = (percent: number | undefined): number | undefined =>
53  percent === undefined || !Number.isFinite(percent) ? undefined : Math.min(100, Math.max(0, percent))
54
55// The model is a read of its own: a failure leaves the figure out and the
56// rest of the turn end stands.
57const modelOf = async (read: () => Promise<string>): Promise<string | undefined> => {
58  try {
59    const model = (await read()).trim()
60    return model === '' ? undefined : model
61  } catch {
62    return undefined
63  }
64}
65
66// The tools a turn-end host does not give. A rule that calls one is logged and
67// skipped, and its tests fail: name what it uses in engine.json `needs`.
68const absent = (name: string) => (): Promise<never> =>
69  Promise.reject(new Error(`${name} is not given to this mod; name it in engine.json needs`))
70
71export const NO_MODEL: TurnIo['model'] = absent('model')
72export const NO_STORE: TurnIo['store'] = { get: absent('store'), set: absent('store') }
73
74// What a turn end reads and writes, as closures over the hook's `$`.
75// `refresh` runs the fetchers; only the host that runs programs gives it.
76export type TurnIo = {
77  usage: () => Promise<SessionUsage>
78  reading: () => Promise<Reading | null>
79  turnStartUsd: () => Promise<number | null>
80  keep: (now: Reading) => Promise<unknown>
81  spend: () => Promise<unknown>
82  endTimer: () => Promise<unknown>
83  model: () => Promise<string>
84  store: TurnEnd['store']
85  clock: Omit<MinuteDeps, 'tick'>
86  redraw: () => Promise<unknown>
87  log: (text: string) => unknown
88  refresh?: () => void
89}
90
91// The figures are read once, at the turn's end. A render hook never writes,
92// so they go into $.state for it to draw. A subagent's turn is not the
93// person's turn.
94export const turnComplete = async (rules: readonly BandRule[], e: Frozen<TurnCompleteInput>, io: TurnIo): Promise<void> => {
95  if (e.agentId !== undefined) return
96  const isFetching = hasFetchers(rules)
97  const isMinutely = isFetching || rules.some(rule => rule.everyMinute !== undefined)
98  if (rules.some(rule => rule.tracksTurn === true)) {
99    // First and on its own: a failed usage read below must not leave it running.
100    stopTurnTimer()
101    try {
102      await io.endTimer()
103    } catch (error) {
104      await io.log(failed('turn timer', error))
105    }
106  }
107  try {
108    const usage = await io.usage()
109    const usd = usage.cost?.usd
110    const percent = clampPercent(usage.context.percent)
111    const previous = await io.reading()
112    const base = (await io.turnStartUsd()) ?? previous?.usd
113    // A cost that fell (a cleared session) leaves the turn's cost unknown.
114    const turnUsd = usd !== undefined && base !== undefined && usd >= base ? usd - base : undefined
115    const date = localDate(await io.clock.now())
116    const model = await modelOf(io.model)
117
118    const usageTokens = tokensOf(e.usage)
119    let now: Reading = {
120      ...(usd === undefined ? {} : { usd }),
121      ...(turnUsd === undefined ? {} : { turnUsd }),
122      ...(percent === undefined ? {} : { percent }),
123      ...(Number.isFinite(usage.startedAt) ? { startedAt: usage.startedAt } : {}),
124      ...(model === undefined ? {} : { model }),
125    }
126    for (const rule of rules) {
127      if (rule.atTurnEnd === undefined) continue
128      try {
129        now = {
130          ...now,
131          ...(await rule.atTurnEnd({
132            reading: now,
133            previous: previous ?? {},
134            ...(usageTokens === undefined ? {} : { usage: usageTokens }),
135            turnUsd,
136            date,
137            store: io.store,
138          })),
139        }
140      } catch (error) {
141        await io.log(failed(rule.id, error))
142      }
143    }
144    await io.keep(now)
145    // Spent: a second end of the same turn adds nothing.
146    await io.spend()
147    if (isMinutely) {
148      const refresh = (): void => {
149        if (isFetching) io.refresh?.()
150      }
151      refresh()
152      await syncMinuteTick(rules, now, {
153        ...io.clock,
154        tick: async () => {
155          try {
156            refresh()
157            await io.redraw()
158          } catch (error) {
159            await io.log(failed('minute', error))
160          }
161        },
162      })
163    }
164  } catch (error) {
165    await io.log(failed('turn end', error))
166  }
167}
168
169// The hooks every band mod has: the cost as the turn begins, and the band.
170// The rest are hosts (engine.json), so a mod has only what its rules use.
171export const registerBand = (on: On, rules: readonly BandRule[], options: PluginOptions): void => {
172  const isMinutely = hasFetchers(rules) || rules.some(rule => rule.everyMinute !== undefined)
173  const isTurnTimed = rules.some(rule => rule.tracksTurn === true)
174  // The band reads the minute atom, so a tick's write redraws it: each minute,
175  // and each second while a turn runs.
176  const isTicking = isMinutely || isTurnTimed
177
178  // The cost as the turn begins: what this turn's cost is measured from.
179  on('turn.start', async ($, e, next) => {
180    try {
181      const usage = await $.session.usage()
182      await update($, turnStartUsd, () => usage.cost?.usd ?? null)
183    } catch (error) {
184      await $.ui.log(failed('turn start', error))
185    }
186    if (isTurnTimed) {
187      try {
188        // The callbacks close over `$`; they never pass it on.
189        await startTurnTimer({
190          now: () => $.clock.now(),
191          begin: at => update($, turnStartedAt, () => at),
192          every: (ms, fn) => $.clock.every(ms, fn),
193          tick: async () => {
194            try {
195              await update($, minute, n => n + 1)
196            } catch (error) {
197              await $.ui.log(failed('turn tick', error))
198            }
199          },
200        })
201      } catch (error) {
202        await $.ui.log(failed('turn timer', error))
203      }
204    }
205    return next(e)
206  })
207
208  on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
209    if (e.props.hasSurvey) return next(e)
210    // A rule may draw from live state before the first turn ends.
211    const current = (await read($, reading)) ?? {}
212    const now = await $.clock.now()
213    const date = localDate(now)
214    const live = {
215      outcomes: await read($, outcomes),
216      pomodoro: await read($, pomodoro),
217      tally: await read($, tally),
218      git: await read($, git),
219      fetched: await read($, fetched),
220      turnStartedAt: await read($, turnStartedAt),
221    }
222    // Read only so its write redraws the band.
223    if (isTicking) await read($, minute)
224    const segments = fitSegments(segmentsOf(rules, { reading: current, options, date, now, ...live }), e.props.bodyColumns)
225    if (segments.length === 0) return next(e)
226
227    const { Box, Text } = $.ui.resolve(e)
228    return bandTree({ Box, Text }, segments)
229  })
230}
231
hooks/hosts/calls.ts 35 lines
1import { atom, update } from 'claude-code'
2import type { On } from 'claude-code'
3
4import type { Outcome, Tally } from '../../types'
5import { failed } from '../engine'
6import type { BandRule } from '../rule'
7import { addCall } from '../tally'
8
9const WINDOW = 20
10
11// The same atoms as engine.tsx: the state scan wants each spelled in the
12// file that reads or writes it. The build writes the mod's own name for the token.
13const outcomes = atom({ plugin: 'band-pack', key: 'outcomes' } as const, [] as readonly Outcome[])
14const tally = atom({ plugin: 'band-pack', key: 'tally' } as const, { calls: {}, failures: 0 } as Tally)
15
16// For the rules that draw from how the tool calls ended: the recent outcomes
17// and the tally of the session. The result is passed on as it came: a denied
18// call stays denied. Only one hook may answer `tool.call` without a matcher.
19export const watchCalls = (on: On, rules: readonly BandRule[]): void => {
20  const isOutcomes = rules.some(rule => rule.tracksOutcomes === true)
21  const isTally = rules.some(rule => rule.tracksTools === true)
22
23  on('tool.call', async ($, e, next) => {
24    const ran = await next(e)
25    try {
26      const outcome: Outcome = ran.deny !== undefined ? 'block' : ran.isError === true ? 'error' : 'ok'
27      if (isOutcomes) await update($, outcomes, recent => [...recent, outcome].slice(-WINDOW))
28      if (isTally) await update($, tally, current => addCall(current, e.tool, outcome !== 'ok'))
29    } catch (error) {
30      await $.ui.log(failed('outcomes', error))
31    }
32    return ran
33  })
34}
35
hooks/hosts/tickers.ts 59 lines
1import { atom, read, update } from 'claude-code'
2import type { On, Timer } from 'claude-code'
3
4import type { Pomodoro } from '../../types'
5import { failed, tickersOf } from '../engine'
6import type { BandRule } from '../rule'
7
8// The same atom as engine.tsx: the state scan wants it spelled in the file
9// that reads or writes it. The build writes the mod's own name for the token.
10const pomodoro = atom({ plugin: 'band-pack', key: 'pomodoro' } as const, null as Pomodoro | null)
11
12// The running intervals, by command name. A handle is not drawn state, so it
13// is a module variable. A hot reload cancels the interval and keeps the state:
14// the timer then freezes until its command stops it.
15const running = new Map<string, Timer>()
16
17// For a rule with a ticker: registers its command handler and runs its
18// interval. The command starts the timer when none runs and stops it when one
19// does. The start host registers the command names (`on("session.start")`
20// takes one hook), from `tickersOf`.
21export const watchTickers = (on: On, rules: readonly BandRule[]): void => {
22  const tickers = tickersOf(rules)
23
24  for (const ticker of tickers) {
25    const name = ticker.command.name
26    on('command.run', { command: name }, async $ => {
27      running.get(name)?.cancel()
28      running.delete(name)
29
30      const now = await $.clock.now()
31      const { next, text } = ticker.toggle(await read($, pomodoro), now)
32      await update($, pomodoro, () => next)
33      if (next === null) return { text }
34
35      // The callback closes over `$`; it never passes it on.
36      running.set(
37        name,
38        $.clock.every(ticker.everyMs, async () => {
39          try {
40            const at = await $.clock.now()
41            let toast: string | undefined
42            // A stop that lands during a tick must stay stopped.
43            await update($, pomodoro, current => {
44              if (current === null) return null
45              const ticked = ticker.tick(current, at)
46              toast = ticked.toast
47              return ticked.next
48            })
49            if (toast !== undefined) await $.ui.toast(toast)
50          } catch (error) {
51            await $.ui.log(failed(name, error))
52          }
53        }),
54      )
55      return { text }
56    })
57  }
58}
59
hooks/hosts/start.ts 15 lines
1import type { On } from 'claude-code'
2
3import { tickersOf } from '../engine'
4import type { BandRule } from '../rule'
5
6// The slash commands of the timer rules. `on("session.start")` takes one hook,
7// so a pack of timer and fetching rules needs a host that does both.
8export const startSession = (on: On, rules: readonly BandRule[]): void => {
9  const tickers = tickersOf(rules)
10  on('session.start', async ($, e, next) => {
11    for (const { command } of tickers) await $.command.register(command)
12    return next(e)
13  })
14}
15
hooks/hosts/turn-end-store.ts 43 lines
1import { atom, read, update } from 'claude-code'
2import type { On } from 'claude-code'
3
4import type { Reading } from '../../types'
5import { NO_MODEL, turnComplete } from '../engine'
6import type { BandRule } from '../rule'
7
8// The same atoms as engine.tsx: the state scan wants each spelled in the file
9// that reads or writes it. The build writes the mod's own name for the token.
10const reading = atom({ plugin: 'band-pack', key: 'reading' } as const, null)
11const turnStartUsd = atom({ plugin: 'band-pack', key: 'turnStartUsd' } as const, null)
12const turnStartedAt = atom({ plugin: 'band-pack', key: 'turnStartedAt' } as const, null as number | null)
13const minute = atom({ plugin: 'band-pack', key: 'minute' } as const, 0)
14
15// The turn's end, for a mod whose rules keep a figure across sessions in the
16// mod's own store. It gives no model read.
17export const endTurnsWithStore = (on: On, rules: readonly BandRule[]): void => {
18  on('turn.complete', async ($, e, next) => {
19    // The callbacks close over `$`; they never pass it on.
20    await turnComplete(rules, e, {
21      usage: () => $.session.usage(),
22      reading: () => read($, reading),
23      turnStartUsd: () => read($, turnStartUsd),
24      keep: (now: Reading) => update($, reading, () => now),
25      spend: () => update($, turnStartUsd, () => null),
26      endTimer: () => update($, turnStartedAt, () => null),
27      model: NO_MODEL,
28      store: {
29        get: (key: string) => $.store.get(key),
30        set: (key: string, value: unknown) => $.store.set(key, value),
31      },
32      clock: {
33        now: () => $.clock.now(),
34        after: (ms, fn) => $.clock.after(ms, fn),
35        every: (ms, fn) => $.clock.every(ms, fn),
36      },
37      redraw: () => update($, minute, n => n + 1),
38      log: text => $.ui.log(text),
39    })
40    return next(e)
41  })
42}
43
hooks/rules/cost-meter.ts 13 lines
1import { dollars } from '../money'
2import type { BandRule } from '../rule'
3
4// The session cost so far, and the last turn's cost once it is known.
5export const rule: BandRule = {
6  id: 'cost-meter',
7  segment: ({ reading }) => {
8    if (reading.usd === undefined) return undefined
9    const turn = reading.turnUsd === undefined ? '' : ` +${dollars(reading.turnUsd)}`
10    return { key: 'cost-meter', text: `${dollars(reading.usd)}${turn}` }
11  },
12}
13
hooks/rules/latte-meter.ts 17 lines
1import type { BandRule } from '../rule'
2
3export const DEFAULT_LATTE_PRICE = 5
4
5// The session cost in coffees. The price is in the cost's currency (US
6// dollars); one that cannot divide falls back to the default.
7export const rule: BandRule = {
8  id: 'latte-meter',
9  segment: ({ reading, options }) => {
10    if (reading.usd === undefined) return undefined
11    const set = options['lattePrice']
12    const price = typeof set === 'number' && Number.isFinite(set) && set > 0 ? set : DEFAULT_LATTE_PRICE
13    const count = (reading.usd / price).toFixed(1)
14    return { key: 'latte-meter', text: `${count} ${count === '1.0' ? 'latte' : 'lattes'}` }
15  },
16}
17
hooks/rules/context-meter.ts 27 lines
1import type { BandRule } from '../rule'
2
3const CELLS = 10
4const YELLOW_FROM = 60
5const RED_FROM = 80
6
7// The color is a second cue: the number says the same without it.
8const colorOf = (percent: number): string | undefined =>
9  percent >= RED_FROM ? 'red' : percent >= YELLOW_FROM ? 'yellow' : undefined
10
11// Context used as a 10 cell bar and a percent. A cell fills per whole ten
12// percent, so the bar reads full only at 100.
13export const rule: BandRule = {
14  id: 'context-meter',
15  segment: ({ reading }) => {
16    if (reading.percent === undefined) return undefined
17    const whole = Math.round(reading.percent)
18    const filled = Math.min(CELLS, Math.floor(whole / 10))
19    const color = colorOf(whole)
20    return {
21      key: 'context-meter',
22      text: `[${'#'.repeat(filled)}${'-'.repeat(CELLS - filled)}] ${whole}%`,
23      ...(color === undefined ? {} : { color }),
24    }
25  },
26}
27
hooks/rules/daily-spend.ts 28 lines
1import type { BandRule } from '../rule'
2import { dollars } from '../money'
3
4const keyFor = (date: string): string => `daily:${date}`
5
6// Today's total across sessions. The store holds one number per local date;
7// each turn adds its own cost delta once (the engine measures it from the
8// cost at turn start, so a turn that ends twice has a delta of zero the
9// second time). Two sessions ending a turn in the same instant can lose one
10// add: the store has no atomic update.
11export const rule: BandRule = {
12  id: 'daily-spend',
13  atTurnEnd: async ({ turnUsd, date, store }) => {
14    const stored = await store.get(keyFor(date))
15    const total = typeof stored === 'number' && Number.isFinite(stored) ? stored : undefined
16    if (turnUsd !== undefined && turnUsd > 0) {
17      const next = (total ?? 0) + turnUsd
18      await store.set(keyFor(date), next)
19      return { dailyUsd: next, dailyDate: date }
20    }
21    return total === undefined ? {} : { dailyUsd: total, dailyDate: date }
22  },
23  segment: ({ reading, date }) =>
24    reading.dailyUsd === undefined || reading.dailyDate !== date
25      ? undefined
26      : { key: 'daily-spend', text: `today ${dollars(reading.dailyUsd)}` },
27}
28
hooks/rules/pomodoro.ts 49 lines
1import type { Pomodoro } from '../../types'
2import type { BandRule } from '../rule'
3
4export const FOCUS_MS = 25 * 60_000
5export const BREAK_MS = 5 * 60_000
6// One tick per second is also one redraw per second at most.
7export const TICK_MS = 1000
8
9const PHASE_MS = { focus: FOCUS_MS, break: BREAK_MS } as const
10
11// MM:SS, rounded up so the timer never reads 00:00 before it switches.
12export const clockText = (ms: number): string => {
13  const total = Math.ceil(Math.max(0, ms) / 1000)
14  return `${String(Math.floor(total / 60)).padStart(2, '0')}:${String(total % 60).padStart(2, '0')}`
15}
16
17const TOAST = {
18  break: 'Focus block done. Take a 5 minute break.',
19  focus: 'Break over. Back to focus for 25 minutes.',
20} as const
21
22// A 25/5 focus timer. `/pomodoro` starts it and a second `/pomodoro` stops it.
23// It sits in the band engine because the segment is the band's and the
24// command's whole job is to move that segment; the engine runs the command
25// and the interval for any rule that names a `ticker`.
26export const rule: BandRule = {
27  id: 'pomodoro',
28  ticker: {
29    command: { name: 'pomodoro', description: 'Start or stop a 25 minute focus, 5 minute break timer in the band.' },
30    everyMs: TICK_MS,
31    toggle: (current, now) =>
32      current === null
33        ? {
34            next: { phase: 'focus', endsAt: now + FOCUS_MS, now },
35            text: 'Pomodoro started: 25 minutes of focus. Run /pomodoro again to stop it.',
36          }
37        : { next: null, text: 'Pomodoro stopped.' },
38    // A phase that ended gives way to the other one, measured from now: a tick
39    // that came late (a sleeping laptop) does not replay the missed phases.
40    tick: (current, now): { next: Pomodoro; toast?: string } => {
41      if (now < current.endsAt) return { next: { ...current, now } }
42      const phase = current.phase === 'focus' ? 'break' : 'focus'
43      return { next: { phase, endsAt: now + PHASE_MS[phase], now }, toast: TOAST[phase] }
44    },
45  },
46  segment: ({ pomodoro }) =>
47    pomodoro === null ? undefined : { key: 'pomodoro', text: `${pomodoro.phase} ${clockText(pomodoro.endsAt - pomodoro.now)}` },
48}
49
hooks/rules/mood-ring.ts 31 lines
1import type { Outcome } from '../../types'
2import type { BandRule } from '../rule'
3
4const TENSE_FROM = 0.1
5const STORMY_FROM = 0.3
6
7type Mood = { word: string; color: string }
8
9// The share of the window that errored or was blocked. Under 10 percent is
10// calm, under 30 tense, from 30 stormy.
11export const moodOf = (recent: readonly Outcome[]): Mood => {
12  const bad = recent.filter(outcome => outcome !== 'ok').length
13  const rate = bad / recent.length
14  if (rate >= STORMY_FROM) return { word: 'stormy', color: 'red' }
15  if (rate >= TENSE_FROM) return { word: 'tense', color: 'yellow' }
16  return { word: 'calm', color: 'green' }
17}
18
19// A colored dot and a word for how the last 20 tool calls went (the engine
20// keeps that window). The word says the same without the color. Calls from
21// subagents count too: they are part of how the session is going.
22export const rule: BandRule = {
23  id: 'mood-ring',
24  tracksOutcomes: true,
25  segment: ({ outcomes }) => {
26    if (outcomes.length === 0) return undefined
27    const { word, color } = moodOf(outcomes)
28    return { key: 'mood-ring', text: `● ${word}`, color }
29  },
30}
31