SLOPSHOPPER

faf-usage-meter

Shows the model in use and its effort, context usage and quota consumption (5h, 7 days) against their limits

panespinnercommandnetwork
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · faf-usage-meter
│ ┃ Claude usage ✕ › fix the failing auth test and add an audit log call │ ┃ Model │ ┃ Opus 5.5 (claude-opus-5-5) ⏺ Read(src/auth.ts) │ ┃ Effort known after the first response ⎿ Read 6 lines │ ┃ ⏺ Update(src/auth.ts) │ ┃ Context ⎿ Added 2 lines, removed 1 line │ ┃ ███████████████████▋░░░░░░░░░░░░░░░░░░░░ 49% ⏺ Bash(bun test) │ ┃ 97k of 200k tokens ⎿ 3 pass, 1 fail │ ┃ │ ┃ Quota ● Done. refresh now rejects expired claims and logs an audit event. │ ┃ 5h ████████████▍░░░░░░░░░░░░░░░░░░░ │ ┃ ✻ Worked for 42s · done 4:20 PM │ ┃ Monthly spend (account) │ ┃ No data: sign in with a claude.ai account. › /faf-usage │ ┃ ⎿ faf-usage-meter: Usage pane opened. │ ┃ Estimated cost of this session (API │ ┃ pricing): $0.42 │ ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Pane · Claude usage
Model Opus 5.5 (claude-opus-5-5) Effort known after the first response Context ███████████████████▋░░░░░░░░░░░░░░░░░░░░ 49% 97k of 200k tokens Quota 5h ████████████▍░░░░░░░░░░░░░░░░░░░░░░░░░░░ 31% / 1 Monthly spend (account) No data: sign in with a claude.ai account. Estimated cost of this session (API pricing): $0.42
README

claude-mods

Mods propios de Claude Code y los instaladores para llevarlos a cualquier equipo.

Un mod es un plugin que cambia la interfaz o el comportamiento de Claude Code: paneles, barras bajo el prompt, comandos /…, hooks… Este repositorio los guarda en un sitio, con su historial, y permite instalarlos de una vez en Windows, Linux, macOS y WSL.

Mods incluidos

ModQué haceComandos
faf-usage-meterMuestra bajo el prompt el modelo en uso y su nivel de esfuerzo, la ocupación del contexto y la cuota usada (5 h y 7 días) con sus límites, y el gasto del mes./faf-usage abre el panel con el desglose · /faf-usage-band muestra u oculta la barra

Estructura

claude-mods/
├── .githooks/         hooks de git con las reglas de ramas y commits
├── .github/workflows/ comprobación de esas reglas en cada PR
├── install/
│   ├── install.sh     instalador para Linux, macOS, WSL y Git Bash
│   ├── install.ps1    instalador para PowerShell (Windows; también pwsh en Linux/macOS)
│   └── install.cmd    lanzador de doble clic para install.ps1
└── mods/
    └── <nombre>/      un mod por carpeta, con su .claude-plugin/plugin.json

Instalación

Clona el repositorio y ejecuta el instalador que corresponda. Sin argumentos instala y activa todos los mods.

Windows: doble clic en install\install.cmd, o desde PowerShell:

.\install\install.ps1

Linux, macOS o WSL:

./install/install.sh

Después cierra y vuelve a abrir Claude Code. Para actualizar, haz git pull y vuelve a ejecutar el instalador.

Qué hace el instalador

  1. Copia cada mod a ~/.claude/mods/<nombre>, sustituyendo la versión anterior. Si Claude Code ha generado tipos de desarrollo en .claude-plugin/types, los conserva.
  2. Guarda una copia de ~/.claude/settings.json en ~/.claude/backups/.
  3. Activa cada mod añadiéndolo a env.CLAUDE_CODE_PLUGIN_DIRS en settings.json. Respeta otras rutas que ya haya en esa variable y el resto de la configuración.

Si CLAUDE_CONFIG_DIR está definida, usa esa carpeta en lugar de ~/.claude.

Opciones

Los dos scripts tienen las mismas opciones:

