Band above the prompt showing context %, tools, skills and MCP share of context, and session and weekly limits, with yellow and red usage indicators

A dim band above the prompt:
context 12.0% · tools 3.0% · skills 30 (0.5%) · mcp 15 (0.0%) · session 10.0% (resets at 11:40) · week 5.0% (resets at Wed 00:00)
context, session and week turn yellow from 75.0% and red from 90.0%.tools is the loaded tools' share of the context window; skills and mcp show a count and their share. All come from the engine's local estimate (/context may differ slightly).session is the five-hour rate-limit window and week the seven-day one; both only appear on a subscription.context can be switched off with its show* option.hooks/register.tsx 171 lines1import { atom, update, read } from 'claude-code'
2import type { Segment } from '../types'
3import type { ContextCategory, EngineInterface, Register, SessionContextBreakdown, SessionRateLimit } from 'claude-code'
4
5const text = atom({ plugin: 'usage-band', key: 'text' } as const, null)
6
7// Soft tones, none near the yellow and red of the indicators.
8const COLORS = {
9 context: '#6fc3d6',
10 tools: '#b8bcc8',
11 skills: '#82c796',
12 mcp: '#c58fd9',
13 session: '#7488e0',
14 week: '#8c9eff',
15} as const
16
17// Yellow from 75% and red from 90%, so the label colors keep clear of both.
18const levelOf = (percent: number): 'yellow' | 'red' | undefined => (percent >= 90 ? 'red' : percent >= 75 ? 'yellow' : undefined)
19
20const pct = (tokens: number, window: number): string =>
21 window > 0 ? `${((tokens / window) * 100).toFixed(1)}%` : '–'
22
23/** Schema tokens of the built-in tools and the loaded MCP tools. */
24export type Counted = { tools: number; mcp: number }
25
26export type Show = { tools: boolean; skills: boolean; mcp: boolean; session: boolean; week: boolean }
27
28const ALL: Show = { tools: true, skills: true, mcp: true, session: true, week: true }
29
30const DAYS = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']
31
32// The reset time in local time, led by the weekday when it is not today.
33const clock = (iso: string): string => {
34 const d = new Date(iso)
35 const time = `${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}`
36 return d.toDateString() === new Date().toDateString() ? time : `${DAYS[d.getDay()]} ${time}`
37}
38
39// A rate-limit window as `label 32% (resets at 14:33)`; absent off a subscription.
40function window(limits: readonly SessionRateLimit[], kind: string): Omit<Segment, 'label' | 'color'> | undefined {
41 const w = limits.find(l => l.kind === kind)
42 if (!w) return undefined
43 return {
44 value: `${w.percentUsed.toFixed(1)}%`,
45 level: levelOf(w.percentUsed),
46 note: w.resetsAt ? `(resets at ${clock(w.resetsAt)})` : undefined,
47 }
48}
49
50const windows = (limits: readonly SessionRateLimit[], show: Show): Segment[] => {
51 const out: Segment[] = []
52 const session = show.session ? window(limits, 'five_hour') : undefined
53 const week = show.week ? window(limits, 'seven_day') : undefined
54 if (session) out.push({ label: 'session', ...session, color: COLORS.session })
55 if (week) out.push({ label: 'week', ...week, color: COLORS.week })
56 return out
57}
58
59const isSystemTools = (c: ContextCategory): boolean => c.kind === 'used' && /^system tools/i.test(c.name)
60
61// Tool and MCP schema tokens as a breakdown carries them.
62export const toolTokensOf = (b: SessionContextBreakdown): Counted => ({
63 tools: b.categories.filter(isSystemTools).reduce((s, c) => s + c.tokens, 0),
64 mcp: b.mcpTools.filter(t => t.isLoaded).reduce((s, t) => s + t.tokens, 0),
65})
66
67// Every figure comes from the breakdown. The built-in tools
68// are told apart by the row's name, the one place the engine's labels are read.
69// `counted` replaces the summary's estimated schema tokens with /context's
70// counted ones. Before the first response the total is an estimate too and
71// moves with them; after it the engine has reconciled the total to the API's.
72export function line(
73 percent: number | undefined,
74 b: SessionContextBreakdown | undefined,
75 limits: readonly SessionRateLimit[] = [],
76 show: Show = ALL,
77 counted?: Counted,
78): Segment[] {
79 const tail = windows(limits, show)
80 if (!b) {
81 const p = percent ?? 0
82 return [{ label: 'context', value: `${p.toFixed(1)}%`, level: levelOf(p), color: COLORS.context }, ...tail]
83 }
84
85 const max = b.rawMaxTokens
86 const estimated = toolTokensOf(b)
87 const { tools: toolTokens, mcp: mcpTokens } = counted ?? estimated
88 const total = b.apiUsage ? b.totalTokens : b.totalTokens - estimated.tools - estimated.mcp + toolTokens + mcpTokens
89 const loaded = b.mcpTools.filter(t => t.isLoaded).length
90 const p = max > 0 ? (total / max) * 100 : (percent ?? 0)
91
92 const parts: Segment[] = [{ label: 'context', value: `${p.toFixed(1)}%`, level: levelOf(p), color: COLORS.context }]
93 if (show.tools) parts.push({ label: 'tools', value: pct(toolTokens, max), color: COLORS.tools })
94 if (show.skills) parts.push({ label: 'skills', value: `${b.skills?.includedSkills ?? 0} (${pct(b.skills?.tokens ?? 0, max)})`, color: COLORS.skills })
95 if (show.mcp) parts.push({ label: 'mcp', value: `${loaded}/${b.mcpTools.length} (${pct(mcpTokens, max)})`, color: COLORS.mcp })
96 parts.push(...tail)
97 return parts
98}
99
100// What the tool schemas in the window are: changes when a deferred tool loads
101// or a server connects, and only then is a counted breakdown worth asking for.
102export const toolSetOf = (b: SessionContextBreakdown): string =>
103 [
104 ...b.categories.filter(c => /^system tools/i.test(c.name)).map(c => `${c.kind}:${c.tokens}`),
105 ...b.mcpTools.filter(t => t.isLoaded).map(t => t.name),
106 ].join('|')
107
108// The last counted schema tokens and the tool set they were counted for. A
109// module variable: a reload counts once more.
110let cache: { set: string; counted: Counted } | undefined
111
112async function draw($: EngineInterface, show: Show): Promise<void> {
113 const usage = await $.session.usage({ breakdown: 'summary' })
114 const b = usage.context.breakdown
115 // The summary estimates tool schemas well above what /context counts; count
116 // them as /context does (one request per tool) only when the set changed.
117 if (b && cache?.set !== toolSetOf(b)) {
118 const full = (await $.session.usage({ breakdown: 'full' })).context.breakdown
119 if (full) cache = { set: toolSetOf(b), counted: toolTokensOf(full) }
120 }
121 await update($, text, () => line(usage.context.percent, b, usage.rateLimits, show, cache?.counted))
122}
123
124// An option left unset, or stored as anything but false, stays on.
125export const showOf = (options: Readonly<Record<string, unknown>>): Show => ({
126 tools: options.showTools !== false,
127 skills: options.showSkills !== false,
128 mcp: options.showMcp !== false,
129 session: options.showSession !== false,
130 week: options.showWeek !== false,
131})
132
133export const register: Register = (on, options) => {
134 const show = showOf(options)
135
136 on('session.start', async ($, e, next) => {
137 await draw($, show)
138 return next(e)
139 })
140
141 on('session.measure', async ($, e, next) => {
142 await draw($, show)
143 return next(e)
144 })
145
146 on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
147 const line = await read($, text)
148 if (e.props.hasSurvey || line === null) return next(e)
149
150 const { Box, Text } = $.ui.resolve(e)
151 return (
152 <Box flexDirection="column">
153 <Text dimColor wrap="truncate">
154 {'─'.repeat(500)}
155 </Text>
156 <Text wrap="truncate">
157 {line.map((seg, i) => (
158 <Text key={seg.label}>
159 {i > 0 ? <Text dimColor>{' · '}</Text> : null}
160 <Text color={seg.color}>{seg.label}</Text>
161 {' '}
162 <Text color={seg.level}>{seg.value}</Text>
163 {seg.note ? ` ${seg.note}` : null}
164 </Text>
165 ))}
166 </Text>
167 </Box>
168 )
169 })
170}
171types/index.d.ts 16 lines1export type Segment = {
2 label: string
3 value: string
4 color: string
5 /** Set from 75% (yellow) and 90% (red); the value is drawn in the default color otherwise. */
6 level?: 'yellow' | 'red'
7 /** Trailing text in the default color, such as when a window resets. */
8 note?: string
9}
10
11declare module 'claude-code' {
12 interface PluginState {
13 'usage-band': { text: Segment[] | null }
14 }
15}
16