A pane listing each prompt's token usage and its cost at standard API (Enterprise usage) rates; /token-panel turns it on and off

A Claude Code mod that shows, for every prompt of the session, how many tokens it used and what it cost.

Requires Claude Code 2.1.287 or newer.
/plugin install token-panel --marketplace flowmux-ai/claude-token-panel
The pane starts hidden. The TokenPanel button above the prompt or /token-panel opens it, and /token-panel hides it again.
cost only.sum row matches /cost. Cost not tied to any prompt shows as etc unplaced.tail, each count only what was written since the last. A count that fails says why in the pane's last line.Tokens times the standard API rates. The rate table lives in hooks/tally.ts and is updated by hand. A model missing from it shows ? instead of $.
claude --plugin-dir . # run the mod from this folder, reloading on save
claude plugin validate .
claude plugin test .
hooks/register.tsx 353 lines1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, Register, Timer } from 'claude-code'
3
4import type { Flash, Row, Usage } from '../types'
5import type { Cursor } from './tally'
6import { cursor, feed, settle } from './tally'
7
8const PANE = 'token-panel'
9const TITLE = 'Claude Token Panel'
10// Above the prompt the table lists five prompts: the frame asks for them, the title, the head, `etc` and `sum`.
11const LIST = 5
12// Column widths in cells: 3, 10 for the model, 7 per token count, 8 for the cost.
13const WIDTH = 49
14const OPEN = { id: PANE, title: TITLE, columns: WIDTH, rows: LIST + 4 }
15const HEAD = [' #', ' model ', ' in', ' out', ' cacheR', ' cacheW', ' cost']
16const COUNTS = ['input', 'output', 'cacheRead', 'cacheWrite'] as const
17const NONE: Usage = { path: null, rows: [], offset: null, mark: 0, marks: {}, rest: 0 }
18const DARK: Flash = null
19const usage = atom({ plugin: 'token-panel', key: 'usage' } as const, NONE)
20const flash = atom({ plugin: 'token-panel', key: 'flash' } as const, DARK)
21const fault = atom({ plugin: 'token-panel', key: 'fault' } as const, null as string | null)
22// How many prompts the list is scrolled up from the newest: 0 keeps the newest in view.
23const back = atom({ plugin: 'token-panel', key: 'back' } as const, 0)
24// Whether the pane is drawn: while it is not, the band above the prompt holds its button.
25const isShown = atom({ plugin: 'token-panel', key: 'isShown' } as const, false)
26
27const tokens = (n: number): string =>
28 n < 1000 ? String(n) : n < 1e6 ? `${(n / 1e3).toFixed(1)}k` : `${(n / 1e6).toFixed(2)}M`
29
30// A prompt's cost is its transcript's plus the internal calls the engine billed in it.
31const cell = (row: Row, key: (typeof COUNTS)[number] | 'usd'): number =>
32 key === 'usd' ? row.usd + row.other : row[key]
33
34const line = (
35 label: string,
36 model: string,
37 of: (key: (typeof COUNTS)[number] | 'usd') => number,
38 isUnpriced: boolean,
39): string[] => [
40 label.padStart(3),
41 ` ${model.padEnd(9)}`,
42 ...COUNTS.map(key => tokens(of(key)).padStart(7)),
43 `${isUnpriced ? '?' : '$'}${of('usd').toFixed(2)}`.padStart(8),
44]
45
46// Where the CLI keeps the transcript, once it is written: for when no classic
47// event named it (another plugin may bypass this one's classic hooks).
48const locate = async ($: EngineInterface): Promise<string | null> => {
49 const path = `${await $.env.get('HOME')}/.claude/projects/${(await $.session.root()).replace(/[^a-zA-Z0-9]/g, '-')}/${await $.session.id()}.jsonl`
50
51 return (await $.fs.exists(path)) ? path : null
52}
53
54// The session's count so far: the transcript's path, its rows, and how far each file is read. A reload
55// starts over, as the module does; so does a new path (/clear).
56// ponytail: a count from zero reads the whole transcript again, 18 MB in five `tail` runs and ~50 ms of parsing
57type Count = { path: string; rows: Row[]; cursors: Map<string, Cursor> }
58let count: Count | undefined
59
60// Feeds `of.rows` what `path` holds past its cursor, in pieces of what a run's output carries (4 MiB): the
61// engine's own read rejects a file over that, `tail` reads from any offset. Two counts at once feed the
62// same lines, which count once, and set the cursor to the same place.
63const pull = async ($: EngineInterface, of: Count, path: string, size: number, isMain: boolean): Promise<void> => {
64 const place = of.cursors.get(path) ?? cursor()
65 of.cursors.set(path, place)
66
67 // Nothing written since the last count: a transcript only grows.
68 if (size <= place.at) {
69 return
70 }
71
72 const start = place.at
73 // The bytes of whole lines fed by this count, and the text read past them: a line cut by a piece's
74 // end is whole with the next piece.
75 let done = 0
76 let rest = ''
77
78 for (let from = start; ; ) {
79 const { exitCode, stdout, stderr, isStdoutTruncated } = await $.process.run(['tail', '-c', `+${from + 1}`, path])
80
81 // A file gone or unreadable mid-way: no partial count.
82 if (exitCode !== 0) {
83 throw new Error(stderr.trim())
84 }
85
86 const text = rest + stdout
87 done += feed(place, of.rows, text, isMain)
88 place.at = start + done
89 rest = text.slice(text.lastIndexOf('\n') + 1)
90 // A cut inside a multi-byte character drops it: the text's own bytes are what was read whole.
91 from += new TextEncoder().encode(stdout).length
92
93 if (!isStdoutTruncated || stdout === '') {
94 return
95 }
96 }
97}
98
99// Counts what the session's transcript, and its subagents' beside it, hold since the last count,
100// then sets what the engine billed beyond them against the prompt it fell in.
101// A count that fails leaves the table as it was and says why in the pane.
102const refresh = async ($: EngineInterface, seen?: string, isNewPrompt = false): Promise<void> => {
103 const path = seen ?? (await read($, usage)).path ?? (await locate($))
104
105 if (path === null) {
106 return
107 }
108
109 try {
110 const of = count?.path === path ? count : { path, rows: [], cursors: new Map<string, Cursor>() }
111 count = of
112
113 // Before the first prompt the transcript is not written yet: count it empty, but keep its path for the next
114 // count. The main transcript goes first: a subagent's prompt entries find their rows in it.
115 if (await $.fs.exists(path)) {
116 await pull($, of, path, (await $.fs.stat(path)).size, true)
117 }
118
119 const folder = path.replace(/\.jsonl$/, '/subagents')
120 const entries = (await $.fs.exists(folder)) ? await $.fs.list(folder) : []
121 await Promise.all(
122 entries
123 .filter(entry => entry.name.endsWith('.jsonl'))
124 .map(entry => pull($, of, `${folder}/${entry.name}`, entry.size, false)),
125 )
126
127 const { cost } = await $.session.usage()
128 // `settle` sets `other` on its rows: copies, so the count's rows stay the transcripts' own.
129 const rows = of.rows.map(row => ({ ...row }))
130
131 await update($, usage, old => settle(old, path, rows, cost?.usd, isNewPrompt))
132 await update($, fault, () => null)
133 } catch (error) {
134 await update($, fault, () => `Token panel: ${String(error)}`)
135 }
136}
137
138// Opens the pane; one that waits undrawn leaves the button up.
139// ponytail: a waiting pane the terminal later widens to seat keeps the button beside it until pressed
140const show = async ($: EngineInterface): Promise<void> => {
141 const { isPlaced } = await $.ui.open(OPEN)
142 await update($, isShown, () => isPlaced)
143}
144
145const shut = ($: EngineInterface): Promise<void> => update($, isShown, () => false)
146
147// The running beat's timer: a module's own, so a reload drops it with the module.
148let beat: Timer | undefined
149// The prompts the list showed when last drawn: how far it can scroll.
150let shown = LIST
151
152// Brings the prompt's row into view and beats its border for three seconds.
153const reveal = async ($: EngineInterface, uuid: string): Promise<void> => {
154 // A row that cannot be brought into view says why; one already in view still beats.
155 const { deny } = await $.ui
156 .scroll({ to: { requestId: uuid }, block: 'center' })
157 .catch((error: unknown) => ({ deny: String(error) }))
158
159 if (deny !== undefined) {
160 $.ui.toast(`Token panel: ${deny}`)
161 }
162
163 let beats = 0
164 beat?.cancel()
165 await update($, flash, () => ({ uuid, isOn: true }))
166 beat = $.clock.every(500, () => {
167 beats += 1
168
169 if (beats >= 6) {
170 beat?.cancel()
171 }
172
173 void update($, flash, () => (beats < 6 ? { uuid, isOn: beats % 2 === 0 } : null))
174 })
175}
176
177export const register: Register = on => {
178 on('session.start', async ($, e, next) => {
179 await $.command.register({
180 name: PANE,
181 description: 'Show or hide the per-prompt token usage and cost pane',
182 })
183 // A reload drops the timer: no beat is left running. A past session's fault is not this one's.
184 await update($, flash, () => null)
185 await update($, fault, () => null)
186
187 // Every session starts with the pane shut: the button above the prompt or /token-panel opens it.
188 await refresh($)
189
190 return next(e)
191 })
192
193 on('command.run', { command: PANE }, async $ => {
194 const isOpen = (await $.ui.panes()).some(pane => pane.id === PANE && pane.isPlaced)
195
196 if (isOpen) {
197 // The pane's own `ui.close` hook below shuts it.
198 await $.ui.close({ id: PANE })
199
200 return { text: 'Token panel off.' }
201 }
202
203 await show($)
204
205 return { text: 'Token panel on.' }
206 })
207
208 // The pane's own close mark: the button takes its place.
209 on('ui.close', { id: PANE }, async ($, e, next) => {
210 const closed = await next(e)
211 await shut($)
212
213 return closed
214 })
215
216 on('classic.SessionStart', async ($, e, next) => {
217 await refresh($, e.transcript_path)
218
219 return next(e)
220 })
221
222 on('classic.UserPromptSubmit', async ($, e, next) => {
223 await refresh($, e.transcript_path, true)
224
225 return next(e)
226 })
227
228 on('classic.PostToolUse', async ($, e, next) => {
229 await refresh($, e.transcript_path)
230
231 return next(e)
232 })
233
234 // The engine billed something: count again, so the sum keeps up with /cost.
235 on('session.measure', async ($, e, next) => {
236 if (e.changed.includes('cost')) {
237 await refresh($)
238 }
239
240 return next(e)
241 })
242
243 on('turn.complete', async ($, e, next) => {
244 const ended = await next(e)
245 await refresh($)
246 // The turn's last response may reach the file a moment after the turn ends.
247 $.clock.after(1000, () => void refresh($))
248
249 return ended
250 })
251
252 on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
253 const { Box, Button, Text } = $.ui.resolve(e)
254 const { rows, rest = 0 } = await read($, usage)
255 const why = await read($, fault)
256 // Docked, the table keeps two empty rows above and below it.
257 const inset = e.props.placement === 'dock' ? 2 : 0
258 // A failed count's line takes one of the list's.
259 const room = Math.max(
260 1,
261 (e.props.placement === 'inline' ? LIST : (e.viewport?.rows ?? 24) - 8 - 2 * inset) - (why === null ? 0 : 1),
262 )
263 const end = rows.length - Math.min(await read($, back), Math.max(0, rows.length - room))
264 const start = Math.max(0, end - room)
265 shown = room
266 // Above the prompt the table spreads over the pane's width; docked it stays compact.
267 const spare = e.props.placement === 'inline' ? e.props.bodyColumns - WIDTH : 0
268 const gap = ' '.repeat(Math.max(0, Math.floor(spare / (HEAD.length - 1))))
269
270 return (
271 <Box flexDirection="column" paddingY={inset}>
272 <Text bold wrap="truncate-end">
273 {TITLE}
274 </Text>
275 <Text bold wrap="truncate-end">
276 {HEAD.join(gap)}
277 </Text>
278 {rows.length === 0 && <Text dimColor>No prompts yet.</Text>}
279 {rows.slice(start, end).map((row: Row, i) => (
280 <Button
281 key={`row:${row.uuid}`}
282 plain
283 label={line(String(start + i + 1), row.model, key => cell(row, key), row.isUnpriced).join(gap)}
284 onPress={() => reveal($, row.uuid)}
285 />
286 ))}
287 {rest >= 0.005 && (
288 <Text dimColor wrap="truncate-end">
289 {line('etc', 'unplaced', key => (key === 'usd' ? rest : 0), false).join(gap)}
290 </Text>
291 )}
292 <Text bold wrap="truncate-end">
293 {line(
294 'sum',
295 '',
296 key => rows.reduce((sum, row) => sum + cell(row, key), key === 'usd' ? rest : 0),
297 rows.some(row => row.isUnpriced),
298 ).join(gap)}
299 </Text>
300 {why !== null && (
301 <Text color="red" wrap="truncate-start">
302 {why}
303 </Text>
304 )}
305 </Box>
306 )
307 })
308
309 // The list scrolls under the title, the head and the sum, which stay put.
310 on('ui.scroll', { requestId: PANE }, async ($, e) => {
311 const { rows } = await read($, usage)
312 await update($, back, old => Math.min(Math.max(0, rows.length - shown), Math.max(0, old - e.by)))
313
314 return {}
315 })
316
317 on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
318 if (e.props.hasSurvey || (await read($, isShown))) {
319 return next(e)
320 }
321
322 const { Box, Button } = $.ui.resolve(e)
323
324 return (
325 <Box width={e.props.bodyColumns} justifyContent="flex-end">
326 <Button
327 key="open"
328 label="TokenPanel"
329 hover={{ scope: 'open', backgroundColor: 'suggestion', color: 'inverseText' }}
330 onPress={() => show($)}
331 />
332 </Box>
333 )
334 })
335
336 on('ui.render', { component: 'UserMessage' }, async ($, e, next) => {
337 const lit = await read($, flash)
338
339 // The engine names a prompt's row by its uuid with the last group zeroed: match the rest.
340 if (lit === null || lit.uuid.slice(0, 23) !== e.requestId.slice(0, 23)) {
341 return next(e)
342 }
343
344 const { Box, Text } = $.ui.resolve(e)
345
346 return (
347 <Box borderStyle="round" borderColor="red" borderDimColor={!lit.isOn} paddingX={1}>
348 <Text bold={lit.isOn}>{e.props.text}</Text>
349 </Box>
350 )
351 })
352}
353hooks/tally.ts 212 lines1import type { Row, Usage } from '../types'
2
3// USD per million tokens at standard API rates, which an Enterprise plan bills
4// usage at: [model id part, input, output, cache read]. The first match wins.
5// A cache write costs 1.25x input (5 minutes) or 2x input (1 hour).
6// ponytail: a table that rots, refresh it from platform.claude.com/docs/en/about-claude/pricing.
7// Not priced: fast mode, US-only inference (1.1x), web search requests, Haiku 5.5's
8// higher rate past a 100K-token prompt.
9const RATES: readonly (readonly [string, number, number, number])[] = [
10 ['claude-fable-5-1', 10, 50, 0.25],
11 ['claude-mythos-5-1', 10, 50, 0.25],
12 ['claude-fable-5', 10, 50, 1],
13 ['claude-mythos-5', 10, 50, 1],
14 ['claude-opus-5-5', 4, 20, 0.2],
15 ['claude-opus-4-1', 15, 75, 1.5],
16 // Opus 4, `claude-opus-4-20250514`: its date follows the version.
17 ['claude-opus-4-2', 15, 75, 1.5],
18 ['claude-opus', 5, 25, 0.5],
19 ['claude-sonnet-5', 2, 10, 0.2],
20 ['claude-sonnet', 3, 15, 0.3],
21 ['claude-haiku-5-5', 0.1, 0.5, 0.01],
22 ['claude-haiku-4-5', 1, 5, 0.1],
23]
24
25// A response's usage as the transcript stores it; `iterations` splits it per
26// request when one response held several (an advisor's call names its own model).
27type Use = {
28 input_tokens?: number
29 output_tokens?: number
30 cache_read_input_tokens?: number
31 cache_creation_input_tokens?: number
32 cache_creation?: { ephemeral_1h_input_tokens?: number }
33 model?: string
34 iterations?: Use[] | null
35}
36
37// Adds `use` to the row, or with `sign` -1 takes it back.
38const spend = (row: Row, model: string, use: Use, sign: 1 | -1): void => {
39 const input = use.input_tokens ?? 0
40 const output = use.output_tokens ?? 0
41 const read = use.cache_read_input_tokens ?? 0
42 const write = use.cache_creation_input_tokens ?? 0
43 const hour = use.cache_creation?.ephemeral_1h_input_tokens ?? 0
44 const rate = RATES.find(([part]) => model.includes(part))
45
46 row.input += sign * input
47 row.output += sign * output
48 row.cacheRead += sign * read
49 row.cacheWrite += sign * write
50
51 if (rate === undefined) {
52 row.isUnpriced ||= input + output + read + write > 0
53
54 return
55 }
56
57 const [, perInput, perOutput, perRead] = rate
58 row.usd +=
59 (sign *
60 (input * perInput +
61 (write - hour) * perInput * 1.25 +
62 hour * perInput * 2 +
63 read * perRead +
64 output * perOutput)) /
65 1e6
66}
67
68// A response's usage as the transcript stores it, counted toward a row at a model.
69type Charge = { row: Row; model: string; usage: Use }
70
71const charge = ({ row, model, usage }: Charge, sign: 1 | -1): void => {
72 for (const use of usage.iterations?.length ? usage.iterations : [usage]) {
73 spend(row, use.model ?? model, use, sign)
74 }
75}
76
77/**
78 * How far one transcript is counted: the bytes fed so far, the prompt the
79 * next response falls in, and what each response counted. A response is
80 * stored once per content block, and a subagent's first copy lacks its
81 * output: a later copy counts in place of the earlier.
82 */
83export type Cursor = { at: number; row: Row | undefined; counted: Map<string, Charge> }
84
85export const cursor = (): Cursor => ({ at: 0, row: undefined, counted: new Map() })
86
87/**
88 * Feeds `text`'s whole lines to `rows`, from the main transcript (`isMain`: a
89 * prompt starts a row) or a subagent's (a prompt finds the row that spawned
90 * it). Returns the bytes fed: a last line without its newline, still being
91 * written or cut by a read, waits. Fed twice, lines count once.
92 */
93export const feed = (cursor: Cursor, rows: Row[], text: string, isMain: boolean): number => {
94 const whole = text.slice(0, text.lastIndexOf('\n') + 1)
95
96 for (const line of whole.split('\n')) {
97 let entry
98
99 try {
100 entry = JSON.parse(line)
101 } catch {
102 // A blank line, or one cut short.
103 continue
104 }
105
106 // A client-local command (/reload-plugins, /clear, …) echoes itself in a user entry but
107 // runs no model turn; it is not a prompt. A model-invoking command keeps its expanded
108 // prompt in a separate entry, so skipping the echo still leaves its row.
109 const content: unknown = entry?.message?.content
110 const isCommand = typeof content === 'string' && /^\s*<(command-|local-command-)/.test(content)
111
112 // A meta entry (a slash command's caveat) is never drawn: the prompt's row takes the next one's uuid.
113 if (
114 entry?.type === 'user' &&
115 entry.isMeta !== true &&
116 !isCommand &&
117 typeof entry.promptId === 'string' &&
118 entry.promptId !== cursor.row?.id
119 ) {
120 let row = rows.find(known => known.id === entry.promptId)
121
122 if (row === undefined && isMain) {
123 row = {
124 id: entry.promptId,
125 uuid: String(entry.uuid),
126 model: '',
127 input: 0,
128 output: 0,
129 cacheRead: 0,
130 cacheWrite: 0,
131 usd: 0,
132 other: 0,
133 isUnpriced: false,
134 }
135 rows.push(row)
136 }
137
138 cursor.row = row
139 }
140
141 const message = entry?.type === 'assistant' ? entry.message : undefined
142
143 if (!message?.usage) {
144 continue
145 }
146
147 // A copy of a response counts toward the row its first copy did; a copy the same as the one counted (fed again) changes nothing.
148 const was = cursor.counted.get(message.id)
149 const owner = was?.row ?? cursor.row ?? rows.at(-1)
150
151 if (owner === undefined || JSON.stringify(was?.usage) === JSON.stringify(message.usage)) {
152 continue
153 }
154
155 const now: Charge = { row: owner, model: String(message.model), usage: message.usage }
156
157 if (was !== undefined) {
158 charge(was, -1)
159 }
160
161 charge(now, 1)
162 cursor.counted.set(message.id, now)
163
164 // The prompt's model is its own loop's last, never a subagent's or a made-up row's.
165 if (isMain && !now.model.startsWith('<')) {
166 owner.model = now.model.replace(/^.*claude-/, '').replace(/-\d{8}$/, '').slice(0, 9)
167 }
168 }
169
170 return new TextEncoder().encode(whole).length
171}
172
173/**
174 * The pane's state after a count: `rows` with each prompt's share of what the
175 * engine billed beyond the transcripts. `engine` is the engine's cost total,
176 * and `isNewPrompt` says a prompt was just submitted: growth up to here is
177 * the earlier prompt's, growth from here the new one's.
178 */
179export const settle = (
180 old: Usage,
181 path: string,
182 rows: Row[],
183 engine: number | undefined,
184 isNewPrompt: boolean,
185): Usage => {
186 if (engine === undefined) {
187 return { ...old, path, rows, rest: 0 }
188 }
189
190 const gap = engine - rows.reduce((sum, row) => sum + row.usd, 0)
191 const offset = old.offset ?? gap
192 const grown = gap - offset
193 const mark = isNewPrompt ? grown : old.mark
194 const marks = { ...old.marks }
195
196 for (const row of rows) {
197 marks[row.id] ??= mark
198 }
199
200 rows.forEach((row, i) => {
201 const next = rows[i + 1]
202 const end = next === undefined ? grown : (marks[next.id] ?? grown)
203 // A count taken between the engine's bill and the transcript's row can dip below zero.
204 row.other = Math.max(0, end - (marks[row.id] ?? end))
205 })
206
207 // Never below zero: a resumed session's engine total may not cover its earlier prompts.
208 const rest = Math.max(0, engine - rows.reduce((sum, row) => sum + row.usd + row.other, 0))
209
210 return { path, rows, offset, mark, marks, rest }
211}
212types/index.d.ts 43 lines1// One prompt of the session: `id` is the transcript's promptId, `uuid` the
2// prompt row's own id (what its UserMessage draws under).
3export type Row = {
4 id: string
5 uuid: string
6 // The main loop's model for the prompt, shortened for the table (`fable-5-1`).
7 model: string
8 input: number
9 output: number
10 cacheRead: number
11 cacheWrite: number
12 usd: number
13 // What the engine billed during the prompt beyond its transcript: internal
14 // calls (a web search's own request, titles, summaries) no transcript row holds.
15 other: number
16 // True when a model no rate is known for answered: `usd` leaves its tokens out.
17 isUnpriced: boolean
18}
19
20export type Usage = {
21 path: string | null
22 rows: Row[]
23 // The engine's cost total less the transcripts', as first seen: what the
24 // difference grows by afterwards is the internal calls' cost. Null until seen.
25 offset: number | null
26 // That growth when the latest prompt was submitted, and when each prompt began.
27 mark: number
28 marks: Record<string, number>
29 // What the engine billed that no row holds (internal calls from before the
30 // mod first counted): with it the table's sum is the engine's total, /cost's.
31 rest: number
32}
33
34// The prompt row whose border beats after its pane row was pressed.
35export type Flash = { uuid: string; isOn: boolean } | null
36
37declare module 'claude-code' {
38 interface PluginState {
39 // `fault` says why the last count failed, while it does: the rows are the last good count's.
40 'token-panel': { usage: Usage; flash: Flash; back: number; isShown: boolean; fault: string | null }
41 }
42}
43