A live forecast of the context window and rate limits, in the band above the prompt.

A Claude Code mod by Toptaab: a live forecast of the context window and rate limits, in the band above the prompt.
It ships through the toptaab-mods marketplace, which lists all of Toptaab's mods.
/plugin marketplace add Toptaab/toptaab-mods
/plugin install token-garden@toptaab-mods
/reload-plugins
Or paste this prompt into Claude Code:
Install token-garden from https://github.com/Toptaab/toptaab-mods
If you added toptaab-mods earlier from Toptaab/token-garden, remove it first: claude plugin marketplace remove toptaab-mods.
If you are an AI agent asked to install this mod, it is a Claude Code plugin listed in the Toptaab/toptaab-mods marketplace. Do not clone it or copy files by hand. Run these two shell commands, in order:
claude plugin marketplace add Toptaab/toptaab-mods
claude plugin install token-garden@toptaab-mods
If the marketplace is already added, run claude plugin marketplace update toptaab-mods instead of the first command; if that marketplace was added from Toptaab/token-garden, run claude plugin marketplace remove toptaab-mods first. Then tell the user to type /reload-plugins or restart the session; you cannot run that yourself. The mod shows up as a band above the prompt.
The band shows above the prompt in every session. /garden hides it or brings it back; /garden hide and /garden show say which. A hidden band stays hidden in later sessions until /garden again.
Under the bars sits a row of two switches: ◧ Agents opens or closes the agent-roster pane (it runs /roster; a toast says so when agent-roster is not installed), and ▾ Garden puts the band away, the same as /garden. While the garden is away the switch row stays, so ▸ Garden brings it back.
Run Claude Code against the working copy, from the repo root:
claude --plugin-dir ./plugins/token-garden
The mod loads straight from disk, hot-reloads on save, and overrides the installed version for that session.
hooks/register.tsx 338 lines1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, Register, SessionContextUsage, SessionRateLimit } from 'claude-code'
3
4import type { Forecast, Limit, Limits } from '../types'
5
6const forecast = atom({ plugin: 'token-garden', key: 'forecast' } as const, null)
7const hidden = atom({ plugin: 'token-garden', key: 'hidden' } as const, false)
8
9const BAR_CELLS = 20
10const MODEL_POLL_MS = 1000
11const LIMITS_KEY = 'limits'
12// Kept across sessions, so a band put away stays away.
13const HIDDEN_KEY = 'hidden'
14// The agent-roster mod's command: the switch row's Agents button runs it.
15const ROSTER_COMMAND = 'roster'
16const MODEL_COLOR = 'green'
17// '🌿 Making progress' is the widest label (an icon is two cells), '999.9k / 999.9k' the widest value.
18const LABEL_CELLS = 19
19const VALUE_CELLS = 16
20const ICON_CELLS = 2
21
22const SKIES = [
23 { from: 100, icon: '🌲', word: 'Overgrown', color: 'red' },
24 { from: 80, icon: '🌳', word: 'Compact soon', color: 'red' },
25 { from: 50, icon: '🪴', word: 'Halfway up', color: 'yellow' },
26 { from: 25, icon: '🌿', word: 'Making progress', color: 'green' },
27 { from: 0, icon: '🌱', word: 'Just started', color: 'green' },
28]
29
30const SUNS = [
31 { from: 100, icon: '🌑', word: 'No light left', color: 'red' },
32 { from: 80, icon: '☁️', word: 'Running low', color: 'red' },
33 { from: 50, icon: '⛅', word: 'Over halfway', color: 'yellow' },
34 { from: 25, icon: '🌤️', word: 'Filling up', color: 'green' },
35 { from: 0, icon: '☀️', word: 'Full sun', color: 'green' },
36]
37
38const SEASONS = [
39 { from: 100, icon: '❄️', word: 'Out of season', color: 'red' },
40 { from: 80, icon: '🍂', word: 'Late season', color: 'red' },
41 { from: 50, icon: '🍁', word: 'Peak season', color: 'yellow' },
42 { from: 25, icon: '🌻', word: 'In season', color: 'green' },
43 { from: 0, icon: '🌿', word: 'Early season', color: 'green' },
44]
45
46// How fast an effort burns the limits, in the tiers' colors; one the table lacks keeps the model's.
47const EFFORT_COLORS: Record<string, string> = {
48 low: 'green',
49 medium: 'green',
50 high: 'yellow',
51 xhigh: 'red',
52 max: 'red',
53}
54
55const tierFor = (tiers: typeof SKIES, percent: number) =>
56 tiers.find(tier => percent >= tier.from) ?? tiers[tiers.length - 1]
57
58// An icon is two cells but one to three UTF-16 units, so only the word is padded.
59const titled = (icon: string, word: string) => `${icon} ${word.padEnd(LABEL_CELLS - ICON_CELLS - 1)}`
60
61const bar = (percent: number) => {
62 const filled = Math.max(0, Math.min(BAR_CELLS, Math.round((percent / 100) * BAR_CELLS)))
63
64 return '█'.repeat(filled) + '░'.repeat(BAR_CELLS - filled)
65}
66
67const compact = (tokens: number) => {
68 const abs = Math.abs(tokens)
69
70 if (abs >= 1_000_000) {
71 return `${(tokens / 1_000_000).toFixed(1).replace(/\.0$/, '')}M`
72 }
73
74 if (abs >= 1000) {
75 return `${(tokens / 1000).toFixed(1).replace(/\.0$/, '')}k`
76 }
77
78 return String(tokens)
79}
80
81const clock = (iso: string) => {
82 const at = new Date(iso)
83 const hours = at.getHours()
84 const hh = String(hours % 12 || 12).padStart(2, '0')
85 const mm = String(at.getMinutes()).padStart(2, '0')
86
87 return `${hh}:${mm} ${hours < 12 ? 'AM' : 'PM'}`
88}
89
90const DAYS = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']
91
92const limitOf = (limits: readonly SessionRateLimit[], kind: string): Limit | null => {
93 const limit = limits.find(each => each.kind === kind)
94
95 return limit ? { percent: limit.percentUsed, resetsAt: limit.resetsAt ?? null } : null
96}
97
98const isLive = (limit: Limit | null | undefined, now: number): limit is Limit =>
99 !!limit && (limit.resetsAt === null || Date.parse(limit.resetsAt) > now)
100
101// The engine learns the limits from an API response, so a new session has none until its first turn:
102// the last reading any session took stands in, unless its window has since reset.
103const limitsOf = async ($: EngineInterface, limits: readonly SessionRateLimit[]): Promise<Limits> => {
104 const kept = ((await $.store.get(LIMITS_KEY)) ?? {}) as Partial<Limits>
105 const now = await $.clock.now()
106 const session = limitOf(limits, 'five_hour') ?? (isLive(kept.session, now) ? kept.session : null)
107 const week = limitOf(limits, 'seven_day') ?? (isLive(kept.week, now) ? kept.week : null)
108
109 if (limits.length > 0) {
110 await $.store.set(LIMITS_KEY, { session, week })
111 }
112
113 return { session, week }
114}
115
116const modelOf = async ($: EngineInterface) =>
117 (await $.session.model()).replace(/^claude-/, '').replace(/-\d{8}$/, '')
118
119// Before the first request the setting stands in; a request then says what was really asked.
120// /effort keeps its level per model, under modelSettings.
121const effortOf = async ($: EngineInterface) => {
122 const settings = await $.settings.read({})
123 const perModel = (settings.modelSettings ?? {}) as Record<string, { effortLevel?: unknown } | undefined>
124 const level = perModel[await $.session.model()]?.effortLevel ?? settings.effortLevel
125
126 return typeof level === 'string' ? level : null
127}
128
129// The setting as last polled: a change in it is an /effort, which raises nothing a mod hears either.
130let polledEffort: string | null | undefined
131
132const forecastOf = (
133 prev: Forecast | null,
134 context: SessionContextUsage,
135 limits: Limits,
136 model: string,
137 effort: string | null,
138 isTurn: boolean,
139): Forecast => {
140 // No response yet (a fresh or just-cleared session): an empty window, so the band shows from the start.
141 const tokens = context.tokens ?? prev?.tokens ?? 0
142 const moved = prev && isTurn ? tokens - prev.tokens : null
143
144 return {
145 tokens,
146 window: context.window,
147 percent: context.percent ?? Math.round((tokens / context.window) * 100),
148 model,
149 // A forecast kept from before the band showed effort has none: undefined, where null says the model takes none.
150 effort: prev?.effort !== undefined ? prev.effort : effort,
151 delta: moved === null || moved === 0 ? (prev?.delta ?? null) : moved,
152 session: limits.session ?? prev?.session ?? null,
153 week: limits.week ?? prev?.week ?? null,
154 }
155}
156
157const measure = async (
158 $: EngineInterface,
159 context: SessionContextUsage,
160 limits: readonly SessionRateLimit[],
161 isTurn: boolean,
162) => {
163 const model = await modelOf($)
164 const effort = await effortOf($)
165 const known = await limitsOf($, limits)
166
167 await update($, forecast, (prev: Forecast | null) => forecastOf(prev, context, known, model, effort, isTurn))
168}
169
170// A /clear empties the session's state and raises no session.start: measure on the spot.
171const current = async ($: EngineInterface) => {
172 const usage = await $.session.usage()
173
174 return forecastOf(null, usage.context, await limitsOf($, usage.rateLimits), await modelOf($), await effortOf($), false)
175}
176
177// A /model switch raises nothing a mod hears, so the model is polled.
178const refresh = async ($: EngineInterface) => {
179 const model = await modelOf($)
180 const effort = await effortOf($)
181 const shown = await read($, forecast)
182 const isSwitched = polledEffort !== undefined && polledEffort !== effort
183 polledEffort = effort
184
185 if (shown === null) {
186 const usage = await $.session.usage()
187 await measure($, usage.context, usage.rateLimits, false)
188 } else if (shown.model !== model || isSwitched) {
189 await update($, forecast, (prev: Forecast | null) =>
190 prev ? { ...prev, model, effort: isSwitched ? effort : prev.effort } : prev,
191 )
192 }
193}
194
195const setHidden = async ($: EngineInterface, isHidden: boolean) => {
196 await update($, hidden, () => isHidden)
197 await $.store.set(HIDDEN_KEY, isHidden)
198}
199
200// Rejects while agent-roster is not loaded: say so rather than fail quietly.
201const toggleAgents = ($: EngineInterface) =>
202 $.command.run({ command: ROSTER_COMMAND }).catch(() => $.ui.toast('agent-roster is not loaded'))
203
204export const register: Register = on => {
205 on('session.start', async ($, e, next) => {
206 await $.command.register({
207 name: 'garden',
208 description: 'Show or hide the token-garden band above the prompt (args: show, hide)',
209 })
210 const isHidden = (await $.store.get(HIDDEN_KEY)) === true
211 await update($, hidden, () => isHidden)
212 const usage = await $.session.usage()
213 await measure($, usage.context, usage.rateLimits, false)
214 $.clock.every(MODEL_POLL_MS, () => void refresh($))
215
216 return next(e)
217 })
218
219 on('session.measure', async ($, e, next) => {
220 await measure($, e.context, e.rateLimits, e.changed.includes('context'))
221
222 return next(e)
223 })
224
225 // A model that takes no effort is sent none: the band then shows the model alone.
226 on('turn.step', async function* ($, e, next) {
227 if (e.agentId === undefined) {
228 const effort = e.effort === undefined ? null : String(e.effort)
229 await update($, forecast, (prev: Forecast | null) => (prev ? { ...prev, effort } : prev))
230 }
231
232 return yield* next(e)
233 })
234
235 on('command.run', { command: 'garden' }, async ($, e) => {
236 const arg = e.args.trim()
237 const isHidden = arg === 'hide' ? true : arg === 'show' ? false : !(await read($, hidden))
238 await setHidden($, isHidden)
239
240 return { text: isHidden ? 'Token garden hidden. /garden brings it back.' : 'Token garden shown.' }
241 })
242
243 on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
244 if (e.props.hasSurvey) {
245 return next(e)
246 }
247
248 const isHidden = await read($, hidden)
249 const { Box, Text, Button } = $.ui.resolve(e)
250
251 // One row of switches for both mods, kept while the garden is put away.
252 const switches = (
253 <Box flexDirection="row" gap={2}>
254 <Button key="agents" plain dimColor label="◧ Agents" onPress={() => toggleAgents($)} />
255 <Button
256 key="garden"
257 plain
258 dimColor
259 label={isHidden ? '▸ Garden' : '▾ Garden'}
260 onPress={() => setHidden($, !isHidden)}
261 />
262 </Box>
263 )
264
265 if (isHidden) {
266 return (
267 <Box flexDirection="column">
268 {switches}
269 {await next(e)}
270 </Box>
271 )
272 }
273
274 const now = (await read($, forecast)) ?? (await current($))
275 // Whatever another plugin draws in the band (agent-roster's roster on the terminal) stays.
276 const beneath = await next(e)
277
278 const sky = tierFor(SKIES, now.percent)
279
280 // The bar takes its title's color; a row with no reading has neither.
281 const row = (label: unknown, value: string, note: string, color?: string) => (
282 <Text>
283 {label}
284 <Text color={color} dimColor={color === undefined}>
285 {value === '' ? bar(0) : bar(parseFloat(value))}
286 </Text>
287 <Text> {value.padEnd(VALUE_CELLS)}</Text>
288 <Text dimColor>{note}</Text>
289 </Text>
290 )
291
292 const limitRow = (label: string, limit: Limit | null, withDay: boolean, tiers: typeof SKIES) => {
293 if (limit === null) {
294 return row(<Text dimColor>{label.padEnd(LABEL_CELLS)}</Text>, '', 'no reading')
295 }
296
297 const tier = tierFor(tiers, Math.round(limit.percent))
298 const name = (
299 <Text color={tier.color} bold>
300 {titled(tier.icon, tier.word)}
301 </Text>
302 )
303
304 const resets = limit.resetsAt
305 ? `resets ${withDay ? `${DAYS[new Date(limit.resetsAt).getDay()]} ` : ''}${clock(limit.resetsAt)}`
306 : ''
307
308 return row(name, `${Math.round(limit.percent)}%`, resets, tier.color)
309 }
310
311 const used = `${compact(now.tokens)} / ${compact(now.window)}`
312 const turn = now.delta === null ? '' : `${now.delta < 0 ? '▼ ' : '▲ +'}${compact(now.delta)} last turn`
313
314 return (
315 <Box flexDirection="column">
316 <Text>
317 <Text color={sky.color} bold>
318 {titled(sky.icon, sky.word)}
319 </Text>
320 <Text color={sky.color}>{bar(now.percent)}</Text>
321 <Text> {used.padEnd(VALUE_CELLS)}</Text>
322 <Text dimColor>{turn}</Text>
323 <Text color={MODEL_COLOR}>
324 {turn === '' ? '' : ' '}
325 {now.model}
326 {now.effort ? ' · ' : ''}
327 </Text>
328 <Text color={EFFORT_COLORS[now.effort ?? ''] ?? MODEL_COLOR}>{now.effort ?? ''}</Text>
329 </Text>
330 {limitRow('Session', now.session, false, SUNS)}
331 {limitRow('Week', now.week, true, SEASONS)}
332 {switches}
333 {beneath}
334 </Box>
335 )
336 })
337}
338types/index.d.ts 25 lines1export type Limit = { percent: number; resetsAt: string | null }
2
3export type Limits = { session: Limit | null; week: Limit | null }
4
5export type Forecast = {
6 tokens: number
7 window: number
8 percent: number
9 delta: number | null
10 model: string
11 effort: string | null
12 session: Limit | null
13 week: Limit | null
14}
15
16declare module 'claude-code' {
17 interface PluginState {
18 'token-garden': {
19 forecast: Forecast | null
20 // Whether the person put the band away with /garden.
21 hidden: boolean
22 }
23 }
24}
25