SLOPSHOPPER

token-meter

Live pane with tokens read, written and the context window fill

panecommandprocesstimer
v0.2.0no licenseupdated 2026-10-18Dumorro/token-meter
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · token-meter
│ ┃ Tokens ✕ › fix the failing auth test and add an audit log call │ ┃ Current session │ ┃ Read 97.4k ⏺ Read(src/auth.ts) │ ┃ uncached 2.1k ⎿ Read 6 lines │ ┃ cache read 91.0k ⏺ Update(src/auth.ts) │ ┃ cache write 4.3k ⎿ Added 2 lines, removed 1 line │ ┃ Written 1.5k ⏺ Bash(bun test) │ ┃ Total 98.9k ⎿ 3 pass, 1 fail │ ┃ Cost $0.08 (estimated, API pricing) │ ┃ opus $0.08 · 98.9k tok · 1 resp ● Done. refresh now rejects expired claims and logs an audit event. │ ┃ 1 API responses · includes subagents · │ ┃ since the mod loaded ✻ Worked for 42s · done 4:20 PM │ ┃ │ ┃ Weekly › /tokens │ ┃ calculating… ⎿ token-meter: Token meter pane opened. │ ┃ │ ┃ Account total │ ┃ calculating… │ ┃ │ ┃ Context window │ ┃ 97.4k / 200.0k (49%) │ ┃ /cost for this process $0.42 │ ┃ │ ┃ Limits │ ┃ 5h window: 69% free (31% used) │ ┃ ████████████░░░░░░░░░░░░░░░░░░░░░░░░░░░░ ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Pane · Tokens
Current session Read 97.4k uncached 2.1k cache read 91.0k cache write 4.3k Written 1.5k Total 98.9k Cost $0.08 (estimated, API pricing) opus $0.08 · 98.9k tok · 1 resp 1 API responses · includes subagents · since the mod loaded Weekly calculating… Account total calculating… Context window 97.4k / 200.0k (49%) /cost for this process $0.42 Limits 5h window: 69% free (31% used) ████████████░░░░░░░░░░░░░░░░░░░░░░░░░░░░
README

token-meter

A Claude Code mod that opens a pane with the tokens read and written in the current session and over the week (across all projects), the account total (every transcript still on disk under ~/.claude/projects, rescanned every 30 minutes), the estimated cost at API prices (total and per model family: fable, opus, sonnet, haiku, other), the context window fill, and the usage limits (5h, weekly) with the time left until each reset.

Install

At the prompt of a Claude Code terminal session:

/plugin install token-meter --marketplace Dumorro/token-meter

Answer y to add the marketplace and pick the user scope. The pane opens when a session starts; reopen it with /tokens.

Requirements

  • jq on the PATH. It reads the transcripts under ~/.claude/projects to total the session (subagents included) and the week. Without jq, the pane shows only what it counted since the mod loaded and the totals saved from earlier sessions.

Notes

  • The cost is an estimate from the API price table in hooks/pricing.ts, not what a plan bills. Models missing from the table are listed as "unpriced" instead of being counted as free.

Development