bashPowerShellQué hace
mod1 mod2mod1 mod2instala solo esos mods
--list-Listmuestra los mods del repositorio y si están instalados y activos
--uninstall [mods]-Uninstall [mods]desactiva y borra esos mods (sin nombres, todos los del repositorio)
--target DESTINO-Target DESTINOdónde instalar (ver abajo)
--distro NOMBRE-Distro NOMBREdistribución de WSL; por defecto, la predeterminada
--helpGet-Help .\install\install.ps1ayuda

Windows con WSL: instalar en los dos de una vez

Claude Code de Windows y Claude Code de WSL tienen configuraciones separadas. Con --target / -Target se elige dónde instalar:

DestinoDesde WSL (install.sh)Desde Windows (install.ps1)
local (por defecto)Claude de WSLClaude de Windows
windowsClaude de WindowsClaude de Windows
wslClaude de WSLClaude de WSL
bothambosambos
./install/install.sh --target both          # desde WSL
.\install\install.ps1 -Target both          # desde Windows

Cada script le pasa al otro la parte del otro sistema: install.sh usa powershell.exe y install.ps1 usa wsl.exe. Si no se puede llegar al otro sistema, el script avisa y no instala nada.

Requisitos

  • install.sh: bash y python3 (para editar settings.json). En Git Bash no hace falta python3, porque el trabajo lo hace install.ps1.
  • install.ps1: Windows PowerShell 5.1 o PowerShell 7.
  • Algunos mods necesitan haber iniciado sesión en Claude Code con una cuenta de claude.ai. Por ejemplo, faf-usage-meter la necesita para mostrar la cuota.

Añadir un mod

  1. Copia la carpeta del mod a mods/<nombre>. Debe contener .claude-plugin/plugin.json, con name igual al nombre de la carpeta.
  2. Añádelo a la tabla de Mods incluidos.
  3. Ejecuta el instalador.

La carpeta .claude-plugin/types que genera Claude Code al desarrollar un mod está en .gitignore: no se sube y se regenera sola.

