A weather forecast for your context window and your plan's 5-hour and weekly limits, with reset times, this session's cost and the last response's output…

一个 Claude Code mod:在输入框上方用天气图标显示上下文窗口占用了多少、订阅的 5 小时和每周额度还剩多少,以及额度的重置时间(本机时间)、本会话按 API 价格算的费用和上一次回复的输出速度。
☁ Ctx 34% used ☁ 5h 57% left ↻ 22:13 ☁ Week 66% left ↻ Thu 11:00 Session $15.98 ⚡ 68 tps
每个数字都标明了含义:上下文是容量,显示占用量(used),进度条越满越接近自动压缩;额度是预算,显示剩余量(left),进度条像电池,满格表示还剩很多。上下文越满、额度剩得越少,天气越差:
| 上下文占用 | 额度剩余 | 显示 |
|---|---|---|
| 25% 以下 | 75% 以上 | ☀ Clear |
| 25%–50% | 50%–75% | ☁ Cloudy |
| 50%–75% | 25%–50% | ☂ Showers |
| 75%–90% | 10%–25% | ☇ Storm |
| 90% 以上 | 10% 以下 | ↯ 红色:上下文显示 Compact soon(快要自动压缩),额度显示 Limit soon |
22:13),跨过午夜会带上星期(Thu 01:30);每周额度总是带星期。340k/1M 这样的用量。Session $15.98 是本会话按 API 价格折算的费用,和 /cost 显示的一样。订阅用户不会真的被扣这笔钱,只是参考值。⚡ 68 tps 是主对话上一次模型回复的输出速度:API 报告的输出 token 数除以从第一个流式分片到结束的时间,不含等待首字的延迟,也不含服务端工具(如 advisor)运行的时间;终端里看不到的思考 token 也算在内。子代理的回复和不到 0.3 秒的短回复不计入,这时保留上一次的数值。每次回复结束时更新为准确值,会话收到第一次回复前不显示。~ 并变暗,例如 ⚡ ~70 tps:回复开始 1 秒后出现,每 0.5 秒刷新,结束时换成准确值。估算按已收到的文字换算 token(中日韩文字约 1 字 1 token,其他约 4 字符 1 token),再用之前几次回复的实际 token 数校正比例,所以前几次回复偏差较大,之后会越来越接近。五项都可以在 /config 里单独关掉,默认全部显示:
| 选项 | 控制的项 |
|---|---|
Show context | Ctx 上下文占用 |
Show 5-hour limit | 5h 5 小时额度 |
Show weekly limit | Week 每周额度 |
Show session cost | Session 本会话费用 |
Show output speed | ⚡ 输出速度 |
全部关掉时这一行不显示。
窄屏时代替进度条的圆环有三种样式,在 /config 里改 Ring style:
| 值 | 图标 | 档位 | 跟随天气颜色 |
|---|---|---|---|
moon(默认) | 🌑 🌒 🌓 🌔 🌕 | 5 档 | 否,emoji 自带颜色 |
nerd | Nerd Font 圆形分片 | 9 档 | 是,需要终端字体是 Nerd Font,否则显示成方框 |
circle | ○ ◔ ◑ ◕ ● | 5 档 | 是,但在多数字体里个头偏小 |
none | 不显示圆环 | — | — |
mod 还自带一个输入框下方的状态栏,显示当前目录、模型和 effort,配色取自 Catppuccin Mocha:
/home/wds Opus 5.5 · xhigh
effort 按强度从冷到暖着色:low 绿、medium 黄、high 橙、xhigh / max 红。
settings.json:mod 只在你没有配置 statusLine 时,把自带的脚本(statusline/statusline.sh)借给合并后的设置。你已经有自己的状态栏的话,保留你的。卸载或停用 mod 后状态栏也随之消失。bash(Windows 上 Claude Code 本来就依赖 Git Bash)。装了 jq 时用它解析会话信息,没装也能用。/config 里关掉 Status line。需要 Claude Code 2.1.287 及以上。这个仓库本身就是一个插件市场:
claude plugin marketplace add fs666666/plan-limits
claude plugin install plan-limits@plan-limits
装好后在会话里运行 /reload-plugins,或者重启 Claude Code。
改完代码后,把 .claude-plugin/plugin.json 里的 version 加一,提交并推送。各台设备运行:
claude plugin marketplace update plan-limits # 拉取市场的最新清单
claude plugin update plan-limits@plan-limits # 把已安装的插件升级到新版本
只运行第一条不会升级已安装的插件。升级后重启 Claude Code,或者在会话里运行 /reload-plugins。
claude plugin validate . # 检查清单和 mod 代码
claude plugin test . # 运行 plan-limits.test.ts
本地调试时可以不安装,直接加载这个目录:claude --plugin-dir ~/plan-limits。
hooks/register.tsx 382 lines1// Plan limits band: a weather forecast for the context window and the plan's 5-hour and weekly
2// rate-limit windows, with each window's reset time, this session's API-equivalent cost and
3// the output speed of the last response, above the prompt.
4//
5// The figures are $.session.usage()'s, the same the status line has: context once a response
6// reported its fill; rateLimits only on a subscription and after the first response; cost is
7// Claude Code's own estimate at API prices (what /cost shows). session.measure pushes a redraw
8// when any of them moves; a one-minute timer redraws so a 5-hour reset gains its weekday after
9// midnight.
10//
11// The speed is the last main-loop response's output tokens over the time from its first streamed
12// chunk to its stop chunk, so the wait before the first token does not count, nor the time a tool
13// the API runs itself (the advisor) held the stream. Thinking the
14// terminal does not show is in output_tokens and in that time too, so the figure stays honest.
15// While a response streams, a live estimate marked ~ stands in: the streamed text counted as
16// tokens by a rule of thumb, scaled by how far that rule was off on the responses before.
17import type { RenderElement, Register, SessionRateLimit } from 'claude-code'
18
19const NAMES: Record<string, string> = {
20 five_hour: '5h',
21 seven_day: 'Week',
22 spend_limit: 'Spend',
23}
24
25// Forecast bands by percent of the window used, in token-weather's style.
26// Single-width text symbols, not emoji: they line up in every terminal font.
27const FORECAST = [
28 { upTo: 25, icon: '☀', word: 'Clear', color: 'yellow' },
29 { upTo: 50, icon: '☁', word: 'Cloudy', color: 'cyan' },
30 { upTo: 75, icon: '☂', word: 'Showers', color: 'blue' },
31 { upTo: 90, icon: '☇', word: 'Storm', color: 'magenta' },
32 { upTo: Infinity, icon: '↯', word: 'Limit soon', color: 'red' },
33] as const
34
35const BAR_CELLS = 10
36
37// Shorter responses than this give a speed that is mostly noise; the last good one stays
38const MIN_SPEED_MS = 300
39// The live estimate waits this long into a response before it shows, then redraws this often
40const LIVE_AFTER_MS = 1_000
41const LIVE_EVERY_MS = 500
42
43// Roughly how many tokens streamed text is: a CJK character about one, other text about four
44// characters to a token. Only a starting point: the scale learnt from finished responses corrects it.
45const CJK = /[\u3000-\u9fff\uac00-\ud7af\uff00-\uffef]/g
46function estimateTokens(s: string): number {
47 const cjk = s.match(CJK)?.length ?? 0
48 return cjk + (s.length - cjk) / 4
49}
50
51// The last band's word, per gauge: a full context window gets compacted, a full limit stops you
52function forecastOf(percent: number, fullWord = 'Limit soon') {
53 const f = FORECAST.find(f => percent <= f.upTo) ?? FORECAST[FORECAST.length - 1]!
54 return { ...f, word: f.upTo === Infinity ? fullWord : f.word, isAlarm: f.upTo === Infinity }
55}
56
57function short(n: number): string {
58 if (n >= 1_000_000) return `${(n / 1_000_000).toFixed(n % 1_000_000 === 0 ? 0 : 1)}M`
59 if (n >= 1_000) return `${Math.round(n / 1_000)}k`
60 return String(n)
61}
62
63// A rate limit is a budget, so it shows what is left, like a battery; the context window is a
64// fill, so it shows what is used. Each number says which it is. The weather always follows what
65// is used: a fuller window or less budget left reads as worse weather.
66function shownOf(used: number, shows: 'used' | 'left'): number {
67 const value = shows === 'used' ? used : 100 - used
68 return Math.max(0, Math.round(value * 10) / 10)
69}
70
71function bar(percent: number): string {
72 const filled = Math.max(0, Math.min(BAR_CELLS, Math.round((percent / 100) * BAR_CELLS)))
73 return '█'.repeat(filled) + '░'.repeat(BAR_CELLS - filled)
74}
75
76// The bar's stand-in where the line has no room for it, following the shown value as the bar
77// does, in the style the ringStyle option picks:
78// - nerd: Nerd Font circle slices, nine steps, take the forecast's colour (needs a Nerd Font)
79// - moon: moon-phase emoji, five steps, at the weather icon's size but in their own colours
80// - circle: plain Unicode quarter circles, five steps, take the colour, but small in most fonts
81// - none: no ring, the narrow line keeps only the percents
82type RingStyle = 'nerd' | 'moon' | 'circle' | 'none'
83type RingGlyphs = Exclude<RingStyle, 'none'>
84const RINGS: Record<RingGlyphs, readonly string[]> = {
85 nerd: ['\u{F0766}', '\u{F0A9E}', '\u{F0A9F}', '\u{F0AA0}', '\u{F0AA1}', '\u{F0AA2}', '\u{F0AA3}', '\u{F0AA4}', '\u{F0AA5}'],
86 moon: ['🌑', '🌒', '🌓', '🌔', '🌕'],
87 circle: ['○', '◔', '◑', '◕', '●'],
88}
89// Emoji take their own colours and every terminal draws them two columns wide
90const COLOURED: Record<RingGlyphs, boolean> = { nerd: true, moon: false, circle: true }
91
92function ringStyleOf(value: unknown): RingStyle {
93 // Moon unless asked otherwise: emoji draw in every terminal, Nerd Font glyphs only with that font
94 return value === 'nerd' || value === 'circle' || value === 'none' ? value : 'moon'
95}
96
97function ring(style: RingGlyphs, percent: number): string {
98 const steps = RINGS[style]
99 const step = Math.round((percent / 100) * (steps.length - 1))
100 return steps[Math.max(0, Math.min(steps.length - 1, step))]!
101}
102
103const WEEKDAYS = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']
104const pad = (n: number) => String(n).padStart(2, '0')
105
106// The reset as a local time (the environment keeps the machine's time zone): 22:13 when it
107// falls today, Thu 01:30 on another day, and always with the weekday for the weekly window
108function resetText(limit: SessionRateLimit, now: number): string {
109 if (!limit.resetsAt) return ''
110 const d = new Date(limit.resetsAt)
111 if (Number.isNaN(d.getTime())) return ''
112 const time = `${pad(d.getHours())}:${pad(d.getMinutes())}`
113 const isToday = d.toDateString() === new Date(now).toDateString()
114 return limit.kind === 'seven_day' || !isToday ? `${WEEKDAYS[d.getDay()]} ${time}` : time
115}
116
117function sortLimits(limits: SessionRateLimit[]): SessionRateLimit[] {
118 const order = ['five_hour', 'seven_day']
119 const rank = (kind: string) => (order.includes(kind) ? order.indexOf(kind) : order.length)
120 return [...limits].sort((a, b) => rank(a.kind) - rank(b.kind))
121}
122
123// Whether the mods after this one left the band empty. With none drawing there, next(e)
124// resolves to the engine's own drawing, { type: 'engine' }, and in the band the engine
125// draws nothing; an empty Box is nothing too.
126function isEmpty(el: RenderElement | null | undefined): boolean {
127 if (!el || el.type === 'engine') return true
128 const children = (el as { children?: unknown[] }).children
129 return el.type === 'Box' && (!children || children.length === 0)
130}
131
132// Roughly how many columns a tree takes on one line: its texts, plus a row's gaps and padding.
133// The weather and reset symbols count two columns: many terminals draw them as wide emoji, and
134// overestimating only costs a little detail, while underestimating wraps the line.
135const WIDE = new Set(['☀', '☁', '☂', '☇', '↯', '↻', '⚡', ...RINGS.moon])
136
137function textWidth(s: string): number {
138 let width = 0
139 for (const ch of s) width += WIDE.has(ch) ? 2 : 1
140 return width
141}
142
143function widthOf(node: unknown): number {
144 if (typeof node === 'string' || typeof node === 'number') return textWidth(String(node))
145 if (!node || typeof node !== 'object') return 0
146 const el = node as { type?: string; props?: Record<string, unknown>; children?: unknown[] }
147 const children = (el.children ?? []).filter(c => c !== null && c !== undefined && c !== false)
148 let width = children.reduce<number>((sum, c) => sum + widthOf(c), 0)
149 if (el.type === 'Box') {
150 const props = el.props ?? {}
151 const gap = Number(props.columnGap ?? props.gap ?? 0)
152 if (props.flexDirection !== 'column') width += gap * Math.max(0, children.length - 1)
153 width += 2 * Number(props.paddingX ?? props.padding ?? 0)
154 }
155 return width
156}
157
158// One gauge on the line: the context window or a rate-limit window; percent is how much is used
159type Gauge = {
160 key: string
161 label: string
162 percent: number
163 shows: 'used' | 'left'
164 fullWord?: string
165 reset?: string
166 size?: string
167}
168
169// How much each window shows, from most to least, picked by what fits on the line
170type Detail = 'full' | 'compact' | 'minimal'
171const DETAILS: Detail[] = ['full', 'compact', 'minimal']
172
173export const register: Register = (on, options) => {
174 const ringStyle = ringStyleOf(options.ringStyle)
175 // Each item on the line can be turned off in /config; unset reads as on
176 const shows = (key: string) => options[key] !== false
177 const showContext = shows('showContext')
178 const showCost = shows('showCost')
179 const showSpeed = shows('showSpeed')
180 const SHOW_LIMIT: Record<string, boolean> = { five_hour: shows('showFiveHour'), seven_day: shows('showWeek') }
181 // Output tokens per second of the last main-loop response, and the live estimate while one
182 // streams; a reload starts both over
183 let tokensPerSecond: number | undefined
184 let liveTokensPerSecond: number | undefined
185 // Real output tokens over estimated ones, averaged over finished responses: it takes in the
186 // language mix and the thinking the stream does not show
187 let scale = 1
188
189 // Time each main-loop response as it streams; subagents stream alongside and are left out
190 on('turn.step', async function* ($, e, next) {
191 if (e.agentId || !showSpeed) return yield* next(e)
192 let firstAt: number | undefined
193 let stopAt: number | undefined
194 let output = 0
195 let drawnAt = 0
196 let estimated = 0
197 try {
198 // Read by hand, not for await: the stream's return value carries the server tool calls
199 const stream = next(e)
200 let step = await stream.next()
201 for (; !step.done; step = await stream.next()) {
202 const chunk = step.value
203 const now = await $.clock.now()
204 if (firstAt === undefined) firstAt = now
205 const ms = now - firstAt
206 if (chunk.kind === 'text' || chunk.kind === 'thinking') estimated += estimateTokens(chunk.text)
207 else if (chunk.kind === 'input') estimated += estimateTokens(chunk.json)
208
209 if (chunk.kind === 'stop') {
210 stopAt = now
211 output = chunk.usage?.output_tokens ?? 0
212 } else if (ms >= LIVE_AFTER_MS && now - drawnAt >= LIVE_EVERY_MS && estimated > 0) {
213 liveTokensPerSecond = (estimated * scale) / (ms / 1000)
214 drawnAt = now
215 $.ui.invalidate('ui.render')
216 }
217 yield chunk
218 }
219
220 if (firstAt !== undefined && stopAt !== undefined) {
221 // A tool the API runs itself (the advisor) holds the stream while the model writes
222 // nothing of this response, so its time is left out as the wait before the first chunk is
223 const start = firstAt
224 const end = stopAt
225 const serverMs = (step.value?.serverToolUses ?? []).reduce((sum, use) => {
226 const from = Math.max(start, use.startedAt)
227 const to = Math.min(end, use.endedAt ?? end)
228 return sum + Math.max(0, to - from)
229 }, 0)
230 const ms = end - start - serverMs
231 if (ms >= MIN_SPEED_MS && output > 0) tokensPerSecond = output / (ms / 1000)
232 // Too few to learn from: a tool call alone, a word or two
233 if (output > 0 && estimated >= 20) {
234 scale = Math.max(0.5, Math.min(4, 0.7 * scale + 0.3 * (output / estimated)))
235 }
236 liveTokensPerSecond = undefined
237 $.ui.invalidate('ui.render')
238 }
239 return step.value
240 } finally {
241 // A response cut off before its stop leaves the last real figure, not a stale estimate
242 if (liveTokensPerSecond !== undefined) {
243 liveTokensPerSecond = undefined
244 $.ui.invalidate('ui.render')
245 }
246 }
247 })
248
249 // The status line under the prompt (directory, model, effort) is the script this mod ships,
250 // lent to the merged settings rather than written to any file: settings that set a status line
251 // of their own keep it, and uninstalling the mod takes ours away with it
252 if (shows('statusLine')) {
253 on('settings.read', async ($, e, next) => {
254 // A call on $ resolves its value wrapped, { value: settings }, or { deny }
255 const result = await next(e)
256 if (e.source || !result.value || result.value.statusLine !== undefined) return result
257 // Forward slashes: Git Bash on Windows takes C:/... as readily as a POSIX shell takes /...
258 const script = `${$.plugin.root.replace(/\\/g, '/')}/statusline/statusline.sh`
259 return { value: { ...result.value, statusLine: { type: 'command', command: `bash "${script}"` } } }
260 })
261 }
262
263 on('session.start', async ($, e, next) => {
264 const result = await next(e)
265 // Redraw once a minute; a reload stops the old timer by itself
266 $.clock.every(60_000, () => $.ui.invalidate('ui.render'))
267 return result
268 })
269
270 on('session.measure', async ($, e, next) => {
271 $.ui.invalidate('ui.render')
272 return next(e)
273 })
274
275 on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
276 if (e.props.hasSurvey) return next(e)
277
278 const { context, rateLimits, cost } = await $.session.usage()
279 const now = await $.clock.now()
280
281 const gauges: Gauge[] = []
282 // The context window has a fill once a response reported one
283 if (showContext && context.window > 0 && (context.percent !== undefined || (context.tokens ?? 0) > 0)) {
284 const tokens = context.tokens ?? 0
285 gauges.push({
286 key: 'context',
287 label: 'Ctx',
288 percent: Math.round(context.percent ?? (tokens / context.window) * 100),
289 shows: 'used',
290 fullWord: 'Compact soon',
291 size: `${short(tokens)}/${short(context.window)}`,
292 })
293 }
294 // A window with no switch of its own (a gateway's spend limit) is always shown
295 for (const limit of sortLimits(rateLimits.filter(l => SHOW_LIMIT[l.kind] !== false))) {
296 gauges.push({
297 key: limit.kind,
298 label: NAMES[limit.kind] ?? limit.kind,
299 percent: limit.percentUsed,
300 shows: 'left',
301 reset: resetText(limit, now),
302 })
303 }
304 const shownCost = showCost ? cost : undefined
305 const isLive = liveTokensPerSecond !== undefined
306 const speed = showSpeed ? liveTokensPerSecond ?? tokensPerSecond : undefined
307 if (gauges.length === 0 && shownCost === undefined && speed === undefined) return next(e)
308
309 const { Box, Text } = $.ui.resolve(e)
310
311 const ours = (detail: Detail) => {
312 const items = gauges.map(g => {
313 const f = forecastOf(g.percent, g.fullWord)
314 const shown = shownOf(g.percent, g.shows)
315 const reset = detail === 'minimal' ? '' : g.reset
316 return (
317 <Box key={g.key} flexDirection="row" columnGap={1}>
318 {/* A trailing space here and after ↻: many terminals draw these symbols two columns wide */}
319 <Text color={f.color}>{`${f.icon} `}</Text>
320 <Text bold>{g.label}</Text>
321 {detail === 'full' || ringStyle === 'none' ? null : COLOURED[ringStyle] ? (
322 // Trailing space as for the icon: a glyph may draw wider than its one column
323 <Text color={f.color}>{`${ring(ringStyle, shown)} `}</Text>
324 ) : (
325 <Text>{ring(ringStyle, shown)}</Text>
326 )}
327 <Text color={f.color} bold={f.isAlarm}>{`${shown}% ${g.shows}`}</Text>
328 {detail === 'full' ? <Text color={f.color}>{bar(shown)}</Text> : null}
329 {detail === 'full' ? <Text color={f.color} bold={f.isAlarm}>{f.word}</Text> : null}
330 {detail === 'full' && g.size ? <Text dimColor>{g.size}</Text> : null}
331 {reset ? (
332 <Text dimColor>
333 {detail === 'full' ? `· resets ${reset}` : `↻ ${reset}`}
334 </Text>
335 ) : null}
336 </Box>
337 )
338 })
339 if (shownCost !== undefined) {
340 items.push(
341 <Box key="cost" flexDirection="row" columnGap={1}>
342 {/* Always labelled: a bare dollar figure reads as nothing in particular */}
343 <Text dimColor>Session</Text>
344 <Text>{`$${shownCost.usd.toFixed(2)}`}</Text>
345 </Box>,
346 )
347 }
348 if (speed !== undefined) {
349 items.push(
350 <Box key="speed" flexDirection="row" columnGap={1}>
351 {/* An emoji: its own colour, two columns wide in every terminal */}
352 <Text>⚡</Text>
353 {/* An estimate is marked ~ and dimmed until the response's own count replaces it */}
354 <Text dimColor={isLive}>{`${isLive ? '~' : ''}${Math.round(speed)} tps`}</Text>
355 </Box>,
356 )
357 }
358 return (
359 <Box key="plan-limits" flexDirection="row" columnGap={3}>
360 {items}
361 </Box>
362 )
363 }
364
365 // Every mod shares the band: put what the mods after this one drew (token-weather)
366 // first on the same line, a divider, then ours in as much detail as still fits
367 const theirs = await next(e)
368 const hasTheirs = !isEmpty(theirs)
369 const room = e.props.bodyColumns - (hasTheirs ? widthOf(theirs) + 5 : 0)
370 const detail = DETAILS.find(d => widthOf(ours(d)) <= room) ?? 'minimal'
371 const line = ours(detail)
372 if (!hasTheirs) return line
373 return (
374 <Box flexDirection="row" columnGap={2}>
375 {theirs}
376 <Text dimColor>│</Text>
377 {line}
378 </Box>
379 )
380 })
381}
382