SLOPSHOPPER

credits-bar

A live usage panel for Claude Code with a little pet: limit bars, pace warning, daily goal, context, tokens, cost per project, history and CSV export. English…

panebandcommandtoastprompttimer
v0.5.0MITupdated 2026-10-09jbug0x/credits-bar
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · credits-bar
│ ┃ credits ✕ › fix the failing auth test and add an audit log call │ ┃ 5h 69% restante │ ┃ █████████████████████░░░░░░░░░ ⏺ Read(src/auth.ts) │ ┃ resetando ⎿ Read 6 lines │ ┃ ⏺ Update(src/auth.ts) │ ┃ Contexto 49% usado ⎿ Added 2 lines, removed 1 line │ ┃ ███████████████░░░░░░░░░░░░░░░ ⏺ Bash(bun test) │ ┃ ⎿ 3 pass, 1 fail │ ┃ Tokens │ ┃ entrada 6k · saída 1k · cache 93% ● Done. refresh now rejects expired claims and logs an audit event. │ ┃ Modelos (sessão) │ ┃ opus-5-5 $0.00 · 1k out ✻ Worked for 42s · done 4:20 PM │ ┃ │ ┃ Sessão $0.42 · última resposta $0.00 › /credits-panel │ ┃ ⎿ credits-bar: Painel de créditos fechado. │ ┃ 7 dias │ ┃ gasto ▁▁▁▁▁▁▁ · hoje $0.00 │ ┃ pico ▁▁▁▁▁▁▁ · hoje 0% │ [ ◔ 69% restante ] ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Band
[ ◔ 69% restante ]
Pane · credits
5h 69% restante █████████████████████░░░░░░░░░ resetando Contexto 49% usado ███████████████░░░░░░░░░░░░░░░ Tokens entrada 6k · saída 1k · cache 93% Modelos (sessão) opus-5-5 $0.00 · 1k out Sessão $0.42 · última resposta $0.00 7 dias gasto ▁▁▁▁▁▁▁ · hoje $0.00 pico ▁▁▁▁▁▁▁ · hoje 0%
README

credits-bar

🇧🇷 Português · 🇺🇸 Read in English

Um mod open source para o Claude Code que mantém o seu uso num painel lateral.

Prévia

<img src="docs/painel.png" alt="O painel de créditos: barras de limite, histórico de gastos e o bichinho no rodapé" width="300"> &nbsp;&nbsp; <img src="docs/demo.gif" alt="Demonstração: o painel e o bichinho reagindo aos cliques" width="300">

No painel

  • Barras de limite (5 horas e 7 dias) que esvaziam conforme você gasta, com um relógio de "reseta em" ao vivo.
  • Aviso de ritmo quando o seu consumo atual esvaziaria uma janela antes de ela resetar (! acaba em 40m).
  • Meta diária: defina uma meta em dólares e ganhe uma barra própria e um aviso quando ela for atingida.
  • Janela de contexto: quanto está cheia e o que a está enchendo. Atualiza a cada 30s, não só depois das respostas.
  • Tokens da sessão, taxa de acerto do cache de prompt e custo por modelo na sessão.
  • Custo: total da sessão, última resposta e um mini gráfico das respostas recentes.
  • Gasto por projeto (as pastas que mais gastaram nos últimos 7 dias).
  • Histórico: sparklines de 7 dias, que crescem para um gráfico de barras de 14 dias quando há dados e espaço.
  • Avisos (toasts) em 80% e 95% (configurável), quando uma janela entra em ritmo de acabar antes do reset, e um resumo ao fim da sessão (total gasto e limites usados).

O bichinho (um Tamagotchi simples, no rodapé do painel em qualquer superfície)

  • Uma criaturinha original (nome configurável, Pip por padrão) mora num palquinho com chão no rodapé do painel e, numa versão de uma linha (•ᴗ•), ao lado do botão de ícone acima do prompt.
  • Clique nele e ele reage: dá risada, comemora, acena, faz carinho, fica tonto (uma reação diferente a cada clique). Não precisa alimentar.
  • Passeia quando está de boa, trabalha enquanto o Claude roda um turno, comemora quando uma resposta termina ou a meta diária é atingida, fica cansado acima do primeiro limiar de alerta, entra em pânico acima do segundo e cai no sono depois de um minuto sem nada acontecendo. De vez em quando solta uma frase.
  • /credits-pet manda ele tirar uma soneca ou chama de volta; a opção pet desliga de vez.
  • Os sprites ficam em hooks/pet.ts e são texto simples, então trocar o personagem é mexer num arquivo só.
      ✻
    (•ᴗ•)
  .  ˙ ✿ .  ˙ o .
   Pip · de boa

Visual por superfície

  • Terminal: texto e caracteres de bloco (barras, sparklines, o bichinho em ASCII).
  • App desktop (e o editor, mobile): o mesmo painel desenhado com vetores: barras redondas e lisas e gráficos de barras com informação ao passar o mouse, para gasto e pico de uso. O bichinho é texto em todas as superfícies.

Layout

  • Janela larga (144+ colunas): o painel abre sozinho no início da sessão.
  • Janela estreita: uma faixa de uma linha acima do prompt faz o papel dele (5h ██████░░░░ 29% restante 7d ████░░░░░░ 22% restante ctx 16% $1.42).
  • Painel baixo: muda para uma visão compacta (compact: auto).
  • Um pequeno botão de ícone (◔ 29% restante) fica sempre acima do prompt: mostra o seu limite mais apertado, e um clique abre ou fecha o painel.
  • /credits-panel abre ou fecha o painel lateral (abre em qualquer largura quando você pede).
  • /credits imprime o resumo completo em texto puro (com o bichinho). Funciona em qualquer superfície, mesmo onde o app não desenha o painel nem a faixa.
  • /credits-debug informa onde o mod está carregado e desenhado (para relatos de bug).
  • /credits-export grava o histórico de gastos em credits-history.csv na pasta atual (date,project,usd,peak_percent).
  • /credits-bar mostra ou esconde a faixa de uma linha acima do prompt (pode ser mostrada mesmo com o painel aberto).

Configurações (userConfig, no menu de configuração de plugins): limiares de alerta, modo compacto, cores (default, colorblind, mono), idioma (pt por padrão, ou en), meta diária, som de alerta e quais blocos mostrar.

Som: o som de alerta usa o reprodutor de áudio do motor, que só existe no macOS. No Windows e no Linux a opção não faz nada.

Instalação

/plugin install credits-bar --marketplace jbug0x/credits-bar

Ou, para desenvolvimento: claude --plugin-dir ./credits-bar.

Observações

  • As janelas de limite vêm dos dados de rate limit que o Claude Code recebe, então só aparecem em conta com assinatura. Sem assinatura você vê apenas o custo da sessão.
  • Nada é enviado para lugar nenhum: o mod só lê números que o motor já tem.
  • Estrutura: hooks/register.tsx (toda a lógica), types/index.d.ts (contrato de estado).

Ideias / roadmap

  • Limites do plano por modelo (depende de o motor expor; hoje só o gasto por modelo é mostrado)
  • Gasto por projeto em períodos mais longos e histórico por sessão
  • Som multiplataforma (o motor só toca áudio no macOS)
  • Mais idiomas (adicione uma tabela em hooks/strings.ts)
  • Metas semanais e mensais

Contribuições são bem-vindas. Licença MIT.