Ramas y commits

  • Nada de commits en main: cada cambio va en una rama tipo/descripcion (feat/faf-usage-meter-model) y llega a main solo por PR, fusionado con squash.
  • Mensajes en Conventional Commits, en español: tipo(ámbito): descripción, con la primera línea de 72 caracteres como máximo. Ejemplo: fix(install): respeta CLAUDE_CONFIG_DIR en WSL.
  • Tipos: feat, fix, docs, refactor, test, chore, ci. El ámbito es el mod o la zona (install), y es opcional.
  • El título de un PR sigue el mismo formato: al fusionar con squash, es la primera línea del commit que llega a main. GitHub le añade (#N), que cuenta para los 72 caracteres.
  • La firma de Claude (Co-Authored-By: Claude …, Generated with Claude Code) es libre. Si no la quieres en tus commits, haz que el hook la rechace en tu clon: git config claude-mods.rejectClaudeSignature true.

Los hooks de .githooks/ lo comprueban en cada commit y cada merge. Git no los activa solo: hay que hacerlo una vez en cada clon:

git config core.hooksPath .githooks

En cada PR, el workflow Git rules comprueba la rama, el título y todos los commits, aunque quien los hizo no tuviera los hooks activados. En los PR del propietario del repositorio comprueba además que ni los commits ni la descripción lleven firma de Claude.

Notas

  • Claude Code separa las rutas de CLAUDE_CODE_PLUGIN_DIRS con ; en Windows y con : en Linux y macOS. Los instaladores eligen el separador correcto.
  • En Windows, install.ps1 reescribe settings.json con la sangría de PowerShell. El contenido no cambia.
Source 2 files
hooks/register.tsx 485 lines
1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, Register } from 'claude-code'
3
4import type { Breakdown, Limit, Model, Monthly, Snapshot } from '../types'
5
6const PANE = 'faf-usage-meter'
7const TITLE = 'Claude usage'
8
9const snap = atom({ plugin: 'faf-usage-meter', key: 'snap' } as const, null)
10const breakdown = atom({ plugin: 'faf-usage-meter', key: 'breakdown' } as const, null)
11const isBandHidden = atom({ plugin: 'faf-usage-meter', key: 'isBandHidden' } as const, false)
12const monthly = atom({ plugin: 'faf-usage-meter', key: 'monthly' } as const, null)
13const model = atom({ plugin: 'faf-usage-meter', key: 'model' } as const, null)
14
15// Endpoint que usa /usage: gasto de extra usage de la cuenta, común a todos los equipos.
16const USAGE_URL = 'https://api.anthropic.com/api/oauth/usage'
17const MONTHLY_TTL_MS = 5 * 60_000
18
19const LIMIT_NAMES: Record<string, string> = {
20  five_hour: '5h',
21  seven_day: '7 days',
22  seven_day_opus: '7 days Opus',
23  seven_day_sonnet: '7 days Sonnet',
24  spend_limit: 'Spend',
25}
26
27const EIGHTHS = ['', '▏', '▎', '▍', '▌', '▋', '▊', '▉']
28
29const EFFORT_LEVELS = ['low', 'medium', 'high', 'xhigh', 'max']
30
31// Barra de `width` celdas con resolución de 1/8 de celda.
32export function bar(percent: number, width: number): { full: string; empty: string } {
33  const p = Math.max(0, Math.min(100, percent))
34  const eighths = Math.round((p / 100) * width * 8)
35  const whole = Math.floor(eighths / 8)
36  const part = EIGHTHS[eighths % 8]
37  const used = '█'.repeat(whole) + part
38  const rest = Math.max(0, width - whole - (part ? 1 : 0))
39
40  return { full: used, empty: '░'.repeat(rest) }
41}
42
43export function levelColor(percent: number): 'success' | 'warning' | 'error' {
44  if (percent >= 70) return 'error'
45  if (percent >= 50) return 'warning'
46  return 'success'
47}
48
49export function tokens(n: number | undefined): string {
50  if (n === undefined) return '—'
51  if (n >= 1_000_000) return `${(n / 1_000_000).toFixed(n % 1_000_000 === 0 ? 0 : 1)}M`
52  if (n >= 1000) return `${Math.round(n / 1000)}k`
53  return String(n)
54}
55
56export function limitName(kind: string): string {
57  return LIMIT_NAMES[kind] ?? kind.replace(/_/g, ' ')
58}
59
60// "2h 13m", "3d 4h", "12m"
61export function untilReset(resetsAt: string | undefined, now: number): string | null {
62  if (!resetsAt) return null
63  const ms = Date.parse(resetsAt) - now
64  if (!Number.isFinite(ms)) return null
65  if (ms <= 0) return 'now'
66  const min = Math.round(ms / 60_000)
67  const d = Math.floor(min / 1440)
68  const h = Math.floor((min % 1440) / 60)
69  const m = min % 60
70  if (d > 0) return `${d}d ${h}h`
71  if (h > 0) return `${h}h ${m}m`
72  return `${m}m`
73}
74
75function resetClock(resetsAt: string | undefined): string | null {
76  if (!resetsAt) return null
77  const date = new Date(resetsAt)
78  if (Number.isNaN(date.getTime())) return null
79  const days = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']
80  const hh = String(date.getHours()).padStart(2, '0')
81  const mm = String(date.getMinutes()).padStart(2, '0')
82
83  return `${days[date.getDay()]} ${hh}:${mm}`
84}
85
86// "claude-opus-5-5" → "Opus 5.5", "claude-sonnet-4-5-20250929[1m]" → "Sonnet 4.5 1M"; lo demás, tal cual.
87export function modelName(id: string): string {
88  const m = /^(?:claude-)?(fable|opus|sonnet|haiku)-(\d+)(?:-(\d{1,2}))?(?:-\d{8})?(\[1m\])?$/i.exec(id.trim())
89  if (!m || !m[1] || !m[2]) return id
90  const family = m[1][0]!.toUpperCase() + m[1].slice(1).toLowerCase()
91  const version = m[3] ? `${m[2]}.${m[3]}` : m[2]
92
93  return `${family} ${version}${m[4] ? ' 1M' : ''}`
94}
95
96// El esfuerzo es un nivel ("high") o un presupuesto de tokens ("8k").
97export function effortLabel(effort: string | number | null | undefined): string | null {
98  if (effort === undefined || effort === null) return null
99  return typeof effort === 'number' ? tokens(effort) : effort
100}
101
102// Nivel de esfuerzo en 5 puntos: high → ●●●○○
103export function effortDots(effort: string | number | null | undefined): { full: string; empty: string } | null {
104  const i = typeof effort === 'string' ? EFFORT_LEVELS.indexOf(effort) : -1
105  if (i < 0) return null
106
107  return { full: '●'.repeat(i + 1), empty: '○'.repeat(EFFORT_LEVELS.length - i - 1) }
108}
109
110const CURRENCY_SYMBOLS: Record<string, string> = { EUR: '€', USD: '$', GBP: '£' }
111
112// "12,34 €"
113export function money(amount: number, currency: string): string {
114  const sign = CURRENCY_SYMBOLS[currency] ?? currency
115
116  return `${amount.toFixed(2).replace('.', ',')} ${sign}`
117}
118
119type Money = { amount_minor: number; currency: string; exponent: number }
120
121type UsageReply = {
122  spend?: { used?: Money; limit?: Money; enabled?: boolean } | null
123  extra_usage?: {
124    is_enabled?: boolean
125    monthly_limit?: number | null
126    used_credits?: number | null
127    currency?: string
128  } | null
129}
130
131const fromMinor = (m: Money): number => m.amount_minor / 10 ** m.exponent
132
133export function toMonthly(reply: UsageReply, now: number): Monthly | null {
134  const spend = reply.spend
135  if (spend?.used) {
136    return {
137      used: fromMinor(spend.used),
138      limit: spend.limit ? fromMinor(spend.limit) : undefined,
139      currency: spend.used.currency,
140      enabled: spend.enabled ?? true,
141      fetchedAt: now,
142    }
143  }
144  const extra = reply.extra_usage
145  if (extra && typeof extra.used_credits === 'number') {
146    return {
147      used: extra.used_credits,
148      limit: extra.monthly_limit ?? undefined,
149      currency: extra.currency ?? 'USD',
150      enabled: extra.is_enabled ?? false,
151      fetchedAt: now,
152    }
153  }
154
155  return null
156}
157
158async function refreshMonthly($: EngineInterface, force = false): Promise<void> {
159  try {
160    const now = await $.clock.now()
161    const current = await read($, monthly)
162    if (!force && current && now - current.fetchedAt < MONTHLY_TTL_MS) return
163    const auth = await $.session.authorize()
164    if (!auth) return
165    const res = await $.http.fetch(USAGE_URL, {
166      auth: auth.handle,
167      headers: { 'anthropic-beta': 'oauth-2025-04-20' },
168    })
169    if (!res.ok) return
170    const value = toMonthly(JSON.parse(res.text) as UsageReply, now)
171    if (value) await update($, monthly, () => value)
172  } catch {
173    // Sin red o sin login de claude.ai: se queda el último dato.
174  }
175}
176
177type Measured = {
178  context: { tokens?: number; window: number; percent?: number }
179  rateLimits: Limit[]
180  cost?: { usd: number }
181}
182
183function toSnapshot(m: Measured): Snapshot {
184  return {
185    tokens: m.context.tokens,
186    window: m.context.window,
187    percent: m.context.percent,
188    limits: m.rateLimits.map(l => ({ kind: l.kind, percentUsed: l.percentUsed, resetsAt: l.resetsAt })),
189    usd: m.cost?.usd,
190  }
191}
192
193async function refreshBreakdown($: EngineInterface): Promise<void> {
194  try {
195    const usage = await $.session.usage({ breakdown: 'summary' })
196    const b = usage.context.breakdown
197    if (!b) return
198    const value: Breakdown = {
199      categories: b.categories
200        .filter(c => !c.isDeferred)
201        .map(c => ({ name: c.name, tokens: c.tokens, color: c.color, kind: c.kind })),
202      totalTokens: b.totalTokens,
203      maxTokens: b.rawMaxTokens,
204      autoCompactAt: b.isAutoCompactEnabled ? b.autoCompactThreshold : undefined,
205    }
206    await update($, breakdown, () => value)
207  } catch {
208    // Sin sesión enlazada todavía: se reintenta en la siguiente medición.
209  }
210}
211
212export const register: Register = on => {
213  let isPaneOpen = false
214
215  on('session.start', async ($, e, next) => {
216    await $.command.register({
217      name: 'faf-usage',
218      description: 'Open the pane with the context breakdown and quotas',
219    })
220    await $.command.register({
221      name: 'faf-usage-band',
222      description: 'Show or hide the context and quota bar below the prompt',
223    })
224    const ran = await next(e)
225    await update($, snap, () => null)
226    try {
227      const usage = await $.session.usage()
228      await update($, snap, () => toSnapshot(usage))
229    } catch {
230      // Se rellenará con la primera medición.
231    }
232    await refreshMonthly($, true)
233    try {
234      const id = await $.session.model()
235      await update($, model, m => ({ id, effort: m?.effort }))
236    } catch {
237      // La primera petición dirá el modelo.
238    }
239
240    return ran
241  })
242
243  on('session.measure', async ($, e, next) => {
244    await update($, snap, () => toSnapshot(e))
245    if (isPaneOpen && e.changed.includes('context')) {
246      await refreshBreakdown($)
247    }
248    if (e.changed.includes('rateLimits') || e.changed.includes('cost')) {
249      await refreshMonthly($)
250    }
251
252    return next(e)
253  })
254
255  // Cada petición del bucle principal dice el modelo y el esfuerzo con que sale (tras /model, /effort o un fallback).
256  on('turn.step', async function* ($, e, next) {
257    if (e.agentId === undefined) {
258      // Una petición sin esfuerzo dice que el modelo no lo admite (null), no que aún no se sepa
259      const effort = e.effort ?? null
260      const m = await read($, model)
261      if (m?.id !== e.model || m.effort !== effort) {
262        const value: Model = { id: e.model, effort }
263        await update($, model, () => value)
264      }
265    }
266
267    return yield* next(e)
268  })
269
270  on('command.run', { command: 'faf-usage' }, async $ => {
271    await refreshBreakdown($)
272    await refreshMonthly($, true)
273    const { isPlaced } = await $.ui.open({ id: PANE, title: TITLE })
274    isPaneOpen = true
275
276    return { text: isPlaced ? 'Usage pane opened.' : 'Usage pane ready; it will appear when there is room.' }
277  })
278
279  on('command.run', { command: 'faf-usage-band' }, async $ => {
280    const hidden = await update($, isBandHidden, v => !v)
281
282    return { text: hidden ? 'Usage bar hidden.' : 'Usage bar shown.' }
283  })
284
285  // Bajo la caja de entrada: la línea de ayuda del motor tal cual y, debajo, las barras.
286  on('ui.render', { component: 'PromptHint' }, async ($, e, next) => {
287    const hint = await next(e)
288    const s = await read($, snap)
289    const mo = await read($, monthly)
290    const mdl = await read($, model)
291    if (s === null || (await read($, isBandHidden))) {
292      return hint
293    }
294
295    const { Box, Text } = $.ui.resolve(e)
296    const now = await $.clock.now()
297    const columns = e.viewport?.columns ?? 100
298    const width = columns >= 140 ? 16 : columns >= 100 ? 10 : 6
299    const pct = s.percent ?? 0
300    const ctx = bar(pct, width)
301
302    return (
303      <Box flexDirection="column" rowGap={1}>
304        {hint}
305        <Box flexDirection="row" flexWrap="wrap" columnGap={2}>
306          {mdl && (
307            <Box flexDirection="row">
308              <Text>{modelName(mdl.id)}</Text>
309              {effortLabel(mdl.effort) && <Text dimColor> · {effortLabel(mdl.effort)}</Text>}
310            </Box>
311          )}
312          <Box flexDirection="row">
313            <Text dimColor>ctx </Text>
314            <Text color={levelColor(pct)}>{ctx.full}</Text>
315            <Text color="inactive">{ctx.empty}</Text>
316            <Text>
317              {' '}
318              {s.percent ?? '—'}% {tokens(s.tokens)}/{tokens(s.window)}
319            </Text>
320          </Box>
321          {s.limits.length === 0 && <Text dimColor>quota: no data yet</Text>}
322          {s.limits.map(l => {
323            const b = bar(l.percentUsed, width)
324            const left = untilReset(l.resetsAt, now)
325
326            return (
327              <Box flexDirection="row" key={l.kind}>
328                <Text dimColor>{limitName(l.kind)} </Text>
329                <Text color={levelColor(l.percentUsed)}>{b.full}</Text>
330                <Text color="inactive">{b.empty}</Text>
331                <Text> {Math.round(l.percentUsed)}%</Text>
332                {left && <Text dimColor> ↻ {left}</Text>}
333              </Box>
334            )
335          })}
336          {s.usd !== undefined && <Text dimColor>${s.usd.toFixed(2)}</Text>}
337          {mo && (
338            <Text dimColor>
339              month {money(mo.used, mo.currency)}
340              {mo.limit ? `/${money(mo.limit, mo.currency)}` : ''}
341            </Text>
342          )}
343        </Box>
344      </Box>
345    )
346  })
347
348  on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
349    const { Box, Text } = $.ui.resolve(e)
350    const s = await read($, snap)
351    const bd = await read($, breakdown)
352    const mo = await read($, monthly)
353    const mdl = await read($, model)
354    const now = await $.clock.now()
355    const columns = e.viewport?.columns ?? 60
356    const width = Math.max(10, Math.min(40, columns - 30))
357
358    if (s === null) {
359      return <Text dimColor>No measurements yet: they appear after the first response.</Text>
360    }
361
362    const pct = s.percent ?? 0
363    const ctx = bar(pct, width)
364    const stackMax = bd?.maxTokens ?? s.window
365    const used = bd?.categories.filter(c => c.kind === 'used' && c.tokens > 0) ?? []
366    const dots = effortDots(mdl?.effort)
367
368    return (
369      <Box flexDirection="column" rowGap={1}>
370        {mdl && (
371          <Box flexDirection="column">
372            <Text weight="bold">Model</Text>
373            <Text>
374              {modelName(mdl.id)}
375              {modelName(mdl.id) !== mdl.id && <Text dimColor> ({mdl.id})</Text>}
376            </Text>
377            <Box flexDirection="row">
378              <Text>{'Effort'.padEnd(12)}</Text>
379              {dots && <Text>{dots.full}</Text>}
380              {dots && <Text color="inactive">{dots.empty}</Text>}
381              <Text dimColor>
382                {dots ? ' ' : ''}
383                {effortLabel(mdl.effort) ??
384                  (mdl.effort === null ? 'not applicable to this model' : 'known after the first response')}
385              </Text>
386            </Box>
387          </Box>
388        )}
389
390        <Box flexDirection="column">
391          <Text weight="bold">Context</Text>
392          <Box flexDirection="row">
393            <Text color={levelColor(pct)}>{ctx.full}</Text>
394            <Text color="inactive">{ctx.empty}</Text>
395            <Text> {s.percent ?? '—'}%</Text>
396          </Box>
397          <Text dimColor>
398            {tokens(s.tokens)} of {tokens(s.window)} tokens
399            {bd?.autoCompactAt ? ` · auto-compacts at ${tokens(bd.autoCompactAt)}` : ''}
400          </Text>
401        </Box>
402
403        {used.length > 0 && (
404          <Box flexDirection="column">
405            <Text weight="bold">Breakdown (estimated)</Text>
406            <Box flexDirection="row">
407              {used.map(c => (
408                <Text key={c.name} color={c.color}>
409                  {'█'.repeat(Math.max(1, Math.round((c.tokens / stackMax) * width)))}
410                </Text>
411              ))}
412            </Box>
413            {used.map(c => (
414              <Box flexDirection="row" key={`row-${c.name}`}>
415                <Text color={c.color}>■ </Text>
416                <Text>{c.name}</Text>
417                <Text dimColor>
418                  {' '}
419                  {tokens(c.tokens)} ({((c.tokens / stackMax) * 100).toFixed(1)}%)
420                </Text>
421              </Box>
422            ))}
423          </Box>
424        )}
425
426        <Box flexDirection="column">
427          <Text weight="bold">Quota</Text>
428          {s.limits.length === 0 && (
429            <Text dimColor>No data (arrives with the first response; subscriptions only).</Text>
430          )}
431          {s.limits.map(l => {
432            const b = bar(l.percentUsed, width)
433            const left = untilReset(l.resetsAt, now)
434            const at = resetClock(l.resetsAt)
435
436            return (
437              <Box flexDirection="column" key={`lim-${l.kind}`}>
438                <Box flexDirection="row">
439                  <Text>{limitName(l.kind).padEnd(12)}</Text>
440                  <Text color={levelColor(l.percentUsed)}>{b.full}</Text>
441                  <Text color="inactive">{b.empty}</Text>
442                  <Text> {l.percentUsed}% / 100%</Text>
443                </Box>
444                {left && (
445                  <Text dimColor>
446                    {'            '}resets in {left}
447                    {at ? ` (${at})` : ''}
448                  </Text>
449                )}
450              </Box>
451            )
452          })}
453        </Box>
454
455        <Box flexDirection="column">
456          <Text weight="bold">Monthly spend (account)</Text>
457          {mo === null && <Text dimColor>No data: sign in with a claude.ai account.</Text>}
458          {mo && !mo.enabled && <Text dimColor>Extra usage disabled: no spend beyond the subscription.</Text>}
459          {mo && mo.enabled && (
460            <Box flexDirection="column">
461              {mo.limit ? (
462                <Box flexDirection="row">
463                  <Text color={levelColor((mo.used / mo.limit) * 100)}>{bar((mo.used / mo.limit) * 100, width).full}</Text>
464                  <Text color="inactive">{bar((mo.used / mo.limit) * 100, width).empty}</Text>
465                  <Text>
466                    {' '}
467                    {money(mo.used, mo.currency)} of {money(mo.limit, mo.currency)}
468                  </Text>
469                </Box>
470              ) : (
471                <Text>
472                  {money(mo.used, mo.currency)} <Text dimColor>(no limit set)</Text>
473                </Text>
474              )}
475              <Text dimColor>Extra usage across all your teams; the fixed subscription quota is separate.</Text>
476            </Box>
477          )}
478        </Box>
479
480        {s.usd !== undefined && <Text dimColor>Estimated cost of this session (API pricing): ${s.usd.toFixed(2)}</Text>}
481      </Box>
482    )
483  })
484}
485
types/index.d.ts 47 lines
1export type Limit = { kind: string; percentUsed: number; resetsAt?: string }
2
3export type Snapshot = {
4  tokens?: number
5  window: number
6  percent?: number
7  limits: Limit[]
8  usd?: number
9}
10
11export type Category = { name: string; tokens: number; color: string; kind: string }
12
13export type Breakdown = {
14  categories: Category[]
15  totalTokens: number
16  maxTokens: number
17  autoCompactAt?: number
18}
19
20// Gasto de la cuenta en el mes (extra usage), en unidades de la moneda.
21export type Monthly = {
22  used: number
23  limit?: number
24  currency: string
25  enabled: boolean
26  fetchedAt: number
27}
28
29// Modelo con que sale la última petición del bucle principal y su esfuerzo (nivel o presupuesto de
30// tokens): null si el modelo no lo admite, ausente mientras no ha salido ninguna petición.
31export type Model = {
32  id: string
33  effort?: string | number | null
34}
35
36declare module 'claude-code' {
37  interface PluginState {
38    'faf-usage-meter': {
39      snap: Snapshot | null
40      breakdown: Breakdown | null
41      isBandHidden: boolean
42      monthly: Monthly | null
43      model: Model | null
44    }
45  }
46}
47