顯示工作進度(任務清單、本回合狀態)與帳號額度剩餘(5 小時 / 7 天 rate limit、context、花費、token 數),額度偏低時提醒,5 小時額度用完時可暫停工作以避免 extra usage

Claude Code mod:在輸入框上方顯示
指令:/meter 開詳細面板;/meter hide、/meter show 隱藏或顯示上方橫條;/meter resume 在額度用完暫停後繼續工作。
非官方的個人專案,與 Anthropic 無關。
/meter 開面板。在 /config 找到下列設定列,修改後會自動重新載入:
| 設定 | 預設 | 說明 |
|---|---|---|
work-meter.alerts | 開 | 額度警示開關 |
work-meter.alertThresholds | 20,10 | 警示門檻(剩餘 %),以逗號分隔、由大到小 |
work-meter.showTokens | 開 | 在橫條與面板顯示 token 數 |
work-meter.longTurnNotifySeconds | 0 | 回合耗時超過這個秒數時通知;0 為關閉 |
work-meter.limitAction | ask | 5 小時額度用完時:ask 先暫停再問你、pause 直接暫停、off 不處理 |
work-meter.pauseAtUsed | 100 | 5 小時額度已用到這個 %(1 到 100)就觸發暫停 |
長回合通知要靠你自己的通知管道,需先在 /config 設定通知方式;沒有設定時不會有任何效果。
5 小時額度的已用 % 達到 pauseAtUsed(預設 100)時:
limitAction 為 ask(預設)時會跳出對話框,讓你選「暫停到重置」或「繼續使用 extra usage」;關掉對話框或沒人回答,就維持暫停。/meter resume 繼續,同一個額度視窗內不會再自動暫停。重新載入外掛不會讓暫停卡住:重置時間一過,下一個提示就會直接通過。work-meter.limitAction 設成 off,會立刻停用,不用等重置。限制:
work-meter.pauseAtUsed 調低(例如目前用量以下的數字),下一次回合結束就會觸發。claude plugin install work-meter --marketplace https://github.com/evasuka/work-meter.git
也可以在 Claude Code 對話裡輸入 /plugin install work-meter --marketplace https://github.com/evasuka/work-meter.git;出現 Add marketplace? 按 y,scope 建議選 user。不需要任何 GitHub 帳號或認證,請使用完整網址。
安裝後新開的對話會自動載入;已開著的對話請輸入 /reload-plugins。輸入 /meter:出現在指令選單並開啟面板,就代表已載入。
想先看過原始碼,或需要離線使用時:
git clone https://github.com/evasuka/work-meter.git ~/claude-mods/work-meter
claude plugin install work-meter --marketplace ~/claude-mods/work-meter
這種方式 Claude Code 會直接讀那個資料夾(不會另外複製一份),資料夾搬動或刪除後 mod 就失效。
先依方式 B clone,然後:
claude --plugin-dir ~/claude-mods/work-meter
只對這一次啟動的 session 有效。
mod 只在本機執行:不會發出任何網路請求,也不會讀寫檔案或執行外部程式。它讀取目前 session 的用量資訊(rate limit、context、花費)與工具呼叫事件,並顯示在畫面上;橫條會顯示工具呼叫的名稱與參數片段(例如 Bash 指令的第一行)。這些內容只出現在你的畫面上,mod 不會把它們寫入檔案或傳送出去。額度警示以畫面上的提示呈現;長回合通知(預設關閉)只會透過你自己設定的通知管道發出。token 數與警示記錄只保存在 session 的狀態裡,mod 不會把它們寫入檔案。額度用完暫停會在觸發時中止回合、拒絕新提示,這是 mod 唯一會干預工作流程的地方,可用 work-meter.limitAction 設成 off 關閉。原始碼在 hooks/,可自行檢視。
claude plugin update work-meter@work-meter-marketplace,再於對話裡輸入 /reload-plugins。claude plugin uninstall work-meter@work-meter-marketplace,再執行 claude plugin marketplace remove work-meter-marketplace。claude plugin validate .
claude plugin test .
編輯器型別提示:用 claude --plugin-dir . 載入一次,Claude Code 會在 .claude-plugin/types/ 產生型別宣告。
limitAction、pauseAtUsed、/meter resume)hooks/register.tsx 475 lines1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, Register, SessionUsage } from 'claude-code'
3
4import type { MeterGuard, MeterItem, MeterUsage } from '../types'
5import { parseThresholds, planAlerts } from './alerts'
6import {
7 bar,
8 breakdown,
9 describeTool,
10 duration,
11 pad,
12 progress,
13 remaining,
14 remainingColor,
15 resetsIn,
16 tokens,
17 windowLabel,
18} from './format'
19import { isBlocking, lifted, OPEN, pauseReason, planGuard, resumed } from './guard'
20import { EMPTY_TOKENS, recordTurn, total } from './tokens'
21
22const PANE = 'work-meter'
23const PANE_TITLE = '工作進度與額度'
24const ALERT_TOAST_MS = 10_000
25const LIFT_MARGIN_MS = 5_000
26const PAUSE_LABEL = '暫停到重置(建議)'
27const CONTINUE_LABEL = '繼續使用 extra usage'
28
29const items = atom({ plugin: 'work-meter', key: 'items' } as const, [])
30const turn = atom({ plugin: 'work-meter', key: 'turn' } as const, null)
31const running = atom({ plugin: 'work-meter', key: 'running' } as const, [])
32const usage = atom({ plugin: 'work-meter', key: 'usage' } as const, null)
33const now = atom({ plugin: 'work-meter', key: 'now' } as const, 0)
34const isBandHidden = atom({ plugin: 'work-meter', key: 'isBandHidden' } as const, false)
35const spent = atom({ plugin: 'work-meter', key: 'tokens' } as const, EMPTY_TOKENS)
36const alerted = atom({ plugin: 'work-meter', key: 'alerted' } as const, {})
37const guard = atom({ plugin: 'work-meter', key: 'guard' } as const, OPEN)
38
39function toUsage(u: Pick<SessionUsage, 'context' | 'rateLimits' | 'cost'>): MeterUsage {
40 return {
41 windows: u.rateLimits.map(w => ({ kind: w.kind, percentUsed: w.percentUsed, resetsAt: w.resetsAt })),
42 contextTokens: u.context.tokens,
43 contextWindow: u.context.window,
44 contextPercent: u.context.percent,
45 costUsd: u.cost?.usd,
46 }
47}
48
49function upsertTask(list: MeterItem[], id: string, patch: Partial<MeterItem>): MeterItem[] {
50 const isKnown = list.some(i => i.source === 'task' && i.id === id)
51 if (!isKnown) {
52 return [...list, { id, subject: `任務 #${id}`, status: 'pending', source: 'task', ...patch }]
53 }
54 return list.map(i => (i.source === 'task' && i.id === id ? { ...i, ...patch } : i))
55}
56
57// Ticks the clock the band reads: every second while a turn runs, else every 30s for the reset countdowns.
58async function tick($: EngineInterface) {
59 const t = await $.clock.now()
60 const current = await read($, turn)
61 const isWorking = current !== null && current.endedAt === undefined
62 if (isWorking || t - (await read($, now)) >= 30_000) {
63 await update($, now, () => t)
64 }
65}
66
67// The five-hour window reset: lift the pause it caused (not a later one).
68async function liftAtReset($: EngineInterface, resetsAt: string | undefined) {
69 const before = await read($, guard)
70 const after = lifted(before, resetsAt)
71 if (after === before) return
72 await update($, guard, () => after)
73 $.ui.toast('5 小時額度已重置,已恢復工作。', { timeoutMs: ALERT_TOAST_MS })
74}
75
76// Dismissed, or nobody to answer: the safe default is to stay paused.
77async function askWhatToDo($: EngineInterface) {
78 let answer: string
79 try {
80 answer = await $.ui.ask('5 小時額度已用完,要暫停到重置,還是繼續使用(可能會使用 extra usage)?', [
81 PAUSE_LABEL,
82 CONTINUE_LABEL,
83 ])
84 } catch {
85 return
86 }
87 if (answer === CONTINUE_LABEL) await update($, guard, prev => (prev.paused ? resumed(prev) : prev))
88}
89
90// Stop the running turn first: a dialog waiting for an answer must not leave it burning extra usage.
91async function engageGuard($: EngineInterface, paused: MeterGuard, t: number, shouldAsk: boolean) {
92 const current = await read($, turn)
93 if (current !== null && current.endedAt === undefined) {
94 try {
95 await $.turn.abort({ turnId: current.id })
96 } catch {
97 // The turn was no longer the running one; the pause still stands.
98 }
99 // An aborted turn may raise no turn.complete: end it here so the band stops counting.
100 await update($, turn, prev => (prev === null || prev.endedAt !== undefined ? prev : { ...prev, endedAt: t }))
101 await update($, running, () => [])
102 }
103 $.ui.toast(pauseReason(paused, t), { timeoutMs: ALERT_TOAST_MS })
104 const at = paused.resetsAt === undefined ? Number.NaN : Date.parse(paused.resetsAt)
105 if (!Number.isNaN(at)) {
106 $.clock.after(Math.max(0, at - t) + LIFT_MARGIN_MS, () => void liftAtReset($, paused.resetsAt))
107 }
108 if (shouldAsk) $.clock.after(0, () => void askWhatToDo($))
109}
110
111export const register: Register = (on, options) => {
112 const isAlertOn = options.alerts !== false
113 const levels = parseThresholds(String(options.alertThresholds ?? ''))
114 const isTokenShown = options.showTokens !== false
115 const longTurnSeconds = Number(options.longTurnNotifySeconds)
116 const longTurnMs = Number.isFinite(longTurnSeconds) && longTurnSeconds > 0 ? longTurnSeconds * 1000 : 0
117 const limitAction = options.limitAction === 'pause' || options.limitAction === 'off' ? options.limitAction : 'ask'
118 const pauseAt = Number(options.pauseAtUsed)
119 const pauseAtUsed = Number.isFinite(pauseAt) && pauseAt >= 1 && pauseAt <= 100 ? pauseAt : 100
120
121 on('session.start', async ($, e, next) => {
122 await $.command.register({
123 name: 'meter',
124 description: '開啟工作進度與帳號額度面板;/meter hide|show 切換橫條,resume 在額度用完暫停後繼續',
125 argumentHint: '[hide|show|resume]',
126 })
127 const measured = toUsage(await $.session.usage())
128 await update($, usage, () => measured)
129 const t = await $.clock.now()
130 await update($, now, () => t)
131 $.clock.every(1000, () => void tick($))
132
133 return next(e)
134 })
135
136 on('command.run', { command: 'meter' }, async ($, e) => {
137 const arg = e.args.trim()
138 if (arg === 'hide' || arg === 'show') {
139 await update($, isBandHidden, () => arg === 'hide')
140 return { text: arg === 'hide' ? '已隱藏工作進度橫條(/meter show 可再顯示)。' : '已顯示工作進度橫條。' }
141 }
142 if (arg === 'resume') {
143 if (!(await read($, guard)).paused) return { text: '目前沒有暫停。' }
144 await update($, guard, resumed)
145 return { text: '已繼續工作,這個額度視窗內不會再自動暫停。' }
146 }
147 const opened = await $.ui.open({ id: PANE, title: PANE_TITLE })
148
149 return { text: opened.isPlaced ? '已開啟工作進度面板。' : '工作進度面板等待中:終端機寬度不足。' }
150 })
151
152 on('session.measure', async ($, e, next) => {
153 const measured = toUsage(e)
154 await update($, usage, () => measured)
155
156 if (isAlertOn) {
157 const t = await $.clock.now()
158 const plan = planAlerts(await read($, alerted), measured.windows, levels, t)
159 await update($, alerted, () => plan.next)
160 for (const message of plan.messages) $.ui.toast(message, { timeoutMs: ALERT_TOAST_MS })
161 }
162
163 if (limitAction !== 'off') {
164 const t = await $.clock.now()
165 const plan = planGuard(await read($, guard), measured.windows, pauseAtUsed, t)
166 if (plan.engage || plan.release) await update($, guard, () => plan.next)
167 if (plan.engage) await engageGuard($, plan.next, t, limitAction === 'ask')
168 }
169
170 return next(e)
171 })
172
173 on('turn.start', async ($, e, next) => {
174 const t = await $.clock.now()
175 await update($, turn, () => ({ id: e.turnId, startedAt: t, tools: 0 }))
176 await update($, running, () => [])
177 await update($, now, () => t)
178
179 return next(e)
180 })
181
182 on('turn.complete', async ($, e, next) => {
183 await update($, spent, prev => recordTurn(prev, e.usage, e.agentId === undefined))
184 if (e.agentId !== undefined) return next(e)
185 const t = await $.clock.now()
186 await update($, turn, prev => (prev === null ? null : { ...prev, endedAt: t }))
187 await update($, running, () => [])
188
189 if (longTurnMs > 0 && !e.isAborted && e.durationMs >= longTurnMs) {
190 // Goes through the person's own notification channel; "not sent" (no channel set up) is fine.
191 await $.ui.notify(`回合完成(耗時 ${duration(e.durationMs)})`, { title: 'work-meter' })
192 }
193
194 return next(e)
195 })
196
197 // While paused, nothing may start a model turn.
198 on('prompt.submit', async ($, e, next) => {
199 const state = await read($, guard)
200 if (!state.paused) return next(e)
201
202 const t = await $.clock.now()
203 if (isBlocking(state, limitAction, t)) return { drop: pauseReason(state, t) }
204
205 // Not blocking although a pause is on record: its window has reset (the timer may have been lost in a reload).
206 if (limitAction !== 'off') await liftAtReset($, state.resetsAt)
207
208 return next(e)
209 })
210
211 // A /clear starts a new conversation in the same process: its token totals start over.
212 on('session.end', async ($, e, next) => {
213 if (e.reason === 'clear') await update($, spent, () => EMPTY_TOKENS)
214
215 return next(e)
216 })
217
218 // Every tool call: count it, and show the main thread's running ones.
219 on('tool.call', async ($, e, next) => {
220 await update($, turn, prev => (prev === null || prev.endedAt !== undefined ? prev : { ...prev, tools: prev.tools + 1 }))
221 if (e.agentId !== undefined) return next(e)
222 const entry = { id: e.tool_use_id, label: describeTool(String(e.tool), e as unknown as Record<string, unknown>) }
223 await update($, running, list => [...list, entry].slice(-20))
224 try {
225 return await next(e)
226 } finally {
227 await update($, running, list => list.filter(r => r.id !== entry.id))
228 }
229 }).catch(($, e, next) => next(e))
230
231 on('tool.call', { tool: 'TaskCreate' }, async ($, e, next) => {
232 const ran = await next(e)
233 if (ran.deny === undefined && ran.isError !== true && ran.result?.task) {
234 const { id } = ran.result.task
235 await update($, items, list =>
236 upsertTask(list, id, { subject: e.subject, activeForm: e.activeForm, status: 'pending' }),
237 )
238 }
239
240 return ran
241 }).catch(($, e, next) => next(e))
242
243 on('tool.call', { tool: 'TaskUpdate' }, async ($, e, next) => {
244 const ran = await next(e)
245 if (ran.deny !== undefined || ran.isError === true) return ran
246 if (e.status === 'deleted') {
247 await update($, items, list => list.filter(i => !(i.source === 'task' && i.id === e.taskId)))
248 } else {
249 const patch: Partial<MeterItem> = {}
250 if (e.subject !== undefined) patch.subject = e.subject
251 if (e.activeForm !== undefined) patch.activeForm = e.activeForm
252 if (e.status !== undefined) patch.status = e.status
253 await update($, items, list => upsertTask(list, e.taskId, patch))
254 }
255
256 return ran
257 }).catch(($, e, next) => next(e))
258
259 // A full listing resyncs the tasks, keeping each one's activeForm.
260 on('tool.call', { tool: 'TaskList' }, async ($, e, next) => {
261 const ran = await next(e)
262 if (ran.deny === undefined && ran.isError !== true && Array.isArray(ran.result?.tasks)) {
263 const listed = ran.result.tasks
264 await update($, items, list => {
265 const kept = new Map(list.filter(i => i.source === 'task').map(i => [i.id, i]))
266 const tasks: MeterItem[] = listed.map(t => ({
267 id: t.id,
268 subject: t.subject,
269 activeForm: kept.get(t.id)?.activeForm,
270 status: t.status,
271 source: 'task',
272 }))
273 return [...tasks, ...list.filter(i => i.source !== 'task')]
274 })
275 }
276
277 return ran
278 }).catch(($, e, next) => next(e))
279
280 on('tool.call', { tool: 'TaskGet' }, async ($, e, next) => {
281 const ran = await next(e)
282 const task = ran.deny === undefined && ran.isError !== true ? ran.result?.task : undefined
283 if (task) {
284 await update($, items, list => upsertTask(list, task.id, { subject: task.subject, status: task.status }))
285 }
286
287 return ran
288 }).catch(($, e, next) => next(e))
289
290 on('tool.call', { tool: 'TodoWrite' }, async ($, e, next) => {
291 if (e.agentId === undefined) {
292 const todos: MeterItem[] = e.todos.map((t, i) => ({
293 id: `todo-${i}`,
294 subject: t.content,
295 activeForm: t.activeForm,
296 status: t.status,
297 source: 'todo',
298 }))
299 await update($, items, list => [...list.filter(i => i.source !== 'todo'), ...todos])
300 }
301
302 return next(e)
303 }).catch(($, e, next) => next(e))
304
305 on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
306 if (e.props.hasSurvey || (await read($, isBandHidden))) return next(e)
307 const list = await read($, items)
308 const current = await read($, turn)
309 const u = await read($, usage)
310 const t = await read($, now)
311 const calls = await read($, running)
312 const spentTokens = await read($, spent)
313 const guardState = await read($, guard)
314 const isPaused = isBlocking(guardState, limitAction, t)
315 const hasWork = list.length > 0 || current !== null
316 if (!hasWork && u === null && !isPaused) return next(e)
317
318 const { Box, Text } = $.ui.resolve(e)
319 const p = progress(list)
320 const isWorking = current !== null && current.endedAt === undefined
321 const tool = calls.at(-1)
322 const pausedAt = guardState.resetsAt === undefined ? Number.NaN : Date.parse(guardState.resetsAt)
323 const pausedReset = Number.isNaN(pausedAt) ? '' : `(${duration(pausedAt - t)}後重置)`
324 const turnBase =
325 current === null
326 ? ''
327 : isWorking
328 ? `工作中 ${duration(t - current.startedAt)} · 工具 ${current.tools} 次${tool ? ` · ${tool.label}` : ''}`
329 : `上回合 ${duration((current.endedAt ?? t) - current.startedAt)} · 工具 ${current.tools} 次`
330 const lastTokens =
331 isTokenShown && !isWorking && spentTokens.last !== null ? ` · ${tokens(total(spentTokens.last))} tok` : ''
332 const sessionTokens =
333 isTokenShown && total(spentTokens.session) > 0 ? ` │ 本 session ${tokens(total(spentTokens.session))} tok` : ''
334 const turnText = turnBase === '' ? '' : `${turnBase}${lastTokens}${sessionTokens}`
335
336 return (
337 <Box flexDirection="column">
338 {isPaused && (
339 <Text key="paused" color="warning" bold wrap="truncate-end">
340 {`⏸ 已暫停:5 小時額度已用完${pausedReset},輸入 /meter resume 可繼續`}
341 </Text>
342 )}
343 {hasWork && (
344 <Text key="work" wrap="truncate-end">
345 {p.total > 0 && (
346 <Text>
347 <Text dimColor>進度 </Text>
348 <Text color="success">{bar(p.done / p.total, 10)}</Text>
349 {` ${p.done}/${p.total}`}
350 {p.active && <Text color="claude">{` ▶ ${p.active.activeForm ?? p.active.subject}`}</Text>}
351 {turnText !== '' && <Text dimColor> │ </Text>}
352 </Text>
353 )}
354 {turnText !== '' && <Text dimColor={!isWorking}>{turnText}</Text>}
355 </Text>
356 )}
357 {u !== null && (
358 <Text key="usage" wrap="truncate-end">
359 <Text dimColor>額度 </Text>
360 {u.windows.length === 0 && <Text dimColor>(尚無 rate limit 資料) </Text>}
361 {u.windows.map(w => {
362 const left = remaining(w)
363 const reset = resetsIn(w, t)
364 return (
365 <Text>
366 {`${windowLabel(w.kind)} `}
367 <Text color={remainingColor(left)} bold>{`剩 ${left}%`}</Text>
368 {reset !== undefined && <Text dimColor>{` (${reset}後重置)`}</Text>}
369 <Text dimColor> │ </Text>
370 </Text>
371 )
372 })}
373 {u.contextPercent !== undefined && (
374 <Text>
375 {'context '}
376 <Text color={remainingColor(100 - u.contextPercent)}>{`${u.contextPercent}%`}</Text>
377 </Text>
378 )}
379 {u.costUsd !== undefined && <Text dimColor>{` │ US$${u.costUsd.toFixed(2)}`}</Text>}
380 </Text>
381 )}
382 </Box>
383 )
384 })
385
386 on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
387 const { Box, Text } = $.ui.resolve(e)
388 const list = await read($, items)
389 const current = await read($, turn)
390 const u = await read($, usage)
391 const t = await read($, now)
392 const calls = await read($, running)
393 const spentTokens = await read($, spent)
394 const p = progress(list)
395 const width = Math.min(24, Math.max(8, e.props.bodyColumns - 34))
396 const isWorking = current !== null && current.endedAt === undefined
397 const hasTokens = isTokenShown && (spentTokens.last !== null || total(spentTokens.session) > 0)
398
399 return (
400 <Box flexDirection="column">
401 <Text bold>
402 工作進度{p.total > 0 && <Text dimColor>{` ${p.done}/${p.total} 完成`}</Text>}
403 </Text>
404 {p.total > 0 && (
405 <Text>
406 <Text color="success">{bar(p.done / p.total, width + 12)}</Text>
407 {` ${Math.round((p.done / p.total) * 100)}%`}
408 </Text>
409 )}
410 {list.length === 0 && <Text dimColor>(目前沒有任務清單)</Text>}
411 {list.map(item =>
412 item.status === 'completed' ? (
413 <Text dimColor wrap="truncate-end">{`✔ ${item.subject}`}</Text>
414 ) : item.status === 'in_progress' ? (
415 <Text color="claude" bold wrap="truncate-end">{`▶ ${item.activeForm ?? item.subject}`}</Text>
416 ) : (
417 <Text wrap="truncate-end">{`○ ${item.subject}`}</Text>
418 ),
419 )}
420 <Text> </Text>
421 <Text bold>本回合</Text>
422 {current === null ? (
423 <Text dimColor>(尚未開始)</Text>
424 ) : (
425 <Text>
426 {isWorking ? '工作中 ' : '已結束 · 耗時 '}
427 {duration((current.endedAt ?? t) - current.startedAt)}
428 {` · 工具 ${current.tools} 次`}
429 </Text>
430 )}
431 {calls.map(c => (
432 <Text dimColor wrap="truncate-end">{` 執行中:${c.label}`}</Text>
433 ))}
434 {hasTokens && <Text> </Text>}
435 {hasTokens && <Text bold>Token</Text>}
436 {hasTokens && spentTokens.last !== null && (
437 <Text wrap="truncate-end">{`上回合 ${breakdown(spentTokens.last)}`}</Text>
438 )}
439 {hasTokens && <Text wrap="truncate-end">{`本 session ${breakdown(spentTokens.session)}`}</Text>}
440 <Text> </Text>
441 <Text bold>帳號額度</Text>
442 {u === null || (u.windows.length === 0 && u.contextPercent === undefined) ? (
443 <Text dimColor>(等待第一次 API 回應後顯示)</Text>
444 ) : null}
445 {u !== null && u.windows.length === 0 && (
446 <Text dimColor>沒有 rate limit 資料(API key 帳號不提供,訂閱帳號於回應後出現)</Text>
447 )}
448 {u?.windows.map(w => {
449 const left = remaining(w)
450 const reset = resetsIn(w, t)
451 return (
452 <Text wrap="truncate-end">
453 {pad(windowLabel(w.kind), 9)}
454 <Text color={remainingColor(left)}>{bar(left / 100, width)}</Text>
455 <Text color={remainingColor(left)} bold>{` 剩 ${left}%`}</Text>
456 {reset !== undefined && <Text dimColor>{` ${reset}後重置`}</Text>}
457 </Text>
458 )
459 })}
460 {u?.contextPercent !== undefined && (
461 <Text wrap="truncate-end">
462 {pad('Context', 9)}
463 <Text color={remainingColor(100 - u.contextPercent)}>{bar(u.contextPercent / 100, width)}</Text>
464 {` 已用 ${u.contextPercent}%`}
465 {u.contextTokens !== undefined && (
466 <Text dimColor>{` ${tokens(u.contextTokens)} / ${tokens(u.contextWindow)}`}</Text>
467 )}
468 </Text>
469 )}
470 {u?.costUsd !== undefined && <Text dimColor>{`本 session 花費 US$${u.costUsd.toFixed(2)}`}</Text>}
471 </Box>
472 )
473 })
474}
475hooks/alerts.ts 50 lines1import type { MeterAlerts, MeterWindow } from '../types'
2import { remaining, resetsIn, windowLabel } from './format'
3
4const DEFAULT_LEVELS = [20, 10]
5
6export type AlertPlan = { messages: string[]; next: MeterAlerts }
7
8// "20,10" -> [20, 10]: whole-percent levels between 1 and 99, high to low, no duplicates.
9export function parseThresholds(text: string): number[] {
10 const levels = new Set<number>()
11 for (const part of text.split(',')) {
12 const n = Number(part.trim())
13 if (Number.isFinite(n) && n >= 1 && n <= 99) levels.add(n)
14 }
15 return levels.size === 0 ? DEFAULT_LEVELS : [...levels].sort((a, b) => b - a)
16}
17
18// What to announce for the latest readings, and what to remember so the same level is not announced twice.
19export function planAlerts(
20 prev: MeterAlerts,
21 windows: readonly MeterWindow[],
22 thresholds: readonly number[],
23 now: number,
24): AlertPlan {
25 const next: MeterAlerts = { ...prev }
26 const messages: string[] = []
27 const levels = [...thresholds].sort((a, b) => b - a)
28
29 for (const w of windows) {
30 const left = remaining(w)
31 const crossed = levels.filter(level => left <= level)
32 const target = crossed.length === 0 ? null : (crossed[crossed.length - 1] ?? null)
33 const announced = prev[w.kind] ?? null
34 const label = windowLabel(w.kind)
35
36 if (target === null) {
37 if (announced !== null) messages.push(`${label}額度已恢復(剩 ${left}%)`)
38 next[w.kind] = null
39 } else if (announced === null || target < announced) {
40 const reset = resetsIn(w, now)
41 messages.push(`${label}額度只剩 ${left}%${reset === undefined ? '' : `(${reset}後重置)`}`)
42 next[w.kind] = target
43 } else {
44 next[w.kind] = target
45 }
46 }
47
48 return { messages, next }
49}
50hooks/format.ts 89 lines1import type { MeterItem, MeterTok, MeterWindow } from '../types'
2
3export function duration(ms: number): string {
4 const s = Math.max(0, Math.round(ms / 1000))
5 if (s < 60) return `${s}s`
6 const m = Math.floor(s / 60)
7 if (m < 60) return `${m}m${String(s % 60).padStart(2, '0')}s`
8 const h = Math.floor(m / 60)
9 if (h < 24) return `${h}h${String(m % 60).padStart(2, '0')}m`
10 return `${Math.floor(h / 24)}d${h % 24}h`
11}
12
13export function bar(fraction: number, width: number): string {
14 const filled = Math.round(Math.min(1, Math.max(0, fraction)) * width)
15 return '█'.repeat(filled) + '░'.repeat(width - filled)
16}
17
18export function tokens(n: number): string {
19 if (n >= 1_000_000) return `${(n / 1_000_000).toFixed(1)}M`
20 if (n >= 1000) return `${(n / 1000).toFixed(1)}k`
21 return String(n)
22}
23
24export function breakdown(t: MeterTok): string {
25 return `輸入 ${tokens(t.input)} · 快取讀 ${tokens(t.cacheRead)} · 快取寫 ${tokens(t.cacheWrite)} · 輸出 ${tokens(t.output)}`
26}
27
28export function windowLabel(kind: string): string {
29 switch (kind) {
30 case 'five_hour':
31 return '5 小時'
32 case 'seven_day':
33 return '7 天'
34 case 'spend_limit':
35 return '花費上限'
36 default:
37 return kind.replace(/_/g, ' ')
38 }
39}
40
41export function remaining(w: MeterWindow): number {
42 return Math.max(0, Math.round((100 - w.percentUsed) * 10) / 10)
43}
44
45export function remainingColor(left: number): 'success' | 'warning' | 'error' {
46 if (left >= 50) return 'success'
47 if (left >= 20) return 'warning'
48 return 'error'
49}
50
51export function resetsIn(w: MeterWindow, now: number): string | undefined {
52 if (w.resetsAt === undefined) return undefined
53 const at = Date.parse(w.resetsAt)
54 return Number.isNaN(at) ? undefined : duration(at - now)
55}
56
57// Terminal cells: CJK and full-width forms take two.
58export function cells(text: string): number {
59 let n = 0
60 for (const ch of text) {
61 const code = ch.codePointAt(0) ?? 0
62 n += code >= 0x1100 && (code <= 0x115f || (code >= 0x2e80 && code <= 0xa4cf) || (code >= 0xac00 && code <= 0xd7a3) || (code >= 0xf900 && code <= 0xfaff) || (code >= 0xfe30 && code <= 0xfe4f) || (code >= 0xff00 && code <= 0xff60) || (code >= 0xffe0 && code <= 0xffe6)) ? 2 : 1
63 }
64 return n
65}
66
67export function pad(text: string, width: number): string {
68 return text + ' '.repeat(Math.max(0, width - cells(text)))
69}
70
71export function progress(items: readonly MeterItem[]) {
72 const done = items.filter(i => i.status === 'completed').length
73 const active = items.find(i => i.status === 'in_progress')
74 return { done, total: items.length, active }
75}
76
77const ARG_KEYS = ['command', 'file_path', 'notebook_path', 'pattern', 'url', 'query', 'description', 'subject', 'prompt'] as const
78
79export function describeTool(tool: string, args: Record<string, unknown>): string {
80 const name = tool.startsWith('mcp__') ? tool.split('__').slice(2).join('__') || tool : tool
81 for (const key of ARG_KEYS) {
82 const value = args[key]
83 if (typeof value !== 'string' || value.trim() === '') continue
84 const text = key.endsWith('_path') ? (value.split('/').pop() ?? value) : (value.trim().split('\n')[0] ?? '')
85 return `${name}: ${text.length > 48 ? `${text.slice(0, 47)}…` : text}`
86 }
87 return name
88}
89hooks/guard.ts 73 lines1import type { MeterGuard, MeterWindow } from '../types'
2import { duration } from './format'
3
4export const OPEN: MeterGuard = { paused: false }
5
6export type GuardPlan = { engage: boolean; release: boolean; next: MeterGuard }
7
8export type LimitAction = 'ask' | 'pause' | 'off'
9
10const windowKey = (resetsAt: string | undefined) => resetsAt ?? 'unknown'
11
12// A pause holds until its window resets. The timer that lifts it at that moment is lost when the module
13// reloads, while the pause itself stays in the session state, so the reset time is checked wherever it matters.
14export function stillPaused(guard: MeterGuard, now: number): boolean {
15 if (!guard.paused) return false
16 if (guard.resetsAt === undefined) return true
17 const at = Date.parse(guard.resetsAt)
18 return Number.isNaN(at) || at > now
19}
20
21// Whether prompts are refused (and the pause shown) right now. Switching limitAction to off ends it at once.
22export function isBlocking(guard: MeterGuard, action: LimitAction, now: number): boolean {
23 return action !== 'off' && stillPaused(guard, now)
24}
25
26// Decides from the latest readings whether the five-hour window has run out (engage),
27// or has room again while paused (release). Other windows never pause anything.
28export function planGuard(
29 guard: MeterGuard,
30 windows: readonly MeterWindow[],
31 threshold: number,
32 now: number,
33): GuardPlan {
34 const five = windows.find(w => w.kind === 'five_hour')
35 if (five === undefined) return { engage: false, release: false, next: guard }
36
37 const isFull = five.percentUsed >= threshold
38 if (stillPaused(guard, now)) {
39 return isFull
40 ? { engage: false, release: false, next: guard }
41 : { engage: false, release: true, next: OPEN }
42 }
43
44 // Open, or paused for a window that has since reset: either way the person's choice or pause is spent.
45 const base = guard.paused ? OPEN : guard
46 const isStale = five.resetsAt !== undefined && Date.parse(five.resetsAt) <= now
47 if (!isFull || isStale || base.overriddenFor === windowKey(five.resetsAt)) {
48 return { engage: false, release: guard.paused, next: base }
49 }
50
51 return {
52 engage: true,
53 release: false,
54 next: five.resetsAt === undefined ? { paused: true } : { paused: true, resetsAt: five.resetsAt },
55 }
56}
57
58// The person chose to keep working: unpause, and do not pause again within this window.
59export function resumed(guard: MeterGuard): MeterGuard {
60 return { paused: false, overriddenFor: windowKey(guard.resetsAt) }
61}
62
63// The window reset: unpause, but only the pause that was caused by that window.
64export function lifted(guard: MeterGuard, resetsAt: string | undefined): MeterGuard {
65 return guard.paused && guard.resetsAt === resetsAt ? OPEN : guard
66}
67
68export function pauseReason(guard: MeterGuard, now: number): string {
69 const at = guard.resetsAt === undefined ? Number.NaN : Date.parse(guard.resetsAt)
70 const reset = Number.isNaN(at) ? '' : `(${duration(at - now)}後重置)`
71 return `5 小時額度已用完,已暫停以避免 extra usage${reset}。輸入 /meter resume 可繼續。`
72}
73hooks/tokens.ts 42 lines1import type { MeterTok, MeterTokens } from '../types'
2
3// The four counts a model response reports, as the engine spells them.
4type UsageLike = {
5 input_tokens: number
6 output_tokens: number
7 cache_read_input_tokens: number
8 cache_creation_input_tokens: number
9}
10
11const ZERO: MeterTok = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 }
12
13export const EMPTY_TOKENS: MeterTokens = { last: null, session: ZERO }
14
15export function fromUsage(usage: UsageLike | undefined): MeterTok {
16 if (usage === undefined) return ZERO
17 return {
18 input: usage.input_tokens,
19 output: usage.output_tokens,
20 cacheRead: usage.cache_read_input_tokens,
21 cacheWrite: usage.cache_creation_input_tokens,
22 }
23}
24
25export function total(t: MeterTok): number {
26 return t.input + t.output + t.cacheRead + t.cacheWrite
27}
28
29export function recordTurn(prev: MeterTokens, usage: UsageLike | undefined, isMain: boolean): MeterTokens {
30 if (usage === undefined) return prev
31 const turn = fromUsage(usage)
32 return {
33 last: isMain ? turn : prev.last,
34 session: {
35 input: prev.session.input + turn.input,
36 output: prev.session.output + turn.output,
37 cacheRead: prev.session.cacheRead + turn.cacheRead,
38 cacheWrite: prev.session.cacheWrite + turn.cacheWrite,
39 },
40 }
41}
42types/index.d.ts 54 lines1export type MeterStatus = 'pending' | 'in_progress' | 'completed'
2
3export type MeterItem = {
4 id: string
5 subject: string
6 activeForm?: string
7 status: MeterStatus
8 source: 'task' | 'todo'
9}
10
11// id: the main-loop turn's id from turn.start, which turn.abort needs.
12export type MeterTurn = { id: string; startedAt: number; endedAt?: number; tools: number }
13
14export type MeterRunning = { id: string; label: string }
15
16export type MeterWindow = { kind: string; percentUsed: number; resetsAt?: string }
17
18export type MeterUsage = {
19 windows: MeterWindow[]
20 contextTokens?: number
21 contextWindow: number
22 contextPercent?: number
23 costUsd?: number
24}
25
26export type MeterTok = { input: number; output: number; cacheRead: number; cacheWrite: number }
27
28// last: the most recent main-thread turn; session: every turn since the conversation began, subagents included.
29export type MeterTokens = { last: MeterTok | null; session: MeterTok }
30
31// Per rate-limit window kind: the lowest alert threshold already announced, null while above every threshold.
32export type MeterAlerts = Record<string, number | null>
33
34// paused: new prompts are refused until the five-hour window resets or the person resumes.
35// resetsAt: when the window that caused the pause resets.
36// overriddenFor: the window ('unknown' when it has no reset time) the person chose to keep working in.
37export type MeterGuard = { paused: boolean; resetsAt?: string; overriddenFor?: string }
38
39declare module 'claude-code' {
40 interface PluginState {
41 'work-meter': {
42 items: MeterItem[]
43 turn: MeterTurn | null
44 running: MeterRunning[]
45 usage: MeterUsage | null
46 now: number
47 isBandHidden: boolean
48 tokens: MeterTokens
49 alerted: MeterAlerts
50 guard: MeterGuard
51 }
52 }
53}
54