Source 7 files
hooks/register.tsx 668 lines
1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, Register } from 'claude-code'
3
4import { PET_WIDTH, POKE_MS, petFloor, petMini, petStage, petState } from './pet'
5import { buildReport } from './report'
6import { barSvg, chartSvg, levelColor } from './svg'
7import { STRINGS } from './strings'
8import {
9  addTokens,
10  barChart,
11  cacheHitPercent,
12  drawBar,
13  formatTokens,
14  goalPercent,
15  historyCsv,
16  labelFor,
17  lastDays,
18  levelLeft,
19  levelUsed,
20  money,
21  newAlerts,
22  paceNote,
23  projectName,
24  projectTotals,
25  recordDay,
26  resetsIn,
27  resolveOptions,
28  shortModel,
29  sparkline,
30  tint,
31  toSnapshot
32} from './usage'
33
34const PANE = 'credits'
35const TICK_MS = 30_000
36const MAX_TURNS = 8
37const CHART_DAYS = 14
38const SVG_W = 250
39const PET_MS = 1500
40
41const snapshot = atom({ plugin: 'credits-bar', key: 'snapshot' } as const, null)
42// 'auto': the band shows only while the panel is not seated; 'on': always; 'off': never.
43const bandMode = atom({ plugin: 'credits-bar', key: 'bandMode' } as const, 'auto')
44const turns = atom({ plugin: 'credits-bar', key: 'turns' } as const, [])
45const tokens = atom({ plugin: 'credits-bar', key: 'tokens' } as const, { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 })
46const history = atom({ plugin: 'credits-bar', key: 'history' } as const, {})
47const tick = atom({ plugin: 'credits-bar', key: 'tick' } as const, 0)
48const models = atom({ plugin: 'credits-bar', key: 'models' } as const, {})
49const pet = atom({ plugin: 'credits-bar', key: 'pet' } as const, {
50  working: false,
51  lastActive: 0,
52  partyUntil: 0,
53  pokes: 0,
54  pokedUntil: 0
55})
56const petOn = atom({ plugin: 'credits-bar', key: 'petOn' } as const, true)
57const frame = atom({ plugin: 'credits-bar', key: 'frame' } as const, 0)
58
59async function isPaneUp($: EngineInterface): Promise<boolean> {
60  try {
61    return (await $.ui.panes()).some(p => p.id === PANE && p.isPlaced)
62  } catch {
63    return false
64  }
65}
66
67// Plays only where the platform has a player (macOS); elsewhere the engine plays nothing.
68async function playAlert($: EngineInterface): Promise<void> {
69  try {
70    await $.audio.play({ asset: 'sounds/alert.wav' })
71  } catch {
72    // no sound is never worth a failure
73  }
74}
75
76export const register: Register = (on, options) => {
77  const opts = resolveOptions(options as Record<string, unknown> | undefined)
78  const str = STRINGS[opts.language]
79
80  // Thresholds already toasted this process (keyed by limit, reset time and threshold).
81  let seen: ReadonlySet<string> = new Set()
82  let lastUsd: number | null = null
83  let pending = 0
84  let sessionSpent = 0
85  let project = ''
86  let goalDay = ''
87  let petBeat = 0
88  // How often each surface asked the hooks to draw (for /credits-debug).
89  const draws: Record<string, number> = {}
90
91  on('session.start', async ($, e, next) => {
92    await update($, bandMode, () => 'auto')
93    project = projectName(await $.session.cwd())
94
95    await $.command.register({ name: 'credits-panel', description: str.cmdPanel })
96    await $.command.register({ name: 'credits-bar', description: str.cmdBar })
97    await $.command.register({ name: 'credits-export', description: str.cmdExport })
98    await $.command.register({ name: 'credits-pet', description: str.cmdPet })
99    await $.command.register({ name: 'credits', description: str.cmdReport })
100    await $.command.register({ name: 'credits-debug', description: 'Report where the mod draws (for bug reports)' })
101
102    await update($, petOn, () => opts.pet)
103    const started = await $.clock.now()
104    await update($, pet, () => ({ working: false, lastActive: started, partyUntil: 0, pokes: 0, pokedUntil: 0 }))
105
106    const stored = await $.store.get('history')
107    if (stored && typeof stored === 'object') {
108      await update($, history, () => stored as Record<string, { usd: number; peak: number }>)
109    }
110
111    // Between responses, refresh the limits and the context fill (a local read, free) and
112    // keep "resets in 48m" moving.
113    $.clock.every(TICK_MS, async () => {
114      try {
115        const value = toSnapshot(await $.session.usage({ breakdown: opts.showBreakdown ? 'summary' : undefined }))
116        await update($, snapshot, () => value)
117      } catch {
118        // keep the previous reading
119      }
120      await update($, tick, n => n + 1)
121    })
122
123    // The pet's heartbeat: a frame every 1.5s, a third of that while it sleeps.
124    $.clock.every(PET_MS, async () => {
125      try {
126        if (!(await read($, petOn))) return
127        const mem = await read($, pet)
128        const asleep = !mem.working && (await $.clock.now()) - mem.lastActive > 60_000
129        petBeat += 1
130        if (asleep && petBeat % 3 !== 0) return
131        await update($, frame, n => n + 1)
132      } catch {
133        // the pet can skip a beat
134      }
135    })
136
137    // Unasked, the pane seats from 144 columns; below that the one-line band stands in.
138    void $.ui.open({ id: PANE, title: str.title })
139
140    return next(e)
141  })
142
143  // /credits-panel: open the side panel (at any width when asked), or close it.
144  on('command.run', { command: 'credits-panel' }, async $ => {
145    if (await isPaneUp($)) {
146      await $.ui.close({ id: PANE })
147
148      return { text: str.panelClosed }
149    }
150
151    const opened = await $.ui.open({ id: PANE, title: str.title })
152
153    return { text: opened.isPlaced ? str.panelOpened : str.panelCannot }
154  })
155
156  // /credits-bar: show the one-line bar above the prompt, or hide it.
157  on('command.run', { command: 'credits-bar' }, async $ => {
158    const isShowing = (await read($, bandMode)) === 'on' || ((await read($, bandMode)) === 'auto' && !(await isPaneUp($)))
159    await update($, bandMode, () => (isShowing ? 'off' : 'on'))
160
161    return { text: isShowing ? str.barHidden : str.barShown }
162  })
163
164  // /credits-pet: send the pet off for a nap, or call it back.
165  on('command.run', { command: 'credits-pet' }, async $ => {
166    const next = !(await read($, petOn))
167    await update($, petOn, () => next)
168
169    return { text: next ? str.petOn : str.petOff }
170  })
171
172  // /credits: the whole panel as plain text, for surfaces that do not draw it.
173  on('command.run', { command: 'credits' }, async $ => {
174    const now = await $.clock.now()
175    const snap = await read($, snapshot)
176    const hist = await read($, history)
177    const mem = await read($, pet)
178    const today = new Date(now).toISOString().slice(0, 10)
179
180    return {
181      text: buildReport({
182        lang: opts.language,
183        now,
184        snap,
185        tokens: await read($, tokens),
186        todayUsd: hist[today]?.usd ?? 0,
187        dailyGoal: opts.dailyGoal,
188        projects: projectTotals(hist, now, 7, 3),
189        petName: opts.petName,
190        mood: petState(mem, now, Math.max(0, ...(snap?.limits ?? []).map(l => l.percentUsed)), {
191          low: opts.alertLow,
192          high: opts.alertHigh
193        }),
194        frame: await read($, frame),
195        pokes: mem.pokes,
196        isPetOn: await read($, petOn)
197      })
198    }
199  })
200
201  // /credits-debug: where is the mod loaded and drawn? Paste the answer into a bug report.
202  on('command.run', { command: 'credits-debug' }, async $ => {
203    const surfaces = await $.session.surfaces()
204    const panes = (await $.ui.panes()).map(p => `${p.id}(placed=${p.isPlaced}, shown=${p.isShown})`)
205    const drawn = Object.entries(draws).map(([k, n]) => `${k}=${n}`)
206    const hasReading = (await read($, snapshot)) !== null
207
208    return {
209      text: [
210        `surfaces: ${surfaces.join(', ') || 'none'}`,
211        `panes: ${panes.join(', ') || 'none'}`,
212        `draw calls: ${drawn.join(', ') || 'none yet'}`,
213        `reading: ${hasReading ? 'yes' : 'not yet (send a prompt)'}`
214      ].join(' | ')
215    }
216  })
217
218  // /credits-export: write the spend history to credits-history.csv in the current folder.
219  on('command.run', { command: 'credits-export' }, async $ => {
220    try {
221      const csv = historyCsv(await read($, history))
222      const path = `${await $.session.cwd()}/credits-history.csv`
223      await $.fs.write(path, csv.text)
224
225      return { text: str.exported(path, csv.rows) }
226    } catch (error) {
227      return { text: str.exportFailed(error instanceof Error ? error.message : 'unknown error') }
228    }
229  })
230
231  // After each response: refresh the numbers, record spend, and raise toasts.
232  on('session.measure', async ($, e, next) => {
233    const now = await $.clock.now()
234    const value = toSnapshot(e)
235
236    if (opts.showBreakdown) {
237      const detailed = await $.session.usage({ breakdown: 'summary' })
238      value.categories = toSnapshot(detailed).categories
239    }
240    await update($, snapshot, () => value)
241
242    const spent = lastUsd !== null && value.usd !== null && value.usd > lastUsd ? value.usd - lastUsd : 0
243    if (value.usd !== null) lastUsd = value.usd
244    pending += spent
245    sessionSpent += spent
246
247    const peak = Math.max(0, ...value.limits.map(l => l.percentUsed))
248    const days = recordDay(await read($, history), now, spent, peak, project || undefined)
249    await update($, history, () => days)
250    await $.store.set('history', days)
251
252    const alerts = newAlerts(value.limits, seen, opts, now)
253    seen = alerts.seen
254    for (const message of alerts.messages) $.ui.toast(message)
255    let isAlert = alerts.messages.length > 0
256
257    // The daily goal, once per day.
258    const today = new Date(now).toISOString().slice(0, 10)
259    const spentToday = days[today]?.usd ?? 0
260    if (opts.dailyGoal > 0 && spentToday >= opts.dailyGoal && goalDay !== today) {
261      goalDay = today
262      $.ui.toast(str.goalHit(money(spentToday), money(opts.dailyGoal)))
263      await update($, pet, p => ({ ...p, partyUntil: now + 12_000 }))
264      isAlert = true
265    }
266
267    if (isAlert && opts.sound) await playAlert($)
268
269    return next(e)
270  })
271
272  // The first reading, so the numbers are there from the first turn.
273  on('prompt.submit', async ($, e, next) => {
274    // Nothing here may get in the way of the prompt.
275    try {
276      const stamp = await $.clock.now()
277      await update($, pet, p => ({ ...p, working: true, lastActive: stamp }))
278      const value = toSnapshot(await $.session.usage({ breakdown: opts.showBreakdown ? 'summary' : undefined }))
279      await update($, snapshot, () => value)
280      if (lastUsd === null && value.usd !== null) lastUsd = value.usd
281    } catch {
282      // keep the previous reading
283    }
284
285    return next(e)
286  })
287
288  // A turn ended: file what it cost, which model ran it and what tokens it used.
289  on('turn.complete', async ($, e, next) => {
290    const stamp = await $.clock.now()
291    await update($, pet, p => ({
292      ...p,
293      working: false,
294      lastActive: stamp,
295      partyUntil: e.reason === 'answer' ? stamp + 5000 : p.partyUntil
296    }))
297
298    const cost = pending
299    pending = 0
300    await update($, turns, list => [...list, cost].slice(-MAX_TURNS))
301    if (e.usage) {
302      const usage = e.usage
303      await update($, tokens, t => addTokens(t, usage))
304      const name = shortModel(usage.model)
305      await update($, models, m => ({
306        ...m,
307        [name]: { usd: (m[name]?.usd ?? 0) + cost, output: (m[name]?.output ?? 0) + usage.output_tokens }
308      }))
309    }
310
311    return next(e)
312  })
313
314  // The session is ending: one toast with the total spent and how far the limits got.
315  on('session.end', async ($, e, next) => {
316    if (opts.sessionSummary) {
317      const snap = await read($, snapshot)
318      const parts = (snap?.limits ?? []).map(l => str.usedShort(labelFor(l.kind), Math.round(l.percentUsed))).join(' · ')
319      const spent = sessionSpent > 0 ? sessionSpent : (snap?.usd ?? 0)
320      if (spent > 0 || parts) $.ui.toast(str.summary(money(spent), parts))
321    }
322
323    return next(e)
324  })
325
326  // The side panel.
327  on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
328    draws[`pane@${e.surface}`] = (draws[`pane@${e.surface}`] ?? 0) + 1
329    const ui = $.ui.resolve(e)
330    const { Box, Text, Button } = ui
331    // Surfaces with a vector element (the desktop app, the editor, mobile) get smooth drawings;
332    // the terminal keeps its text. The pet is text on every surface.
333    const Svg = (ui as unknown as { Svg?: (props: Record<string, unknown>) => unknown }).Svg
334    const isVector = e.surface !== 'terminal' && Svg !== undefined
335    const snap = await read($, snapshot)
336    const isPetOn = await read($, petOn)
337    const frameNo = isPetOn ? await read($, frame) : 0
338    const mem = await read($, pet)
339
340    await read($, tick)
341    const now = Date.now()
342    const rows = e.viewport?.rows ?? 40
343    const isCompact = opts.compact === 'always' || (opts.compact === 'auto' && rows < 24)
344
345    const mood = petState(
346      mem,
347      now,
348      Math.max(0, ...(snap?.limits ?? []).map(l => l.percentUsed)),
349      { low: opts.alertLow, high: opts.alertHigh }
350    )
351    // O bichinho mora no rodapé do painel, em qualquer superfície; clicar nele faz uma reação.
352    const range = Math.max(0, Math.min(14, (e.viewport?.columns ?? 40) - 4 - PET_WIDTH))
353    const stage = petStage(mood, frameNo, range, mem.pokes)
354    const bubble =
355      mood === 'poked'
356        ? str.pokeBubbles[mem.pokes % str.pokeBubbles.length]
357        : str.bubbles[mood][Math.floor(now / 15_000) % str.bubbles[mood].length]
358    const onPoke = async () => {
359      const stamp = await $.clock.now()
360      await update($, pet, p => ({ ...p, pokes: p.pokes + 1, pokedUntil: stamp + POKE_MS, lastActive: stamp }))
361    }
362    const petBlock = isPetOn ? (
363      <Box flexDirection="column">
364        <Text> </Text>
365        {isCompact ? (
366          <Box>
367            <Button key="pet" plain label={petMini(mood, frameNo, mem.pokes)} onPress={onPoke} />
368            <Text dimColor>{`  ${opts.petName} · ${str.mood[mood]}`}</Text>
369          </Box>
370        ) : (
371          <Box flexDirection="column">
372            <Text dimColor>{stage.air || ' '}</Text>
373            <Box marginLeft={stage.x}>
374              <Button key="pet" plain label={stage.face} onPress={onPoke} />
375            </Box>
376            <Text dimColor>{petFloor(Math.max(8, Math.min(30, (e.viewport?.columns ?? 40) - 4)))}</Text>
377            <Text dimColor>{` ${opts.petName} · ${str.mood[mood]}`}</Text>
378            <Text dimColor>{` » ${bubble}`}</Text>
379          </Box>
380        )}
381      </Box>
382    ) : null
383
384    if (snap === null) {
385      return (
386        <Box flexDirection="column">
387          <Text dimColor>{str.noReading}</Text>
388          {petBlock}
389        </Box>
390      )
391    }
392
393    const width = Math.max(8, Math.min(30, (e.viewport?.columns ?? 40) - 4))
394    const paint = (level: 'good' | 'warn' | 'bad') => tint(level, opts.palette)
395    // A bar: smooth on the vector surfaces, blocks on the terminal.
396    const bar = (percentFull: number, level: 'good' | 'warn' | 'bad', key?: string) =>
397      isVector && Svg ? (
398        <Svg key={key} source={barSvg(percentFull, levelColor(level, opts.palette), SVG_W)} alt={`${Math.round(percentFull)}%`} width={SVG_W} height={10} />
399      ) : (
400        <Text key={key} color={paint(level)}>{drawBar(percentFull, width)}</Text>
401      )
402
403    const turnCosts = await read($, turns)
404    const lastCost = turnCosts.length > 0 ? turnCosts[turnCosts.length - 1] : undefined
405    const tok = await read($, tokens)
406    const hit = cacheHitPercent(tok)
407    const byModel = Object.entries(await read($, models)).sort((a, b) => b[1].usd - a[1].usd)
408    const hist = await read($, history)
409    const days = lastDays(hist, now, 7)
410    const today = days[days.length - 1]
411    const goal = today ? goalPercent(today.usd, opts.dailyGoal) : null
412    const dataDays = Object.keys(hist).length
413    const isTall = rows >= 30 && dataDays >= 4 && !isCompact
414    const longDays = lastDays(hist, now, CHART_DAYS)
415    const topProjects = projectTotals(hist, now, 7, 3)
416
417    return (
418      <Box flexDirection="column">
419        {snap.limits.length === 0 ? (
420          <Text dimColor>{str.noLimit}</Text>
421        ) : (
422          snap.limits.map(l => {
423            const left = Math.round((100 - l.percentUsed) * 10) / 10
424            const color = paint(levelLeft(left))
425            const pace = paceNote(l, now, opts.language)
426
427            return isCompact ? (
428              <Text key={l.kind} color={color}>
429                {labelFor(l.kind)} {drawBar(left, width - 10)} {left}%
430                <Text dimColor> {resetsIn(l.resetsAt, now, opts.language).replace(/^[^ ]+ [^ ]+ /, '')}</Text>
431                {pace ? <Text bold> !</Text> : null}
432              </Text>
433            ) : (
434              <Box key={l.kind} flexDirection="column">
435                <Text bold>
436                  {labelFor(l.kind)} <Text color={color}>{str.left(left)}</Text>
437                </Text>
438                {bar(left, levelLeft(left))}
439                <Text dimColor>{resetsIn(l.resetsAt, now, opts.language) || ' '}</Text>
440                {pace ? <Text color={paint('bad')} bold>{`! ${pace}`}</Text> : null}
441                <Text> </Text>
442              </Box>
443            )
444          })
445        )}
446
447        {goal !== null && today ? (
448          <Box flexDirection="column">
449            <Text bold>
450              {str.goal} <Text color={paint(levelUsed(Math.min(100, goal)))}>{goal}%</Text>
451            </Text>
452            {isCompact ? null : (
453              bar(100 - Math.min(100, goal), levelUsed(Math.min(100, goal)))
454            )}
455            <Text dimColor>{str.goalLine(money(today.usd), money(opts.dailyGoal))}</Text>
456            {isCompact ? null : <Text> </Text>}
457          </Box>
458        ) : null}
459
460        {snap.contextPercent !== null ? (
461          <Box flexDirection="column">
462            <Text bold>
463              {str.context} <Text color={paint(levelUsed(snap.contextPercent))}>{str.usedPercent(snap.contextPercent)}</Text>
464            </Text>
465            {isCompact ? null : (
466              bar(100 - snap.contextPercent, levelUsed(snap.contextPercent))
467            )}
468            {!isCompact && opts.showBreakdown
469              ? snap.categories.map(c => (
470                  <Text key={c.name} dimColor>
471                    {`  ${c.name} ${formatTokens(c.tokens)}`}
472                  </Text>
473                ))
474              : null}
475            {isCompact ? null : <Text> </Text>}
476          </Box>
477        ) : null}
478
479        {opts.showTokens && !isCompact && tok.input + tok.output + tok.cacheRead > 0 ? (
480          <Box flexDirection="column">
481            <Text bold>{str.tokens}</Text>
482            <Text dimColor>
483              {`  ${str.tokensLine(formatTokens(tok.input + tok.cacheWrite), formatTokens(tok.output))}`}
484              {hit !== null ? ` · ${str.cacheHit(hit)}` : ''}
485            </Text>
486            {byModel.length > 0 ? (
487              <Box flexDirection="column">
488                <Text bold>{str.models}</Text>
489                {byModel.slice(0, 3).map(([name, m]) => (
490                  <Text key={name} dimColor>{`  ${name} ${money(m.usd)} · ${formatTokens(m.output)} out`}</Text>
491                ))}
492              </Box>
493            ) : null}
494            <Text> </Text>
495          </Box>
496        ) : null}
497
498        {snap.usd !== null ? (
499          <Text dimColor>
500            {`${str.session} ${money(snap.usd)}`}
501            {opts.showTurns && lastCost !== undefined ? ` · ${str.lastReply} ${money(lastCost)}` : ''}
502          </Text>
503        ) : null}
504        {opts.showTurns && !isCompact && turnCosts.length > 1 ? (
505          isVector && Svg ? (
506            <Box flexDirection="column">
507              <Text dimColor>{str.replies}</Text>
508              <Svg
509                source={chartSvg(turnCosts, levelColor('good', opts.palette), turnCosts.map(c => money(c)), SVG_W, 26)}
510                alt={str.replies}
511                width={SVG_W}
512                height={26}
513              />
514            </Box>
515          ) : (
516            <Text dimColor>{`${str.replies} ${sparkline(turnCosts)}`}</Text>
517          )
518        ) : null}
519
520        {opts.showProjects && !isCompact && topProjects.length > 0 ? (
521          <Box flexDirection="column">
522            <Text> </Text>
523            <Text bold>{str.projects}</Text>
524            {topProjects.map(([name, usd]) => (
525              <Text key={name} dimColor>{`  ${name} ${money(usd)}`}</Text>
526            ))}
527          </Box>
528        ) : null}
529
530        {opts.showHistory && !isCompact && today ? (
531          <Box flexDirection="column">
532            <Text> </Text>
533            <Text bold>{str.days(isVector || isTall ? CHART_DAYS : 7)}</Text>
534            {isVector && Svg ? (
535              <Box flexDirection="column">
536                <Text dimColor>{`  ${str.spend} · ${str.today} ${money(today.usd)}`}</Text>
537                <Svg
538                  source={chartSvg(
539                    longDays.map(d => d.usd),
540                    levelColor('good', opts.palette),
541                    longDays.map(d => `${d.key}: ${money(d.usd)}`),
542                    SVG_W,
543                    52
544                  )}
545                  alt={str.spend}
546                  width={SVG_W}
547                  height={52}
548                  isInteractive
549                />
550                <Text dimColor>{`  ${str.peak} · ${str.today} ${Math.round(today.peak)}%`}</Text>
551                <Svg
552                  source={chartSvg(
553                    longDays.map(d => d.peak),
554                    levelColor(levelUsed(today.peak), opts.palette),
555                    longDays.map(d => `${d.key}: ${Math.round(d.peak)}%`),
556                    SVG_W,
557                    36
558                  )}
559                  alt={str.peak}
560                  width={SVG_W}
561                  height={36}
562                  isInteractive
563                />
564              </Box>
565            ) : isTall ? (
566              <Box flexDirection="column">
567                {barChart(longDays.map(d => d.usd), 4).map((line, i) => (
568                  <Text key={i} dimColor>{`  ${line}`}</Text>
569                ))}
570                <Text dimColor>{`  ${str.spend} · ${str.today} ${money(today.usd)}`}</Text>
571              </Box>
572            ) : (
573              <Box flexDirection="column">
574                <Text dimColor>{`  ${str.spend} ${sparkline(days.map(d => d.usd))} · ${str.today} ${money(today.usd)}`}</Text>
575                <Text dimColor>{`  ${str.peak}  ${sparkline(days.map(d => d.peak))} · ${str.today} ${Math.round(today.peak)}%`}</Text>
576              </Box>
577            )}
578          </Box>
579        ) : null}
580
581        {petBlock}
582      </Box>
583    )
584  })
585
586  // The one-line bar: the fallback while the panel is not seated, or always with /credits-bar.
587  on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
588    draws[`band@${e.surface}`] = (draws[`band@${e.surface}`] ?? 0) + 1
589    if (e.props.hasSurvey) {
590      return next(e)
591    }
592
593    const snap = await read($, snapshot)
594    const mode = await read($, bandMode)
595    const isWanted = mode === 'on' || (mode === 'auto' && !(await isPaneUp($)))
596
597    await read($, tick)
598    const { Box, Text, Button } = $.ui.resolve(e)
599    const now = Date.now()
600    const paint = (level: 'good' | 'warn' | 'bad') => tint(level, opts.palette)
601
602    // The icon button: always there, shows the tightest limit, click toggles the side panel.
603    const tightest = snap && snap.limits.length > 0 ? Math.min(...snap.limits.map(l => 100 - l.percentUsed)) : null
604    const chip = (
605      <Button
606        key="credits-chip"
607        label={tightest === null ? str.chipEmpty : str.chipLeft(Math.round(tightest))}
608        onPress={async () => {
609          if (await isPaneUp($)) await $.ui.close({ id: PANE })
610          else await $.ui.open({ id: PANE, title: str.title })
611        }}
612      />
613    )
614
615    // The pet rides along, just left of the icon button.
616    const isPetOn = await read($, petOn)
617    const bandFrame = isPetOn ? await read($, frame) : 0
618    const bandMem = await read($, pet)
619    const bandPokes = bandMem.pokes
620    const bandMood = petState(
621      bandMem,
622      now,
623      Math.max(0, ...(snap?.limits ?? []).map(l => l.percentUsed)),
624      { low: opts.alertLow, high: opts.alertHigh }
625    )
626    const right = (
627      <Box>
628        {isPetOn ? <Text>{`${petMini(bandMood, bandFrame, bandPokes)}  `}</Text> : null}
629        {chip}
630      </Box>
631    )
632
633    if (snap === null || !isWanted) {
634      return <Box justifyContent="flex-end">{right}</Box>
635    }
636
637    // The bar's readings on the left, the icon button pushed to the right edge.
638    return (
639      <Box justifyContent="space-between">
640        <Box>
641          {snap.limits.length === 0 ? (
642            <Text dimColor>{str.noLimitBar}</Text>
643          ) : (
644            snap.limits.map(l => {
645              const left = Math.round((100 - l.percentUsed) * 10) / 10
646              const pace = paceNote(l, now, opts.language)
647
648              return (
649                <Text key={l.kind} color={paint(levelLeft(left))}>
650                  {labelFor(l.kind)} {drawBar(left, 10)} {str.left(left)}
651                  {pace ? <Text bold>{` (${pace})`}</Text> : null}
652                  {'  '}
653                </Text>
654              )
655            })
656          )}
657          {snap.contextPercent !== null ? (
658            <Text color={paint(levelUsed(snap.contextPercent))}>ctx {snap.contextPercent}% </Text>
659          ) : null}
660          {snap.usd !== null ? <Text dimColor>{money(snap.usd)} </Text> : null}
661          <Button key="hide" label={str.hide} onPress={() => update($, bandMode, () => 'off')} />
662        </Box>
663        {right}
664      </Box>
665    )
666  })
667}
668
hooks/pet.ts 158 lines
1// O bichinho: um personagem original desenhado com caracteres simples, no estilo da barra.
2// Só funções puras, para trocar o visual (ou testar) sem tocar no código do motor.
3export type PetState = 'idle' | 'sleep' | 'work' | 'tired' | 'scared' | 'party' | 'poked'
4
5export type PetMemory = {
6  working: boolean
7  lastActive: number
8  partyUntil: number
9  // quantas vezes foi cutucado (escolhe a reação) e até quando dura a reação atual
10  pokes: number
11  pokedUntil: number
12}
13
14export const PET_SLEEP_AFTER_MS = 60_000
15export const POKE_MS = 3200
16// Colunas que o corpo ocupa; o painel deixa ele passear pelo espaço que sobrar.
17export const PET_WIDTH = 9
18
19// O que ele está fazendo agora. Um cutucão vence tudo; depois comemorar, o medo e o cansaço
20// (pelo limite mais apertado) e o trabalho. Sem nada acontecendo ele fica de boa, e depois de
21// um minuto pega no sono.
22export function petState(
23  pet: PetMemory,
24  now: number,
25  maxUsedPercent: number,
26  alerts: { low: number; high: number } = { low: 80, high: 95 }
27): PetState {
28  if (now < pet.pokedUntil) return 'poked'
29  if (now < pet.partyUntil) return 'party'
30  if (maxUsedPercent >= alerts.high) return 'scared'
31  if (maxUsedPercent >= alerts.low) return 'tired'
32  if (pet.working) return 'work'
33  if (now - pet.lastActive > PET_SLEEP_AFTER_MS) return 'sleep'
34
35  return 'idle'
36}
37
38const EYES: Record<Exclude<PetState, 'poked'>, string> = {
39  idle: '•ᴗ•',
40  sleep: '-ᴗ-',
41  work: '•_•',
42  tired: 'ˇ_ˇ',
43  scared: '°o°',
44  party: '^ᴗ^'
45}
46
47// As reações ao clique, uma por cutucão, em rodízio. Cada uma tem dois quadros (rosto e enfeite).
48export const REACTIONS: { faces: [string, string]; aside: [string, string] }[] = [
49  { faces: ['(>ᴗ<)', '(>ᴗ<)'], aside: ['♥', '♥ ♥'] }, // cócegas
50  { faces: ['\\(^ᴗ^)/', '(^ᴗ^)'], aside: ['♪', '♫'] }, // comemora
51  { faces: ['(•ᴗ•)/', '(•ᴗ•) /'], aside: ['!', '!!'] }, // acena
52  { faces: ['(•ᴗ•)♥', '(^ᴗ^)♥'], aside: ['♥', '·'] }, // carinho
53  { faces: ['(@ᴗ@)', '(@_@)'], aside: ['~', '≈'] } // tontura
54]
55export const REACTION_COUNT = REACTIONS.length
56
57// Um enfeite ao lado da cabeça, um por humor, alternando com o quadro.
58function aside(state: Exclude<PetState, 'poked'>, frame: number): string {
59  const odd = frame % 2 === 1
60  switch (state) {
61    case 'sleep':
62      return odd ? 'Z' : 'z'
63    case 'work':
64      return odd ? '..' : '.'
65    case 'tired':
66      return odd ? "'" : ' '
67    case 'scared':
68      return odd ? '!!' : '!'
69    case 'party':
70      return odd ? '♪' : '♫'
71    default:
72      return ''
73  }
74}
75
76// Onde o bichinho de boa está, de 0 a `range`: passeia para a direita, descansa, volta e
77// descansa. `isMoving` diz se está no meio do passeio.
78export function wander(frame: number, range: number): { x: number; isMoving: boolean } {
79  if (range <= 0) return { x: 0, isMoving: false }
80  const pause = 5
81  const cycle = 2 * range + 2 * pause
82  let t = frame % cycle
83
84  if (t < pause) return { x: 0, isMoving: false }
85  t -= pause
86  if (t < range) return { x: t + 1 > range ? range : t + 1, isMoving: true }
87  t -= range
88  if (t < pause) return { x: range, isMoving: false }
89  t -= pause
90
91  return { x: Math.max(0, range - t - 1), isMoving: true }
92}
93
94const pad = (n: number) => ' '.repeat(Math.max(0, n))
95
96export type PetStage = {
97  // coluna do bichinho (cada linha já vem com o recuo aplicado, menos o `face`)
98  x: number
99  // linha do ar: antena brilhando, Zs, corações, confete...
100  air: string
101  // o rosto, que vira o rótulo do botão clicável
102  face: string
103}
104
105// O palco do bichinho. Passeia quando está de boa, balança quando está cansado, treme de medo,
106// cochila com Zs, e reage ao clique com `pokes` escolhendo qual das reações.
107export function petStage(state: PetState, frame: number, range = 0, pokes = 0): PetStage {
108  const mid = Math.floor(range / 2)
109  const odd = frame % 2 === 1
110  let x = mid
111
112  if (state === 'idle') x = wander(frame, range).x
113  if (state === 'tired') x = Math.max(0, mid + (frame % 4 < 2 ? 0 : 1))
114  if (state === 'scared') x = Math.max(0, mid + [0, 1, 0, -1][frame % 4]!)
115
116  if (state === 'poked') {
117    const reaction = REACTIONS[pokes % REACTION_COUNT]!
118    const i = odd ? 1 : 0
119
120    return { x, air: `${pad(x + 3)}${reaction.aside[i]}`, face: reaction.faces[i] }
121  }
122
123  const blink = state === 'idle' && frame % 7 === 6
124  const eyes = blink ? '-ᴗ-' : EYES[state]
125  const twinkle = odd ? '✦' : '✻'
126  const face = state === 'party' ? `\\(${EYES.party})/` : `(${eyes})`
127  const tail = aside(state, frame)
128  const crown = state === 'sleep' ? '' : twinkle
129
130  return { x, air: `${pad(x + 3)}${crown}${crown && tail ? ' ' : ''}${tail}`.trimEnd(), face }
131}
132
133// O chão do palco: pedrinhas, uma florzinha e uma bolinha, só enfeite.
134export function petFloor(width: number): string {
135  const w = Math.max(8, width)
136  const cells = Array.from({ length: w }, (_, i) => (i % 3 === 0 ? '.' : i % 3 === 1 ? ' ' : '˙'))
137  cells[Math.min(w - 1, 3)] = '✿'
138  cells[Math.max(0, w - 4)] = 'o'
139
140  return cells.join('')
141}
142
143// Um bichinho de uma linha para a faixa acima do prompt.
144export function petMini(state: PetState, frame: number, pokes = 0): string {
145  if (state === 'poked') {
146    const reaction = REACTIONS[pokes % REACTION_COUNT]!
147    const i = frame % 2
148
149    return `${reaction.faces[i]} ${reaction.aside[i]}`
150  }
151
152  const blink = state === 'idle' && frame % 6 === 5
153  const eyes = blink ? '-ᴗ-' : EYES[state]
154  const tail = aside(state, frame)
155
156  return state === 'party' ? `\\(${EYES.party})/ ${tail}` : `(${eyes}) ${tail}`.trimEnd()
157}
158
hooks/report.ts 68 lines
1// A plain-text summary of everything the panel shows, for surfaces that do not draw it (and for
2// the /credits command). Pure: give it the readings, get lines back.
3import type { Snapshot, TokenTotals } from '../types'
4import { petMini } from './pet'
5import type { PetState } from './pet'
6import { STRINGS } from './strings'
7import type { Lang } from './strings'
8import { cacheHitPercent, drawBar, formatTokens, labelFor, money, paceNote, resetsIn } from './usage'
9
10export type ReportInput = {
11  lang: Lang
12  now: number
13  snap: Snapshot | null
14  tokens: TokenTotals
15  todayUsd: number
16  dailyGoal: number
17  projects: [string, number][]
18  petName: string
19  mood: PetState
20  frame: number
21  pokes?: number
22  isPetOn: boolean
23}
24
25export function buildReport(r: ReportInput): string {
26  const str = STRINGS[r.lang]
27  const lines: string[] = []
28
29  if (r.isPetOn) lines.push(`${petMini(r.mood, r.frame, r.pokes ?? 0)}  ${r.petName} · ${str.mood[r.mood]}`)
30
31  if (r.snap === null) {
32    lines.push(str.noReading)
33
34    return lines.join('\n')
35  }
36
37  if (r.snap.limits.length === 0) lines.push(str.noLimit)
38  for (const l of r.snap.limits) {
39    const left = Math.round((100 - l.percentUsed) * 10) / 10
40    const pace = paceNote(l, r.now, r.lang)
41    const reset = resetsIn(l.resetsAt, r.now, r.lang)
42    lines.push(`${labelFor(l.kind)}  ${drawBar(left, 14)}  ${str.left(left)}${reset ? ` · ${reset}` : ''}${pace ? ` · ! ${pace}` : ''}`)
43  }
44
45  if (r.dailyGoal > 0) {
46    const pct = Math.round((r.todayUsd / r.dailyGoal) * 100)
47    lines.push(`${str.goal}  ${drawBar(100 - Math.min(100, pct), 14)}  ${pct}% · ${str.goalLine(money(r.todayUsd), money(r.dailyGoal))}`)
48  }
49
50  if (r.snap.contextPercent !== null) {
51    const top = r.snap.categories.map(c => `${c.name} ${formatTokens(c.tokens)}`).join(', ')
52    lines.push(`${str.context}  ${drawBar(100 - r.snap.contextPercent, 14)}  ${str.usedPercent(r.snap.contextPercent)}${top ? ` (${top})` : ''}`)
53  }
54
55  const total = r.tokens.input + r.tokens.output + r.tokens.cacheRead
56  if (total > 0) {
57    const hit = cacheHitPercent(r.tokens)
58    lines.push(
59      `${str.tokens}  ${str.tokensLine(formatTokens(r.tokens.input + r.tokens.cacheWrite), formatTokens(r.tokens.output))}${hit !== null ? ` · ${str.cacheHit(hit)}` : ''}`
60    )
61  }
62
63  if (r.snap.usd !== null) lines.push(`${str.session}  ${money(r.snap.usd)}`)
64  if (r.projects.length > 0) lines.push(`${str.projects}  ${r.projects.map(([n, usd]) => `${n} ${money(usd)}`).join(' · ')}`)
65
66  return lines.join('\n')
67}
68
hooks/svg.ts 61 lines
1// Vector drawings for the surfaces that have an Svg element (the desktop app, the editor, mobile):
2// smooth bars and bar charts. Pure functions that return markup strings.
3import type { Level, Options } from './usage'
4
5type Palette = Options['palette']
6
7const COLORS: Record<Palette, Record<Level, string>> = {
8  default: { good: '#4caf6a', warn: '#e0a526', bad: '#e5534b' },
9  colorblind: { good: '#3b82c4', warn: '#e0a526', bad: '#c0489a' },
10  mono: { good: '#9aa0a6', warn: '#9aa0a6', bad: '#9aa0a6' }
11}
12
13export function levelColor(level: Level, palette: Palette): string {
14  return COLORS[palette][level]
15}
16
17const TRACK = 'rgba(128,128,128,0.28)'
18
19const esc = (s: string) => s.replace(/&/g, '&amp;').replace(/</g, '&lt;')
20
21// A rounded progress bar: `percent` of the track filled (0 to 100).
22export function barSvg(percent: number, color: string, width = 260, height = 10): string {
23  const p = Math.max(0, Math.min(100, percent))
24  const fill = (p / 100) * width
25  const r = height / 2
26
27  return (
28    `<svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="${height}" viewBox="0 0 ${width} ${height}">` +
29    `<rect width="${width}" height="${height}" rx="${r}" fill="${TRACK}"/>` +
30    (fill > 0 ? `<rect width="${Math.max(height, fill).toFixed(1)}" height="${height}" rx="${r}" fill="${color}"/>` : '') +
31    `</svg>`
32  )
33}
34
35// Vertical bars, one per value, the last one highlighted. `title` per bar shows on hover.
36export function chartSvg(
37  values: number[],
38  color: string,
39  titles: string[] = [],
40  width = 260,
41  height = 56
42): string {
43  const max = Math.max(...values, 0)
44  const n = Math.max(1, values.length)
45  const gap = 4
46  const bw = (width - gap * (n - 1)) / n
47  const bars = values
48    .map((v, i) => {
49      const h = max > 0 ? Math.max(v > 0 ? 3 : 1.5, (v / max) * (height - 4)) : 1.5
50      const x = i * (bw + gap)
51      const isLast = i === n - 1
52      return (
53        `<rect x="${x.toFixed(1)}" y="${(height - h).toFixed(1)}" width="${bw.toFixed(1)}" height="${h.toFixed(1)}" rx="2" ` +
54        `fill="${isLast ? color : TRACK}"${isLast ? '' : ' opacity="1"'}><title>${esc(titles[i] ?? '')}</title></rect>`
55      )
56    })
57    .join('')
58
59  return `<svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="${height}" viewBox="0 0 ${width} ${height}">${bars}</svg>`
60}
61
hooks/strings.ts 194 lines
1// Every label the mod draws or toasts, in each language. Add a language by adding a table.
2export type Lang = 'en' | 'pt'
3
4type Table = {
5  left: (percent: number) => string
6  resetsIn: (duration: string) => string
7  resetting: string
8  outIn: (duration: string) => string
9  noReading: string
10  noLimit: string
11  noLimitBar: string
12  context: string
13  usedPercent: (percent: number) => string
14  tokens: string
15  tokensLine: (input: string, output: string) => string
16  cacheHit: (percent: number) => string
17  session: string
18  lastReply: string
19  replies: string
20  days: (n: number) => string
21  spend: string
22  peak: string
23  today: string
24  projects: string
25  models: string
26  goal: string
27  goalLine: (spent: string, goal: string) => string
28  hide: string
29  chipEmpty: string
30  chipLeft: (percent: number) => string
31  // toasts
32  limitUsed: (label: string, percent: number) => string
33  paceWarn: (label: string, pace: string) => string
34  goalHit: (spent: string, goal: string) => string
35  summary: (spent: string, parts: string) => string
36  usedShort: (label: string, percent: number) => string
37  // commands
38  panelClosed: string
39  panelOpened: string
40  panelCannot: string
41  barHidden: string
42  barShown: string
43  exported: (path: string, rows: number) => string
44  exportFailed: (reason: string) => string
45  cmdPanel: string
46  cmdBar: string
47  cmdExport: string
48  cmdPet: string
49  cmdReport: string
50  petOn: string
51  petOff: string
52  title: string
53  mood: Record<'idle' | 'sleep' | 'work' | 'tired' | 'scared' | 'party' | 'poked', string>
54  // what the pet mutters, a few per mood, rotating
55  bubbles: Record<'idle' | 'sleep' | 'work' | 'tired' | 'scared' | 'party', string[]>
56  // a fala de cada reação ao clique, na mesma ordem das reações do bichinho
57  pokeBubbles: string[]
58}
59
60export const STRINGS: Record<Lang, Table> = {
61  en: {
62    left: p => `${p}% left`,
63    resetsIn: d => `resets in ${d}`,
64    resetting: 'resetting',
65    outIn: d => `out in ${d}`,
66    noReading: 'No usage reading yet. Send a prompt.',
67    noLimit: 'No usage limit reported (not on a subscription?).',
68    noLimitBar: 'Credits: no usage limit reported yet ',
69    context: 'Context',
70    usedPercent: p => `${p}% used`,
71    tokens: 'Tokens',
72    tokensLine: (i, o) => `in ${i} · out ${o}`,
73    cacheHit: p => `cache ${p}%`,
74    session: 'Session',
75    lastReply: 'last reply',
76    replies: 'Replies',
77    days: n => `${n} days`,
78    spend: 'spend',
79    peak: 'peak',
80    today: 'today',
81    projects: 'Projects (7d)',
82    models: 'Models (session)',
83    goal: 'Daily goal',
84    goalLine: (s, g) => `${s} of ${g}`,
85    hide: 'Hide (/credits-bar to restore)',
86    chipEmpty: '◔ credits',
87    chipLeft: p => `◔ ${p}% left`,
88    limitUsed: (l, p) => `${l} limit ${p}% used`,
89    paceWarn: (l, p) => `${l} window ${p}, before it resets`,
90    goalHit: (s, g) => `Daily goal reached: ${s} of ${g}`,
91    summary: (s, parts) => `Session ended: ${s} spent${parts ? ` · ${parts}` : ''}`,
92    usedShort: (l, p) => `${l} ${p}% used`,
93    panelClosed: 'Credits panel closed.',
94    panelOpened: 'Credits panel opened.',
95    panelCannot: 'The panel could not be placed here.',
96    barHidden: 'Credits bar hidden. Run /credits-bar to show it again.',
97    barShown: 'Credits bar shown.',
98    exported: (p, n) => `History exported: ${n} rows in ${p}`,
99    exportFailed: r => `Could not export the history: ${r}`,
100    cmdPanel: 'Open or close the usage side panel',
101    cmdBar: 'Show or hide the one-line usage bar above the prompt',
102    cmdExport: 'Export the spend history to credits-history.csv in the current folder',
103    cmdPet: 'Show or hide the pet',
104    cmdReport: 'Show the full usage summary as text (works on every surface)',
105    petOn: 'The pet is back.',
106    petOff: 'The pet went to nap. Run /credits-pet to bring it back.',
107    title: 'Credits',
108    mood: {
109      poked: 'playing',
110      idle: 'chilling',
111      sleep: 'sleeping',
112      work: 'working',
113      tired: 'tired',
114      scared: 'panicking',
115      party: 'celebrating'
116    },
117    pokeBubbles: ['hehe, that tickles!', 'yay!', 'hi there!', 'aww, thanks!', 'whoa, dizzy...'],
118    bubbles: {
119      idle: ['all quiet in here', 'got any tasks for me?', 'watching the bars', 'psst, nice code'],
120      sleep: ['zzz...', 'five more minutes', 'dreaming of green bars'],
121      work: ['clack clack clack', 'on it!', 'crunching tokens', 'almost there...'],
122      tired: ['phew, that is a lot', 'could use a break', 'running low...'],
123      scared: ['the limit is right there!', 'abort abort', 'please slow down'],
124      party: ['we did it!', 'nailed it', 'another one done!']
125    }
126  },
127  pt: {
128    left: p => `${p}% restante`,
129    resetsIn: d => `reseta em ${d}`,
130    resetting: 'resetando',
131    outIn: d => `acaba em ${d}`,
132    noReading: 'Ainda sem leitura de uso. Envie um prompt.',
133    noLimit: 'Nenhum limite de uso informado (sem assinatura?).',
134    noLimitBar: 'Créditos: nenhum limite informado ainda ',
135    context: 'Contexto',
136    usedPercent: p => `${p}% usado`,
137    tokens: 'Tokens',
138    tokensLine: (i, o) => `entrada ${i} · saída ${o}`,
139    cacheHit: p => `cache ${p}%`,
140    session: 'Sessão',
141    lastReply: 'última resposta',
142    replies: 'Respostas',
143    days: n => `${n} dias`,
144    spend: 'gasto',
145    peak: 'pico',
146    today: 'hoje',
147    projects: 'Projetos (7d)',
148    models: 'Modelos (sessão)',
149    goal: 'Meta diária',
150    goalLine: (s, g) => `${s} de ${g}`,
151    hide: 'Ocultar (/credits-bar para voltar)',
152    chipEmpty: '◔ créditos',
153    chipLeft: p => `◔ ${p}% restante`,
154    limitUsed: (l, p) => `Limite de ${l}: ${p}% usado`,
155    paceWarn: (l, p) => `Janela de ${l} ${p}, antes de resetar`,
156    goalHit: (s, g) => `Meta diária atingida: ${s} de ${g}`,
157    summary: (s, parts) => `Sessão encerrada: ${s} gastos${parts ? ` · ${parts}` : ''}`,
158    usedShort: (l, p) => `${l} ${p}% usado`,
159    panelClosed: 'Painel de créditos fechado.',
160    panelOpened: 'Painel de créditos aberto.',
161    panelCannot: 'Não foi possível posicionar o painel aqui.',
162    barHidden: 'Barra de créditos oculta. Use /credits-bar para mostrar de novo.',
163    barShown: 'Barra de créditos exibida.',
164    exported: (p, n) => `Histórico exportado: ${n} linhas em ${p}`,
165    exportFailed: r => `Não foi possível exportar o histórico: ${r}`,
166    cmdPanel: 'Abrir ou fechar o painel lateral de uso',
167    cmdBar: 'Mostrar ou ocultar a barra de uma linha acima do prompt',
168    cmdExport: 'Exportar o histórico de gastos para credits-history.csv na pasta atual',
169    cmdPet: 'Mostrar ou esconder o bichinho',
170    cmdReport: 'Mostrar o resumo completo de uso em texto (funciona em qualquer superfície)',
171    petOn: 'O bichinho voltou.',
172    petOff: 'O bichinho foi tirar uma soneca. Use /credits-pet para chamá-lo de volta.',
173    title: 'Créditos',
174    mood: {
175      poked: 'brincando',
176      idle: 'de boa',
177      sleep: 'dormindo',
178      work: 'trabalhando',
179      tired: 'cansado',
180      scared: 'em pânico',
181      party: 'comemorando'
182    },
183    pokeBubbles: ['hihi, cócegas!', 'oba!', 'oi, oi!', 'ai, que fofo!', 'uiii, tontura...'],
184    bubbles: {
185      idle: ['tudo quieto por aqui', 'tem tarefa pra mim?', 'de olho nas barras', 'psiu, bom código'],
186      sleep: ['zzz...', 'só mais cinco minutinhos', 'sonhando com barras verdes'],
187      work: ['tec tec tec', 'deixa comigo!', 'mastigando tokens', 'quase lá...'],
188      tired: ['ufa, é muita coisa', 'precisava de uma pausa', 'ficando sem fôlego...'],
189      scared: ['o limite tá logo ali!', 'socorro', 'vai com calma, por favor'],
190      party: ['conseguimos!', 'mandou bem', 'mais uma pronta!']
191    }
192  }
193}
194
hooks/usage.ts 360 lines
1// Pure helpers (no engine calls) so they can be unit-tested.
2import type { Category, DayRecord, History, Limit, Snapshot, TokenTotals } from '../types'
3import { STRINGS } from './strings'
4import type { Lang } from './strings'
5
6export const WINDOW_MS: Record<string, number> = {
7  five_hour: 5 * 60 * 60 * 1000,
8  seven_day: 7 * 24 * 60 * 60 * 1000
9}
10
11export type Options = {
12  alertLow: number
13  alertHigh: number
14  showHistory: boolean
15  showBreakdown: boolean
16  showTokens: boolean
17  showTurns: boolean
18  compact: 'auto' | 'always' | 'never'
19  palette: 'default' | 'colorblind' | 'mono'
20  language: Lang
21  dailyGoal: number
22  sessionSummary: boolean
23  showProjects: boolean
24  sound: boolean
25  pet: boolean
26  petName: string
27}
28
29export const DEFAULT_OPTIONS: Options = {
30  alertLow: 80,
31  alertHigh: 95,
32  showHistory: true,
33  showBreakdown: true,
34  showTokens: true,
35  showTurns: true,
36  compact: 'auto',
37  palette: 'default',
38  language: 'pt',
39  dailyGoal: 0,
40  sessionSummary: true,
41  showProjects: true,
42  sound: false,
43  pet: true,
44  petName: 'Pip'
45}
46
47// `userConfig` values arrive loosely typed (numbers may arrive as strings): clamp and default each.
48export function resolveOptions(raw: Record<string, unknown> | undefined): Options {
49  const o = raw ?? {}
50  const num = (v: unknown, d: number) =>
51    v !== '' && v !== null && v !== undefined && Number.isFinite(Number(v)) ? Number(v) : d
52  const bool = (v: unknown, d: boolean) => (typeof v === 'boolean' ? v : d)
53  const pick = <T extends string>(v: unknown, allowed: readonly T[], d: T): T =>
54    allowed.includes(v as T) ? (v as T) : d
55
56  const low = Math.min(100, Math.max(1, num(o.alertLow, DEFAULT_OPTIONS.alertLow)))
57  const high = Math.min(100, Math.max(low, num(o.alertHigh, DEFAULT_OPTIONS.alertHigh)))
58
59  return {
60    alertLow: low,
61    alertHigh: high,
62    showHistory: bool(o.showHistory, true),
63    showBreakdown: bool(o.showBreakdown, true),
64    showTokens: bool(o.showTokens, true),
65    showTurns: bool(o.showTurns, true),
66    compact: pick(o.compact, ['auto', 'always', 'never'] as const, 'auto'),
67    palette: pick(o.palette, ['default', 'colorblind', 'mono'] as const, 'default'),
68    language: pick(o.language, ['en', 'pt'] as const, 'pt'),
69    dailyGoal: Math.max(0, num(o.dailyGoal, 0)),
70    sessionSummary: bool(o.sessionSummary, true),
71    showProjects: bool(o.showProjects, true),
72    sound: bool(o.sound, false),
73    pet: bool(o.pet, true),
74    petName:
75      typeof o.petName === 'string' && o.petName.trim() !== '' ? o.petName.trim().slice(0, 16) : DEFAULT_OPTIONS.petName
76  }
77}
78
79type RawLimit = { kind: string; percentUsed: number; resetsAt?: string }
80type RawCategory = { name: string; tokens: number; kind: string }
81type RawUsage = {
82  rateLimits: RawLimit[]
83  cost?: { usd: number }
84  context: { percent?: number; breakdown?: { categories: RawCategory[] } }
85}
86
87export function toSnapshot(u: RawUsage): Snapshot {
88  return {
89    limits: u.rateLimits.map(l => ({ kind: l.kind, percentUsed: l.percentUsed, resetsAt: l.resetsAt })),
90    usd: u.cost?.usd ?? null,
91    contextPercent: u.context.percent ?? null,
92    categories: topCategories(u.context.breakdown?.categories ?? [])
93  }
94}
95
96// What is filling the window: the biggest `used` rows, largest first.
97export function topCategories(rows: RawCategory[], n = 4): Category[] {
98  return rows
99    .filter(r => r.kind === 'used' && r.tokens > 0)
100    .sort((a, b) => b.tokens - a.tokens)
101    .slice(0, n)
102    .map(r => ({ name: r.name, tokens: r.tokens }))
103}
104
105export function formatTokens(n: number): string {
106  if (n >= 1_000_000) return `${(n / 1_000_000).toFixed(1)}M`
107  if (n >= 1000) return `${Math.round(n / 1000)}k`
108
109  return String(n)
110}
111
112// "Out in 40m": if the current burn rate holds, when does this window run dry?
113// Returns null when there is not enough signal or the window will last until reset.
114export function paceNote(limit: Limit, now: number, lang: Lang = 'en'): string | null {
115  const windowMs = WINDOW_MS[limit.kind]
116  if (!windowMs || !limit.resetsAt || limit.percentUsed < 10) return null
117
118  const remainingMs = Date.parse(limit.resetsAt) - now
119  const elapsedMs = windowMs - remainingMs
120  if (!(remainingMs > 0) || elapsedMs < windowMs * 0.05) return null
121
122  const msToEmpty = (elapsedMs * (100 - limit.percentUsed)) / limit.percentUsed
123  if (msToEmpty >= remainingMs) return null
124
125  return STRINGS[lang].outIn(formatDuration(msToEmpty))
126}
127
128export function formatDuration(ms: number): string {
129  const minutes = Math.max(1, Math.round(ms / 60000))
130  if (minutes < 60) return `${minutes}m`
131  if (minutes < 24 * 60) return `${Math.round(minutes / 60)}h`
132
133  return `${Math.round(minutes / (24 * 60))}d`
134}
135
136export function resetsIn(iso: string | undefined, now: number, lang: Lang = 'en'): string {
137  if (!iso) return ''
138  const ms = Date.parse(iso) - now
139  if (!(ms > 0)) return STRINGS[lang].resetting
140
141  return STRINGS[lang].resetsIn(formatDuration(ms))
142}
143
144export function labelFor(kind: string): string {
145  return kind === 'five_hour' ? '5h' : kind === 'seven_day' ? '7d' : kind === 'spend_limit' ? 'Spend' : kind
146}
147
148// Toasts: a limit passing `alertLow` or `alertHigh`, and a window newly on pace to run dry.
149// Each fires once per window (keys include the reset time).
150export function newAlerts(
151  limits: Limit[],
152  seen: ReadonlySet<string>,
153  opts: Pick<Options, 'alertLow' | 'alertHigh'> & { language?: Lang } = DEFAULT_OPTIONS,
154  now = 0
155): { messages: string[]; seen: Set<string> } {
156  const str = STRINGS[opts.language ?? 'en']
157  const next = new Set(seen)
158  const messages: string[] = []
159
160  for (const l of limits) {
161    const label = labelFor(l.kind)
162
163    for (const t of [opts.alertLow, opts.alertHigh]) {
164      const key = `${l.kind}:${l.resetsAt ?? ''}:${t}`
165      if (l.percentUsed >= t && !next.has(key)) {
166        next.add(key)
167        messages.push(str.limitUsed(label, Math.floor(l.percentUsed)))
168      }
169    }
170
171    const pace = now ? paceNote(l, now, opts.language ?? 'en') : null
172    const paceKey = `pace:${l.kind}:${l.resetsAt ?? ''}`
173    if (pace && !next.has(paceKey)) {
174      next.add(paceKey)
175      messages.push(str.paceWarn(label, pace))
176    }
177  }
178
179  // Crossing both thresholds in one jump yields the same text twice; show it once.
180  return { messages: [...new Set(messages)], seen: next }
181}
182
183// --- history (kept across sessions in $.store) ---
184
185export const HISTORY_DAYS = 14
186
187export function dayKey(ms: number): string {
188  return new Date(ms).toISOString().slice(0, 10)
189}
190
191// Adds `usd` spent and the highest limit percentage seen to today's record, pruning old days.
192export function recordDay(history: History, ms: number, usd: number, peak: number, project?: string): History {
193  const key = dayKey(ms)
194  const prev: DayRecord = history[key] ?? { usd: 0, peak: 0 }
195  const add = Math.max(0, usd)
196  const projects = { ...(prev.projects ?? {}) }
197  if (project && add > 0) projects[project] = (projects[project] ?? 0) + add
198  const next: History = {
199    ...history,
200    [key]: {
201      usd: prev.usd + add,
202      peak: Math.max(prev.peak, peak),
203      ...(Object.keys(projects).length > 0 ? { projects } : {})
204    }
205  }
206  const keep = Object.keys(next).sort().slice(-HISTORY_DAYS)
207
208  return Object.fromEntries(keep.map(k => [k, next[k] as DayRecord]))
209}
210
211// The last `days` days, oldest first, zero-filled.
212export function lastDays(history: History, ms: number, days = 7): { key: string; usd: number; peak: number }[] {
213  const out = []
214  for (let i = days - 1; i >= 0; i--) {
215    const key = dayKey(ms - i * 24 * 3600 * 1000)
216    const r = history[key]
217    out.push({ key, usd: r?.usd ?? 0, peak: r?.peak ?? 0 })
218  }
219
220  return out
221}
222
223const BLOCKS = '▁▂▃▄▅▆▇█'
224
225export function sparkline(values: number[]): string {
226  const max = Math.max(...values, 0)
227  if (max <= 0) return BLOCKS.charAt(0).repeat(values.length)
228
229  return values
230    .map(v => (v <= 0 ? BLOCKS.charAt(0) : BLOCKS.charAt(Math.min(7, Math.ceil((v / max) * 7)))))
231    .join('')
232}
233
234// --- tokens ---
235
236export function addTokens(
237  t: TokenTotals,
238  u: {
239    input_tokens: number
240    output_tokens: number
241    cache_read_input_tokens: number
242    cache_creation_input_tokens: number
243  }
244): TokenTotals {
245  return {
246    input: t.input + u.input_tokens,
247    output: t.output + u.output_tokens,
248    cacheRead: t.cacheRead + u.cache_read_input_tokens,
249    cacheWrite: t.cacheWrite + u.cache_creation_input_tokens
250  }
251}
252
253// Share of input served from the prompt cache, 0 to 100; null with no input yet.
254export function cacheHitPercent(t: TokenTotals): number | null {
255  const total = t.input + t.cacheRead + t.cacheWrite
256  if (total <= 0) return null
257
258  return Math.round((t.cacheRead / total) * 100)
259}
260
261// --- palette ---
262
263export type Level = 'good' | 'warn' | 'bad'
264export type Tint = 'green' | 'yellow' | 'red' | 'blue' | 'magenta' | undefined
265
266export function tint(level: Level, palette: Options['palette']): Tint {
267  if (palette === 'mono') return undefined
268  if (palette === 'colorblind') return level === 'good' ? 'blue' : level === 'warn' ? 'yellow' : 'magenta'
269
270  return level === 'good' ? 'green' : level === 'warn' ? 'yellow' : 'red'
271}
272
273export const levelLeft = (percentLeft: number): Level => (percentLeft > 50 ? 'good' : percentLeft > 20 ? 'warn' : 'bad')
274export const levelUsed = (percentUsed: number): Level => (percentUsed < 50 ? 'good' : percentUsed < 80 ? 'warn' : 'bad')
275
276export function drawBar(percentLeft: number, width: number): string {
277  const filled = Math.round((Math.max(0, Math.min(100, percentLeft)) / 100) * width)
278
279  return '█'.repeat(filled) + '░'.repeat(width - filled)
280}
281
282// --- projects, models, goal, chart, csv ---
283
284// The folder's own name: "C:\code\my-app" and "/home/me/my-app" both give "my-app".
285export function projectName(cwd: string): string {
286  const parts = cwd.split(/[\\/]+/).filter(Boolean)
287
288  return parts[parts.length - 1] ?? cwd
289}
290
291// Spend per project over the last `days` days, biggest first.
292export function projectTotals(history: History, ms: number, days = 7, n = 4): [string, number][] {
293  const totals: Record<string, number> = {}
294  for (const d of lastDays(history, ms, days)) {
295    for (const [name, usd] of Object.entries(history[d.key]?.projects ?? {})) totals[name] = (totals[name] ?? 0) + usd
296  }
297
298  return Object.entries(totals)
299    .sort((a, b) => b[1] - a[1])
300    .slice(0, n)
301}
302
303// "claude-opus-4-5-20251001" -> "opus-4-5"
304export function shortModel(model: string): string {
305  return model.replace(/^claude-/, '').replace(/-\d{8}$/, '')
306}
307
308export function money(usd: number): string {
309  return `$${usd.toFixed(2)}`
310}
311
312// How far along the daily goal is, 0 to 100+; null when no goal is set.
313export function goalPercent(spent: number, goal: number): number | null {
314  return goal > 0 ? Math.round((spent / goal) * 100) : null
315}
316
317// A vertical bar chart `height` rows tall, one column pair per value; rows run top to bottom.
318export function barChart(values: number[], height: number): string[] {
319  const max = Math.max(...values, 0)
320  const rows: string[] = []
321
322  for (let r = height - 1; r >= 0; r--) {
323    let line = ''
324    for (const v of values) {
325      const units = max > 0 ? Math.round((v / max) * height * 8) : 0
326      const fill = Math.max(0, Math.min(8, units - r * 8))
327      const cell = fill === 0 ? ' ' : BLOCKS.charAt(fill - 1)
328      line += cell + cell
329    }
330    rows.push(line.replace(/\s+$/, ''))
331  }
332
333  return rows
334}
335
336// The spend history as CSV: one row per day and project (a "-" project when none was recorded).
337export function historyCsv(history: History): { text: string; rows: number } {
338  const lines = ['date,project,usd,peak_percent']
339  let rows = 0
340
341  for (const date of Object.keys(history).sort()) {
342    const rec = history[date] as DayRecord
343    const entries = Object.entries(rec.projects ?? {})
344    const named = entries.reduce((sum, [, v]) => sum + v, 0)
345    const csvName = (n: string) => (/[",\n]/.test(n) ? `"${n.replace(/"/g, '""')}"` : n)
346
347    for (const [name, usd] of entries) {
348      lines.push(`${date},${csvName(name)},${usd.toFixed(4)},${Math.round(rec.peak)}`)
349      rows++
350    }
351    const rest = rec.usd - named
352    if (entries.length === 0 || rest > 0.00005) {
353      lines.push(`${date},-,${Math.max(0, rest).toFixed(4)},${Math.round(rec.peak)}`)
354      rows++
355    }
356  }
357
358  return { text: lines.join('\n') + '\n', rows }
359}
360
types/index.d.ts 37 lines
1export type Limit = { kind: string; percentUsed: number; resetsAt?: string }
2export type Category = { name: string; tokens: number }
3export type Snapshot = {
4  limits: Limit[]
5  usd: number | null
6  contextPercent: number | null
7  categories: Category[]
8}
9export type TokenTotals = { input: number; output: number; cacheRead: number; cacheWrite: number }
10export type DayRecord = { usd: number; peak: number; projects?: Record<string, number> }
11export type ModelTotals = Record<string, { usd: number; output: number }>
12export type History = Record<string, DayRecord>
13export type PetMemory = {
14  working: boolean
15  lastActive: number
16  partyUntil: number
17  pokes: number
18  pokedUntil: number
19}
20
21declare module 'claude-code' {
22  interface PluginState {
23    'credits-bar': {
24      snapshot: Snapshot | null
25      bandMode: 'auto' | 'on' | 'off'
26      turns: number[]
27      tokens: TokenTotals
28      history: History
29      tick: number
30      models: ModelTotals
31      pet: PetMemory
32      petOn: boolean
33      frame: number
34    }
35  }
36}
37