Session meters: a band above the prompt on desktop, a status line under the prompt on the terminal, and a subagent line while a subagent's transcript is in view

A Claude Code plugin marketplace of mods: function-hooks plugins that draw bands, panes and other UI inside Claude Code.
| Plugin | What it does |
|---|---|
meter | Desktop: a band above the prompt with context, prompt cache, usage limits and cost, details on hover. Terminal: a row under the prompt's mode line with model (warning colour on a fallback), effort, directory, branch with a ● when dirty and ↑N↓N against the upstream, then context, usage limits and cost. On either, while a subagent's transcript is in view, a line above the prompt shows that agent's name and task, status, model and effort, context, tool calls and elapsed time. |
agent-graph | Pane graphing the session's running subagents: a left-to-right card graph in the desktop app, which opens it on the first subagent, and an indented tree in the terminal, opened with /agent-graph. |
git clone <repo-url> claude-mods
claude plugin marketplace add ./claude-mods
claude plugin install meter@claude-mods --scope user
claude plugin install agent-graph@claude-mods --scope user
The statusline plugin is now part of meter; if you installed it, remove it with claude plugin uninstall statusline@claude-mods --scope user.
claude-mods/
├── .claude-plugin/
│ └── marketplace.json # marketplace name, owner, plugin list
└── plugins/
└── <name>/
├── .claude-plugin/
│ └── plugin.json # name, version, description
├── hooks/ # hooks.json and the function-hooks modules
├── types/ # this plugin's exported types ("types" in plugin.json)
└── tsconfig.json
Installed plugins load in place from this checkout. After editing, run /reload-plugins or restart Claude Code. For live iteration without installing, run claude --plugin-dir plugins/<name>.
Check a plugin with:
claude plugin validate plugins/<name>
cd plugins/<name> && claude plugin test .
Check the marketplace with claude plugin validate . from the repo root.
hooks/register.tsx 264 lines1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, Register, Timer } from 'claude-code'
3
4import type { GitInfo, Measure, WorkspaceState } from '../types'
5import { EMPTY_SUBAGENTS, addAgentStep, addAgentTool, agentView, mergeAgentRows, toAgentRow } from './agents'
6import { drawAgentLine } from './agentline'
7import { drawBand } from './band'
8import { clean } from './format'
9import { EMPTY_MODEL, addAnswer, keepSelection, resolveModel, selectModel } from './model'
10import { DEFAULT_COLUMNS, HOST_INSET, drawStatusLine } from './statusline'
11import { parseGitStatus } from './workspace'
12
13const cacheAtom = atom({ plugin: 'meter', key: 'cache' } as const, null)
14const measureAtom = atom({ plugin: 'meter', key: 'measure' } as const, null)
15const nowAtom = atom({ plugin: 'meter', key: 'now' } as const, 0)
16
17const EMPTY_WORKSPACE: WorkspaceState = { cwd: null, home: null, git: null }
18
19const subagentsAtom = atom({ plugin: 'meter', key: 'subagents' } as const, EMPTY_SUBAGENTS)
20const modelAtom = atom({ plugin: 'meter', key: 'model' } as const, EMPTY_MODEL)
21const workspaceAtom = atom({ plugin: 'meter', key: 'workspace' } as const, EMPTY_WORKSPACE)
22
23const GIT_TIMEOUT_MS = 2000
24const TOOL_DEBOUNCE_MS = 1000
25const TREE_TOOLS = new Set(['Bash', 'Edit', 'Write', 'NotebookEdit'])
26
27let modelTicket = 0
28let resetCount = 0
29let workspaceTicket = 0
30let toolTimer: Timer | null = null
31let tickTimer: Timer | null = null
32
33const toMeasure = (m: Measure): Measure => ({
34 context: { tokens: m.context.tokens, window: m.context.window, percent: m.context.percent },
35 rateLimits: m.rateLimits.map(l => ({ kind: clean(l.kind), percentUsed: l.percentUsed, resetsAt: l.resetsAt })),
36 cost: m.cost && { usd: m.cost.usd },
37})
38
39async function refreshModel($: EngineInterface) {
40 const ticket = ++modelTicket
41 const at = await $.clock.now()
42 const id = clean(await $.session.model())
43 if (id.trim() === '' || ticket !== modelTicket) return
44 await update($, modelAtom, m => selectModel(m, id, at))
45}
46
47async function readGit($: EngineInterface, cwd: string): Promise<GitInfo | null> {
48 try {
49 const run = await $.process.run(['git', '--no-optional-locks', 'status', '--porcelain=v2', '--branch'], {
50 cwd,
51 timeoutMs: GIT_TIMEOUT_MS,
52 })
53
54 return run.exitCode === 0 ? parseGitStatus(run.stdout) : null
55 } catch {
56 return null
57 }
58}
59
60async function refreshWorkspace($: EngineInterface) {
61 const ticket = ++workspaceTicket
62 if (!(await $.session.surfaces()).includes('terminal')) return
63 const cwd = clean(await $.session.cwd())
64 const home = (await $.env.get('HOME')) ?? null
65 const git = await readGit($, cwd)
66 if (ticket !== workspaceTicket) return
67 await update($, workspaceAtom, () => ({ cwd, home, git }))
68}
69
70async function refreshAgents($: EngineInterface, resetsAtStart: number) {
71 try {
72 const list = await $.agent.list()
73 if (resetCount !== resetsAtStart) return
74 await update($, subagentsAtom, s => ({ ...s, list: mergeAgentRows(s.list, list.map(toAgentRow)) }))
75 } catch {}
76}
77
78async function recordAgentTool($: EngineInterface, agentId: string, tool: string, startedAt: number, resetsAtStart: number) {
79 try {
80 if (resetCount !== resetsAtStart) return
81 const at = await $.clock.now()
82 await update($, subagentsAtom, s => addAgentTool(s, agentId, tool, startedAt, at))
83 } catch {}
84}
85
86async function resetSession($: EngineInterface) {
87 resetCount++
88 await update($, cacheAtom, () => null)
89 await update($, measureAtom, () => null)
90 await update($, subagentsAtom, () => EMPTY_SUBAGENTS)
91 await update($, modelAtom, keepSelection)
92}
93
94export const register: Register = on => {
95 on('session.start', async ($, e, next) => {
96 try {
97 const usage = await $.session.usage()
98 await update($, measureAtom, () => toMeasure(usage))
99 } catch {}
100 tickTimer?.cancel()
101 tickTimer = $.clock.every(30_000, async () => {
102 const t = await $.clock.now()
103 await update($, nowAtom, () => t)
104 })
105 void refreshModel($).catch(() => {})
106 void refreshWorkspace($).catch(() => {})
107
108 return next(e)
109 })
110
111 on('session.end', async ($, e, next) => {
112 const isReset = e.reason === 'clear' || e.reason === 'resume'
113 if (isReset) await resetSession($)
114 const result = await next(e)
115 if (isReset) void refreshModel($).catch(() => {})
116
117 return result
118 })
119
120 on('turn.start', async ($, e, next) => {
121 void refreshModel($).catch(() => {})
122
123 return next(e)
124 })
125
126 on('command.run', { command: 'model' }, async ($, e, next) => {
127 try {
128 return await next(e)
129 } finally {
130 void refreshModel($).catch(() => {})
131 }
132 })
133
134 on('session.measure', async ($, e, next) => {
135 await update($, measureAtom, () => toMeasure(e))
136
137 return next(e)
138 })
139
140 on('turn.step', async function* ($, e, next) {
141 const agentId = e.agentId
142 const resetsAtStart = resetCount
143 const t0 = await $.clock.now()
144 const result = yield* next(e)
145 const usage = result.usage
146 if (!usage) return result
147 const t1 = await $.clock.now()
148 const effort = e.effort === undefined ? null : String(e.effort)
149 if (resetCount !== resetsAtStart) return result
150 if (agentId === undefined) {
151 await update($, cacheAtom, prev => ({
152 lastRead: usage.cache_read_input_tokens,
153 lastWrite: usage.cache_creation_input_tokens,
154 lastUncached: usage.input_tokens,
155 totalRead: (prev?.totalRead ?? 0) + usage.cache_read_input_tokens,
156 totalWrite: (prev?.totalWrite ?? 0) + usage.cache_creation_input_tokens,
157 totalUncached: (prev?.totalUncached ?? 0) + usage.input_tokens,
158 lastAt: t1,
159 }))
160 await update($, modelAtom, m =>
161 addAnswer(m, {
162 answered: usage.model,
163 requested: e.model,
164 effort,
165 requestedAt: t0,
166 }),
167 )
168
169 return result
170 }
171 const id = clean(agentId)
172 const seen = await read($, subagentsAtom)
173 const isNew = (seen.activity[id]?.requests ?? 0) === 0 && !seen.list.some(row => row.id === id)
174 await update($, subagentsAtom, s => addAgentStep(s, agentId, { usage, requested: e.model, effort, startedAt: t0, at: t1 }))
175 if (isNew) void refreshAgents($, resetsAtStart)
176
177 return result
178 })
179
180 on('turn.complete', async ($, e, next) => {
181 const resetsAtStart = resetCount
182 const result = await next(e)
183 if (e.agentId === undefined) void refreshWorkspace($).catch(() => {})
184 else void refreshAgents($, resetsAtStart)
185
186 return result
187 })
188
189 on('tool.call', async ($, e, next) => {
190 const t0 = await $.clock.now()
191 const resetsAtStart = resetCount
192 try {
193 return await next(e)
194 } finally {
195 if (e.agentId !== undefined) await recordAgentTool($, e.agentId, e.tool, t0, resetsAtStart)
196 if (e.tool === 'Agent') void refreshAgents($, resetsAtStart)
197 if (TREE_TOOLS.has(e.tool)) {
198 toolTimer?.cancel()
199 toolTimer = $.clock.after(TOOL_DEBOUNCE_MS, () => {
200 toolTimer = null
201 void refreshWorkspace($).catch(() => {})
202 })
203 }
204 }
205 })
206
207 on('classic.CwdChanged', async ($, e, next) => {
208 const result = await next(e)
209 void refreshWorkspace($).catch(() => {})
210
211 return result
212 })
213
214 on('ui.render', { component: 'PromptHint' }, async ($, e, next) => {
215 const engine = await next(e)
216 if (e.surface !== 'terminal') return engine
217 const columns = (e.viewport?.columns ?? DEFAULT_COLUMNS) - 2 * HOST_INSET
218 const els = $.ui.resolve(e)
219 const model = resolveModel(await read($, modelAtom))
220 const workspace = await read($, workspaceAtom)
221 const measure = await read($, measureAtom)
222 await read($, nowAtom)
223 const now = await $.clock.now()
224 const line = drawStatusLine(els, { model, workspace, measure, now }, columns)
225 if (!line) return engine
226 const { Box } = els
227
228 return (
229 <Box key="statusline-hint" flexDirection="column">
230 {line}
231 {engine}
232 </Box>
233 )
234 })
235
236 on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
237 if (e.surface !== 'desktop' && e.surface !== 'terminal') return next(e)
238 if (e.props.hasSurvey) return next(e)
239 const agentId = e.props.view?.agentId
240 if (agentId !== undefined) {
241 const stats = await read($, subagentsAtom)
242 await read($, nowAtom)
243 const live = await $.agent.list().catch(() => null)
244 const now = await $.clock.now()
245
246 return drawAgentLine($.ui.resolve(e), e.surface, agentView(agentId, live, stats), { bodyColumns: e.props.bodyColumns, now })
247 }
248 if (e.surface !== 'desktop') return next(e)
249
250 const measure = await read($, measureAtom)
251 const cache = await read($, cacheAtom)
252 const model = await read($, modelAtom)
253 await read($, nowAtom)
254 const now = await $.clock.now()
255 const tree = drawBand(
256 $.ui.resolve(e),
257 { measure, cache, model: resolveModel(model) },
258 { bodyColumns: e.props.bodyColumns, now, isWorking: e.props.isWorking },
259 )
260
261 return tree ?? next(e)
262 })
263}
264hooks/agents.ts 90 lines1import type { AgentInfo } from 'claude-code'
2
3import type { AgentActivity, AgentRow, SubagentStats } from '../types'
4import { clean } from './format'
5
6export type StepUsage = {
7 input_tokens: number
8 output_tokens: number
9 cache_read_input_tokens: number
10 cache_creation_input_tokens: number
11 model: string
12}
13export type AgentStep = { usage: StepUsage; requested: string; effort: string | null; startedAt: number; at: number }
14export type AgentView = { id: string; row: AgentRow | null; activity: AgentActivity | null }
15
16const ACTIVITY_MAX = 50
17const LIST_MAX = 50
18
19export const EMPTY_SUBAGENTS: SubagentStats = { activity: {}, list: [] }
20
21const blank = (at: number): AgentActivity => ({
22 firstAt: at,
23 lastAt: at,
24 model: null,
25 context: null,
26 output: 0,
27 requests: 0,
28 tools: 0,
29 lastTool: null,
30})
31
32const touch = (
33 s: SubagentStats,
34 agentId: string,
35 startedAt: number,
36 at: number,
37 fn: (a: AgentActivity) => AgentActivity,
38): SubagentStats => {
39 const id = clean(agentId)
40 const activity = { ...s.activity, [id]: { ...fn(s.activity[id] ?? blank(startedAt)), lastAt: at } }
41 const ids = Object.keys(activity)
42 if (ids.length > ACTIVITY_MAX) {
43 const oldest = ids.reduce((m, k) => (activity[k]!.lastAt < activity[m]!.lastAt ? k : m))
44 delete activity[oldest]
45 }
46
47 return { ...s, activity }
48}
49
50export const addAgentStep = (s: SubagentStats, agentId: string, step: AgentStep): SubagentStats =>
51 touch(s, agentId, step.startedAt, step.at, a => ({
52 ...a,
53 model: { answered: clean(step.usage.model), requested: clean(step.requested), effort: step.effort === null ? null : clean(step.effort) },
54 context: step.usage.input_tokens + step.usage.cache_read_input_tokens + step.usage.cache_creation_input_tokens,
55 output: a.output + step.usage.output_tokens,
56 requests: a.requests + 1,
57 }))
58
59export const addAgentTool = (s: SubagentStats, agentId: string, tool: string, startedAt: number, at: number): SubagentStats =>
60 touch(s, agentId, startedAt, at, a => ({ ...a, tools: a.tools + 1, lastTool: clean(tool) }))
61
62export const toAgentRow = (row: AgentInfo): AgentRow => ({
63 id: clean(row.id),
64 type: clean(row.type),
65 description: clean(row.description),
66 status: clean(row.status),
67 ...(row.name !== undefined && { name: clean(row.name) }),
68})
69
70export const mergeAgentRows = (prev: readonly AgentRow[], fresh: readonly AgentRow[]): AgentRow[] => {
71 const ids = new Set(fresh.map(r => r.id))
72
73 return [...prev.filter(r => !ids.has(r.id)), ...fresh].slice(-LIST_MAX)
74}
75
76export const ENDED = new Set(['completed', 'failed', 'killed'])
77
78export const agentView = (agentId: string, live: readonly AgentInfo[] | null, s: SubagentStats): AgentView => {
79 const id = clean(agentId)
80 const fromLive = live?.find(r => clean(r.id) === id)
81 const stored = s.list.find(r => r.id === id)
82 const row = fromLive
83 ? toAgentRow(fromLive)
84 : stored && live !== null && !ENDED.has(stored.status)
85 ? { ...stored, status: 'completed' }
86 : (stored ?? null)
87
88 return { id, row, activity: s.activity[id] ?? null }
89}
90hooks/agentline.tsx 106 lines1import type { RenderElement } from 'claude-code'
2
3import { ENDED, type AgentView } from './agents'
4import { type Els, type Run, type Surface, dimRun } from './draw'
5import { fmtSpan, fmtTokens, shortId } from './format'
6import { resolveAnswer } from './model'
7import { type Segment, cut, drawRow, fitRow, levelsFrom, modelRuns } from './row'
8
9type AgentLevel = {
10 gap: number
11 description: number | null
12 lastTool: boolean
13 effort: boolean
14 fallbackFrom: boolean
15 elapsed: boolean
16 statusWord: boolean
17 tools: boolean
18}
19
20const FULL: AgentLevel = {
21 gap: 3,
22 description: 40,
23 lastTool: true,
24 effort: true,
25 fallbackFrom: true,
26 elapsed: true,
27 statusWord: true,
28 tools: true,
29}
30
31const LEVELS = levelsFrom(FULL, [
32 {},
33 { gap: 2 },
34 { description: 20 },
35 { lastTool: false },
36 { description: null },
37 { effort: false, fallbackFrom: false },
38 { elapsed: false },
39 { statusWord: false },
40 { tools: false },
41])
42
43const TERMINAL_INSET = 2
44const LAST_TOOL_MAX = 24
45
46const IDLE_LOOK: { dot: Partial<Run>; word: Partial<Run> } = { dot: { dim: true }, word: { dim: true } }
47const LOOKS: Record<string, { dot: Partial<Run>; word: Partial<Run> }> = {
48 running: { dot: { color: 'success' }, word: {} },
49 waiting: { dot: { color: 'warning' }, word: {} },
50 failed: { dot: { color: 'error' }, word: { color: 'error' } },
51 killed: { dot: { color: 'warning' }, word: { dim: true } },
52}
53
54export const agentSegments = (v: AgentView, level: AgentLevel, now: number): Segment[] => {
55 const segments: Segment[] = []
56 const { row, activity } = v
57
58 const label = row ? row.name || row.type : ''
59 if (row && label !== '') {
60 const runs: Run[] = [{ text: label, bold: true }]
61 if (level.description !== null && row.description !== '') runs.push({ text: ` ${cut(row.description, level.description)}`, dim: true })
62 segments.push({ key: 'who', runs })
63 } else {
64 segments.push({ key: 'who', runs: [dimRun('Agent '), { text: shortId(v.id) }] })
65 }
66
67 if (row) {
68 const look = Object.hasOwn(LOOKS, row.status) ? LOOKS[row.status]! : IDLE_LOOK
69 const runs: Run[] = [{ text: '●', ...look.dot }]
70 if (level.statusWord) runs.push({ text: ` ${row.status}`, ...look.word })
71 segments.push({ key: 'status', runs })
72 }
73
74 if (activity?.model) {
75 segments.push({
76 key: 'model',
77 runs: modelRuns(resolveAnswer(activity.model), { isBold: false, effort: level.effort, fallbackFrom: level.fallbackFrom }),
78 })
79 }
80
81 if (activity && typeof activity.context === 'number') {
82 segments.push({ key: 'ctx', runs: [dimRun('Ctx '), { text: fmtTokens(activity.context) }] })
83 }
84
85 if (level.tools && activity && activity.tools > 0) {
86 const n = activity.tools
87 const runs: Run[] = [{ text: `${n} tool${n === 1 ? '' : 's'}` }]
88 if (level.lastTool && activity.lastTool !== null) runs.push({ text: ` · ${cut(activity.lastTool, LAST_TOOL_MAX)}`, dim: true })
89 segments.push({ key: 'tools', runs })
90 }
91
92 if (level.elapsed && activity) {
93 const end = row && ENDED.has(row.status) ? activity.lastAt : now
94 segments.push({ key: 'elapsed', runs: [{ text: fmtSpan(Math.max(0, end - activity.firstAt)), dim: true }] })
95 }
96
97 return segments
98}
99
100export const drawAgentLine = (els: Els, surface: Surface, v: AgentView, opts: { bodyColumns: number; now: number }): RenderElement => {
101 const build = (level: AgentLevel) => agentSegments(v, level, opts.now)
102 if (surface === 'desktop') return drawRow(els, 'meter-agent', { segments: build(FULL), gap: FULL.gap }, 'wrap')
103
104 return drawRow(els, 'meter-agent', fitRow(LEVELS, build, opts.bodyColumns - TERMINAL_INSET), 'nowrap', { marginTop: 1, paddingLeft: TERMINAL_INSET })
105}
106hooks/band.tsx 144 lines1import type { Elements, RenderElement } from 'claude-code'
2
3import type { CacheStats, Measure, ResolvedModel } from '../types'
4import { type Run, dimRun, drawGauge, runsText, toneRun } from './draw'
5import { type Tone, cacheState, fmtCost, fmtDuration, fmtSpan, fmtTokens, hitRate, hitTone, limitLabel, limitTone, loadTone, resetIn } from './format'
6
7type BandData = { measure: Measure | null; cache: CacheStats | null; model: ResolvedModel | null }
8type BandOpts = { bodyColumns: number; now: number; isWorking: boolean }
9
10type Item =
11 | { key: string; runs: Run[] }
12 | { key: string; gauge: { pct: number; tone: Tone; px: number }; alt: string }
13type Segment = { key: string; items: Item[] }
14
15type Detail = { limitGauges: boolean }
16
17const CTX_PX = 56
18const LIMIT_PX = 36
19const DESKTOP_LIMIT_GAUGES = 80
20
21const desktopDetail = (cols: number): Detail => ({ limitGauges: cols >= DESKTOP_LIMIT_GAUGES })
22
23const text = (key: string, ...runs: Run[]): Item => ({ key, runs })
24const label = (name: string) => text('label', dimRun(name))
25
26const buildSegments = (data: BandData, detail: Detail, opts: BandOpts): Segment[] => {
27 const { measure, cache } = data
28 const segments: Segment[] = []
29
30 const ctx = measure?.context
31 if (ctx) {
32 const pct = ctx.percent
33 const items: Item[] = [label('Context')]
34 if (pct === undefined) {
35 items.push(text('v', dimRun(`${fmtTokens(ctx.window)} window`)))
36 } else {
37 const tone = loadTone(pct)
38 items.push({ key: 'bar', gauge: { pct, tone, px: CTX_PX }, alt: `Context ${pct}%` })
39 items.push(text('v', toneRun(`${pct}%`, tone)))
40 }
41 segments.push({ key: 'ctx', items })
42 }
43
44 if (cache) {
45 const hit = hitRate(cache.lastRead, cache.lastWrite, cache.lastUncached)
46 const state = cacheState(cache.lastAt, opts.now, opts.isWorking)
47 const value = hit === null ? text('v', dimRun('-')) : text('v', toneRun(`${hit}%`, hitTone(hit)), dimRun(' hit'))
48 segments.push({
49 key: 'cache',
50 items: [label('Cache'), value, text('s', { text: '●', color: state.dot }, dimRun(` ${state.text}`))],
51 })
52 }
53
54 for (const l of measure?.rateLimits ?? []) {
55 const name = limitLabel(l.kind)
56 const pct = Math.round(l.percentUsed)
57 const left = resetIn(l, opts.now)
58 const tone = limitTone(l, opts.now)
59 const items: Item[] = [label(name)]
60 if (detail.limitGauges) {
61 items.push({ key: 'bar', gauge: { pct, tone, px: LIMIT_PX }, alt: `${name} limit ${pct}%` })
62 }
63 items.push(text('v', toneRun(`${pct}%`, tone)))
64 if (left > 0) items.push(text('r', dimRun(`↻ ${fmtSpan(left)}`)))
65 segments.push({ key: `limit-${l.kind}`, items })
66 }
67
68 if (measure?.cost) segments.push({ key: 'cost', items: [text('v', { text: fmtCost(measure.cost.usd) })] })
69
70 return segments
71}
72
73const bandDetails = (data: BandData, now: number): [string, string][] => {
74 const { measure, cache, model } = data
75 const details: [string, string][] = []
76 const ctx = measure?.context
77 if (model) {
78 const parts = [model.name]
79 if (model.fallbackFrom) parts.push(`fallback from ${model.fallbackFrom}`)
80 if (model.effort) parts.push(`${model.effort} effort`)
81 if (model.id !== model.name) parts.push(model.id)
82 details.push(['Model', parts.join(' · ')])
83 }
84 if (ctx?.tokens !== undefined) {
85 details.push(['Context', `${ctx.tokens.toLocaleString()} of ${ctx.window.toLocaleString()} tokens`])
86 }
87 if (cache) {
88 const { idle, ttlLeft } = cacheState(cache.lastAt, now, false)
89 details.push(['Last request', `${fmtTokens(cache.lastRead)} read · ${fmtTokens(cache.lastWrite)} written · ${fmtTokens(cache.lastUncached)} uncached`])
90 const sess = hitRate(cache.totalRead, cache.totalWrite, cache.totalUncached)
91 details.push(['Session cache', `${sess ?? '-'}% hit · ${fmtTokens(cache.totalRead)} read · ${fmtTokens(cache.totalWrite)} written`])
92 details.push(['Cache TTL', ttlLeft > 0 ? `~${fmtDuration(ttlLeft)} left (idle ${fmtDuration(idle)}, assumes 1h)` : `expired ${fmtDuration(-ttlLeft)} ago`])
93 }
94 for (const l of measure?.rateLimits ?? []) {
95 if (l.resetsAt && Date.parse(l.resetsAt) > now) {
96 const at = new Date(l.resetsAt)
97 details.push([`${limitLabel(l.kind)} limit`, `${Math.round(l.percentUsed)}% used · resets ${at.toLocaleString(undefined, { weekday: 'short', hour: 'numeric', minute: '2-digit' })}`])
98 }
99 }
100
101 return details
102}
103
104export const drawBand = (els: Elements['desktop'], data: BandData, opts: BandOpts): RenderElement | null => {
105 const { Box, Text, Svg } = els
106 if (!data.measure && !data.cache) return null
107
108 const segments = buildSegments(data, desktopDetail(opts.bodyColumns), opts)
109 if (segments.length === 0) return null
110
111 const details = bandDetails(data, opts.now)
112 const labelWidth = Math.max(...details.map(([k]) => k.length))
113
114 const card =
115 details.length === 0 ? null : (
116 <Box key="card" display="none" hover={{ display: 'flex', scope: 'meter' }} flexDirection="column" marginBottom={1}>
117 {details.map(([k, v]) => (
118 <Box key={k} columnGap={2}>
119 <Box width={labelWidth + 1}>
120 <Text dimColor>{k}</Text>
121 </Box>
122 <Text>{v}</Text>
123 </Box>
124 ))}
125 </Box>
126 )
127
128 const draw = (item: Item) =>
129 'gauge' in item ? drawGauge(Svg, item.key, item.gauge.pct, item.gauge.tone, item.gauge.px, item.alt) : runsText(Text, item.key, item.runs)
130
131 return (
132 <Box key="meter" flexDirection="column" hover={{ scope: 'meter' }}>
133 {card}
134 <Box key="row" flexWrap="wrap" alignItems="center" columnGap={3}>
135 {segments.map(s => (
136 <Box key={s.key} alignItems="center" columnGap={1}>
137 {s.items.map(draw)}
138 </Box>
139 ))}
140 </Box>
141 </Box>
142 )
143}
144hooks/format.ts 63 lines1export const SVG_COLORS: Record<'warning' | 'error', string> = { warning: '#c98a1b', error: '#d0544a' }
2
3export const fmtTokens = (n: number) =>
4 Math.round(n / 1000) >= 1000 ? `${(n / 1_000_000).toFixed(1)}M` : n >= 1000 ? `${Math.round(n / 1000)}k` : `${n}`
5
6export const fmtDuration = (ms: number) => {
7 const m = Math.max(0, Math.round(ms / 60000))
8 if (m < 60) return `${m}m`
9 const h = Math.floor(m / 60)
10 if (h < 24) return m % 60 ? `${h}h ${m % 60}m` : `${h}h`
11 return h % 24 ? `${Math.floor(h / 24)}d ${h % 24}h` : `${Math.floor(h / 24)}d`
12}
13
14export const fmtCost = (usd: number) => `$${usd.toFixed(2)}`
15
16export const fmtSpan = (ms: number) => (ms < 60_000 ? '<1m' : fmtDuration(ms))
17
18export type Tone = 'rest' | 'idle' | 'warning' | 'error'
19
20export const loadTone = (pct: number): Tone => (pct >= 80 ? 'error' : pct >= 50 ? 'warning' : 'rest')
21export const resetIn = (l: { resetsAt?: string }, now: number) => (l.resetsAt ? Date.parse(l.resetsAt) - now : NaN)
22
23export const limitTone = (l: { percentUsed: number; resetsAt?: string }, now: number): Tone => {
24 const left = resetIn(l, now)
25
26 return Number.isFinite(left) && left <= 0 ? 'idle' : loadTone(Math.round(l.percentUsed))
27}
28
29export const hitTone = (pct: number): Tone => (pct < 40 ? 'error' : pct < 80 ? 'warning' : 'rest')
30
31const CACHE_TTL_MS = 60 * 60 * 1000
32const CACHE_WARN_MS = 10 * 60000
33
34export const cacheState = (lastAt: number, now: number, isWorking: boolean) => {
35 const idle = Math.max(0, now - lastAt)
36 const ttlLeft = CACHE_TTL_MS - idle
37 const state = isWorking
38 ? { dot: 'success', text: 'live', short: 'live' }
39 : ttlLeft > 0
40 ? { dot: ttlLeft < CACHE_WARN_MS ? 'warning' : 'success', text: `warm ${fmtDuration(ttlLeft)}`, short: fmtDuration(ttlLeft) }
41 : { dot: 'error', text: 'cold', short: 'cold' }
42
43 return { idle, ttlLeft, ...state }
44}
45
46export const hitRate = (read: number, write: number, uncached: number) => {
47 const total = read + write + uncached
48 return total === 0 ? null : Math.round((read / total) * 100)
49}
50
51export const limitLabel = (kind: string) =>
52 kind === 'five_hour' ? '5h' : kind === 'seven_day' ? 'Week' : kind === 'spend_limit' ? 'Spend' : kind
53
54const CONTROL = /[\u0000-\u001f\u007f-\u009f]/g
55
56export const clean = (s: string) => {
57 const cut = s.replace(CONTROL, ' ').slice(0, 200)
58 const last = cut.charCodeAt(cut.length - 1)
59 return last >= 0xd800 && last <= 0xdbff ? cut.slice(0, -1) : cut
60}
61
62export const shortId = (id: string) => (id.length > 20 ? `${id.slice(0, 8)}…${id.slice(-6)}` : id)
63hooks/model.ts 63 lines1import type { ModelState, ResolvedModel } from '../types'
2import { clean } from './format'
3
4const capitalize = (s: string) => `${s[0]!.toUpperCase()}${s.slice(1).toLowerCase()}`
5
6export const modelName = (id: string) => {
7 const versioned = /(opus|sonnet|haiku|fable)-(\d{1,2})(?:-(\d{1,2})(?!\d)|(?=$|\[|-(?:\d{8}(?!\d)|v\d)))/i.exec(id)
8 if (versioned) return `${capitalize(versioned[1]!)} ${versioned[2]}${versioned[3] === undefined ? '' : `.${versioned[3]}`}`
9 const alias = /^(opus|sonnet|haiku|fable)(?:\[[^\]]*\])?$/i.exec(id)
10 if (alias) return capitalize(alias[1]!)
11
12 return id.replace(/\[[^\]]*\]$/, '').replace(/-\d{8}$/, '')
13}
14
15export const EMPTY_MODEL: ModelState = {
16 selected: null,
17 selectedAt: 0,
18 answered: null,
19 requested: null,
20 effort: null,
21 answeredRequestedAt: 0,
22}
23
24export const selectModel = (m: ModelState, id: string, at: number): ModelState =>
25 m.selected === id ? m : { ...m, selected: id, selectedAt: at }
26
27export type Answer = { answered: string; requested: string; effort: string | null; requestedAt: number }
28
29export const addAnswer = (m: ModelState, a: Answer): ModelState => ({
30 ...m,
31 answered: clean(a.answered),
32 requested: clean(a.requested),
33 effort: a.effort === null ? null : clean(a.effort),
34 answeredRequestedAt: a.requestedAt,
35})
36
37export const keepSelection = (m: ModelState): ModelState => ({
38 ...EMPTY_MODEL,
39 selected: m.selected,
40 selectedAt: m.selectedAt,
41})
42
43const answerWins = (m: ModelState) =>
44 m.answered !== null &&
45 (m.selected === null ||
46 m.answeredRequestedAt >= m.selectedAt ||
47 (m.requested !== null && modelName(m.requested) === modelName(m.selected)))
48
49export const resolveAnswer = (a: { answered: string; requested: string | null; effort: string | null }): ResolvedModel => {
50 const name = modelName(a.answered)
51 const requested = a.requested === null ? null : modelName(a.requested)
52
53 return { name, id: a.answered, fallbackFrom: requested !== null && requested !== name ? requested : null, effort: a.effort }
54}
55
56export const resolveModel = (m: ModelState): ResolvedModel | null => {
57 if (m.answered !== null && answerWins(m)) {
58 return resolveAnswer({ answered: m.answered, requested: m.requested, effort: m.effort })
59 }
60
61 return m.selected === null ? null : { name: modelName(m.selected), id: m.selected, fallbackFrom: null, effort: null }
62}
63hooks/statusline.tsx 97 lines1import type { RenderElement } from 'claude-code'
2
3import type { Measure, ResolvedModel, WorkspaceState } from '../types'
4import { type Els, type Run, dimRun, toneRun } from './draw'
5import { fmtCost, fmtSpan, limitLabel, limitTone, loadTone, resetIn } from './format'
6import { type Segment, cut, drawRow, fitRow, levelsFrom, modelRuns } from './row'
7import { basename, shortenPath, splitPath } from './workspace'
8
9type StatusLevel = {
10 gap: number
11 path: number | 'base' | null
12 effort: boolean
13 fallbackFrom: boolean
14 branchMax: number
15 cost: boolean
16 resets: boolean
17 limits: 'all' | 'hot' | 'none'
18 ctx: boolean
19}
20export type StatusData = { model: ResolvedModel | null; workspace: WorkspaceState; measure: Measure | null; now: number }
21
22export const HOST_INSET = 2
23export const DEFAULT_COLUMNS = 80
24
25const FULL: StatusLevel = { gap: 3, path: 48, effort: true, fallbackFrom: true, branchMax: 48, cost: true, resets: true, limits: 'all', ctx: true }
26
27const STEPS: Partial<StatusLevel>[] = [
28 {},
29 { gap: 2 },
30 { cost: false },
31 { path: 28 },
32 { limits: 'hot' },
33 { resets: false },
34 { path: 'base' },
35 { effort: false, fallbackFrom: false },
36 { branchMax: 24 },
37 { path: null },
38 { limits: 'none' },
39 { branchMax: 12 },
40 { ctx: false },
41]
42
43const LEVELS = levelsFrom(FULL, STEPS)
44
45const statusSegments = (d: StatusData, level: StatusLevel): Segment[] => {
46 const { model, workspace: ws } = d
47 const segments: Segment[] = []
48
49 if (model && model.name !== '') {
50 segments.push({ key: 'model', runs: modelRuns(model, { isBold: true, effort: level.effort, fallbackFrom: level.fallbackFrom }) })
51 }
52
53 if (ws.cwd !== null && ws.cwd !== '' && level.path !== null) {
54 const shown =
55 level.path === 'base' ? basename(shortenPath(ws.cwd, ws.home, Infinity)) : shortenPath(ws.cwd, ws.home, level.path)
56 const { parent, base } = splitPath(shown)
57 const runs: Run[] = []
58 if (parent !== '') runs.push({ text: parent, dim: true })
59 runs.push({ text: base })
60 segments.push({ key: 'path', runs })
61 }
62
63 if (ws.git !== null) {
64 const g = ws.git
65 const runs: Run[] = [{ text: cut(g.head, level.branchMax), color: g.isDetached ? 'warning' : undefined }]
66 if (g.isDirty) runs.push({ text: ' ' }, { text: '●' })
67 if (g.ahead > 0 || g.behind > 0) {
68 runs.push({ text: ' ' })
69 if (g.ahead > 0) runs.push({ text: `↑${g.ahead}` })
70 if (g.behind > 0) runs.push({ text: `↓${g.behind}`, color: 'warning' })
71 }
72 segments.push({ key: 'git', runs })
73 }
74
75 const pct = d.measure?.context.percent
76 if (level.ctx && pct !== undefined) segments.push({ key: 'ctx', runs: [dimRun('Ctx '), toneRun(`${pct}%`, loadTone(pct))] })
77
78 for (const l of d.measure?.rateLimits ?? []) {
79 const tone = limitTone(l, d.now)
80 if (level.limits === 'none' || (level.limits === 'hot' && tone !== 'warning' && tone !== 'error')) continue
81 const runs: Run[] = [dimRun(`${limitLabel(l.kind)} `), toneRun(`${Math.round(l.percentUsed)}%`, tone)]
82 const left = resetIn(l, d.now)
83 if (level.resets && left > 0) runs.push(dimRun(` ↻ ${fmtSpan(left)}`))
84 segments.push({ key: `limit-${l.kind}`, runs })
85 }
86
87 if (level.cost && d.measure?.cost) segments.push({ key: 'cost', runs: [{ text: fmtCost(d.measure.cost.usd) }] })
88
89 return segments
90}
91
92export const drawStatusLine = (els: Els, d: StatusData, columns: number): RenderElement | null => {
93 const row = fitRow(LEVELS, level => statusSegments(d, level), columns)
94
95 return row.segments.length === 0 ? null : drawRow(els, 'statusline', row, 'nowrap', { marginTop: 1 })
96}
97hooks/workspace.ts 57 lines1import type { GitInfo } from '../types'
2import { clean } from './format'
3
4const SHORT_SHA = 7
5
6export const shortenPath = (cwd: string, home: string | null, max: number): string => {
7 const root = home === null ? '' : home.replace(/\/+$/, '')
8 const shown = root !== '' && (cwd === root || cwd.startsWith(`${root}/`)) ? `~${cwd.slice(root.length)}` : cwd
9 if (shown.length <= max) return shown
10
11 const segments = shown.split('/').filter(Boolean)
12 let kept = segments.slice(-1)
13 for (let i = segments.length - 2; i >= 0; i--) {
14 const next = [segments[i]!, ...kept]
15 if (`…/${next.join('/')}`.length > max) break
16 kept = next
17 }
18
19 return `…/${kept.join('/')}`
20}
21
22export const splitPath = (shown: string): { parent: string; base: string } => {
23 if (shown === '~' || shown === '/') return { parent: '', base: shown }
24 const cut = shown.lastIndexOf('/') + 1
25
26 return { parent: shown.slice(0, cut), base: shown.slice(cut) }
27}
28
29export const basename = (shown: string) => splitPath(shown).base
30
31export const parseGitStatus = (stdout: string): GitInfo | null => {
32 let oid = ''
33 let head = ''
34 let ahead = 0
35 let behind = 0
36 let isDirty = false
37 for (const line of stdout.split('\n')) {
38 if (line === '') continue
39 if (!line.startsWith('# ')) {
40 isDirty = true
41 continue
42 }
43 const [key, ...rest] = line.slice(2).split(' ')
44 if (key === 'branch.oid') oid = rest.join(' ')
45 else if (key === 'branch.head') head = rest.join(' ')
46 else if (key === 'branch.ab') {
47 ahead = Number(/^\+(\d+)$/.exec(rest[0] ?? '')?.[1] ?? 0)
48 behind = Number(/^-(\d+)$/.exec(rest[1] ?? '')?.[1] ?? 0)
49 }
50 }
51 const isDetached = head === '(detached)'
52 const name = isDetached ? `@${oid.slice(0, SHORT_SHA)}` : head
53 if (name === '' || name === '@') return null
54
55 return { head: clean(name), isDetached, isDirty, ahead, behind }
56}
57hooks/draw.tsx 30 lines1import type { Color, Elements } from 'claude-code'
2
3import type { Tone } from './format'
4import { gaugeSvg } from './svg'
5
6export type Els = Elements['terminal'] | Elements['desktop']
7export type Surface = 'terminal' | 'desktop'
8export type Run = { text: string; color?: Color; dim?: boolean; bold?: boolean }
9
10export const textWidth = (s: string) => [...s].length
11export const runsWidth = (runs: readonly Run[]) => runs.reduce((n, r) => n + textWidth(r.text), 0)
12export const dimRun = (text: string): Run => ({ text, dim: true })
13export const toneRun = (text: string, tone: Tone): Run =>
14 tone === 'rest' ? { text, bold: false } : tone === 'idle' ? { text, dim: true, bold: false } : { text, color: tone, bold: true }
15
16export const runText = (Text: Els['Text'], key: string, r: Run) => (
17 <Text key={key} color={r.color} dimColor={r.dim} bold={r.bold}>
18 {r.text}
19 </Text>
20)
21
22export const runsText = (Text: Els['Text'], key: string, runs: readonly Run[]) =>
23 runs.length === 1 ? runText(Text, key, runs[0]!) : <Text key={key}>{runs.map((r, i) => runText(Text, `r${i}`, r))}</Text>
24
25export const drawGauge = (Svg: Elements['desktop']['Svg'], key: string, pct: number, tone: Tone, px: number, alt: string, height = 6) => {
26 const doc = gaugeSvg(pct, tone, alt, px, height)
27
28 return <Svg key={key} source={doc.source} width={doc.width} height={doc.height} alt={doc.alt} />
29}
30hooks/row.tsx 54 lines1import type { RenderElement } from 'claude-code'
2
3import type { ResolvedModel } from '../types'
4import { type Els, type Run, runText, runsWidth, textWidth } from './draw'
5
6export type Segment = { key: string; runs: Run[] }
7export type Row = { segments: Segment[]; gap: number }
8
9export const cut = (s: string, max: number) => (textWidth(s) <= max ? s : `${[...s].slice(0, max - 1).join('')}…`)
10
11export const levelsFrom = <L,>(full: L, steps: readonly Partial<L>[]): L[] =>
12 steps.reduce<L[]>((levels, step) => [...levels, { ...(levels.at(-1) ?? full), ...step }], [])
13
14const rowWidth = (segments: readonly Segment[], gap: number) =>
15 segments.reduce((n, s) => n + runsWidth(s.runs), 0) + gap * Math.max(0, segments.length - 1)
16
17export const fitRow = <L extends { gap: number }>(levels: readonly L[], build: (level: L) => Segment[], columns: number): Row => {
18 for (const level of levels) {
19 const segments = build(level)
20 if (rowWidth(segments, level.gap) <= columns) return { segments, gap: level.gap }
21 }
22 const floor = levels.at(-1)!
23
24 return { segments: build(floor), gap: floor.gap }
25}
26
27export const modelRuns = (model: ResolvedModel, o: { isBold: boolean; effort: boolean; fallbackFrom: boolean }): Run[] => {
28 const bold = o.isBold ? { bold: true } : {}
29 if (model.fallbackFrom !== null) {
30 return [
31 { text: model.name, color: 'warning', ...bold },
32 { text: o.fallbackFrom ? ` fallback from ${model.fallbackFrom}` : ' fallback', dim: true },
33 ]
34 }
35 const runs: Run[] = [{ text: model.name, ...bold }]
36 if (o.effort && model.effort !== null && model.effort !== '') runs.push({ text: ` ${model.effort}`, dim: true })
37
38 return runs
39}
40
41export const drawRow = (els: Els, key: string, row: Row, flexWrap: 'wrap' | 'nowrap', box: { marginTop?: number; paddingLeft?: number } = {}): RenderElement => {
42 const { Box, Text } = els
43
44 return (
45 <Box key={key} marginTop={box.marginTop} paddingLeft={box.paddingLeft} columnGap={row.gap} flexWrap={flexWrap}>
46 {row.segments.map(s => (
47 <Text key={s.key} wrap="truncate-end">
48 {s.runs.map((r, i) => runText(Text, `r${i}`, r))}
49 </Text>
50 ))}
51 </Box>
52 )
53}
54hooks/svg.ts 23 lines1import { SVG_COLORS, type Tone } from './format'
2
3export type SvgDoc = { source: string; width: number; height: number; alt: string }
4
5const NEUTRAL = 'rgba(128,128,128,0.28)'
6const IDLE_FILL = 'rgba(128,128,128,0.6)'
7const PALETTE_STYLE = '<style>.s1{fill:#2a78d6}@media (prefers-color-scheme: dark){.s1{fill:#3987e5}}</style>'
8
9const wrap = (width: number, height: number, body: string, hasPalette: boolean): string =>
10 `<svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="${height}" viewBox="0 0 ${width} ${height}">${hasPalette ? PALETTE_STYLE : ''}${body}</svg>`
11
12const toneFill = (tone: Tone) =>
13 tone === 'rest' ? ' class="s1"' : tone === 'idle' ? ` fill="${IDLE_FILL}"` : ` fill="${SVG_COLORS[tone]}"`
14
15export const gaugeSvg = (pct: number, tone: Tone, alt: string, width = 160, height = 6): SvgDoc => {
16 const ratio = Math.min(Math.max(pct, 0), 100) / 100
17 const fill = ratio === 0 ? 0 : Math.max(3, Math.round(ratio * width))
18 const rx = height / 2
19 const body = `<rect width="${width}" height="${height}" rx="${rx}" fill="${NEUTRAL}"/><rect width="${fill}" height="${height}" rx="${rx}"${toneFill(tone)}/>`
20
21 return { source: wrap(width, height, body, tone === 'rest'), width, height, alt }
22}
23types/index.d.ts 49 lines1export type CacheStats = {
2 lastRead: number
3 lastWrite: number
4 lastUncached: number
5 totalRead: number
6 totalWrite: number
7 totalUncached: number
8 lastAt: number
9}
10
11export type RateLimit = { kind: string; percentUsed: number; resetsAt?: string }
12
13export type Measure = {
14 context: { tokens?: number; window: number; percent?: number }
15 rateLimits: RateLimit[]
16 cost?: { usd: number }
17}
18
19export type ModelState = { selected: string | null; selectedAt: number; answered: string | null; requested: string | null; effort: string | null; answeredRequestedAt: number }
20export type ResolvedModel = { name: string; id: string; fallbackFrom: string | null; effort: string | null }
21export type AgentRow = { id: string; type: string; description: string; status: string; name?: string }
22export type AgentModel = { answered: string; requested: string; effort: string | null }
23export type AgentActivity = {
24 firstAt: number
25 lastAt: number
26 model: AgentModel | null
27 context: number | null
28 output: number
29 requests: number
30 tools: number
31 lastTool: string | null
32}
33export type SubagentStats = { activity: Record<string, AgentActivity>; list: AgentRow[] }
34export type GitInfo = { head: string; isDetached: boolean; isDirty: boolean; ahead: number; behind: number }
35export type WorkspaceState = { cwd: string | null; home: string | null; git: GitInfo | null }
36
37declare module 'claude-code' {
38 interface PluginState {
39 'meter': {
40 cache: CacheStats | null
41 measure: Measure | null
42 now: number
43 model: ModelState
44 workspace: WorkspaceState
45 subagents: SubagentStats
46 }
47 }
48}
49