在輸入框上方顯示目前模型、context 用量,以及本 session 各 plugin 的 skill 與 hook 注入量

Claude Code mod:在輸入框上方顯示目前的模型、context 用量,以及這個 session 裡各 plugin 透過 skill 和 hook 注入了多少內容。終端機與 desktop app 都適用。
送給模型的 context 裡,有一部分是 plugin 加進來的。這個 mod 把這部分拆成兩類:
不只算 skill:hook 注入、MCP 工具和記憶檔也都算在內。另外,注入是 session 累計,對話壓縮(compact)後也不會扣掉,所以可能比 context 裡實際剩下的還多。context 目前用了多少,以 ctx 為準。
由左到右依序是:
● Opus 5.5:目前的模型。ctx 7%:context window 目前用掉的比例,涵蓋系統提示、工具定義、對話紀錄等所有內容,數字是 Claude Code 在本機估算的。↑1.2k:最近一輪主對話裡,模型總共輸出了多少 token。一輪是指從你送出訊息,到模型回覆完畢為止。這段時間裡每一次請求的輸出都會加總,包括思考、文字和工具呼叫的參數;subagent 的輸出不算。新的一輪開始時這個數字會先消失,回覆完畢後才再出現。ponytail 2.6k 這類項目:各 plugin 在這個 session 累計注入的量,由多到少排列。subagent 排在一般來源之後,未比中固定排在最後。名稱前有 ● 的,表示這一輪有注入。按「明細」展開,分成注入、常駐兩段,最後列出未比中的合計:
×N 是次數。注入依事件分列,因為不同事件的注入次數差很多:有的整個 session 只注入一次,有的每輪、甚至每次工具呼叫都會注入。同一個 plugin 的總量差不多時,每輪都注入的那種,對話越長越吃 context。
| 事件 | 何時注入 | 次數 |
|---|---|---|
| SessionStart | session 開始或恢復時 | 每個 session 一次 |
| UserPromptSubmit | 你送出訊息後、模型處理之前 | 每輪一次 |
| PreToolUse | 每次呼叫工具之前 | 每次工具呼叫 |
| PostToolUse | 工具執行成功之後 | 每次工具呼叫 |
| SubagentStart | 啟動 subagent 時,注入給該 subagent | 每個 subagent 一次 |
| Stop | 模型回覆完畢時 | 每輪一次 |
其他會注入內容的事件,以及每段注入最多 10,000 字元的限制,請見官方文件的 Add context for Claude。
引擎不會告訴 mod 某段 hook 注入是哪個 plugin 的,所以要自己設定比對規則。執行 /config,找到「hook 比對規則」,一條寫一行,格式是「開頭文字=名稱」:
PONYTAIL MODE=ponytail
CAVEMAN MODE=caveman
<EXTREMELY_IMPORTANT>=superpowers
mod 算完 token 就把內容丟掉,所以畫面上看不到未比中的是什麼,要從下面兩個地方找。
方法一:從對話紀錄找(建議先用這個)
Claude Code 會把每個 session 的紀錄存成 ~/.claude/projects/<專案>/<session id>.jsonl,裡面記有每段 hook 注入的內容。開一個已經用過一陣子的 session,在終端機執行下面的指令。它會讀最近更新的那份紀錄,每段 hook 注入只印一行:
python3 - "$(ls -t ~/.claude/projects/*/*.jsonl | head -1)" <<'EOF'
import json, sys
seen = set()
for line in open(sys.argv[1], encoding='utf-8'):
try:
a = json.loads(line).get('attachment') or {}
except ValueError:
continue
if a.get('type') not in ('hook_success', 'hook_additional_context'):
continue
text = a.get('content') or ''
if isinstance(text, list):
text = '\n'.join(map(str, text))
first = text.strip().split('\n', 1)[0][:80]
if first and first not in seen:
seen.add(first)
print(f"{a.get('hookEvent')}\t{first}\t{a.get('command', '')}")
EOF
輸出分三欄,以 Tab 分隔:事件名稱、注入內容的第一行、hook 的指令或狀態訊息(可能是空的)。例如:
SessionStart PONYTAIL MODE ACTIVE — level: full Loading ponytail mode...
SessionStart CAVEMAN MODE ACTIVE — mode: caveman Loading caveman mode...
SessionStart <EXTREMELY_IMPORTANT>
UserPromptSubmit CAVEMAN MODE ACTIVE (caveman). Respond terse like smart caveman. All technical s
第二欄就是要拿來寫規則的開頭文字。第一欄和第三欄用來判斷是哪個 plugin:通常第二欄或第三欄就看得出來;看不出來時,用方法二對照。
方法二:從 plugin 的 hook 設定找
~/.claude/plugins/installed_plugins.json,每個 plugin 的 installPath 就是它的安裝位置。hooks/hooks.json。如果 .claude-plugin/plugin.json 有 hooks 欄位,就以它為準:欄位的值是路徑時打開那個檔案,是物件時定義就寫在裡面。SessionStart、UserPromptSubmit 這類事件底下 type 為 command 的指令,打開指令執行的腳本,看它輸出的第一行。${CLAUDE_PLUGIN_ROOT} 代表安裝位置。PONYTAIL MODE ACTIVE — level: full 的 full 會隨設定改變,規則寫成 PONYTAIL MODE=ponytail。CAVEMAN MODE,寫一條就夠了。< 會把其他 plugin 的注入也算進來。規則依順序比對,第一條比中的就生效。可以把下面這段直接貼給 Claude Code,讓它代為產生規則:
請幫我產生 session-lens 的 hook 比對規則:
1. 依 session-lens README「找出開頭文字」的方法一,執行那段 python3 指令,列出 hook 注入的第一行。
2. 判斷每一行屬於哪個 plugin;判斷不出來時,依方法二讀該 plugin 的 hook 設定與腳本對照,只讀不執行。
3. 依「挑開頭文字的原則」,每個 plugin 寫出「開頭文字=plugin 名稱」,一條一行。
4. 只列出規則給我,不要修改任何設定檔;我會自己到 /config 的「hook 比對規則」貼上。
5. 對話紀錄裡只讀 hook 注入的那幾筆,不要讀取或引用其他對話內容。
[-] 是 Claude Code 本身的收合鈕,按下或按 ctrl+x ctrl+a 會收起整條。+N。視窗窄到一個都放不下時,不顯示 +N。/reload-plugins 後,session 開頭的 hook 注入會被重送一次,數字會多算一次。/clear、resume)時清空。@ 提到的檔案、系統提醒等其他內容一律直接放行,不讀取也不計算。在 Claude Code 的輸入框執行:
/plugin install session-lens --marketplace danielcheng80/session-lens
出現提示時輸入 y 新增 marketplace,再選擇安裝範圍。
Claude Code 依 plugin.json 的版本號判斷有沒有新版,版本號沒變就不會更新。
從 0.x 升到 1.0 時,統計的資料結構換了,升級後請開一個新的 session。
claude plugin validate .
claude plugin test .
本機開發時,把這個資料夾登記成 marketplace 後安裝,修改檔案再執行 /reload-plugins 即可生效:
claude plugin marketplace add ~/projects/session-lens
claude plugin install session-lens@session-lens
介面改了之後,修改 docs/images/render.py 裡的示意內容,再執行 python3 docs/images/render.py 重新產生 README 的兩張圖。
hooks/register.tsx 348 lines1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, Register } from 'claude-code'
3
4import type { Injection, Injections, Resident } from '../types'
5
6const model = atom({ plugin: 'session-lens', key: 'model' } as const, '')
7const injections = atom({ plugin: 'session-lens', key: 'injections' } as const, {} as Injections)
8const round = atom({ plugin: 'session-lens', key: 'round' } as const, 0)
9const output = atom({ plugin: 'session-lens', key: 'output' } as const, 0)
10const contextPercent = atom({ plugin: 'session-lens', key: 'contextPercent' } as const, null as number | null)
11const resident = atom({ plugin: 'session-lens', key: 'resident' } as const, [] as Resident[])
12const isExpanded = atom({ plugin: 'session-lens', key: 'isExpanded' } as const, false)
13
14const ACCENT = '#1f717a'
15const CJK = /[ᄀ-ᅟ⺀-가-힣豈-︰-﹏-⦆¢-₩\u{20000}-\u{3FFFD}]/u
16const WIDE = new RegExp(`${CJK.source}|\\p{Emoji_Presentation}`, 'u')
17// 未比中規則的 hook 注入歸在這一組
18const UNMATCHED = ''
19const UNMATCHED_LABEL = '未比中'
20// 不屬於任何 plugin 的 skill 歸在這一組
21const LOCAL = '本機'
22// 送進 subagent 的 hook 注入歸在這一組
23const SUBAGENT = '\u0000subagent'
24const NAME_MAX = 64
25// 明細的名稱欄最寬 32 格
26const NAME_W = 32
27
28// 分組在畫面上的名稱
29const groupLabel = (name: string): string =>
30 name === UNMATCHED ? UNMATCHED_LABEL : name === SUBAGENT ? 'subagent' : name
31
32// 中日韓字元約一字一 token,其餘約四字元一 token
33export const estimateTokens = (text: string): number => {
34 let cjk = 0
35 let chars = 0
36 for (const ch of text) {
37 chars += 1
38 if (CJK.test(ch)) cjk += 1
39 }
40 return Math.round(cjk + (chars - cjk) / 4)
41}
42
43// 終端機顯示寬度:全形字與 emoji 佔兩格
44const width = (text: string): number => {
45 let w = 0
46 for (const ch of text) w += WIDE.test(ch) ? 2 : 1
47 return w
48}
49
50const clip = (text: string, max: number): string => {
51 if (width(text) <= max) return text
52 let out = ''
53 for (const ch of text) {
54 if (width(out + ch) > max - 1) break
55 out += ch
56 }
57 return out + '…'
58}
59
60export const formatTokens = (n: number): string =>
61 n < 1000 ? String(n) : `${(n / 1000).toFixed(n < 9950 ? 1 : 0)}k`
62
63// claude-opus-5-5 → Opus 5.5,claude-opus-4-20250514 → Opus 4;認不出來就原樣顯示
64export const prettyModel = (id: string): string => {
65 const m = /^claude-([a-z]+)-(\d+)(?:-(\d{1,2})(?!\d))?/.exec(id)
66 if (!m) return id
67 const [, family = '', major, minor] = m
68 return `${family[0]?.toUpperCase()}${family.slice(1)} ${major}${minor ? `.${minor}` : ''}`
69}
70
71// 「開頭文字=名稱」,以最後一個等號分開;格式不對的規則略過
72export const parseRules = (lines: readonly string[]): [string, string][] =>
73 lines.flatMap(line => {
74 const at = line.lastIndexOf('=')
75 const prefix = line.slice(0, at).trim()
76 const name = line.slice(at + 1).trim()
77 return at > 0 && prefix && name ? [[prefix, name.slice(0, NAME_MAX)] as [string, string]] : []
78 })
79
80// 只看注入內容的第一個非空行,先去掉引擎加的「SessionStart:startup hook success: 」這類前綴
81export const matchRule = (rules: readonly [string, string][], text: string): string | undefined => {
82 const first = (text.trimStart().split('\n', 1)[0] ?? '').replace(/^[\w:]+ hook [^:]*: /, '')
83 return rules.find(([prefix]) => first.startsWith(prefix))?.[1]
84}
85
86// 依傳入的順序,挑出一行放得下的項目,其餘併成 +N
87export const fitInline = (
88 list: readonly (readonly [string, number])[],
89 room: number,
90): { shown: [string, string][]; rest: number } => {
91 const shown: [string, string][] = []
92 let used = 0
93 for (const [i, [name, tokens]] of list.entries()) {
94 const restAfter = list.length - i - 1
95 const reserve = restAfter > 0 ? width(` +${restAfter}`) : 0
96 const piece = ` ${name} ${formatTokens(tokens)}`
97 if (used + width(piece) + reserve > room) break
98 shown.push([name, formatTokens(tokens)])
99 used += width(piece)
100 }
101 return { shown, rest: list.length - shown.length }
102}
103
104const record = async ($: EngineInterface, group: string, item: string, tokens: number) => {
105 const now = await read($, round)
106 const g = group.slice(0, NAME_MAX)
107 const k = item.slice(0, NAME_MAX)
108 await update($, injections, all => {
109 const items = all[g] ?? {}
110 const prev = items[k] ?? { tokens: 0, count: 0, round: now }
111 return { ...all, [g]: { ...items, [k]: { tokens: prev.tokens + tokens, count: prev.count + 1, round: now } } }
112 })
113}
114
115const refreshModel = async ($: EngineInterface) => {
116 const id = await $.session.model()
117 await update($, model, () => id)
118}
119
120// 常駐成本:skill 清單依 plugin 分組,已載入的 MCP 工具依 server 分組,subagent 定義與記憶檔各一列
121const refreshResident = async ($: EngineInterface) => {
122 const { context } = await $.session.usage({ breakdown: 'summary' })
123 const b = context.breakdown
124 const sums = new Map<string, number>()
125 const add = (name: string, tokens: number) => {
126 const n = name.slice(0, NAME_MAX)
127 sums.set(n, (sums.get(n) ?? 0) + tokens)
128 }
129 for (const s of b?.skills?.skillFrontmatter ?? []) add(s.pluginName || LOCAL, s.tokens)
130 for (const t of b?.mcpTools ?? []) if (t.isLoaded) add(`MCP ${t.serverName}`, t.tokens)
131 for (const a of b?.agents ?? []) add('subagent 定義', a.tokens)
132 for (const f of b?.memoryFiles ?? []) add('記憶檔', f.tokens)
133 const list = [...sums].map(([name, tokens]) => ({ name, tokens })).filter(r => r.tokens > 0)
134 await Promise.all([
135 update($, resident, () => list.sort((a, b) => b.tokens - a.tokens)),
136 update($, contextPercent, () => context.percent ?? null),
137 ])
138}
139
140export const register: Register = (on, options) => {
141 const labels = options.hookLabels
142 const rules = parseRules(Array.isArray(labels) ? labels : [])
143
144 on('session.start', async ($, e, next) => {
145 await refreshModel($)
146 return next(e)
147 })
148
149 // /clear(含 /new)開出的新 session 不會觸發 session.start,改在這裡重新查模型與常駐成本
150 on('classic.SessionStart', async ($, e, next) => {
151 const result = await next(e)
152 if (e.source === 'clear') await Promise.all([refreshModel($), refreshResident($)])
153 return result
154 })
155
156 // session 結束(離開、/clear、resume)時清空統計與展開狀態
157 on('session.end', async ($, e, next) => {
158 await Promise.all([
159 update($, injections, () => ({})),
160 update($, round, () => 0),
161 update($, output, () => 0),
162 update($, contextPercent, () => null),
163 update($, resident, () => []),
164 update($, isExpanded, () => false),
165 ])
166 return next(e)
167 })
168
169 // 每段注入送給模型前觸發;只統計 hook 的輸出,其他來源直接放行
170 on('prompt.attachment', async ($, e, next) => {
171 const result = await next(e)
172 if (e.origin.kind !== 'hook' || result.text === null) return result
173 const event = e.origin.event
174 const tokens = estimateTokens(result.text)
175 const name = matchRule(rules, result.text)
176 // 主對話裡未比中的只記合計;subagent 裡未比中的依事件分列
177 if (e.agentId) await record($, SUBAGENT, name ?? `${event} hook`, tokens)
178 else if (name) await record($, name, `${event} hook`, tokens)
179 else await record($, UNMATCHED, UNMATCHED, tokens)
180 return result
181 })
182
183 // 使用者每送出一則訊息,主對話就開始新的一輪;只處理主對話的 turn
184 on('turn.start', async ($, e, next) => {
185 if (!e.agentId) {
186 await Promise.all([update($, round, n => n + 1), update($, output, () => 0), refreshModel($)])
187 }
188 return next(e)
189 })
190
191 // 一輪結束後才查 context 用量與常駐成本
192 on('turn.complete', async ($, e, next) => {
193 const result = await next(e)
194 if (!e.agentId) {
195 const out = result.usage?.output_tokens ?? 0
196 await Promise.all([update($, output, n => n + out), refreshResident($)])
197 }
198 return result
199 })
200
201 on('skill.prompt', async ($, e, next) => {
202 const result = await next(e)
203 await record($, e.pluginName || LOCAL, e.skill, estimateTokens(result.text))
204 return result
205 })
206
207 on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
208 if (e.props.hasSurvey) return next(e)
209
210 const [id, all, now, out, pct, residents, expanded] = await Promise.all([
211 read($, model),
212 read($, injections),
213 read($, round),
214 read($, output),
215 read($, contextPercent),
216 read($, resident),
217 read($, isExpanded),
218 ])
219 if (!id) return next(e)
220
221 // subagent 排在一般來源之後,未比中排在最後
222 const rank = (name: string) => (name === UNMATCHED ? 2 : name === SUBAGENT ? 1 : 0)
223 const sum = (items: Record<string, Injection>) => Object.values(items).reduce((s, u) => s + u.tokens, 0)
224 const isNow = (u: Injection) => now > 0 && u.round === now
225 const isFresh = (items: Record<string, Injection>) => Object.values(items).some(isNow)
226 const groups = Object.entries(all)
227 .map(([name, items]) => ({ name, items, tokens: sum(items), isFresh: isFresh(items) }))
228 .sort((a, b) => rank(a.name) - rank(b.name) || b.tokens - a.tokens)
229 const named = groups.filter(g => g.name !== UNMATCHED)
230 const unmatched = all[UNMATCHED] ?? {}
231 const total = groups.reduce((s, g) => s + g.tokens, 0)
232 const residentTotal = residents.reduce((s, r) => s + r.tokens, 0)
233
234 // 外框兩側各一格框線、一格留白
235 const cols = e.props.bodyColumns - 4
236 const { Box, Text, Button } = $.ui.resolve(e)
237 const frame = (body: unknown) => (
238 <Box borderStyle="round" borderDimColor paddingX={1}>
239 {body}
240 </Box>
241 )
242
243 const head = `● ${prettyModel(id)}`
244 const usage = `${pct === null ? '' : ` · ctx ${Math.round(pct)}%`}${out > 0 ? ` · ↑${formatTokens(out)}` : ''}`
245 const toggleLabel = expanded ? '收合' : '明細'
246 const toggle = (
247 <Button key="toggle" label={toggleLabel} onPress={() => update($, isExpanded, v => !v)} />
248 )
249 const headParts = [
250 <Text key="model" color={ACCENT} bold>{head}</Text>,
251 <Text key="usage" dimColor>{usage}</Text>,
252 ]
253
254 if (!expanded) {
255 const inline = groups.map(g => [`${g.isFresh ? '●' : ''}${groupLabel(g.name)}`, g.tokens] as const)
256 const empty = inline.length ? '' : ' · 尚未有注入'
257 // 終端機把按鈕畫成「[ 標籤 ]」;寬度另外扣一格
258 const room = cols - width(head + usage + empty) - 1 - width(`[ ${toggleLabel} ]`)
259 const { shown, rest } = fitInline(inline, Math.max(0, room))
260 return frame(
261 <Box flexDirection="row" justifyContent="space-between" flexGrow={1}>
262 <Text wrap="truncate-end">
263 {headParts}
264 <Text dimColor>{empty}</Text>
265 {shown.map(([name, tok], i) => (
266 <Text key={groups[i]?.name}>
267 {' '}
268 {name} <Text dimColor>{tok}</Text>
269 </Text>
270 ))}
271 {rest > 0 && shown.length > 0 ? <Text dimColor>{` +${rest}`}</Text> : null}
272 </Text>
273 {toggle}
274 </Box>
275 )
276 }
277
278 // 明細:注入、常駐兩段,未比中只列合計
279 const items = named.flatMap(g => Object.values(g.items))
280 const max = Math.max(1, ...items.map(u => u.tokens))
281 const labels = [
282 ...named.flatMap(g => [groupLabel(g.name), ...Object.keys(g.items).map(k => ` ${k}`)]),
283 ...residents.map(r => r.name),
284 ]
285 // 每列另需標記 2 格、空白 1 格、數字 5 格與次數 3 格;有長條時再加長條與 1 格空白
286 // 48 欄以上一定畫長條,最少 8 格,空間不夠時先縮短名稱
287 const longest = Math.max(...labels.map(width))
288 const barW = cols >= 48 ? Math.max(8, Math.min(20, cols - 16 - Math.min(NAME_W, longest))) : 0
289 const nameW = Math.max(4, Math.min(NAME_W, cols - 11 - (barW > 0 ? barW + 5 : 0), longest))
290 const row = (key: string, name: string, use: { tokens: number; count?: number }, bar: boolean, fresh = false) => {
291 const label = clip(name, nameW)
292 const filled = Math.max(1, Math.round((use.tokens / max) * barW))
293 const showBar = bar && barW > 0
294 return (
295 <Text key={key} wrap="truncate-end">
296 <Text color={ACCENT}>{fresh ? '● ' : ' '}</Text>
297 {label}
298 {' '.repeat(nameW - width(label) + 1)}
299 {showBar ? '█'.repeat(filled) : null}
300 {showBar ? <Text dimColor>{'░'.repeat(barW - filled)} </Text> : null}
301 {!bar && barW > 0 ? ' '.repeat(barW + 1) : null}
302 {formatTokens(use.tokens).padStart(5)}
303 <Text dimColor>{(use.count ?? 0) > 1 ? ` ×${use.count}` : ''}</Text>
304 </Text>
305 )
306 }
307 // 段落標題後接一句說明,放不下時截斷
308 const heading = (key: string, text: string, note = '') => (
309 <Text key={key} dimColor wrap="truncate-end">
310 {note ? `${text} ${note}` : text}
311 </Text>
312 )
313 // 全螢幕時常駐全部列出;否則明細限半個視窗高,常駐放不下的併成一行
314 const rows = e.viewport?.rows
315 const limit = e.viewport?.isFullscreen === false && rows ? Math.floor(rows / 2) : Infinity
316 const isEmpty = named.length === 0 && Object.keys(unmatched).length === 0
317 // 外框上下、模型列、注入標題、常駐標題、未比中各佔一行
318 const fixed = 4 + (isEmpty ? 1 : 0) + named.reduce((n, g) => n + 1 + Object.keys(g.items).length, 0)
319 + (residents.length ? 1 : 0) + (Object.keys(unmatched).length ? 1 : 0)
320 const room = limit - fixed
321 const shownResident = barW === 0 ? [] : residents.length <= room ? residents : residents.slice(0, Math.max(0, room - 1))
322 const restResident = residents.length - shownResident.length
323
324 return frame(
325 <Box flexDirection="column" flexGrow={1}>
326 <Box flexDirection="row" justifyContent="space-between">
327 <Text wrap="truncate-end">{headParts}</Text>
328 {toggle}
329 </Box>
330 {heading('h-inj', `注入 ≈ ${formatTokens(total)}`, 'skill 與 hook 加進對話的內容')}
331 {isEmpty ? heading('none', ' 尚未有注入') : null}
332 {named.flatMap(g => [
333 row(`g:${g.name}`, groupLabel(g.name), { tokens: g.tokens }, false, g.isFresh),
334 ...Object.entries(g.items)
335 .sort((a, b) => b[1].tokens - a[1].tokens)
336 .map(([k, u]) => row(`i:${JSON.stringify([g.name, k])}`, ` ${k}`, u, true, isNow(u))),
337 ])}
338 {residents.length ? heading('h-res', `常駐 ≈ ${formatTokens(residentTotal)}`, '每輪固定送出的內容') : null}
339 {shownResident.map(r => row(`r:${r.name}`, r.name, r, false))}
340 {restResident > 0 && barW > 0 ? heading('r-rest', ` 其他 ${restResident} 項`) : null}
341 {Object.keys(unmatched).length
342 ? heading('h-un', `${UNMATCHED_LABEL} ≈ ${formatTokens(sum(unmatched))}`, '認不出來源的 hook 注入')
343 : null}
344 </Box>
345 )
346 })
347}
348types/index.d.ts 18 lines1export type Injection = { tokens: number; count: number; round: number }
2export type Injections = Record<string, Record<string, Injection>>
3export type Resident = { name: string; tokens: number }
4
5declare module 'claude-code' {
6 interface PluginState {
7 'session-lens': {
8 model: string
9 injections: Injections
10 round: number
11 output: number
12 contextPercent: number | null
13 resident: Resident[]
14 isExpanded: boolean
15 }
16 }
17}
18