See your other Claude Code sessions from this one: which are working, which wait for you, which are done, and which share this folder. Each session writes a…

Eight small Claude Code mods, free to use under the MIT licence. A mod is a plugin made of function hooks: Claude Code calls it at every step (a tool call, a slash command, a redraw), and it can answer, change or watch that step.
Each mod has its own on/off switch, /<mod> on, /<mod> off and /<mod> status, kept across sessions. secret-guard starts on; the other seven start off, so installing one changes nothing until you turn it on. See Switching a mod on and off.
| Mod | What it does | Command |
|---|---|---|
| secret-guard | Reads every .env and .env.* from your session's folder up to the drive root when a session starts and hides their secret values (keys named like PASSWORD, SECRET, TOKEN, API_KEY) in every tool result before Claude reads it, along with anything that looks like a secret on its own: KEY=VALUE under such a name, the password in postgres://user:REDACTED@host, private keys, JWTs, AWS keys, Kubernetes Secret data. A secret reaches Claude as ‹hidden: DB_PASSWORD›. It tells Claude, in every conversation, to use $DB_PASSWORD instead of printing the value, and it refuses the few commands that would print a whole env file or a decrypted secret. | /secret-guard lists the protected files and key names; /secret-guard off / on |
| plan-meter | A one-line band above the prompt that says how far your plan is: plan ▸ Ship the export · phases 1/3 · steps 3/6 (50%) · now: API · Claude's tasks 2/5. It reads your plan file (and the phase files it links to) in many formats, and Claude's own task list. It updates when a file changes. | /plan-meter on / off / status; /plan-meter opens a pane with the details; /plan-meter docs/roadmap.md picks a file |
| done-gate | When Claude marks a task done while code it changed has not been tested since, it tells Claude, in the tool result Claude reads, and you, in a toast. A band shows the last test run: done-gate ▸ tests ✔ passed 4 min ago · 2 files changed since. It warns; it never blocks. | /done-gate on / off; /done-gate status lists the changed files and the last test command |
| context-meter | A band above the prompt with what fills the context window, by category and in /context's colours (context ▸ 90k of 1M · 9% · compacts at 987k), and a countdown to when the prompt cache expires, which turns from green through amber to red: cache ▸ 41:07 left (1h TTL, assumed: subscription). A Compact button (or c while the band has focus) runs the same compaction as /compact. | /context-meter on / off / status; the button |
| idea-shelf | Park an idea while Claude works, without interrupting it: /idea try the bulk endpoint later keeps it on this project's shelf, across sessions. The band counts them (ideas ▸ 3 ideas parked [Shelf]); the shelf lists them with Send, Edit and Delete. Send puts the idea in the prompt box, or sends it when the box is empty and Claude is idle. A parked idea never reaches the model until you send it. | /idea <text>; /idea opens the shelf; /idea-shelf on / off / status |
| session-monitor | See your other Claude Code sessions from this one: other sessions ▸ 1 waiting · 2 working · 1 done [List], waiting first, in the colour for "needs you". Sessions in this same folder get their own line: also here ▸ "Fix the export" · working. Waiting means a permission dialog or a question is open. | /session-monitor on / off / status; /session-monitor list opens the list |
| prompt-enhancer | An Enhance button above the prompt: Haiku rewrites your draft so it names the skills that fit, lists what Claude should ask you first, and says what done looks like. The rewrite replaces the draft; nothing is sent until you press Enter or Send. | /prompt-enhancer on / off / status; the buttons |
| assumption-check | After a turn that edited files or ran commands, Haiku lists the choices Claude made that you did not state (assumptions ▸ 6 to check [Review]): a date format, a default, a library. Mark each Right or Wrong, add a note, and Send corrections puts one prompt in the box that says what to change and what to keep. | /assumption-check on / off / status; /assumption-check review opens the list |
Tested on Claude Code 2.1.296 on Windows 11 (secret-guard, plan-meter, done-gate and context-meter first on 2.1.291 to 2.1.295). Mods are an early-access feature, so the API can change between versions; if a mod stops loading after an update, check claude plugin validate on its folder.
git clone https://github.com/vumichien/claude-code-mods-kit.git
claude --plugin-dir claude-code-mods-kit/plugins/plan-meter
--plugin-dir loads the mod for that session only. Repeat the flag to load more than one.
claude plugin marketplace add vumichien/claude-code-mods-kit
claude plugin install secret-guard@chien-mods
claude plugin install plan-meter@chien-mods
claude plugin install done-gate@chien-mods
claude plugin install context-meter@chien-mods
claude plugin install idea-shelf@chien-mods
claude plugin install session-monitor@chien-mods
claude plugin install prompt-enhancer@chien-mods
claude plugin install assumption-check@chien-mods
Start a new session afterwards. To remove one: claude plugin uninstall plan-meter@chien-mods.
Every mod answers /<mod> on, /<mod> off and /<mod> status (a bare /<mod> is status). The switch is kept in the mod's own store, so it holds in every later session, in every folder, until you change it.
secret-guard OFF: secrets not hidden, and its note to Claude and the hiding both stop./plan-meter on, /idea-shelf on, and so on.claude plugin disable <mod>@chien-mods still unloads a mod entirely, and each one's tests include one that feeds every hooked event to the mod while it is off and finds each one passed on unchanged.Up to version 0.2 of plan-meter, done-gate and context-meter, on and off only showed or hid the band for the session; now they switch the whole mod, and the choice stays.
Every option has a default, so all eight mods work without any. plan-meter, done-gate and context-meter share one: band, on (default) or off. With off, a mod that is switched on keeps working (the plan is read, done-gate still tells Claude, context-meter still measures) but draws no band. To change one, use /plugin configure <name>@chien-mods inside Claude Code, pass --config key=value to claude plugin install, or pipe a JSON object to claude plugin configure <name>@chien-mods --values-stdin. With --plugin-dir, put them in a settings file: --settings '{"pluginConfigs":{"done-gate":{"options":{"testCommands":"make ci"}}}}'.
secret-guard
mode: value (default) hides secrets in results and refuses the commands listed below. command instead refuses any call whose command or path names a protected env file, except to load it (source .env, --env-file .env), without reading values or changing results; it is simpler, but it blocks harmless commands and misses reads that don't name the file.secretFiles (default .env, .env.*, !*.example): comma-separated globs of the env files to read. A file name is looked for in the session's folder and every folder above it, up to the drive root. A path is read where it points: ~/vault//.env (from your home folder; goes up to 8 folders deep and skips node_modules, .git, .venv, venv and __pycache__), an absolute path, or one relative to the session's folder. !glob leaves files out. Each file must be in .env format.secretKeys: comma-separated key names to treat as secrets on top of the built-in rule. The rule: a key is a secret when a part of its name (split at _, -, . and camelCase) is PASS, PASSWD, PASSWORD, PW, PWD, SECRET, TOKEN, KEY, DSN, CREDENTIAL or PRIVATE, or ends with one of the first seven (APIKEY, DBPASS). So DB_PASSWORD, apiKey and AWS_SECRET_ACCESS_KEY are secrets; DB_NAME, DB_HOST, ACCOUNT_ID, MAX_TOKENS, TOKENIZER_PATH and the shell's own PWD are not.identifierKeys: comma-separated keys that match the rule but hold names, not secrets (KMS_KEY_ID, SSH_KEY_NAME). They are never hidden.Values shorter than 8 characters are never hidden (except the password in a URL such as postgres://user:REDACTED@host, which is always hidden), so PW=1 or TOKEN_TTL=60 does not mask every 1 or 60. The values of non-secret keys are never hidden at all, so database names, hosts, users and account ids stay readable.
In value mode it refuses these commands, each time naming a way to do the same without printing the secret: cat, type, Get-Content, less, more, head, tail or bat of a protected file (cat .env | cut -d= -f1 is allowed, it prints names); a bare env, printenv, set or Get-ChildItem env:; and, unless the output goes to a file or a variable (> out.json, VALUE=$(...)), aws ssm ... --with-decryption, aws secretsmanager get-secret-value and kubectl get secret ... -o yaml|json. It never refuses loading a file: source .env, . .env, set -a, --env-file .env.
Every conversation starts with a short # secret-guard note to Claude: the protected files and key names (names only), what ‹hidden: NAME› means, and the convention (reference $NAME, let scripts load the env file, never print a secret, report only whether a command worked). So you no longer need to remind each session. The note is rebuilt after a compaction or /clear. Messages Claude sends to another agent or session (SendMessage) are scrubbed like tool results. So is what Claude Code attaches to a message on its own, which never passes through a tool call: a file Claude read, attached again after a compaction; a file changed on disk; a file you @-mention; a settings hook's output.
plan-meter
plan: comma-separated paths, relative to the project, tried in order; the first one that matches a file wins. A * in any part matches anything, and among several matches the most recently changed file wins. Default: plans/*/plan.md, PLAN.md, plan.md, TODO.md, TASKS.md, ROADMAP.md, todo.txt, TODO.org.refreshSeconds (default 15, at least 5): how often the plan is read again, so an edit you make in your own editor shows up too. Edits Claude makes show up at once.The band shows only when there is a plan or a task list. The pane draws in the terminal and the desktop app; under claude -p, /plan-meter answers with the band's line. (The command was /plan up to 0.1.0; Claude Code 2.1.294 has a built-in /plan, which refused the name.)
context-meter
cacheTtl: auto (default), 5m or 1h. A mod cannot read the cache lifetime Claude Code asks for, so auto follows Claude Code's defaults: one hour on a Claude subscription (the session reports rate-limit windows), five minutes with an API key or a cloud provider. Set it when you know better: you set promptCacheTtl or ENABLE_PROMPT_CACHING_1H, or you are drawing on usage credits, where Claude Code drops to five minutes. The band always says which lifetime it assumed and why.breakdown: summary (default) estimates the categories locally and sends nothing. full counts them with the token-count API after every turn, as /context does: more exact, one request per tool and memory file.Every request of the main conversation that hits the cache resets its timer, so the clock restarts at each model request, from the moment it was sent, not only when a turn ends. While Claude works the band says the cache is being kept warm; the countdown runs between turns, from the last request. A subagent's requests have caches of their own and are left out. After a compaction it starts again with the next message. The button is hidden while a turn runs and before the conversation's first reply, when Claude Code refuses a compaction ("Not enough messages to compact"); if a compaction is refused or a hook vetoes it, the band says why, and so does a toast. If you set CLAUDE_AUTOCOMPACT_PCT_OVERRIDE, which can only bring auto-compaction earlier, the header shows that point and marks it as your setting (compacts at 500k (your 50% setting)), since the breakdown Claude Code returns may still give its default; that one environment variable is all context-meter reads. In the desktop app and the IDE extensions, which run Claude Code through its SDK, Claude Code cannot compact between turns yet, so there the button runs /compact as if you had typed it. Below the bar, every category and the free part get a coloured entry with their tokens and share of the window, wrapped onto as many rows as they need. Compacting is a model call: the band costs no tokens, the button does. With little room above the prompt the band keeps two rows, the fill and the cache clock.
done-gate
testCommands: comma-separated commands that run your tests, added to the usual runners. Example: ./scripts/check.sh, make ci. Each one counts when it is the command itself, with or without arguments, so check does not match git checkout.ignore (default .md,.mdx,.markdown,.txt,.rst,.adoc,.org): file endings whose changes need no test run.The usual runners it knows: pytest, python -m pytest or unittest, npm/pnpm/yarn/bun test or run test, vitest, jest, mocha, go test, cargo test, cargo nextest, mvn test or verify, gradle test, dotnet test, rspec, phpunit, mix test, swift test, ctest, make test or check, tox, nox, deno test, claude plugin test. A runner counts when it is a command in the line, after &&, ; or cd api && and behind FOO=1, npx, uv run or poetry run; a runner named inside an argument (echo pytest, git commit -m "fix pytest") does not.
idea-shelf, session-monitor, prompt-enhancer and assumption-check have no options.
Each paragraph ends with the mod's calls: line from claude plugin validate: every call it makes into Claude Code. Costs are what the author's checks measured on Claude Code 2.1.296 with Haiku 5.5, at Anthropic's list prices; on a Claude subscription the same calls count against your usage instead.
idea-shelf. /idea <text> runs at once, even while Claude works, and does not interrupt the turn. The shelf is one list per project (the session's root folder), at most 200 ideas of 2,000 characters, in the mod's store on your machine. It sends nothing to the model. The line /idea <text> leaves in the conversation would carry the idea to the model, so idea-shelf rewrites that line before it is stored: the model and the transcript read /idea (an idea, kept on the shelf); the shelf keeps the text. In the author's check, a word typed after /idea was absent from the messages the model reads before and after. An idea reaches the model only when you send it, and then it arrives as a prompt "from the idea-shelf plugin". The shelf's text box is in its pane, so it draws in the terminal and the desktop app; elsewhere /idea <text> still parks. Cost: none. calls: $.clock.now, $.command.register, $.prompt.fill, $.prompt.read, $.prompt.submit, $.session.root, $.state.get, $.state.set, $.store.get, $.store.set, $.ui.open, $.ui.resolve
session-monitor. Each session that has it on writes one small file, ~/.cache/claude-mods/session-monitor/<session id>.json: the session id, its folder, its state (working, waiting or done), when that state began, when the file was written, and a title, which is the title Claude Code gave the session, else the folder's name. No prompt or command text. The file is rewritten at every change of state and every 15 seconds, and each session reads the others' files on the same beat; that is the mod's only reach beyond its own session. Working runs from a prompt to the end of the turn; waiting, while a permission dialog is open or Claude's question waits for you (in auto mode the classifier answers most permission checks, so waiting is brief there); done, otherwise. A closing session marks its file ended; a file not rewritten for 90 seconds (a killed session) is skipped. Mods cannot delete files, so the files stay, one per session, about 240 bytes each: delete the folder whenever you like. It sends nothing to the model. Cost: none. calls: $.clock.every, $.clock.now, $.command.register, $.env.get (HOME, USERPROFILE), $.fs.list, $.fs.read, $.fs.write, $.session.id, $.session.root, $.state.get, $.state.set, $.store.get, $.store.set, $.ui.open, $.ui.resolve
prompt-enhancer. Nothing happens until you press Enhance (e after Ctrl+X, Tab gives the band the keyboard). Then it sends Haiku one request holding your draft, the name and the first 100 characters of the description of each skill and command your session has (built-in commands left out), and the first 40 lines of the project's CLAUDE.md. It never reads .env files. It sends nothing when the draft is empty, longer than 4,000 characters, or holds secret-guard's ‹hidden: …› placeholder or a value shaped like a key (a private key, sk-…, AKIA…, ghp_…, xox?-…, a JWT); the band says why. A rewrite arrives in a few seconds and replaces the draft. If you edited the draft meanwhile, your edit wins and the rewrite is dropped. After 20 seconds it gives up and the draft stays. It never submits: Enter or Send (n) does. A command cannot read the prompt box, so Enhance is a button only. Cost: one press with about 150 skills and commands in the session took 6,615 input and 661 output tokens, about $0.001; the band and /prompt-enhancer status show each press's tokens. calls: $.command.list, $.command.register, $.fs.read (CLAUDE.md), $.model.complete, $.prompt.fill, $.prompt.read, $.prompt.submit, $.session.root, $.state.get, $.state.set, $.store.get, $.store.set, $.ui.resolve
assumption-check. It counts the edits and commands of each turn. When a turn that edited a file or ran a command ends (not one that only read, nor one you interrupted), it sends Haiku one request: that turn's messages, from your last prompt on, each tool call's input cut to 1,500 characters, the whole at most 30,000. These are messages the model already read, after secret-guard (if on) hid what it hides. It asks for at most 8 assumptions as JSON, and asks once more if the answer does not parse. The check starts after the turn has ended, so the turn never waits for it. The list lives for the session only. Send corrections puts a prompt in the box ("You assumed: … That is wrong: <your note>", and the ones you marked right, to keep); pressed again, it sends that prompt, but never while Claude is working. In the author's check, Claude wrote a date parser that read 3/4/2026 day first; the list named that choice first; marked wrong with the note "our users are in the US", the correction changed the two date formats and nothing else. It lists what it finds; it does not prove the list complete. Cost: a median of 1,176 input and 1,339 output tokens per checked turn over 13 checks, about $0.0008; /assumption-check status shows the last one. calls: $.clock.after, $.command.register, $.model.complete, $.prompt.fill, $.prompt.read, $.prompt.submit, $.session.messages, $.state.get, $.state.set, $.store.get, $.store.set, $.ui.open, $.ui.resolve
plan-meter does not ask you to write your plan its way. It recognises these, alone or mixed in one file:
| Format | Example | What it counts | ||||||||
|---|---|---|---|---|---|---|---|---|---|---|
| Checklist | - [x] write the schema | One step per item. Bullets -, *, +, 1., 1). Marks: x or X done; / or ~ in progress (Obsidian); - cancelled, left out of the count; a space, >, <, ! or ? still to do. | ||||||||
| Status table | `\ | Phase \ | Name \ | Status \ | with a row \ | 2 \ | API \ | 🚧 In progress \ | ` | One phase per row. The status column is the one headed Status, State, Progress, Done or Done?, Trạng thái, Tình trạng, ステータス or 状態. The name comes from a Name, Title, Task, Item, What, Deliverable, Tên or Công việc column, else Phase, Step, Milestone, Stage or Giai đoạn, else the first cell with words in it (so a Phase column holding only 2 is skipped). |
| Headings as phases | ## Phase 2: API (in progress), ## Step 3 ✅ | Used when the file has no status table. A heading named Phase, Step, Stage, Milestone, Sprint, Part or Task with a number (also Giai đoạn 1, Bước 2, フェーズ1) is a phase. Its status comes from a mark in it, a status at its end ((done), [WIP], — done, : in progress), the checklist beneath it (all ticked is done, some ticked is in progress), or the phase file it links to. Any other heading counts only when it ends with a status alone: ## Setup (done). | ||||||||
| Linked phase files | Phase 1 | Links in the plan (in text, tables or headings) to Markdown files whose name starts with phase, step, stage, milestone, sprint, part or task and goes on with a number or a dash: phase-01-schema.md, phase1.md, steps.md, part_2.md, but not department.md. Relative to the plan's folder, up to 30; a #section part is ignored, and two links to one file count it once. Their checklists add to the steps. A phase whose status the plan leaves blank or unknown takes the file's status from its frontmatter or status line, else from its checklist; a status the plan states, such as Pending, wins. A plan with no phases of its own takes one phase per linked file. | ||||||||
| YAML frontmatter | title: Ship the export / status: in_progress | The plan's title and its own status. | ||||||||
| Status line | Status: Draft, phase 3 next, Status: …, Status (2026-10-07): … | The plan's own status, shown as written when nothing in the file can be counted. | ||||||||
| org-mode | * TODO write the schema, ** DONE tests | One step per headline. DONE done; DOING, IN-PROGRESS, STARTED, WAITING, HOLD in progress; CANCELLED left out; TODO, NEXT to do. | ||||||||
| todo.txt | x 2026-10-01 call the bank | A file named todo.txt (or *.todo.txt): one step per line, x at the start is done. |
Status words it understands in tables, headings, status lines and frontmatter, in English, Vietnamese and Japanese. When a cell holds several, the first one wins, so Done (review pending) is done and Not started is to do.
[x]in-progress, in_progress), WIP, doing, ongoing, active, started, running, in review, reviewing, blocked, đang, đang làm, 進行中, 🚧 🔄 ⏳ ▶[ ]The title is the frontmatter title:, else the first # heading (a leading Plan: is dropped). Anything inside a fenced code block is skipped.
Claude's own tasks. When Claude keeps a task list (its TodoWrite, TaskCreate and TaskUpdate tools), the band adds Claude's tasks done/total, and the
hooks/register.tsx 288 lines1import { atom, read, update } from 'claude-code'
2import type { Register } from 'claude-code'
3
4import type { Beat, State } from '../types'
5import { BEAT_MS, STALE_MS, ago, alsoHere, counts, folderName, liveOthers, readBeat, titleOf } from './monitor'
6import { STORE_KEY, storedSwitch, switchText, switchWord } from './toggle'
7
8const PANE = 'session-monitor'
9// The switch as this session read it (toggle.ts). Off, every hook passes its event on unchanged: no heartbeat is
10// written or read and no timer runs. The mod starts off; `/session-monitor on` turns it on for every session.
11const enabled = atom({ plugin: 'session-monitor', key: 'enabled' } as const, false)
12const others = atom({ plugin: 'session-monitor', key: 'others' } as const, [] as Beat[])
13const now = atom({ plugin: 'session-monitor', key: 'now' } as const, 0)
14// Whether the list's pane is open, so that the band's button reads List or Hide.
15const isOpen = atom({ plugin: 'session-monitor', key: 'isOpen' } as const, false)
16
17// This session as its heartbeat describes it. `base`: working from a turn's start to its end, else done.
18// `asking`: the tool calls now waiting for the person (a permission dialog, a question); any makes it waiting.
19type Session = {
20 id: string
21 folder: string
22 dir: string
23 sessionTitle: unknown
24 base: 'working' | 'done'
25 asking: Set<string>
26 state: State
27 since: number
28 timer: { cancel: () => void } | undefined
29}
30
31const stateOf = (s: Session): State => (s.asking.size > 0 ? 'waiting' : s.base)
32
33// Every session's file sits in one folder under the home directory, one file per session, named by its id.
34async function heartbeatDir($: any): Promise<string> {
35 const home = (await $.env.get('HOME')) ?? (await $.env.get('USERPROFILE')) ?? ''
36 return `${home.replace(/\\/g, '/')}/.cache/claude-mods/session-monitor`
37}
38
39async function writeBeat($: any, s: Session, state: State | 'ended'): Promise<void> {
40 const beat: Beat = { v: 1, id: s.id, folder: s.folder, title: titleOf(s.sessionTitle, s.folder), state, since: s.since, updatedAt: await $.clock.now() }
41 await $.fs.write(`${s.dir}/${s.id}.json`, JSON.stringify(beat))
42}
43
44// Reads the other sessions' files. A file untouched for 90 seconds is not even opened.
45async function scan($: any, s: Session): Promise<void> {
46 const at = await $.clock.now()
47 const entries: { name: string; kind: string; mtimeMs: number }[] = await $.fs.list(s.dir).catch(() => [])
48 const beats: Beat[] = []
49 for (const f of entries) {
50 if (f.kind !== 'file' || !f.name.endsWith('.json') || f.name === `${s.id}.json`) continue
51 if (f.mtimeMs > 0 && at - f.mtimeMs > STALE_MS) continue
52 const beat = readBeat(await $.fs.read(`${s.dir}/${f.name}`).catch(() => ''))
53 if (beat !== undefined) beats.push(beat)
54 }
55 await update($, others, () => liveOthers(beats, s.id, at))
56 await update($, now, () => at)
57}
58
59async function tick($: any, s: Session): Promise<void> {
60 await writeBeat($, s, s.state)
61 await scan($, s)
62}
63
64// Writes the file when this session's state changes; the timer rewrites it every 15 seconds in any case.
65async function refresh($: any, s: Session): Promise<void> {
66 const state = stateOf(s)
67 if (state === s.state) return
68 s.state = state
69 s.since = await $.clock.now()
70 await writeBeat($, s, state)
71}
72
73// Starts the heartbeat: the first write and read now, then every 15 seconds. The timer is returned so that
74// `/session-monitor off` and the session's end can stop it.
75async function begin($: any, s: Session): Promise<{ cancel: () => void }> {
76 s.id = await $.session.id()
77 s.folder = await $.session.root()
78 s.dir = await heartbeatDir($)
79 s.state = stateOf(s)
80 s.since = await $.clock.now()
81 await tick($, s)
82 return $.clock.every(BEAT_MS, () => void tick($, s).catch(() => undefined))
83}
84
85// Stops the heartbeat and marks the file ended, in one write: a mod cannot delete a file, so readers skip it.
86async function finish($: any, s: Session): Promise<void> {
87 s.timer?.cancel()
88 s.timer = undefined
89 if (s.id !== '') await writeBeat($, s, 'ended')
90}
91
92async function openList($: any): Promise<void> {
93 // Panes draw only in the terminal and the desktop app; elsewhere the command's line is the answer.
94 const opened = await $.ui.open({ id: PANE, title: 'Sessions', closeOnEscape: true }).catch(() => undefined)
95 if (opened !== undefined) await update($, isOpen, () => true)
96}
97
98async function closeList($: any): Promise<void> {
99 await $.ui.close({ id: PANE }).catch(() => undefined)
100 await update($, isOpen, () => false)
101}
102
103// The engine's record of open panes, not the atom: a pane closed by an unload never told this module.
104async function isListUp($: any): Promise<boolean> {
105 return (await $.ui.panes().catch(() => [])).some((pane: { id: string }) => pane.id === PANE)
106}
107
108// The band's button: a press on an open list closes it, on a closed one opens it.
109async function toggleList($: any): Promise<void> {
110 if (await isListUp($)) await closeList($)
111 else await openList($)
112}
113
114function summary(list: readonly Beat[]): string {
115 const n = counts(list)
116 const parts = (['waiting', 'working', 'done'] as const).filter(k => n[k] > 0).map(k => `${n[k]} ${k}`)
117 return parts.length === 0 ? 'no other session open' : `${list.length} other session${list.length === 1 ? '' : 's'}: ${parts.join(' · ')}`
118}
119
120export const register: Register = on => {
121 const s: Session = { id: '', folder: '', dir: '', sessionTitle: undefined, base: 'done', asking: new Set(), state: 'done', since: 0, timer: undefined }
122
123 on('session.start', async ($, e, next) => {
124 // Registered even when the mod is off, so that it can be turned on.
125 await $.command
126 .register({ name: 'session-monitor', description: 'Switch the session monitor on or off, show its status, or list the other open sessions', argumentHint: '[on|off|status|list]', immediate: true })
127 .catch(() => undefined)
128 // A reload runs session.start again: the old timer stops before a new one starts.
129 s.timer?.cancel()
130 s.timer = undefined
131 const isOn = storedSwitch(await $.store.get(STORE_KEY).catch(() => undefined), false)
132 await update($, enabled, () => isOn)
133 // A reload keeps a pane that was up: the band's button starts from the engine's record.
134 const isUp = await isListUp($)
135 await update($, isOpen, () => isUp)
136 if (isOn) s.timer = await begin($, s)
137 return next(e)
138 })
139
140 on('command.run', { command: 'session-monitor' }, async ($, e) => {
141 const isList = (e.args ?? '').trim().toLowerCase() === 'list'
142 const word = isList ? 'status' : switchWord(e.args)
143 if (word === undefined) return { text: 'use /session-monitor on, off, status or list' }
144 if (word === 'status') {
145 if (!(await read($, enabled))) return { text: switchText('session-monitor', false) }
146 await scan($, s)
147 if (isList) await openList($)
148 return { text: `${switchText('session-monitor', true)} · ${summary(await read($, others))}` }
149 }
150 const isOn = word === 'on'
151 await $.store.set(STORE_KEY, isOn)
152 await update($, enabled, () => isOn)
153 if (isOn && s.timer === undefined) s.timer = await begin($, s)
154 if (!isOn) {
155 await finish($, s)
156 await update($, others, () => [])
157 }
158 return { text: switchText('session-monitor', isOn) }
159 })
160
161 // The title Claude Code gives the session rides on these two settings-hook events, when it has one.
162 on('classic.SessionStart', async ($, e, next) => {
163 if (!(await read($, enabled))) return next(e)
164 if (typeof e.session_title === 'string' && e.session_title !== '') s.sessionTitle = e.session_title
165 return next(e)
166 }).catch(($, e, next) => next(e))
167
168 on('classic.UserPromptSubmit', async ($, e, next) => {
169 if (!(await read($, enabled))) return next(e)
170 if (typeof e.session_title === 'string' && e.session_title !== '') s.sessionTitle = e.session_title
171 return next(e)
172 }).catch(($, e, next) => next(e))
173
174 on('turn.start', async ($, e, next) => {
175 if (!(await read($, enabled))) return next(e)
176 s.base = 'working'
177 await refresh($, s).catch(() => undefined)
178 return next(e)
179 })
180
181 on('turn.complete', async ($, e, next) => {
182 if (!(await read($, enabled)) || e.agentId !== undefined) return next(e)
183 s.base = 'done'
184 // A question left open by a turn that ended does not keep the session waiting.
185 s.asking.clear()
186 await refresh($, s).catch(() => undefined)
187 return next(e)
188 })
189
190 // An ask verdict opens a permission dialog (in auto mode the classifier answers it instead, so it is brief).
191 // An observer: the verdict goes back as it came.
192 on('tool.check', async ($, e, next) => {
193 if (!(await read($, enabled))) return next(e)
194 const verdict = await next(e)
195 if (verdict.decision === 'ask' && e.tool_use_id !== undefined) {
196 s.asking.add(e.tool_use_id)
197 await refresh($, s).catch(() => undefined)
198 }
199 return verdict
200 }).catch(($, e, next) => next(e))
201
202 // The call's own run ends the wait its check opened. A question Claude asks waits for the whole run.
203 on('tool.call', async ($, e, next) => {
204 if (!(await read($, enabled))) return next(e)
205 const id = e.tool_use_id
206 if (e.tool === 'AskUserQuestion' && id !== undefined) {
207 s.asking.add(id)
208 await refresh($, s).catch(() => undefined)
209 }
210 const ran = await next(e)
211 if (id !== undefined && s.asking.delete(id)) await refresh($, s).catch(() => undefined)
212 return ran
213 }).catch(($, e, next) => next(e))
214
215 // One quick write: the end event has a short budget.
216 on('session.end', async ($, e, next) => {
217 if (!(await read($, enabled))) return next(e)
218 await finish($, s).catch(() => undefined)
219 return next(e)
220 })
221
222 // A close by the person (Escape, the engine's own close mark or key) turns the band's button back
223 // to List; this module's own closes set it themselves. An observer: the close goes on as it came.
224 on('ui.close', { id: PANE }, async ($, e, next) => {
225 const done = await next(e)
226 await update($, isOpen, () => false)
227 return done
228 }).catch(($, e, next) => next(e))
229
230 on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
231 const below = await next(e)
232 if (!(await read($, enabled))) return below
233 const list = await read($, others)
234 if (e.props.hasSurvey || list.length === 0) return below
235 const { Box, Button, Text } = $.ui.resolve(e)
236 const n = counts(list)
237 const rest = (['working', 'done'] as const).filter(k => n[k] > 0).map(k => `${n[k]} ${k}`)
238 const here = alsoHere(list, s.folder).slice(0, 3)
239 const shown = await read($, isOpen)
240 return (
241 <Box flexDirection="column">
242 <Box>
243 <Text dimColor>{'other sessions ▸ '}</Text>
244 {n.waiting > 0 && <Text color="warning" bold>{`${n.waiting} waiting${rest.length > 0 ? ' · ' : ' '}`}</Text>}
245 {rest.length > 0 && <Text dimColor>{`${rest.join(' · ')} `}</Text>}
246 <Button key="list" label={shown ? 'Hide' : 'List'} hotkey="s" onPress={() => toggleList($)} />
247 </Box>
248 {here.map(b => (
249 <Text key={`here-${b.id}`} wrap="truncate" {...(b.state === 'waiting' ? { color: 'warning' } : { dimColor: true })}>
250 {`also here ▸ "${b.title}" · ${b.state}`}
251 </Text>
252 ))}
253 {below}
254 </Box>
255 )
256 })
257
258 on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
259 const { Box, Button, Text } = $.ui.resolve(e)
260 // A desktop draws the dismiss Button as its own close mark at the pane's edge; the terminal as a button.
261 const close = <Button key="close" label="Close" role="dismiss" onPress={() => closeList($)} />
262 if (!(await read($, enabled))) {
263 return (
264 <Box>
265 <Text dimColor>{`${switchText('session-monitor', false)} `}</Text>
266 {close}
267 </Box>
268 )
269 }
270 const list = await read($, others)
271 const at = await read($, now)
272 const here = new Set(alsoHere(list, s.folder).map(b => b.id))
273 return (
274 <Box flexDirection="column">
275 <Box>
276 <Text bold wrap="truncate">{`Sessions · ${summary(list)} `}</Text>
277 {close}
278 </Box>
279 {list.map(b => (
280 <Text key={`row-${b.id}`} wrap="truncate" {...(b.state === 'waiting' ? { color: 'warning' } : {})}>
281 {`${folderName(b.folder)} · "${b.title}" · ${b.state} ${ago(at - b.since)}${here.has(b.id) ? ' · this folder' : ''}`}
282 </Text>
283 ))}
284 </Box>
285 )
286 })
287}
288hooks/monitor.ts 77 lines1// session-monitor's pure parts: the heartbeat file each session writes, and what a session reads from the others'.
2import type { Beat, State } from '../types'
3
4// A session rewrites its file at every change of state and every 15 seconds. A file not rewritten for 90 seconds
5// belongs to a session that is gone (killed, or closed without its last write), and readers skip it.
6export const BEAT_MS = 15_000
7export const STALE_MS = 90_000
8export const MAX_TITLE = 60
9
10const STATES: readonly string[] = ['working', 'waiting', 'done', 'ended']
11const ORDER: Record<State, number> = { waiting: 0, working: 1, done: 2 }
12
13// Two spellings of one folder match: a Windows path is compared without regard to case or separator.
14export function folderKey(path: string): string {
15 const clean = path.split('\\').join('/').replace(/\/+$/, '')
16 return /^[A-Za-z]:\//.test(clean) ? clean.toLowerCase() : clean
17}
18
19export function folderName(path: string): string {
20 const clean = path.split('\\').join('/').replace(/\/+$/, '')
21 return clean.slice(clean.lastIndexOf('/') + 1) || clean
22}
23
24// The title Claude Code gave the session, else the folder's name: never the text of a prompt.
25export function titleOf(sessionTitle: unknown, folder: string): string {
26 const given = typeof sessionTitle === 'string' ? sessionTitle.replace(/\s+/g, ' ').trim() : ''
27 const text = given !== '' ? given : folderName(folder)
28 return text.length > MAX_TITLE ? `${text.slice(0, MAX_TITLE - 1)}…` : text
29}
30
31// One heartbeat file's text as a Beat; anything else (half written, hand edited, another program's) is skipped.
32export function readBeat(text: string): Beat | undefined {
33 let value: unknown
34 try {
35 value = JSON.parse(text)
36 } catch {
37 return undefined
38 }
39 if (value === null || typeof value !== 'object') return undefined
40 const b = value as Record<string, unknown>
41 const isBeat =
42 b.v === 1 &&
43 typeof b.id === 'string' &&
44 typeof b.folder === 'string' &&
45 typeof b.title === 'string' &&
46 typeof b.state === 'string' &&
47 STATES.includes(b.state) &&
48 typeof b.since === 'number' &&
49 typeof b.updatedAt === 'number'
50 return isBeat ? (b as unknown as Beat) : undefined
51}
52
53// The other sessions still open: not this one, not ended, written within the last 90 seconds. Waiting first.
54export function liveOthers(beats: readonly Beat[], selfId: string, now: number): Beat[] {
55 return beats
56 .filter((b): b is Beat & { state: State } => b.id !== selfId && b.state !== 'ended' && now - b.updatedAt <= STALE_MS)
57 .sort((a, b) => ORDER[a.state] - ORDER[b.state] || b.updatedAt - a.updatedAt)
58}
59
60export function counts(others: readonly Beat[]): Record<State, number> {
61 const n: Record<State, number> = { waiting: 0, working: 0, done: 0 }
62 for (const b of others) if (b.state !== 'ended') n[b.state]++
63 return n
64}
65
66export function alsoHere(others: readonly Beat[], folder: string): Beat[] {
67 const key = folderKey(folder)
68 return others.filter(b => folderKey(b.folder) === key)
69}
70
71export function ago(ms: number): string {
72 const s = Math.max(0, Math.round(ms / 1000))
73 if (s < 60) return `${s}s`
74 const m = Math.floor(s / 60)
75 return m < 60 ? `${m}m` : `${Math.floor(m / 60)}h`
76}
77hooks/toggle.ts 24 lines1// The mod's on/off switch, `/<mod> on|off|status`. The value is kept in $.store under STORE_KEY: one store per
2// plugin, shared by every session and folder, so the switch holds across restarts. A session reads it as it
3// starts and when its own command changes it; a session already open elsewhere picks a change up when it next
4// starts. Pure helpers only: `claude plugin validate` follows `$` only within the file that uses it.
5export const STORE_KEY = 'enabled'
6
7export type SwitchWord = 'on' | 'off' | 'status'
8
9// The command's argument as a switch word: '' and 'status' ask, 'on' and 'off' set; anything else is the mod's own.
10export function switchWord(args: string | undefined): SwitchWord | undefined {
11 const word = (args ?? '').trim().toLowerCase()
12 if (word === '' || word === 'status') return 'status'
13 return word === 'on' || word === 'off' ? word : undefined
14}
15
16// The stored value, or the mod's default when it was never set (or holds something else).
17export function storedSwitch(value: unknown, byDefault: boolean): boolean {
18 return typeof value === 'boolean' ? value : byDefault
19}
20
21export function switchText(mod: string, isOn: boolean): string {
22 return isOn ? `on (/${mod} off turns it off)` : `off (/${mod} on turns it on)`
23}
24types/index.d.ts 16 lines1// What a session is doing: working (a turn runs), waiting (a permission dialog or a question is open), done (idle).
2export type State = 'working' | 'waiting' | 'done'
3
4// One session's heartbeat file. `ended`: the session closed. `since`: when the state began. `updatedAt`: the last
5// write, so a reader can tell a live session from one that is gone.
6export type Beat = { v: 1; id: string; folder: string; title: string; state: State | 'ended'; since: number; updatedAt: number }
7
8declare module 'claude-code' {
9 interface PluginState {
10 // enabled: the mod's on/off switch as this session read it from the store, or as /session-monitor on|off set it.
11 // others: the other sessions still open, as the last read of their files found them. now: when that read ran.
12 // isOpen: the list's pane is open.
13 'session-monitor': { enabled: boolean; others: Beat[]; now: number; isOpen: boolean }
14 }
15}
16