claude plugin validate .
claude plugin test .
Source 4 files
hooks/register.tsx 420 lines
1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, Register, RenderChildren, SessionContextUsage } from 'claude-code'
3
4import type { Account, Limit, Source, Totals, Week, Window } from '../types'
5
6import { costOf } from './pricing'
7import type { ModelUsage } from './pricing'
8import { addFamily, AGGREGATE, EMPTY, summarize } from './usage'
9
10const PANE = 'token-meter'
11const WEEK_MS = 7 * 86_400_000
12const WEEK_EVERY_MS = 10 * 60_000
13const ACCOUNT_EVERY_MS = 30 * 60_000
14
15const totals = atom({ plugin: 'token-meter', key: 'totals' } as const, EMPTY)
16const week = atom({ plugin: 'token-meter', key: 'week' } as const, null as Week | null)
17const account = atom({ plugin: 'token-meter', key: 'account' } as const, null as Account | null)
18const source = atom({ plugin: 'token-meter', key: 'source' } as const, 'live' as Source)
19const window = atom({ plugin: 'token-meter', key: 'window' } as const, null)
20const usd = atom({ plugin: 'token-meter', key: 'usd' } as const, null)
21const limits = atom({ plugin: 'token-meter', key: 'limits' } as const, [] as Limit[])
22
23const STORE_PREFIX = 'session:'
24const STORE_WEEK = 'week'
25const STORE_ACCOUNT = 'account'
26const STORE_KEEP = 200
27
28const projectKey = (dir: string) => dir.replace(/[^A-Za-z0-9]/g, '-')
29const projectsDir = async ($: EngineInterface) => `${(await $.env.get('HOME')) ?? ''}/.claude/projects`
30
31// Saved totals from before usd or the per-family split existed lack them; treat them as tokens without a price.
32const withDefaults = (t: Partial<Totals>): Totals => ({
33  ...EMPTY,
34  ...t,
35  byFamily: t.byFamily ?? [],
36  unpricedModels: t.unpricedModels ?? [],
37})
38
39async function transcriptFiles($: EngineInterface, sessionId: string): Promise<string[]> {
40  const projects = await projectsDir($)
41  const hasTranscript = (name: string) => $.fs.exists(`${projects}/${name}/${sessionId}.jsonl`)
42  // The transcript lives under the launch directory's key; search every project only when it moved.
43  let name: string | undefined
44  for (const guess of [projectKey(await $.session.root()), projectKey(await $.session.cwd())]) {
45    if (await hasTranscript(guess)) {
46      name = guess
47      break
48    }
49  }
50  if (name === undefined) {
51    for (const entry of await $.fs.list(projects)) {
52      if (entry.kind === 'dir' && (await hasTranscript(entry.name))) {
53        name = entry.name
54        break
55      }
56    }
57  }
58  if (name === undefined) return []
59  const dir = `${projects}/${name}`
60  const files = [`${dir}/${sessionId}.jsonl`]
61  const subagents = `${dir}/${sessionId}/subagents`
62  if (await $.fs.exists(subagents)) {
63    for (const f of await $.fs.list(subagents)) {
64      if (f.kind === 'file' && f.name.endsWith('.jsonl')) files.push(`${subagents}/${f.name}`)
65    }
66  }
67
68  return files
69}
70
71async function scanSession($: EngineInterface): Promise<Totals | null> {
72  const files = await transcriptFiles($, await $.session.id())
73  if (files.length === 0) return null
74  const r = await $.process.run(['jq', '-ncR', '--arg', 'since', '', AGGREGATE, ...files], { timeoutMs: 60_000 })
75  if (r.exitCode !== 0) return null
76
77  return summarize(JSON.parse(r.stdout) as ModelUsage[])
78}
79
80// Every session of every project since the start of the weekly limit window: files touched in the
81// window, assistant lines only (grep), then the same aggregate filtered by timestamp.
82async function scanWeek($: EngineInterface, since: number, now: number): Promise<Totals | null> {
83  const minutes = String(Math.ceil((now - since) / 60_000) + 60)
84  const script =
85    'find "$1" -name "*.jsonl" -mmin "-$2" -print0 | xargs -0 grep -h -F \'"type":"assistant"\' | jq -ncR --arg since "$3" "$4"'
86  const r = await $.process.run(
87    ['sh', '-c', script, 'sh', await projectsDir($), minutes, new Date(since).toISOString(), AGGREGATE],
88    { timeoutMs: 120_000 },
89  )
90  if (r.exitCode !== 0) return null
91
92  return summarize(JSON.parse(r.stdout) as ModelUsage[])
93}
94
95// Every session of every project still on disk, no time filter; the first stdout line is the
96// oldest transcript's mtime in seconds, the second the aggregate.
97async function scanAccount($: EngineInterface): Promise<Omit<Account, 'at'> | null> {
98  const script =
99    'oldest=$(find "$1" -name "*.jsonl" -exec stat -f %m {} + | sort -n | head -1); echo "${oldest:-0}"; ' +
100    'find "$1" -name "*.jsonl" -print0 | xargs -0 grep -h -F \'"type":"assistant"\' | jq -ncR --arg since "" "$2"'
101  const r = await $.process.run(['sh', '-c', script, 'sh', await projectsDir($), AGGREGATE], { timeoutMs: 300_000 })
102  if (r.exitCode !== 0) return null
103  const [first, ...rest] = r.stdout.split('\n')
104  const oldest = Number(first) * 1000
105
106  return { oldest: oldest > 0 ? oldest : null, totals: summarize(JSON.parse(rest.join('\n')) as ModelUsage[]) }
107}
108
109async function saveSession($: EngineInterface, t: Totals) {
110  await $.store.set(`${STORE_PREFIX}${await $.session.id()}`, t)
111  const keys = (await $.store.keys()).filter(k => k.startsWith(STORE_PREFIX))
112  for (const old of keys.slice(0, Math.max(0, keys.length - STORE_KEEP))) await $.store.delete(old)
113}
114
115let isScanning = false
116let isScanningWeek = false
117let isScanningAccount = false
118
119async function refreshSession($: EngineInterface) {
120  if (isScanning) return
121  isScanning = true
122  try {
123    const t = await scanSession($)
124    if (t) {
125      await update($, totals, () => t)
126      await update($, source, () => 'transcript' as Source)
127      await saveSession($, t)
128    }
129  } catch {
130    // keep what is shown; the next turn retries
131  } finally {
132    isScanning = false
133  }
134}
135
136// The weekly limit's own window when the API reported one, else the last seven days.
137async function weekStart($: EngineInterface, now: number) {
138  const resetsAt = (await read($, limits)).find(l => l.kind === 'seven_day')?.resetsAt
139  const reset = resetsAt === undefined ? NaN : Date.parse(resetsAt)
140
141  return Number.isNaN(reset) ? now - WEEK_MS : reset - WEEK_MS
142}
143
144async function refreshWeek($: EngineInterface) {
145  if (isScanningWeek) return
146  isScanningWeek = true
147  try {
148    const now = await $.clock.now()
149    const since = await weekStart($, now)
150    const t = await scanWeek($, since, now)
151    if (t) {
152      const w: Week = { since, at: now, totals: t }
153      await update($, week, () => w)
154      await $.store.set(STORE_WEEK, w)
155    }
156  } catch {
157    // keep what is shown; the next period retries
158  } finally {
159    isScanningWeek = false
160  }
161}
162
163async function refreshAccount($: EngineInterface) {
164  if (isScanningAccount) return
165  isScanningAccount = true
166  try {
167    const a = await scanAccount($)
168    if (a) {
169      const value: Account = { ...a, at: await $.clock.now() }
170      await update($, account, () => value)
171      await $.store.set(STORE_ACCOUNT, value)
172    }
173  } catch {
174    // keep what is shown; the next period retries
175  } finally {
176    isScanningAccount = false
177  }
178}
179
180const fmt = (n: number) =>
181  n >= 1_000_000_000
182    ? `${(n / 1_000_000_000).toFixed(2)}B`
183    : n >= 1_000_000
184      ? `${(n / 1_000_000).toFixed(2)}M`
185      : n >= 1_000
186        ? `${(n / 1_000).toFixed(1)}k`
187        : `${n}`
188
189const money = (n: number) => `$${n.toFixed(2)}`
190
191const ddmm = (ms: number) => {
192  const d = new Date(ms)
193  const two = (n: number) => String(n).padStart(2, '0')
194
195  return `${two(d.getDate())}/${two(d.getMonth() + 1)} ${two(d.getHours())}:${two(d.getMinutes())}`
196}
197
198const LIMIT_LABEL: Record<string, string> = {
199  five_hour: '5h window',
200  seven_day: 'Weekly',
201  spend_limit: 'Spend',
202}
203
204const until = (resetsAt: string | undefined, now: number) => {
205  const at = resetsAt === undefined ? NaN : Date.parse(resetsAt)
206  if (Number.isNaN(at)) return ''
207  const min = Math.max(0, Math.round((at - now) / 60_000))
208  const d = Math.floor(min / 1440)
209  const h = Math.floor((min % 1440) / 60)
210  const m = min % 60
211
212  return ` · resets in ${d > 0 ? `${d}d ${h}h` : h > 0 ? `${h}h${String(m).padStart(2, '0')}` : `${m}min`}`
213}
214
215const limitColor = (used: number) => (used >= 85 ? 'red' : used >= 60 ? 'yellow' : 'green')
216
217const BAR_MAX = 40
218
219// Cells of the usage bar: filled for the used share, rounded, clamped to [0, width].
220const barCells = (used: number, width: number) => {
221  const filled = Math.min(width, Math.max(0, Math.round((used / 100) * width)))
222
223  return { filled: '█'.repeat(filled), empty: '░'.repeat(width - filled) }
224}
225
226const toWindow = (c: SessionContextUsage): Window => ({
227  tokens: c.tokens ?? null,
228  size: c.window,
229  percent: c.percent ?? null,
230})
231
232export const register: Register = on => {
233  on('session.start', async ($, e, next) => {
234    await $.command.register({
235      name: 'tokens',
236      description: 'Open the token meter pane',
237    })
238    const saved = (await $.store.get(`${STORE_PREFIX}${await $.session.id()}`)) as Partial<Totals> | undefined
239    if (saved) {
240      await update($, totals, () => withDefaults(saved))
241      await update($, source, () => 'saved' as Source)
242    }
243    const savedWeek = (await $.store.get(STORE_WEEK)) as Week | undefined
244    if (savedWeek) await update($, week, () => ({ ...savedWeek, totals: withDefaults(savedWeek.totals) }))
245    const savedAccount = (await $.store.get(STORE_ACCOUNT)) as Account | undefined
246    if (savedAccount) await update($, account, () => ({ ...savedAccount, totals: withDefaults(savedAccount.totals) }))
247    const usage = await $.session.usage()
248    await update($, window, () => toWindow(usage.context))
249    await update($, usd, () => usage.cost?.usd ?? null)
250    await update($, limits, () => usage.rateLimits)
251    void refreshSession($)
252    $.clock.every(WEEK_EVERY_MS, () => void refreshWeek($))
253    // The week scan goes first: both read every project, and the account one reads all of it.
254    void refreshWeek($).then(() => refreshAccount($))
255    $.clock.every(ACCOUNT_EVERY_MS, () => void refreshAccount($))
256    void $.ui.open({ id: PANE, title: 'Tokens' })
257
258    return next(e)
259  })
260
261  on('command.run', { command: 'tokens' }, async $ => {
262    await $.ui.open({ id: PANE, title: 'Tokens' })
263
264    return { text: 'Token meter pane opened.' }
265  })
266
267  on('turn.complete', async ($, e, next) => {
268    const u = e.usage
269    if (u) {
270      const turnUsd =
271        costOf({
272          model: u.model,
273          fast: false,
274          input: u.input_tokens,
275          cacheRead: u.cache_read_input_tokens,
276          cacheWrite: u.cache_creation_input_tokens,
277          cacheWrite1h: 0,
278          output: u.output_tokens,
279          responses: 1,
280        }) ?? 0
281      const t = await update($, totals, t => ({
282        ...t,
283        input: t.input + u.input_tokens,
284        cacheRead: t.cacheRead + u.cache_read_input_tokens,
285        cacheWrite: t.cacheWrite + u.cache_creation_input_tokens,
286        output: t.output + u.output_tokens,
287        turns: t.turns + 1,
288        usd: t.usd + turnUsd,
289        byFamily: addFamily(
290          t.byFamily,
291          u.model,
292          u.input_tokens + u.cache_read_input_tokens + u.cache_creation_input_tokens + u.output_tokens,
293          turnUsd,
294          1,
295        ),
296      }))
297      await saveSession($, t)
298    }
299    const ran = await next(e)
300    if (e.agentId === undefined) void refreshSession($)
301
302    return ran
303  })
304
305  on('session.measure', async ($, e, next) => {
306    await update($, window, () => toWindow(e.context))
307    await update($, usd, () => e.cost?.usd ?? null)
308    await update($, limits, () => e.rateLimits)
309
310    return next(e)
311  })
312
313  on('session.end', async ($, e, next) => {
314    if (e.reason === 'clear') {
315      await update($, totals, () => EMPTY)
316      await update($, source, () => 'live' as Source)
317      await update($, window, () => null)
318    }
319
320    return next(e)
321  })
322
323  on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
324    const { Box, Text } = $.ui.resolve(e)
325    const t = await read($, totals)
326    const wk = await read($, week)
327    const acct = await read($, account)
328    const from = await read($, source)
329    const w = await read($, window)
330    const cost = await read($, usd)
331    const rate = await read($, limits)
332    const now = await $.clock.now()
333    const barWidth = Math.max(10, Math.min(BAR_MAX, e.props.bodyColumns - 4))
334
335    const block = (x: Totals, note: RenderChildren) => {
336      const readTotal = x.input + x.cacheRead + x.cacheWrite
337
338      return (
339        <Box flexDirection="column">
340          <Text>  Read     {fmt(readTotal)}</Text>
341          <Text dimColor>    uncached    {fmt(x.input)}</Text>
342          <Text dimColor>    cache read  {fmt(x.cacheRead)}</Text>
343          <Text dimColor>    cache write {fmt(x.cacheWrite)}</Text>
344          <Text>  Written  {fmt(x.output)}</Text>
345          <Text>  Total    {fmt(readTotal + x.output)}</Text>
346          <Text color="cyan">  Cost     {money(x.usd)} (estimated, API pricing)</Text>
347          {x.byFamily.map(f => (
348            <Text dimColor>
349              {`    ${f.family.padEnd(7)} ${money(f.usd).padStart(9)} · ${fmt(f.tokens)} tok · ${f.responses} resp`}
350            </Text>
351          ))}
352          {x.unpricedModels.length > 0 && (
353            <Text dimColor>    unpriced: {x.unpricedModels.join(', ')}</Text>
354          )}
355          <Text dimColor>
356            {'  '}
357            {x.turns} API responses · {note}
358          </Text>
359        </Box>
360      )
361    }
362
363    return (
364      <Box flexDirection="column">
365        <Text bold>Current session</Text>
366        {block(
367          t,
368          `includes subagents · ${from === 'transcript' ? 'transcript' : from === 'saved' ? 'saved' : 'since the mod loaded'}`,
369        )}
370        <Text> </Text>
371        <Text bold>Weekly{wk ? ` (since ${ddmm(wk.since)})` : ''}</Text>
372        {wk ? (
373          block(wk.totals, `all projects · updated ${ddmm(wk.at)}`)
374        ) : (
375          <Text dimColor>  calculating…</Text>
376        )}
377        <Text> </Text>
378        <Text bold>Account total{acct?.oldest ? ` (since ${ddmm(acct.oldest)})` : ''}</Text>
379        {acct ? (
380          block(acct.totals, `all projects · transcripts on disk · updated ${ddmm(acct.at)}`)
381        ) : (
382          <Text dimColor>  calculating…</Text>
383        )}
384        <Text> </Text>
385        <Text bold>Context window</Text>
386        {w === null || w.tokens === null ? (
387          <Text dimColor>  waiting for first response</Text>
388        ) : (
389          <Text color={(w.percent ?? 0) >= 85 ? 'red' : (w.percent ?? 0) >= 60 ? 'yellow' : 'green'}>
390            {'  '}
391            {fmt(w.tokens)} / {fmt(w.size)} ({w.percent ?? 0}%)
392          </Text>
393        )}
394        {cost !== null && <Text dimColor>  /cost for this process {money(cost)}</Text>}
395        <Text> </Text>
396        <Text bold>Limits</Text>
397        {rate.length === 0 && <Text dimColor>  no reading yet</Text>}
398        {rate.map(l => {
399          const bar = barCells(l.percentUsed, barWidth)
400
401          return (
402            <Box flexDirection="column">
403              <Text color={limitColor(l.percentUsed)}>
404                {'  '}
405                {LIMIT_LABEL[l.kind] ?? l.kind}: {Math.max(0, Math.round((100 - l.percentUsed) * 10) / 10)}% free (
406                {l.percentUsed}% used){until(l.resetsAt, now)}
407              </Text>
408              <Box flexDirection="row">
409                <Text>{'  '}</Text>
410                <Text color={limitColor(l.percentUsed)}>{bar.filled}</Text>
411                <Text dimColor>{bar.empty}</Text>
412              </Box>
413            </Box>
414          )
415        })}
416      </Box>
417    )
418  })
419}
420
hooks/pricing.ts 62 lines
1// US$ per million tokens, Anthropic first-party list prices (claude-api skill, cached 2026-09-25).
2// Cache writes are 1.25x input (5 min) and 2x input (1 h); cache reads are 0.1x input except
3// where a model sets its own rate.
4import type { Family } from '../types'
5
6type Rate = { input: number; output: number; cacheRead: number }
7
8const RATES: [prefix: string, rate: Rate][] = [
9  ['claude-fable-5-1', { input: 10, output: 50, cacheRead: 0.25 }],
10  ['claude-mythos-5-1', { input: 10, output: 50, cacheRead: 0.25 }],
11  ['claude-fable-5', { input: 10, output: 50, cacheRead: 1 }],
12  ['claude-mythos-5', { input: 10, output: 50, cacheRead: 1 }],
13  ['claude-opus-5-5', { input: 4, output: 20, cacheRead: 0.2 }],
14  ['claude-opus-5', { input: 5, output: 25, cacheRead: 0.5 }],
15  ['claude-opus-4-8', { input: 5, output: 25, cacheRead: 0.5 }],
16  ['claude-opus-4-7', { input: 5, output: 25, cacheRead: 0.5 }],
17  ['claude-opus-4-6', { input: 5, output: 25, cacheRead: 0.5 }],
18  ['claude-sonnet-5-5', { input: 2, output: 10, cacheRead: 0.2 }],
19  ['claude-sonnet-5', { input: 2, output: 10, cacheRead: 0.2 }],
20  ['claude-sonnet-4-6', { input: 3, output: 15, cacheRead: 0.3 }],
21  ['claude-haiku-4-5', { input: 1, output: 5, cacheRead: 0.1 }],
22]
23
24// Display order of the per-family cost lines; anything else falls under 'other'.
25export const FAMILIES: Family[] = ['fable', 'opus', 'sonnet', 'haiku', 'other']
26
27export const familyOf = (model: string): Family =>
28  FAMILIES.find(f => f !== 'other' && model.startsWith(`claude-${f}`)) ?? 'other'
29
30// Longest prefix first, so claude-opus-5-5 never matches claude-opus-5.
31const BY_LENGTH = [...RATES].sort((a, b) => b[0].length - a[0].length)
32
33export const rateOf = (model: string): Rate | undefined =>
34  BY_LENGTH.find(([prefix]) => model.startsWith(prefix))?.[1]
35
36export type ModelUsage = {
37  model: string
38  fast: boolean
39  input: number
40  cacheRead: number
41  cacheWrite: number
42  cacheWrite1h: number
43  output: number
44  responses: number
45}
46
47// Estimated cost of one model's usage; undefined when the model has no known price.
48export function costOf(u: ModelUsage): number | undefined {
49  const r = rateOf(u.model)
50  if (!r) return undefined
51  const write5m = Math.max(0, u.cacheWrite - u.cacheWrite1h)
52  const usd =
53    (u.input * r.input +
54      u.cacheRead * r.cacheRead +
55      write5m * r.input * 1.25 +
56      u.cacheWrite1h * r.input * 2 +
57      u.output * r.output) /
58    1_000_000
59
60  return u.fast ? usd * 2 : usd
61}
62
hooks/usage.ts 70 lines
1import type { FamilyCost, Totals } from '../types'
2
3import { costOf, familyOf, FAMILIES } from './pricing'
4import type { ModelUsage } from './pricing'
5
6// Every assistant record carries its API response's usage, repeated once per content block:
7// dedupe by message id, keep records at or after $since, and sum per model and speed.
8// Lines a writer left half-written are skipped.
9export const AGGREGATE = [
10  '[inputs | fromjson? | select(.type == "assistant" and .message.usage != null and (.timestamp // "") >= $since)',
11  '| .message as $m | $m.usage as $u',
12  '| {k: ($m.id // .requestId // ""), m: ($m.model // "?"), f: (($u.speed // "standard") == "fast"),',
13  'in: ($u.input_tokens // 0), cr: ($u.cache_read_input_tokens // 0),',
14  'w1: ($u.cache_creation.ephemeral_1h_input_tokens // 0), w: ($u.cache_creation_input_tokens // 0),',
15  'out: ($u.output_tokens // 0)}]',
16  '| unique_by(.k) | group_by([.m, .f])',
17  '| map({model: .[0].m, fast: .[0].f, input: (map(.in) | add), cacheRead: (map(.cr) | add),',
18  'cacheWrite: (map(.w) | add), cacheWrite1h: (map(.w1) | add), output: (map(.out) | add), responses: length})',
19].join(' ')
20
21export const EMPTY: Totals = {
22  input: 0,
23  cacheRead: 0,
24  cacheWrite: 0,
25  output: 0,
26  turns: 0,
27  usd: 0,
28  byFamily: [],
29  unpricedModels: [],
30}
31
32// Adds one model's tokens and cost to its family's line; never mutates the list it is given.
33export function addFamily(
34  list: readonly FamilyCost[],
35  model: string,
36  tokens: number,
37  usd: number,
38  responses: number,
39): FamilyCost[] {
40  if (tokens === 0) return [...list]
41  const family = familyOf(model)
42  const next = list.some(f => f.family === family)
43    ? list.map(f =>
44        f.family === family
45          ? { ...f, tokens: f.tokens + tokens, usd: f.usd + usd, responses: f.responses + responses }
46          : f,
47      )
48    : [...list, { family, tokens, usd, responses }]
49
50  return next.sort((a, b) => FAMILIES.indexOf(a.family) - FAMILIES.indexOf(b.family))
51}
52
53export function summarize(rows: readonly ModelUsage[]): Totals {
54  const t: Totals = { ...EMPTY, byFamily: [], unpricedModels: [] }
55  for (const r of rows) {
56    t.input += r.input
57    t.cacheRead += r.cacheRead
58    t.cacheWrite += r.cacheWrite
59    t.output += r.output
60    t.turns += r.responses
61    const tokens = r.input + r.cacheRead + r.cacheWrite + r.output
62    const usd = costOf(r)
63    if (usd !== undefined) t.usd += usd
64    else if (tokens > 0) t.unpricedModels.push(r.model)
65    t.byFamily = addFamily(t.byFamily, r.model, tokens, usd ?? 0, r.responses)
66  }
67
68  return t
69}
70
types/index.d.ts 41 lines
1export type Family = 'fable' | 'opus' | 'sonnet' | 'haiku' | 'other'
2
3// Tokens and estimated cost of one model family; only families with tokens appear, in a fixed order.
4export type FamilyCost = { family: Family; tokens: number; usd: number; responses: number }
5
6export type Totals = {
7  input: number
8  cacheRead: number
9  cacheWrite: number
10  output: number
11  turns: number
12  usd: number
13  byFamily: FamilyCost[]
14  unpricedModels: string[]
15}
16
17export type Week = { since: number; at: number; totals: Totals }
18
19// Every transcript still on disk, across all projects; `oldest` is the earliest file's mtime.
20export type Account = { oldest: number | null; at: number; totals: Totals }
21
22export type Source = 'transcript' | 'saved' | 'live'
23
24export type Limit = { kind: string; percentUsed: number; resetsAt?: string }
25
26export type Window = { tokens: number | null; size: number; percent: number | null }
27
28declare module 'claude-code' {
29  interface PluginState {
30    'token-meter': {
31      totals: Totals
32      week: Week | null
33      account: Account | null
34      source: Source
35      window: Window | null
36      usd: number | null
37      limits: Limit[]
38    }
39  }
40}
41