SLOPSHOPPER

usage-limits

Consumo de tokens, custo, previsão dos limites de 5h e semanal e recomendação de modelo

panebandcommandtoaststatusprocess
★ 1v0.8.0MITupdated 2026-10-15kevinmedeiros/claude-mods/plugins/usage-limits
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · usage-limits
│ ┃ Limites ✕ › fix the failing auth╭────────────────────────────────────────────╮ │ ┃ atualizado 08:53 [ ↻ Atualizar ] │ usage-limits │ │ ┃ ⏺ Read(src/auth.ts) │ Modo economia ligado: o fio principal │ │ ┃ 5 horas ████████░░░░░░░░░░░░░░░░░░ 31% ⎿ Read 6 lines │ orquestra, os novos subagentes executam em │ │ ┃ duração estimada — · reset em — ⏺ Update(src/auth.ts) │ Haiku 5.5. │ │ ┃ ritmo — recente · — média da janela ⎿ Added 2 lines, re╰────────────────────────────────────────────╯ │ ┃ Sem projeção para esta janela ⏺ Bash(bun test) │ ┃ ⎿ 3 pass, 1 fail │ ┃ ╭──────────────────────────────────────────╮ │ ┃ │ Qual modelo usar │ ● Done. refresh now rejects expired claims and logs an audit event. │ ┃ │ A recomendação aparece depois de algumas │ │ ┃ │ respostas com os limites medidos. │ ✻ Worked for 42s · done 4:20 PM │ ┃ │ [ Desligar economia ] │ │ ┃ │ Estimativa pelo preço de API de cada │ › /limites │ ┃ │ modelo; a assinatura pode pesar os │ ⎿ usage-limits: Painel de limites aberto. │ ┃ │ modelos de outro jeito. │ │ ┃ ╰──────────────────────────────────────────╯ │ ┃ │ ┃ Sessões │ ┃ ● work Opus 5.5 0 tok │ ┃ US$ 0,42 · 100% (esta) │ ┃ Total (1 sessão aberta): 0 tok · US$ 0,42 │ ┃ Hoje nesta máquina, fechadas inclusive: 1 │ ┃ sessões · 0 tok · US$ 0,42 │ ┃ Custo equivalente em preço de API; no plano, │ ┃ o que conta são os limites de 5h e semanal. 5h ██░░░░░░ 31% US$ 0,42 · /limites Economia ligada ✕ ↻ ▾ ⟨Claude Code's own drawing⟩ ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts ⚠ usage-limits: 5h 31% │ US$ 0,42

Draws

Band
5h ██░░░░░░ 31% US$ 0,42 · /limites Economia ligada ✕ ↻ ▾ ⟨Claude Code's own drawing⟩
Pane · Limites
atualizado 08:53 [ ↻ Atualizar ] 5 horas ████████░░░░░░░░░░░░░░░░░░ 31% duração estimada — · reset em — ritmo — recente · — média da janela Sem projeção para esta janela ╭──────────────────────────────────────────────────────────╮ │ Qual modelo usar │ │ A recomendação aparece depois de algumas respostas com │ │ os limites medidos. │ │ [ Desligar economia ] │ │ Estimativa pelo preço de API de cada modelo; a │ │ assinatura pode pesar os modelos de outro jeito. │ ╰──────────────────────────────────────────────────────────╯ Sessões ● work Opus 5.5 0 tok US$ 0,42 · 100% (esta) Total (1 sessão aberta): 0 tok · US$ 0,42 Hoje nesta máquina, fechadas inclusive: 1 sessões · 0 tok · US$ 0,42 Custo equivalente em preço de API; no plano, o que conta são os limites de 5h e semanal. Esta sessão entrada 0 · saída 0 · cache lido 0 · cache escrito 0 total 0 em 1 turno · custo US$ 0,42 · contexto 49%
README

usage-limits

Your Claude Code plan limits with how long they will last at your current pace, sessions, per-project spend, API credits and model advice.

See the main README · Português.

Source 10 files
hooks/register.tsx 630 lines
1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, Register, SessionRateLimit, SessionUsage, TurnUsage } from 'claude-code'
3
4import type { Advice, ApiSpend, Mix, ProjectBucket, SessionRecord, Snapshot, Totals, WindowView } from '../types'
5import { apiProblem, costReportUrl, cycleBounds, projectApi, sumCostReport } from './api'
6import { sessionsView, upsertSession } from './sessions'
7import type { SessionBook } from './sessions'
8import { addToMix, advise, emptyMix } from './advisor'
9import { activeHoursPerDay, addActivity, addHourly, recentMix, updateCalibration, weekPerFive } from './pace'
10import type { Calibration, HourlyMix } from './pace'
11import { HAIKU_ID, costOf, family, modelKey } from './pricing'
12import {
13  HOUR,
14  MINUTE,
15  addSample,
16  apiShort,
17  clockTime,
18  duration,
19  emptyTotals,
20  percent,
21  project,
22  projectName,
23  projectShares,
24  readingAge,
25  sameWindow,
26  statusLine,
27  totalTokens,
28} from './projection'
29import type { SampleLog, TokenBucket } from './projection'
30import { RichBand, RichPane, TerminalBand, TerminalPane } from './view'
31import type { Actions, ViewData } from './view'
32
33const PANE = 'usage-limits'
34const COMMAND = 'limites'
35const ECONOMY_COMMAND = 'economia'
36
37const snapshot = atom({ plugin: 'usage-limits', key: 'snapshot' } as const, null)
38const session = atom({ plugin: 'usage-limits', key: 'session' } as const, emptyTotals())
39const economy = atom({ plugin: 'usage-limits', key: 'economy' } as const, false)
40const setup = atom({ plugin: 'usage-limits', key: 'setup' } as const, {})
41const currentProject = atom({ plugin: 'usage-limits', key: 'project' } as const, '')
42const api = atom({ plugin: 'usage-limits', key: 'api' } as const, null)
43const bandCollapsed = atom({ plugin: 'usage-limits', key: 'bandCollapsed' } as const, false)
44const BAND_KEY = 'band-collapsed'
45
46type Alerts = { resetsAt: number; sent: string[] }
47
48const samplesKey = (kind: string) => `samples:${kind}`
49const bucketKey = (kind: string) => `tokens:${kind}`
50const alertsKey = (kind: string) => `alerts:${kind}`
51const mixKey = (kind: string) => `mix:${kind}`
52const projectsKey = (kind: string) => `projects:${kind}`
53const ECONOMY_KEY = 'economy'
54const CALIBRATION_KEY = 'calibration'
55const ACTIVITY_KEY = 'activity'
56const HOURLY_KEY = 'hourly'
57
58/** A leitura desta sessão e os arquivos que as sessões da máquina compartilham. */
59const reading = { ownAt: 0, own: [] as SessionRateLimit[], sharedFile: '', sessionsFile: '', selfId: '', startedAt: 0 }
60
61/** As opções dos créditos de API, do /plugin. */
62const apiConfig = { key: '', creditUsd: 200, cycleDay: 1 }
63
64const readBook = async ($: EngineInterface): Promise<SessionBook | undefined> => {
65  if (!reading.sessionsFile) return undefined
66  try {
67    if (!(await $.fs.exists(reading.sessionsFile))) return undefined
68    const raw = JSON.parse(await $.fs.read(reading.sessionsFile)) as Record<string, unknown>
69    const book: SessionBook = {}
70    for (const [id, r] of Object.entries(raw ?? {})) {
71      const rec = r as Partial<SessionRecord> | null
72      if (rec && typeof rec === 'object' && rec.id === id && typeof rec.updatedAt === 'number' && rec.tokens) {
73        book[id] = rec as SessionRecord
74      }
75    }
76    return book
77  } catch {
78    return undefined
79  }
80}
81
82/** Grava o consumo desta sessão no livro de sessões da máquina e devolve o livro. */
83const writeSelf = async ($: EngineInterface, costUsd: number | undefined, ended = false) => {
84  if (!reading.sessionsFile || !reading.selfId) return undefined
85  const now = await $.clock.now()
86  const held = await readBook($)
87  const previous = held?.[reading.selfId]
88  const record: SessionRecord = {
89    id: reading.selfId,
90    project: await read($, currentProject),
91    model: (await read($, setup)).mainModel,
92    startedAt: reading.startedAt || now,
93    updatedAt: now,
94    tokens: await read($, session),
95    costUsd: costUsd ?? previous?.costUsd ?? 0,
96    ended,
97  }
98  const book = upsertSession(held, record, now)
99  try {
100    await $.fs.write(reading.sessionsFile, JSON.stringify(book))
101  } catch {
102    // Sem o arquivo, a lista mostra só esta sessão.
103  }
104
105  return book
106}
107
108/** Lê do Console quanto dos créditos de API o ciclo já gastou. */
109const refreshApi = async ($: EngineInterface) => {
110  if (!apiConfig.key) return
111  const now = await $.clock.now()
112  const bounds = cycleBounds(now, apiConfig.cycleDay)
113  let usdTotal = 0
114  const byModel: Record<string, number> = {}
115  let page: string | undefined
116  try {
117    for (let i = 0; i < 5; i++) {
118      const r = await $.http.fetch(costReportUrl(bounds.start, now, page), {
119        headers: { 'x-api-key': apiConfig.key, 'anthropic-version': '2023-06-01', 'user-agent': 'usage-limits-mod/0.6' },
120      })
121      if (!r.ok) {
122        const held = await read($, api)
123        await update($, api, () => ({ ...(held ?? projectApi(0, {}, bounds, now, apiConfig.creditUsd)), problem: apiProblem(r.status, r.text) }))
124        return
125      }
126      const pageSum = sumCostReport(r.text)
127      usdTotal += pageSum.usd
128      for (const [m, v] of Object.entries(pageSum.byModel)) byModel[m] = (byModel[m] ?? 0) + v
129      page = pageSum.next
130      if (!page) break
131    }
132    await update($, api, () => projectApi(usdTotal, byModel, bounds, now, apiConfig.creditUsd))
133  } catch (error) {
134    const held = await read($, api)
135    await update($, api, () => ({
136      ...(held ?? projectApi(0, {}, bounds, now, apiConfig.creditUsd)),
137      problem: `Não consegui falar com o Console: ${String(error).slice(0, 120)}`,
138    }))
139  }
140}
141
142const apiStatus = (spend: ApiSpend | null) => (spend && !spend.problem ? apiShort(spend.spentUsd, spend.creditUsd) : undefined)
143
144type SharedReading = { at: number; rateLimits: SessionRateLimit[] }
145
146const readShared = async ($: EngineInterface): Promise<SharedReading | undefined> => {
147  if (!reading.sharedFile) return undefined
148  try {
149    if (!(await $.fs.exists(reading.sharedFile))) return undefined
150    const data = JSON.parse(await $.fs.read(reading.sharedFile)) as Partial<SharedReading>
151    return typeof data.at === 'number' && Array.isArray(data.rateLimits) ? (data as SharedReading) : undefined
152  } catch {
153    return undefined
154  }
155}
156
157const writeShared = async ($: EngineInterface, value: SharedReading) => {
158  if (!reading.sharedFile) return
159  try {
160    await $.fs.write(reading.sharedFile, JSON.stringify(value))
161  } catch {
162    // Sem arquivo compartilhado, cada sessão segue com a própria leitura.
163  }
164}
165
166const resetOf = (w: SessionRateLimit) => (w.resetsAt ? Date.parse(w.resetsAt) : NaN)
167
168const loadMix = async ($: EngineInterface, w: WindowView): Promise<Mix | undefined> => {
169  const held = (await $.store.get(mixKey(w.kind))) as Mix | undefined
170
171  return held && w.resetsAt !== undefined && sameWindow(held.resetsAt, w.resetsAt) ? held : undefined
172}
173
174/**
175 * Recalcula tudo a partir da leitura mais nova da máquina: a desta sessão ou a
176 * que outra sessão gravou no arquivo compartilhado. `record` diz que a leitura
177 * desta sessão acabou de mudar.
178 */
179const refresh = async ($: EngineInterface, usage: SessionUsage, record: boolean) => {
180  const now = await $.clock.now()
181  if (record && usage.rateLimits.length > 0) {
182    reading.ownAt = now
183    reading.own = usage.rateLimits
184    await writeShared($, { at: now, rateLimits: usage.rateLimits })
185    const five = usage.rateLimits.find(w => w.kind === 'five_hour')
186    const week = usage.rateLimits.find(w => w.kind === 'seven_day')
187    if (five && week) {
188      const held = (await $.store.get(CALIBRATION_KEY)) as Calibration | undefined
189      const next = updateCalibration(held, five, week)
190      if (next) await $.store.set(CALIBRATION_KEY, next)
191    }
192  }
193
194  let limits = reading.own.length > 0 ? reading.own : usage.rateLimits
195  let readAt: number | undefined = reading.ownAt || undefined
196  let isShared = false
197  const shared = await readShared($)
198  if (shared && shared.rateLimits.length > 0 && shared.at > (reading.ownAt || 0) + 30_000) {
199    limits = shared.rateLimits
200    readAt = shared.at
201    isShared = true
202  }
203  // O 5h primeiro: o ritmo dele alimenta o do semanal.
204  const ordered = [...limits].sort((a, b) => (a.kind === 'five_hour' ? -1 : b.kind === 'five_hour' ? 1 : 0))
205
206  const perDay = activeHoursPerDay((await $.store.get(ACTIVITY_KEY)) as number[] | undefined, now)
207  const ratio = weekPerFive((await $.store.get(CALIBRATION_KEY)) as Calibration | undefined)
208  let fiveRate: number | undefined
209  const windows: WindowView[] = []
210  const mixes: Record<string, Mix | undefined> = {}
211
212  for (const raw of ordered) {
213    const resetsAt = resetOf(raw)
214    let log = (await $.store.get(samplesKey(raw.kind))) as SampleLog | undefined
215    if ((record || isShared) && !Number.isNaN(resetsAt)) {
216      log = addSample(log, resetsAt, { t: readAt ?? now, pct: raw.percentUsed })
217      await $.store.set(samplesKey(raw.kind), log)
218    }
219    const bucket = (await $.store.get(bucketKey(raw.kind))) as TokenBucket | undefined
220    const view = project(raw, now, log, bucket, { fiveRate, weekPerFive: ratio, activeHoursPerDay: perDay })
221    if (raw.kind === 'five_hour') {
222      // Nos primeiros 30 min de uma janela de 5h o ritmo é só ruído (1% em 9 min viraria 6,7%/h).
223      const elapsed5 = 5 * HOUR - (view.msToReset ?? 5 * HOUR)
224      const recent = view.recentRatePerHour ?? 0
225      fiveRate =
226        elapsed5 < 30 * MINUTE ? undefined : recent > 0 ? recent : (view.windowRatePerHour ?? 0) > 0 ? view.windowRatePerHour : undefined
227    }
228    windows.push(view)
229    mixes[raw.kind] = await loadMix($, view)
230    const projects = (await $.store.get(projectsKey(raw.kind))) as ProjectBucket | undefined
231    if (projects && view.resetsAt !== undefined && sameWindow(projects.resetsAt, view.resetsAt)) {
232      view.projects = projectShares(projects, view.pct)
233    }
234  }
235
236  const recent = recentMix((await $.store.get(HOURLY_KEY)) as HourlyMix | undefined, now, 0)
237  const book = await writeSelf($, usage.cost?.usd)
238  const sessions = reading.selfId ? sessionsView(book, now, reading.selfId) : undefined
239  const next: Snapshot = {
240    updatedAt: now,
241    windows,
242    costUsd: usage.cost?.usd,
243    contextPercent: usage.context.percent,
244    advice: advise(windows, mixes, await read($, setup), recent),
245    readAt,
246    isSharedReading: isShared,
247    sessions,
248    selfId: reading.selfId,
249  }
250  await update($, snapshot, () => next)
251  $.ui.status(
252    statusLine(windows, await read($, session), next.costUsd, readingAge(readAt, now), {
253      sessions: sessions && {
254        count: sessions.total.count,
255        tokens: totalTokens(sessions.total.tokens),
256        costUsd: sessions.total.costUsd,
257      },
258      api: apiStatus(await read($, api)),
259    }),
260  )
261  await alert($, windows, now, next.advice)
262}
263
264/** Avisa uma vez por janela em cada nível, e uma vez por recomendação. */
265const alert = async ($: EngineInterface, windows: WindowView[], now: number, advice?: Advice) => {
266  for (const w of windows) {
267    if (w.resetsAt === undefined) continue
268    const stored = (await $.store.get(alertsKey(w.kind))) as Alerts | undefined
269    const held = stored && sameWindow(stored.resetsAt, w.resetsAt) ? stored.sent : []
270    const sent = [...held]
271    const once = (level: string, text: string) => {
272      if (sent.includes(level)) return
273      sent.push(level)
274      $.ui.toast(text, { timeoutMs: 8000 })
275    }
276
277    if (w.verdict === 'exhausted') {
278      once('100', `Limite ${w.label} esgotado. Volta às ${clockTime(w.resetsAt, now)}.`)
279    } else if (w.pct >= 95) {
280      once('95', `Limite ${w.label} em ${percent(w.pct)}. Reset às ${clockTime(w.resetsAt, now)}.`)
281    } else if (w.pct >= 80) {
282      once('80', `Limite ${w.label} em ${percent(w.pct)}. Reset às ${clockTime(w.resetsAt, now)}.`)
283    }
284    if (w.verdict === 'exhausts' && w.exhaustAt !== undefined && w.pct >= 25) {
285      once(
286        'projection',
287        `No ritmo atual o limite ${w.label} acaba ~${clockTime(w.exhaustAt, now)}, ` +
288          `${duration(w.resetsAt - w.exhaustAt)} antes do reset.`,
289      )
290    }
291    if (advice?.pick && advice.windowKind === w.kind && w.pct >= 15) {
292      once(`advice:${advice.pick}`, `${advice.headline} Veja /limites.`)
293    }
294
295    if (sent.length !== held.length) {
296      await $.store.set(alertsKey(w.kind), { resetsAt: w.resetsAt, sent })
297    }
298  }
299}
300
301/** Soma os tokens de uma resposta às janelas abertas. */
302const countTokens = async ($: EngineInterface, tokens: number) => {
303  const last = await read($, snapshot)
304  for (const w of last?.windows ?? []) {
305    if (w.resetsAt === undefined) continue
306    const held = (await $.store.get(bucketKey(w.kind))) as TokenBucket | undefined
307    const bucket: TokenBucket =
308      held && sameWindow(held.resetsAt, w.resetsAt)
309        ? { ...held, tokens: held.tokens + tokens }
310        : { resetsAt: w.resetsAt, tokens, firstPct: w.pct }
311    await $.store.set(bucketKey(w.kind), bucket)
312  }
313}
314
315/** Soma uma resposta ao gasto por modelo e por papel de cada janela aberta. */
316const countMix = async ($: EngineInterface, role: 'main' | 'sub', usage: TurnUsage) => {
317  const last = await read($, snapshot)
318  const tokens = {
319    input: usage.input_tokens,
320    output: usage.output_tokens,
321    cacheRead: usage.cache_read_input_tokens,
322    cacheWrite: usage.cache_creation_input_tokens,
323  }
324  for (const w of last?.windows ?? []) {
325    if (w.resetsAt === undefined) continue
326    const held = (await loadMix($, w)) ?? emptyMix(w.resetsAt)
327    await $.store.set(mixKey(w.kind), addToMix(held, role, usage.model, tokens))
328  }
329}
330
331/** Anota a hora de trabalho e soma a resposta ao gasto por hora (para a recomendação). */
332const countRecent = async ($: EngineInterface, role: 'main' | 'sub', usage: TurnUsage) => {
333  const now = await $.clock.now()
334  await $.store.set(ACTIVITY_KEY, addActivity((await $.store.get(ACTIVITY_KEY)) as number[] | undefined, now))
335  const tokens = {
336    input: usage.input_tokens,
337    output: usage.output_tokens,
338    cacheRead: usage.cache_read_input_tokens,
339    cacheWrite: usage.cache_creation_input_tokens,
340  }
341  const held = (await $.store.get(HOURLY_KEY)) as HourlyMix | undefined
342  await $.store.set(HOURLY_KEY, addHourly(held, now, role, modelKey(usage.model), tokens))
343}
344
345/** Soma o custo de uma resposta ao projeto da sessão em cada janela aberta. */
346const countProject = async ($: EngineInterface, usage: TurnUsage) => {
347  const name = await read($, currentProject)
348  const last = await read($, snapshot)
349  if (!name) return
350  const cost = costOf(
351    {
352      input: usage.input_tokens,
353      output: usage.output_tokens,
354      cacheRead: usage.cache_read_input_tokens,
355      cacheWrite: usage.cache_creation_input_tokens,
356    },
357    modelKey(usage.model),
358  )
359  for (const w of last?.windows ?? []) {
360    if (w.resetsAt === undefined) continue
361    const held = (await $.store.get(projectsKey(w.kind))) as ProjectBucket | undefined
362    const bucket: ProjectBucket =
363      held && sameWindow(held.resetsAt, w.resetsAt) ? held : { resetsAt: w.resetsAt, firstPct: w.pct, byProject: {} }
364    bucket.byProject[name] = (bucket.byProject[name] ?? 0) + cost
365    await $.store.set(projectsKey(w.kind), bucket)
366  }
367}
368
369/** Raiz do git da pasta da sessão, ou a própria pasta. */
370const findProject = async ($: EngineInterface, cwd: string) => {
371  try {
372    const { exitCode, stdout } = await $.process.run(['git', 'rev-parse', '--show-toplevel'], { cwd, timeoutMs: 5000 })
373    return projectName(exitCode === 0 && stdout.trim() ? stdout.trim() : cwd)
374  } catch {
375    return projectName(cwd)
376  }
377}
378
379/** Soma uma chamada ao modelo (principal ou subagente) aos totais da sessão e das janelas. */
380const addTotals = async ($: EngineInterface, usage: TurnUsage) => {
381  const add = {
382    input: usage.input_tokens,
383    output: usage.output_tokens,
384    cacheRead: usage.cache_read_input_tokens,
385    cacheWrite: usage.cache_creation_input_tokens,
386  }
387  await update($, session, t => ({
388    input: t.input + add.input,
389    output: t.output + add.output,
390    cacheRead: t.cacheRead + add.cacheRead,
391    cacheWrite: t.cacheWrite + add.cacheWrite,
392    turns: t.turns,
393  }))
394  await countTokens($, add.input + add.output + add.cacheRead + add.cacheWrite)
395}
396
397const setCollapsed = async ($: EngineInterface, collapsed: boolean) => {
398  await update($, bandCollapsed, () => collapsed)
399  await $.store.set(BAND_KEY, collapsed)
400}
401
402const setEconomy = async ($: EngineInterface, on: boolean) => {
403  await update($, economy, () => on)
404  await $.store.set(ECONOMY_KEY, on)
405  $.ui.toast(
406    on
407      ? 'Modo economia ligado: o fio principal orquestra, os novos subagentes executam em Haiku 5.5.'
408      : 'Modo economia desligado: os subagentes voltam ao modelo de sempre.',
409  )
410}
411
412/**
413 * O botão ↻: relê a leitura mais nova da máquina, recalcula, atualiza a lista
414 * de sessões e os créditos de API. O % da conta em si só muda quando alguma
415 * sessão recebe uma resposta da API (uma chamada avulsa não o traz).
416 */
417const reloadAll = async ($: EngineInterface) => {
418  if (apiConfig.key) await refreshApi($)
419  await refresh($, await $.session.usage(), false)
420  const age = readingAge((await read($, snapshot))?.readAt, await $.clock.now())
421  $.ui.toast(
422    age
423      ? `Atualizado. A leitura da conta é de ${age}; um número novo chega na próxima resposta do Claude em qualquer sessão desta máquina.`
424      : 'Atualizado com a leitura mais recente da conta.',
425    { timeoutMs: 6000 },
426  )
427}
428
429const actionsFor = ($: EngineInterface, withDetails: boolean): Actions => ({
430  details: withDetails ? () => void $.ui.open({ id: PANE, title: 'Limites' }) : undefined,
431  reload: () => void reloadAll($),
432  toggleEconomy: () => void read($, economy).then(on => setEconomy($, !on)),
433  toggleBand: () => void read($, bandCollapsed).then(c => setCollapsed($, !c)),
434  fillModel: alias => void $.prompt.fill({ text: `/model ${alias}` }),
435})
436
437const viewData = async ($: EngineInterface, snap: Snapshot): Promise<ViewData> => ({
438  snap,
439  totals: await read($, session),
440  economy: await read($, economy),
441  api: await read($, api),
442  collapsed: await read($, bandCollapsed),
443})
444
445export const register: Register = (on, options) => {
446  apiConfig.key = String(options.adminApiKey ?? '').trim()
447  apiConfig.creditUsd = Number(options.apiMonthlyCredit ?? 200)
448  apiConfig.cycleDay = Number(options.apiCycleDay ?? 1)
449
450  /** Subagentes já decididos: true roda em Haiku. Um agente nunca troca no meio. */
451  const haikuAgents = new Map<string, boolean>()
452  const forks = new Set<string>()
453
454  on('session.start', async ($, e, next) => {
455    const started = await next(e)
456    const home = (await $.env.get('HOME')) ?? (await $.env.get('USERPROFILE'))
457    const dir = home ? `${home.replaceAll('\\', '/')}/.claude/usage-limits` : ''
458    reading.sharedFile = dir ? `${dir}/latest.json` : ''
459    reading.sessionsFile = dir ? `${dir}/sessions.json` : ''
460    reading.selfId = await $.session.id()
461    reading.startedAt = (await $.session.usage()).startedAt
462    const name = await findProject($, started.cwd)
463    await update($, currentProject, () => name)
464    await $.command.register({
465      name: COMMAND,
466      description: 'Mostra consumo de tokens, previsão dos limites e qual modelo usar',
467    })
468    await $.command.register({
469      name: ECONOMY_COMMAND,
470      description: 'Liga/desliga o modo economia: o principal orquestra, subagentes executam em Haiku',
471    })
472    const isEconomy = (await $.store.get(ECONOMY_KEY)) === true
473    const isCollapsed = (await $.store.get(BAND_KEY)) === true
474    await update($, bandCollapsed, () => isCollapsed)
475    await update($, economy, () => isEconomy)
476    // O modelo da sessão já ao abrir, para a recomendação não dizer "o modelo atual".
477    try {
478      const model = await $.session.model()
479      if (model) await update($, setup, held => (held.mainModel ? held : { ...held, mainModel: model }))
480    } catch {
481      // Sem o modelo agora, ele chega na primeira resposta.
482    }
483    await refresh($, await $.session.usage(), false)
484    $.clock.every(60_000, () => {
485      void $.session.usage().then(usage => refresh($, usage, false))
486    })
487    if (apiConfig.key) {
488      void refreshApi($)
489      $.clock.every(10 * 60_000, () => void refreshApi($))
490    }
491
492    return started
493  })
494
495  on('session.measure', async ($, e, next) => {
496    const result = await next(e)
497    await refresh($, { startedAt: 0, ...e }, e.changed.includes('rateLimits'))
498
499    return result
500  })
501
502  on('agent.spawn', async ($, e, next) => {
503    const result = await next(e)
504    if (e.fork && result.agentId) forks.add(result.agentId)
505
506    return result
507  })
508
509  // Cada chamada ao modelo: anota o modelo principal, põe subagentes em Haiku
510  // no modo economia e soma o gasto por modelo e papel.
511  on('turn.step', async function* ($, e, next) {
512    let step = e
513    if (e.agentId) {
514      let isHaiku = haikuAgents.get(e.agentId)
515      if (isHaiku === undefined) {
516        isHaiku = e.index === 0 && !forks.has(e.agentId) && (await read($, economy))
517        haikuAgents.set(e.agentId, isHaiku)
518      }
519      if (isHaiku && family(modelKey(e.model)) !== 'haiku') step = { ...e, model: HAIKU_ID }
520    } else {
521      const held = await read($, setup)
522      if (held.mainModel !== e.model || held.mainEffort !== e.effort) {
523        const effort = typeof e.effort === 'number' ? String(e.effort) : e.effort
524        await update($, setup, () => ({ mainModel: e.model, mainEffort: effort }))
525      }
526    }
527
528    const result = yield* next(step)
529    if (result.usage) {
530      await addTotals($, result.usage)
531      await countMix($, e.agentId ? 'sub' : 'main', result.usage)
532      await countProject($, result.usage)
533      await countRecent($, e.agentId ? 'sub' : 'main', result.usage)
534    }
535
536    return result
537  })
538
539  // Os tokens já foram somados a cada chamada (turn.step); aqui conta o turno e
540  // grava o livro de sessões. O `usage` do fim do turno nem sempre vem.
541  on('turn.complete', async ($, e, next) => {
542    const result = await next(e)
543    if (!e.agentId) {
544      const totals = await update($, session, t => ({ ...t, turns: t.turns + 1 }))
545      const last = await read($, snapshot)
546      await writeSelf($, last?.costUsd)
547      $.ui.status(
548        statusLine(last?.windows ?? [], totals, last?.costUsd, readingAge(last?.readAt, await $.clock.now()), {
549          api: apiStatus(await read($, api)),
550        }),
551      )
552    }
553
554    return result
555  })
556
557  // Ao fechar: marca a sessão como encerrada na lista da máquina (dentro do tempo curto do fim).
558  on('session.end', async ($, e, next) => {
559    try {
560      await writeSelf($, (await read($, snapshot))?.costUsd, true)
561    } catch {
562      // O fim da sessão não espera pelo mod.
563    }
564    return next(e)
565  })
566
567  on('command.run', { command: COMMAND }, async $ => {
568    if (apiConfig.key) void refreshApi($)
569    await refresh($, await $.session.usage(), false)
570    await $.ui.open({ id: PANE, title: 'Limites' })
571
572    return { text: 'Painel de limites aberto.' }
573  })
574
575  on('command.run', { command: ECONOMY_COMMAND }, async ($, e) => {
576    const arg = e.args.trim().toLowerCase()
577    const isOn = arg === 'on' || arg === 'ligar' ? true : arg === 'off' || arg === 'desligar' ? false : !(await read($, economy))
578    await setEconomy($, isOn)
579    await refresh($, await $.session.usage(), false)
580
581    return {
582      text: isOn
583        ? 'Modo economia ligado: novos subagentes rodam em Haiku 5.5; o fio principal continua no modelo atual.'
584        : 'Modo economia desligado.',
585    }
586  })
587
588  on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
589    const snap = await read($, snapshot)
590    if (e.surface === 'terminal') {
591      const ui = $.ui.resolve(e)
592      if (snap === null) return <ui.Text dimColor>Aguardando a primeira leitura…</ui.Text>
593
594      return TerminalPane(ui, await viewData($, snap), e.props.bodyColumns, actionsFor($, false))
595    }
596    const ui = $.ui.resolve(e)
597    if (snap === null) return <ui.Text dimColor>Aguardando a primeira leitura…</ui.Text>
598
599    return RichPane(ui, await viewData($, snap), e.props.bodyColumns, actionsFor($, false))
600  })
601
602  // Faixa acima do prompt: barras SVG no desktop, texto no terminal.
603  // Empilha sobre o que outros plugins desenham na faixa, em vez de substituir.
604  on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
605    const below = await next(e)
606    if (e.props.hasSurvey) return below
607    const snap = await read($, snapshot)
608    if (snap === null || snap.windows.length === 0) return below
609    const data = await viewData($, snap)
610    if (e.surface === 'terminal') {
611      const ui = $.ui.resolve(e)
612      return (
613        <ui.Box flexDirection="column">
614          {TerminalBand(ui, data, actionsFor($, true))}
615          {below}
616        </ui.Box>
617      )
618    }
619    if (e.surface !== 'desktop') return below
620    const ui = $.ui.resolve(e)
621
622    return (
623      <ui.Box flexDirection="column">
624        {RichBand(ui, data, actionsFor($, true))}
625        {below}
626      </ui.Box>
627    )
628  })
629}
630
hooks/api.ts 105 lines
1import type { ApiSpend } from '../types'
2import { DAY } from './projection'
3
4/** O ciclo dos créditos: começa no dia `day` de cada mês, à meia-noite local. */
5export const cycleBounds = (now: number, day: number): { start: number; end: number } => {
6  const d = new Date(now)
7  const clamp = (year: number, month: number) => Math.min(Math.max(1, Math.round(day)), new Date(year, month + 1, 0).getDate())
8  let start = new Date(d.getFullYear(), d.getMonth(), clamp(d.getFullYear(), d.getMonth()))
9  if (start.getTime() > now) {
10    const prev = new Date(d.getFullYear(), d.getMonth() - 1, 1)
11    start = new Date(prev.getFullYear(), prev.getMonth(), clamp(prev.getFullYear(), prev.getMonth()))
12  }
13  const after = new Date(start.getFullYear(), start.getMonth() + 1, 1)
14  const end = new Date(after.getFullYear(), after.getMonth(), clamp(after.getFullYear(), after.getMonth()))
15
16  return { start: start.getTime(), end: end.getTime() }
17}
18
19type CostReport = {
20  data?: { starting_at?: string; results?: { amount?: string; model?: string | null; description?: string | null }[] }[]
21  has_more?: boolean
22  next_page?: string | null
23}
24
25/** Soma uma página do relatório de custo: total e por modelo, em US$. */
26export const sumCostReport = (json: string): { usd: number; byModel: Record<string, number>; next?: string } => {
27  const report = JSON.parse(json) as CostReport
28  let cents = 0
29  const byModel: Record<string, number> = {}
30  for (const bucket of report.data ?? []) {
31    for (const item of bucket.results ?? []) {
32      const amount = Number(item.amount ?? 0)
33      if (!Number.isFinite(amount)) continue
34      cents += amount
35      const model = item.model ?? (item.description?.split(' Usage')[0] || 'outros')
36      byModel[model] = (byModel[model] ?? 0) + amount / 100
37    }
38  }
39
40  return { usd: cents / 100, byModel, next: report.has_more && report.next_page ? report.next_page : undefined }
41}
42
43export const costReportUrl = (start: number, now: number, page?: string) => {
44  // Os baldes são diários em UTC: pede do dia do início até o fim de hoje.
45  const from = new Date(start)
46  from.setUTCHours(0, 0, 0, 0)
47  const to = new Date(now + DAY)
48  to.setUTCHours(0, 0, 0, 0)
49  const params = [
50    `starting_at=${encodeURIComponent(from.toISOString())}`,
51    `ending_at=${encodeURIComponent(to.toISOString())}`,
52    'group_by[]=description',
53    'limit=31',
54  ]
55  if (page) params.push(`page=${encodeURIComponent(page)}`)
56
57  return `https://api.anthropic.com/v1/organizations/cost_report?${params.join('&')}`
58}
59
60/** Quanto do crédito foi gasto, o ritmo por dia e quando acaba nesse ritmo. */
61export const projectApi = (
62  spentUsd: number,
63  byModel: Record<string, number>,
64  bounds: { start: number; end: number },
65  now: number,
66  creditUsd: number,
67): ApiSpend => {
68  const elapsedDays = Math.max(1, (now - bounds.start) / DAY)
69  const dailyUsd = spentUsd / elapsedDays
70  const daysLeft = Math.max(0, (bounds.end - now) / DAY)
71  const projectedUsd = spentUsd + dailyUsd * daysLeft
72  const spend: ApiSpend = {
73    cycleStart: bounds.start,
74    cycleEnd: bounds.end,
75    spentUsd,
76    creditUsd,
77    byModel: Object.entries(byModel)
78      .map(([model, usd]) => ({ model, usd }))
79      .filter(m => m.usd > 0)
80      .sort((a, b) => b.usd - a.usd),
81    dailyUsd,
82    projectedUsd,
83    fetchedAt: now,
84  }
85  if (dailyUsd > 0 && projectedUsd > creditUsd) {
86    spend.runsOutAt = now + ((creditUsd - spentUsd) / dailyUsd) * DAY
87  }
88
89  return spend
90}
91
92/** O motivo de a chave não funcionar, em palavras. */
93export const apiProblem = (status: number, text: string) => {
94  if (status === 401 || status === 403) {
95    return (
96      'A chave não tem acesso ao relatório de custo. Ela precisa ser uma Admin API key (sk-ant-admin…) da ' +
97      'organização ligada aos créditos; contas individuais do Console não têm Admin API (crie uma organização ' +
98      'em Console > Settings > Organization).'
99    )
100  }
101  if (status === 429) return 'O Console pediu para esperar; tento de novo em alguns minutos.'
102
103  return `O Console respondeu ${status}: ${text.slice(0, 160)}`
104}
105
hooks/sessions.ts 49 lines
1import type { SessionRecord, SessionsView, Totals } from '../types'
2import { DAY, MINUTE, totalTokens } from './projection'
3
4/** Uma sessão sem sinal há mais de 3 min é tratada como fechada. */
5export const RUNNING_WINDOW = 3 * MINUTE
6
7export type SessionBook = Record<string, SessionRecord>
8
9const emptyTotals = (): Totals => ({ input: 0, output: 0, cacheRead: 0, cacheWrite: 0, turns: 0 })
10
11/** Grava o registro desta sessão no livro da máquina e descarta os de mais de 2 dias. */
12export const upsertSession = (book: SessionBook | undefined, record: SessionRecord, now: number): SessionBook => {
13  const next: SessionBook = {}
14  for (const [id, r] of Object.entries(book ?? {})) if (now - r.updatedAt < 2 * DAY) next[id] = r
15  next[record.id] = record
16
17  return next
18}
19
20const sameDay = (a: number, b: number) => new Date(a).toDateString() === new Date(b).toDateString()
21
22export const isRunning = (r: SessionRecord, now: number) => !r.ended && now - r.updatedAt < RUNNING_WINDOW
23
24/** As sessões abertas agora (esta primeiro, depois as que mais gastaram) e o total de hoje. */
25export const sessionsView = (book: SessionBook | undefined, now: number, selfId: string): SessionsView => {
26  const all = Object.values(book ?? {})
27  const running = all
28    .filter(r => r.id === selfId || isRunning(r, now))
29    .sort((a, b) => (a.id === selfId ? -1 : b.id === selfId ? 1 : b.costUsd - a.costUsd))
30  const today = all.filter(r => sameDay(r.updatedAt, now))
31  const sum = (list: SessionRecord[]) => {
32    const tokens = emptyTotals()
33    let costUsd = 0
34    for (const r of list) {
35      tokens.input += r.tokens.input
36      tokens.output += r.tokens.output
37      tokens.cacheRead += r.tokens.cacheRead
38      tokens.cacheWrite += r.tokens.cacheWrite
39      tokens.turns += r.tokens.turns
40      costUsd += r.costUsd
41    }
42    return { tokens, costUsd, count: list.length }
43  }
44
45  return { running, total: sum(running), today: sum(today) }
46}
47
48export const sessionTokens = (r: SessionRecord) => totalTokens(r.tokens)
49
hooks/advisor.ts 169 lines
1import type { Advice, Mix, Scenario, ScenarioId, Setup, Tokens, WindowView } from '../types'
2import { HAIKU, SONNET, costOf, family, modelKey, modelLabel } from './pricing'
3import { HOUR, hours, percent } from './projection'
4
5export const emptyMix = (resetsAt: number): Mix => ({ resetsAt, main: {}, sub: {} })
6
7/** Junta os tokens de uma resposta ao modelo e ao papel que a fizeram. */
8export const addToMix = (mix: Mix, role: 'main' | 'sub', model: string, t: Tokens): Mix => {
9  const key = modelKey(model)
10  const held = mix[role][key] ?? { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 }
11
12  return {
13    ...mix,
14    [role]: {
15      ...mix[role],
16      [key]: {
17        input: held.input + t.input,
18        output: held.output + t.output,
19        cacheRead: held.cacheRead + t.cacheRead,
20        cacheWrite: held.cacheWrite + t.cacheWrite,
21      },
22    },
23  }
24}
25
26const costAt = (byModel: Record<string, Tokens>, as?: string) =>
27  Object.entries(byModel).reduce((sum, [key, t]) => sum + costOf(t, as ?? key), 0)
28
29const windowName = (kind: string) =>
30  kind === 'five_hour' ? 'de 5h' : kind.startsWith('seven_day') ? 'semanal' : kind
31
32/** Do menos ao mais disruptivo para a qualidade do trabalho. */
33const ORDER: ScenarioId[] = ['sub-haiku', 'all-sonnet', 'main-sonnet-sub-haiku', 'all-haiku']
34
35/** Abaixo disso o limite chega ao reset com folga. */
36const COMFORT = 85
37
38/**
39 * Recomenda a troca de modelo menos disruptiva que faz o limite mais apertado
40 * durar até o reset, estimando o gasto de cada cenário pelo preço de API.
41 */
42export const advise = (
43  windows: WindowView[],
44  mixes: Record<string, Mix | undefined>,
45  setup: Setup,
46  recent?: Mix,
47): Advice | undefined => {
48  const open = windows.filter(
49    w => w.ratePerHour !== undefined && w.msToReset !== undefined && w.verdict !== 'exhausted',
50  )
51  const binding = open.reduce<WindowView | undefined>(
52    (worst, w) => (worst === undefined || (w.pctAtReset ?? 0) > (worst.pctAtReset ?? 0) ? w : worst),
53    undefined,
54  )
55  if (binding === undefined) return undefined
56
57  const mainKey = setup.mainModel ? modelKey(setup.mainModel) : undefined
58  const mainName = mainKey ? modelLabel(mainKey) : 'o modelo atual'
59  const name = windowName(binding.kind)
60  // O gasto das últimas horas mostra o que você está usando agora; a janela toda só na falta dele.
61  const mix = recent ?? mixes[binding.kind]
62  const mainCost = mix ? costAt(mix.main) : 0
63  const subCost = mix ? costAt(mix.sub) : 0
64  const total = mainCost + subCost
65  const subModels = mix ? Object.keys(mix.sub).filter(k => costOf(mix.sub[k]!, k) > 0) : []
66  const advice: Advice = {
67    windowKind: binding.kind,
68    windowLabel: binding.label,
69    mainModel: mainKey,
70    mainEffort: setup.mainEffort,
71    subShare: total > 0 ? subCost / total : 0,
72    subModels,
73    scenarios: [],
74    isFine: binding.verdict === 'ok',
75    mixBasis: recent ? 'recent' : 'window',
76    headline: '',
77  }
78  if (setup.mainEffort === 'xhigh' || setup.mainEffort === 'max') {
79    advice.tip = `Baixar o effort de ${setup.mainEffort} para high (/effort high) também reduz o gasto do fio principal.`
80  }
81
82  if (total > 0 && mix) {
83    const costs: Record<ScenarioId, number> = {
84      'sub-haiku': mainCost + costAt(mix.sub, HAIKU),
85      'all-sonnet': costAt(mix.main, SONNET) + costAt(mix.sub, SONNET),
86      'main-sonnet-sub-haiku': costAt(mix.main, SONNET) + costAt(mix.sub, HAIKU),
87      'all-haiku': costAt(mix.main, HAIKU) + costAt(mix.sub, HAIKU),
88    }
89    const labels: Record<ScenarioId, string> = {
90      'sub-haiku': `${mainName} orquestra, Haiku executa`,
91      'all-sonnet': 'Sonnet 5.5 em tudo',
92      'main-sonnet-sub-haiku': 'Sonnet orquestra, Haiku executa',
93      'all-haiku': 'Haiku 5.5 em tudo',
94    }
95    const rate = binding.ratePerHour ?? 0
96    for (const id of ORDER) {
97      const factor = costs[id] / total
98      const seen = advice.scenarios.some(s => Math.abs(s.factor - factor) < 0.02)
99      if (factor > 0.97 || seen) continue
100      const scenarioRate = rate * factor
101      const pctAtReset = binding.pct + scenarioRate * (binding.hoursAhead ?? (binding.msToReset ?? 0) / HOUR)
102      advice.scenarios.push({
103        id,
104        label: labels[id],
105        factor,
106        hoursLeft: scenarioRate > 0 ? (100 - binding.pct) / scenarioRate : undefined,
107        pctAtReset,
108        lasts: pctAtReset < 100,
109      })
110    }
111  }
112
113  const unit = ''
114
115  if (advice.isFine) {
116    advice.headline =
117      `✓ Mantendo o uso atual, seu plano dura até o reset ` +
118      `(~${percent(binding.pctAtReset ?? binding.pct)} do limite ${name} no fim).`
119
120    return advice
121  }
122
123  const pick =
124    advice.scenarios.find(s => s.pctAtReset < COMFORT) ?? advice.scenarios.find(s => s.lasts)
125  const current =
126    `Você está usando ${mainName}` +
127    (setup.mainEffort ? ` (effort ${setup.mainEffort})` : '') +
128    (advice.subShare >= 0.1
129      ? ` e ${percent(advice.subShare * 100)} do gasto vem de subagentes em ${subModels.map(modelLabel).join(', ')}`
130      : '')
131
132  if (pick === undefined) {
133    const best = advice.scenarios.reduce<Scenario | undefined>(
134      (low, s) => (low === undefined || s.factor < low.factor ? s : low),
135      undefined,
136    )
137    advice.headline =
138      best === undefined
139        ? `⚠ No ritmo atual o limite ${name} acaba antes do reset. Use ${mainName} só para orquestrar e ` +
140          'deixe a execução para subagentes em Haiku.'
141        : `⚠ ${current}. Nem com ${best.label} o limite ${name} chega ao reset; ` +
142          `assim ele dura ~${hours(best.hoursLeft ?? 0)}${unit} em vez de ~${hours(binding.hoursLeft ?? 0)}${unit}.`
143
144    return advice
145  }
146
147  advice.pick = pick.id
148  const action: Record<ScenarioId, string> = {
149    'sub-haiku': `use ${mainName} para orquestrar e Haiku para executar`,
150    'all-sonnet': 'troque para Sonnet 5.5 (/model sonnet)',
151    'main-sonnet-sub-haiku': 'use Sonnet 5.5 para orquestrar (/model sonnet) e Haiku para executar',
152    'all-haiku': 'use Haiku 5.5 em tudo (/model haiku)',
153  }
154  advice.headline =
155    `💡 ${current}. Para não ficar sem uso, ${action[pick.id]}: ` +
156    `o limite ${name} passa a durar ~${hours(pick.hoursLeft ?? 0)}${unit} e seu plano dura até o reset ` +
157    `(~${percent(pick.pctAtReset)} no fim).`
158
159  return advice
160}
161
162/** Se um cenário põe os subagentes em Haiku (o que o modo economia faz). */
163export const usesSubHaiku = (id: ScenarioId | undefined) =>
164  id === 'sub-haiku' || id === 'main-sonnet-sub-haiku' || id === 'all-haiku'
165
166/** Se um cenário pede outro modelo no fio principal. */
167export const changesMain = (id: ScenarioId | undefined, mainModel?: string) =>
168  (id === 'all-sonnet' || id === 'main-sonnet-sub-haiku') && family(mainModel ?? '') !== 'sonnet'
169
hooks/pace.ts 136 lines
1import type { Mix, Tokens } from '../types'
2import { HOUR, sameWindow } from './projection'
3import type { RawWindow } from './projection'
4
5/**
6 * Quantos pontos do semanal custa cada ponto do limite de 5h, medido nas
7 * mesmas respostas. O de 5h anda rápido; com essa razão, o ritmo semanal
8 * passa a refletir a última hora de trabalho, não o dia inteiro.
9 */
10export type Calibration = {
11  /** Versão da regra de medição; uma calibração de outra versão começa do zero. */
12  v?: number
13  weekResetsAt: number
14  sum5: number
15  sumWeek: number
16  last?: { p5: number; reset5: number; pWeek: number }
17}
18
19const resetOf = (w: RawWindow) => (w.resetsAt ? Date.parse(w.resetsAt) : NaN)
20
21export const updateCalibration = (
22  held: Calibration | undefined,
23  five: RawWindow,
24  week: RawWindow,
25): Calibration | undefined => {
26  const weekReset = resetOf(week)
27  const reset5 = resetOf(five)
28  if (Number.isNaN(weekReset) || Number.isNaN(reset5)) return held
29  const c: Calibration =
30    held && held.v === CALIBRATION_VERSION && sameWindow(held.weekResetsAt, weekReset)
31      ? { ...held }
32      : { v: CALIBRATION_VERSION, weekResetsAt: weekReset, sum5: 0, sumWeek: 0 }
33  // Só mede dentro da mesma janela de 5h. Entre janelas o mod não vê o fim da
34  // anterior, e o salto do semanal pareceria vir de quase nada do 5h.
35  if (c.last && sameWindow(c.last.reset5, reset5)) {
36    const d5 = five.percentUsed - c.last.p5
37    const dWeek = week.percentUsed - c.last.pWeek
38    if (d5 >= 0 && dWeek >= 0) {
39      c.sum5 += d5
40      c.sumWeek += dWeek
41    }
42  }
43  c.last = { p5: five.percentUsed, reset5, pWeek: week.percentUsed }
44
45  return c
46}
47
48export const CALIBRATION_VERSION = 2
49
50/**
51 * Pontos do semanal por ponto do 5h; só com movimento suficiente para medir e
52 * dentro de uma faixa plausível (um ponto do 5h nunca vale mais que 1,5 do semanal).
53 */
54export const weekPerFive = (c: Calibration | undefined) => {
55  if (!c || c.v !== CALIBRATION_VERSION || c.sum5 < 6 || c.sumWeek <= 0) return undefined
56  const ratio = c.sumWeek / c.sum5
57
58  return ratio >= 0.05 && ratio <= 1.5 ? ratio : undefined
59}
60
61// ---------- horas de trabalho por dia ----------
62
63/** As horas (índice `floor(t / 1h)`) em que houve resposta, dos últimos 14 dias. */
64export const addActivity = (hours: number[] | undefined, now: number): number[] => {
65  const h = Math.floor(now / HOUR)
66  const list = hours ?? []
67  if (list.includes(h)) return list
68
69  return [...list, h].filter(x => x > h - 14 * 24).sort((a, b) => a - b)
70}
71
72/**
73 * Horas de trabalho por dia. Com menos de 2 dias de histórico, supõe pelo menos
74 * 8h por dia, para não tratar a primeira manhã como o ritmo da semana inteira.
75 */
76export const activeHoursPerDay = (hours: number[] | undefined, now: number): number => {
77  const list = hours ?? []
78  const nowH = Math.floor(now / HOUR)
79  const first = list[0]
80  // Dias de calendário cobertos pelo histórico, contando o primeiro dia inteiro.
81  const days = first === undefined ? 0 : Math.ceil((nowH - first + 1) / 24)
82  if (days < 2) return Math.max(8, list.filter(h => h > nowH - 24).length)
83  const span = Math.min(7, days)
84  const inSpan = list.filter(h => h > nowH - span * 24).length
85
86  return Math.min(24, Math.max(1, inSpan / span))
87}
88
89// ---------- gasto recente por modelo ----------
90
91export type HourlyMix = Record<string, { main: Record<string, Tokens>; sub: Record<string, Tokens> }>
92
93const addTokens = (a: Tokens | undefined, b: Tokens): Tokens => ({
94  input: (a?.input ?? 0) + b.input,
95  output: (a?.output ?? 0) + b.output,
96  cacheRead: (a?.cacheRead ?? 0) + b.cacheRead,
97  cacheWrite: (a?.cacheWrite ?? 0) + b.cacheWrite,
98})
99
100/** Soma uma resposta ao balde da hora atual; guarda as últimas 72 horas. */
101export const addHourly = (
102  held: HourlyMix | undefined,
103  now: number,
104  role: 'main' | 'sub',
105  modelKey: string,
106  t: Tokens,
107): HourlyMix => {
108  const h = Math.floor(now / HOUR)
109  const next: HourlyMix = {}
110  for (const [k, v] of Object.entries(held ?? {})) if (Number(k) > h - 72) next[k] = v
111  const bucket = next[h] ?? { main: {}, sub: {} }
112  next[h] = { ...bucket, [role]: { ...bucket[role], [modelKey]: addTokens(bucket[role][modelKey], t) } }
113
114  return next
115}
116
117/** O gasto das últimas `count` horas com resposta, dentro das últimas 12h. */
118export const recentMix = (held: HourlyMix | undefined, now: number, resetsAt: number, count = 3): Mix | undefined => {
119  const h = Math.floor(now / HOUR)
120  const hours = Object.keys(held ?? {})
121    .map(Number)
122    .filter(k => k > h - 12)
123    .sort((a, b) => b - a)
124    .slice(0, count)
125  if (hours.length === 0) return undefined
126  const mix: Mix = { resetsAt, main: {}, sub: {} }
127  for (const k of hours) {
128    const bucket = held![k]!
129    for (const role of ['main', 'sub'] as const) {
130      for (const [model, t] of Object.entries(bucket[role])) mix[role][model] = addTokens(mix[role][model], t)
131    }
132  }
133
134  return mix
135}
136
hooks/pricing.ts 79 lines
1import type { Tokens } from '../types'
2
3/** US$ por milhão de tokens, preço de API (tabela de 2026-10). */
4type Price = { input: number; output: number; cacheWrite: number; cacheRead: number }
5
6const p = (input: number, output: number, cacheRead: number): Price => ({
7  input,
8  output,
9  cacheWrite: input * 1.25,
10  cacheRead,
11})
12
13const PRICES: Record<string, Price> = {
14  'fable-5-1': p(10, 50, 0.25),
15  'fable-5': p(10, 50, 1),
16  'mythos-5-1': p(10, 50, 0.25),
17  'opus-5-5': p(4, 20, 0.2),
18  'opus-5': p(5, 25, 0.5),
19  'opus-4-8': p(5, 25, 0.5),
20  'opus-4-7': p(5, 25, 0.5),
21  'opus-4-6': p(5, 25, 0.5),
22  'opus-4-5': p(5, 25, 0.5),
23  'opus-4-1': p(15, 75, 1.5),
24  'opus-4': p(15, 75, 1.5),
25  'sonnet-5-5': p(2, 10, 0.2),
26  'sonnet-5': p(2, 10, 0.2),
27  'sonnet-4-6': p(3, 15, 0.3),
28  'sonnet-4-5': p(3, 15, 0.3),
29  'sonnet-4': p(3, 15, 0.3),
30  'haiku-5-5': p(0.1, 0.5, 0.01),
31  'haiku-4-5': p(1, 5, 0.1),
32}
33
34/** Modelo atual de cada família, para ids que a tabela não conhece. */
35const LATEST: Record<string, string> = {
36  fable: 'fable-5-1',
37  mythos: 'mythos-5-1',
38  opus: 'opus-5-5',
39  sonnet: 'sonnet-5-5',
40  haiku: 'haiku-5-5',
41}
42
43export const HAIKU = 'haiku-5-5'
44export const SONNET = 'sonnet-5-5'
45export const HAIKU_ID = 'claude-haiku-5-5'
46
47/** `claude-opus-5-5[1m]`, `claude-opus-4-5-20251101` → `opus-5-5`, `opus-4-5`. */
48export const modelKey = (id: string): string => {
49  const m = /(fable|mythos|opus|sonnet|haiku)-(\d{1,2})(?:-(\d{1,2})(?!\d))?/.exec(id.toLowerCase())
50  if (!m) return id
51  const key = m[3] ? `${m[1]}-${m[2]}-${m[3]}` : `${m[1]}-${m[2]}`
52
53  return PRICES[key] ? key : (LATEST[m[1] ?? ''] ?? key)
54}
55
56export const family = (key: string) => key.split('-')[0] ?? key
57
58/** `opus-5-5` → `Opus 5.5`. */
59export const modelLabel = (key: string): string => {
60  const [name = key, ...version] = key.split('-')
61
62  return `${name.charAt(0).toUpperCase()}${name.slice(1)} ${version.join('.')}`.trim()
63}
64
65const priceOf = (key: string): Price => PRICES[key] ?? PRICES[LATEST[family(key)] ?? ''] ?? p(4, 20, 0.2)
66
67/** Custo em US$ de um lote de tokens num modelo. */
68export const costOf = (t: Tokens, key: string): number => {
69  const price = priceOf(key)
70
71  return (
72    (t.input * price.input +
73      t.output * price.output +
74      t.cacheWrite * price.cacheWrite +
75      t.cacheRead * price.cacheRead) /
76    1e6
77  )
78}
79
hooks/projection.ts 300 lines
1import type { ProjectBucket, ProjectShare, Totals, Verdict, WindowView } from '../types'
2
3export const MINUTE = 60_000
4export const HOUR = 60 * MINUTE
5export const DAY = 24 * HOUR
6
7export type Sample = { t: number; pct: number }
8
9/** Amostras de uma janela, guardadas em $.store entre sessões. */
10export type SampleLog = { resetsAt: number; points: Sample[] }
11
12/** Tokens contados numa janela, guardados em $.store entre sessões. */
13export type TokenBucket = { resetsAt: number; tokens: number; firstPct: number }
14
15export type RawWindow = { kind: string; percentUsed: number; resetsAt?: string }
16
17export const emptyTotals = (): Totals => ({
18  input: 0,
19  output: 0,
20  cacheRead: 0,
21  cacheWrite: 0,
22  turns: 0,
23})
24
25export const totalTokens = (t: Totals) =>
26  t.input + t.output + t.cacheRead + t.cacheWrite
27
28export const windowLength = (kind: string): number | undefined =>
29  kind === 'five_hour' ? 5 * HOUR : kind.startsWith('seven_day') ? 7 * DAY : undefined
30
31/** Quanto tempo de histórico vale como "ritmo atual". */
32const recentLookback = (length: number) => (length <= 5 * HOUR ? HOUR : DAY)
33
34/**
35 * O menor período por onde dividir o uso. No semanal o ritmo é por dia: as
36 * primeiras horas de trabalho não valem para as noites e pausas da semana.
37 */
38const minPeriod = (length: number) => (length <= 5 * HOUR ? 5 * MINUTE : DAY)
39
40export const windowLabel = (kind: string): string => {
41  if (kind === 'five_hour') return '5 horas'
42  if (kind === 'seven_day') return 'Semanal'
43  if (kind.startsWith('seven_day_')) return `Semanal (${kind.slice('seven_day_'.length)})`
44  if (kind === 'spend_limit') return 'Gasto'
45  return kind
46}
47
48export const shortLabel = (kind: string): string => {
49  if (kind === 'five_hour') return '5h'
50  if (kind === 'seven_day') return 'Sem'
51  if (kind.startsWith('seven_day_')) return `Sem·${kind.slice('seven_day_'.length)}`
52  return kind
53}
54
55/** Dois resets a menos de 10 min um do outro são a mesma janela. */
56export const sameWindow = (a: number, b: number) => Math.abs(a - b) < 10 * MINUTE
57
58/** Junta uma leitura ao log, reiniciando-o quando a janela virou. */
59export const addSample = (
60  log: SampleLog | undefined,
61  resetsAt: number,
62  sample: Sample,
63): SampleLog => {
64  const points = log && sameWindow(log.resetsAt, resetsAt) ? log.points : []
65  const last = points[points.length - 1]
66  if (last && last.pct === sample.pct) return { resetsAt, points }
67
68  return { resetsAt, points: [...points, sample].slice(-500) }
69}
70
71/**
72 * %/h nos últimos `lookback` ms: do valor que valia no começo do período até o
73 * valor de agora. Parado, o ritmo cai para zero sozinho.
74 */
75export const recentRate = (
76  points: Sample[],
77  pctNow: number,
78  now: number,
79  lookback: number,
80  floor = 0,
81): number | undefined => {
82  const from = now - lookback
83  const before = [...points].reverse().find(p => p.t <= from)
84  const start = before ? { t: from, pct: before.pct } : points[0]
85  if (!start) return undefined
86  const span = now - start.t
87  if (span < Math.min(lookback / 4, 2 * HOUR)) return undefined
88
89  return Math.max(0, ((pctNow - start.pct) / Math.max(span, floor)) * HOUR)
90}
91
92/** O que a projeção do semanal precisa para medir o ritmo em horas de trabalho. */
93export type WorkPace = {
94  /** %/h do limite de 5h agora (o mais responsivo que temos). */
95  fiveRate?: number
96  /** Pontos do semanal por ponto do 5h. */
97  weekPerFive?: number
98  activeHoursPerDay: number
99}
100
101export const project = (
102  raw: RawWindow,
103  now: number,
104  log?: SampleLog,
105  bucket?: TokenBucket,
106  work?: WorkPace,
107): WindowView => {
108  const pct = raw.percentUsed
109  const resetsAt = raw.resetsAt ? Date.parse(raw.resetsAt) : undefined
110  const length = windowLength(raw.kind)
111  const view: WindowView = {
112    kind: raw.kind,
113    label: windowLabel(raw.kind),
114    pct,
115    rateSource: 'none',
116    verdict: 'unknown',
117  }
118
119  if (resetsAt === undefined || Number.isNaN(resetsAt)) return view
120  view.resetsAt = resetsAt
121  view.msToReset = Math.max(0, resetsAt - now)
122
123  // A leitura é de antes do reset: a janela já renovou e o uso voltou a zero.
124  if (resetsAt <= now) {
125    view.isRenewed = true
126    view.pct = 0
127    return view
128  }
129
130  if (bucket && sameWindow(bucket.resetsAt, resetsAt)) {
131    view.windowTokens = bucket.tokens
132    const moved = pct - bucket.firstPct
133    if (moved >= 1 && bucket.tokens > 0) view.tokensPerPct = bucket.tokens / moved
134  }
135
136  if (pct >= 100) {
137    view.verdict = 'exhausted'
138    return view
139  }
140  if (length === undefined) return view
141
142  const elapsed = Math.max(minPeriod(length), now - (resetsAt - length))
143  view.windowRatePerHour = (pct / elapsed) * HOUR
144
145  const points = log && sameWindow(log.resetsAt, resetsAt) ? log.points : []
146  view.recentRatePerHour = recentRate(points, pct, now, recentLookback(length), minPeriod(length))
147
148  // Extra do semanal: horas de uso no ritmo da última hora, pelo limite de 5h.
149  // A projeção principal segue o número da conta (todas as máquinas, noite inclusive).
150  if (raw.kind === 'seven_day' && work?.weekPerFive !== undefined && work.fiveRate !== undefined && work.fiveRate > 0) {
151    view.workRatePerHour = work.weekPerFive * work.fiveRate
152    view.workHoursLeft = (100 - pct) / view.workRatePerHour
153    view.activeHoursPerDay = work.activeHoursPerDay
154  }
155
156  const rate = view.recentRatePerHour ?? view.windowRatePerHour
157  view.rateSource = view.recentRatePerHour !== undefined ? 'recent' : 'window'
158  view.ratePerHour = rate
159  view.hoursAhead = view.msToReset / HOUR
160  view.pctAtReset = pct + rate * view.hoursAhead
161
162  view.verdict = verdictOf(view.pctAtReset)
163  if (rate > 0) view.hoursLeft = (100 - pct) / rate
164  if (rate > 0 && view.pctAtReset >= 100) {
165    view.exhaustAt = now + ((100 - pct) / rate) * HOUR
166  }
167
168  return view
169}
170
171const verdictOf = (pctAtReset: number): Verdict =>
172  pctAtReset >= 100 ? 'exhausts' : pctAtReset >= 85 ? 'tight' : 'ok'
173
174/** Divide o que a janela andou entre os projetos, pela fração do gasto de cada um. */
175export const projectShares = (bucket: ProjectBucket | undefined, pct: number): ProjectShare[] => {
176  if (!bucket) return []
177  const total = Object.values(bucket.byProject).reduce((sum, n) => sum + n, 0)
178  if (total <= 0) return []
179  const moved = pct - bucket.firstPct
180
181  return Object.entries(bucket.byProject)
182    .map(([name, cost]) => ({
183      name,
184      share: cost / total,
185      points: moved >= 1 ? (cost / total) * moved : undefined,
186    }))
187    .sort((a, b) => b.share - a.share)
188}
189
190/** Nome curto do projeto a partir da raiz do git ou da pasta da sessão. */
191export const projectName = (dir: string): string => {
192  const clean = dir.replace(/[\\/]+$/, '').replace(/[\\/]\.claude[\\/]worktrees[\\/].*$/, '')
193  const parts = clean.split(/[\\/]/).filter(Boolean)
194  const last = parts[parts.length - 1] ?? dir
195  const generic = ['workdir', 'workspace', 'src', 'app', 'repo']
196
197  return generic.includes(last.toLowerCase()) && parts.length > 1 ? (parts[parts.length - 2] ?? last) : last
198}
199
200// ---------- formatação ----------
201
202const WEEKDAYS = ['dom', 'seg', 'ter', 'qua', 'qui', 'sex', 'sáb']
203const pad = (n: number) => String(n).padStart(2, '0')
204
205export const clockTime = (t: number, now: number): string => {
206  const d = new Date(t)
207  const hm = `${pad(d.getHours())}:${pad(d.getMinutes())}`
208  const sameDay = new Date(now).toDateString() === d.toDateString()
209
210  return sameDay ? hm : `${WEEKDAYS[d.getDay()]} ${hm}`
211}
212
213export const duration = (ms: number): string => {
214  const minutes = Math.max(0, Math.round(ms / MINUTE))
215  if (minutes < 60) return `${minutes}min`
216  const hours = Math.floor(minutes / 60)
217  if (hours < 24) return `${hours}h${pad(minutes % 60)}`
218  const days = Math.floor(hours / 24)
219
220  return `${days}d${hours % 24}h`
221}
222
223export const compact = (n: number): string => {
224  if (n >= 1e9) return `${(n / 1e9).toFixed(1)}B`
225  if (n >= 1e6) return `${(n / 1e6).toFixed(1)}M`
226  if (n >= 1e3) return `${(n / 1e3).toFixed(1)}k`
227
228  return String(Math.round(n))
229}
230
231export const percent = (n: number) => `${Math.round(n)}%`
232
233/** Horas em pt-BR: "2,3h" abaixo de 10, "52h" acima. */
234export const hours = (h: number): string =>
235  h < 10 ? `${h.toFixed(1).replace('.', ',')}h` : `${Math.round(h)}h`
236
237export const usd = (n: number) => `US$ ${n.toFixed(2).replace('.', ',')}`
238
239export const bar = (pct: number, width: number): string => {
240  const full = Math.round((Math.min(100, Math.max(0, pct)) / 100) * width)
241
242  return '█'.repeat(full) + '░'.repeat(width - full)
243}
244
245/** "~38h de uso" no semanal medido por trabalho, "~2,3h" no resto. */
246export const durationLabel = (w: WindowView) =>
247  w.hoursLeft === undefined ? '' : `~${hours(w.hoursLeft)}${w.rateSource === 'work' ? ' de uso' : ''}`
248
249/** Há quanto tempo foi a leitura, quando passa de 10 min. */
250export const readingAge = (readAt: number | undefined, now: number) => {
251  if (readAt === undefined || now - readAt < 10 * MINUTE) return undefined
252  const minutes = Math.round((now - readAt) / MINUTE)
253
254  return minutes < 60 ? `há ${minutes}min` : `há ${hours(minutes / 60)}`
255}
256
257/**
258 * O trecho de uma janela na linha de status: curto, porque o terminal corta a
259 * linha; o reset e os detalhes ficam na faixa e no painel.
260 */
261export const statusPart = (w: WindowView): string => {
262  const head = `${shortLabel(w.kind)} ${percent(w.pct)}`
263  if (w.isRenewed) return `${head} renovado`
264  if (w.verdict === 'exhausted') {
265    return `${head} ⛔ volta em ${hours((w.msToReset ?? 0) / HOUR)}`
266  }
267  if (w.ratePerHour === undefined) return head
268  if (w.hoursLeft === undefined) return `${head} parado ✓`
269  const mark = w.verdict === 'exhausts' ? '⚠' : w.verdict === 'tight' ? '△' : '✓'
270  if (w.hoursLeft >= (w.msToReset ?? 0) / HOUR) return `${head} até renovar ${mark}`
271
272  return `${head} dura ${durationLabel(w)} ${mark}`
273}
274
275export const statusLine = (
276  windows: WindowView[],
277  session: Totals,
278  costUsd: number | undefined,
279  age?: string,
280  extra?: { sessions?: { count: number; tokens: number; costUsd: number }; api?: string },
281) => {
282  const parts = windows.map(statusPart)
283  if (age) parts.push(`leitura ${age}`)
284  const all = extra?.sessions
285  if (all && all.count > 1) {
286    parts.push(`${all.count} sessões · ${all.tokens > 0 ? `${compact(all.tokens)} tok · ` : ''}${usd(all.costUsd)}`)
287  } else {
288    const usage = totalTokens(session) > 0 ? [`${compact(totalTokens(session))} tok`] : []
289    if (costUsd !== undefined) usage.push(usd(costUsd))
290    if (usage.length > 0) parts.push(usage.join(' · '))
291  }
292  if (extra?.api) parts.push(extra.api)
293
294  return parts.join(' │ ')
295}
296
297/** "API US$ 37/200" para a linha de status. */
298export const apiShort = (spentUsd: number, creditUsd: number) =>
299  `API US$ ${Math.round(spentUsd)}/${Math.round(creditUsd)}`
300
hooks/view.tsx 896 lines
1import type { Elements } from 'claude-code'
2
3import type { Advice, ApiSpend, ProjectShare, SessionRecord, Snapshot, Totals, WindowView } from '../types'
4import { changesMain, usesSubHaiku } from './advisor'
5import { modelKey, modelLabel } from './pricing'
6import {
7  HOUR,
8  bar,
9  clockTime,
10  compact,
11  durationLabel,
12  readingAge,
13  duration,
14  hours,
15  percent,
16  shortLabel,
17  totalTokens,
18  usd,
19} from './projection'
20import { HEX, TOKEN_HEX, limitBarSvg, limitRingSvg, shareSvg, tokenMixSvg } from './svg'
21
22type TerminalUi = Elements['terminal']
23/** O que desktop, VS Code e mobile têm em comum: caixas, texto, SVG e botões. */
24type RichUi = Pick<Elements['desktop'], 'Box' | 'Text' | 'Svg' | 'Button'>
25
26/** Caixas, texto e botões: o que todas as superfícies desenham. */
27type BasicUi = Pick<TerminalUi, 'Box' | 'Text' | 'Button'>
28
29export type ViewData = { snap: Snapshot; totals: Totals; economy: boolean; api: ApiSpend | null; collapsed?: boolean }
30
31/** O que os botões fazem; `details` só existe fora do painel. */
32export type Actions = {
33  details?: () => void
34  /** ↻ Atualizar: relê a leitura mais nova e recalcula tudo. */
35  reload?: () => void
36  toggleEconomy: () => void
37  /** Minimiza ou expande a faixa acima do prompt. */
38  toggleBand?: () => void
39  fillModel: (alias: string) => void
40}
41
42// ---------- textos comuns ----------
43
44const rateText = (rate: number | undefined) =>
45  rate === undefined ? '—' : `${rate.toFixed(rate < 10 ? 1 : 0).replace('.', ',')}%/h`
46
47export const colorOf = (w: WindowView) =>
48  w.verdict === 'exhausted' || w.verdict === 'exhausts'
49    ? 'error'
50    : w.verdict === 'tight'
51      ? 'warning'
52      : w.verdict === 'ok'
53        ? 'success'
54        : 'subtle'
55
56const verdictText = (w: WindowView, now: number): string => {
57  if (w.isRenewed) return '↺ Renovou: o uso novo aparece na próxima resposta do Claude'
58  switch (w.verdict) {
59    case 'exhausted':
60      return `⛔ Esgotado: renova ${w.resetsAt ? clockTime(w.resetsAt, now) : '?'}`
61    case 'exhausts':
62      return w.exhaustAt !== undefined && w.resetsAt !== undefined
63        ? `⚠ No ritmo atual acaba ~${clockTime(w.exhaustAt, now)}, ` +
64            `${duration(w.resetsAt - w.exhaustAt)} antes de renovar`
65        : '⚠ No ritmo atual acaba antes de renovar'
66    case 'tight':
67      return `△ Apertado: chega a ~${percent(w.pctAtReset ?? w.pct)} quando renovar`
68    case 'ok':
69      return `✓ Dura até renovar (~${percent(w.pctAtReset ?? w.pct)} no fim)`
70    default:
71      return 'Sem projeção para esta janela'
72  }
73}
74
75const durationText = (w: WindowView) =>
76  w.verdict === 'exhausted'
77    ? 'esgotado'
78    : w.ratePerHour === undefined
79      ? '—'
80      : w.hoursLeft === undefined
81        ? 'sem consumo'
82        : durationLabel(w)
83
84/** Só no semanal: horas de uso no ritmo da última hora de trabalho (pelo limite de 5h). */
85const workDaysText = (w: WindowView) =>
86  w.workHoursLeft !== undefined
87    ? `~${hours(w.workHoursLeft)} de uso no ritmo da última hora` +
88      (w.activeHoursPerDay ? ` (≈ ${(w.workHoursLeft / w.activeHoursPerDay).toFixed(1).replace('.', ',')} dias de ~${Math.round(w.activeHoursPerDay)}h)` : '')
89    : undefined
90
91/** No semanal: quantos pontos por dia a conta está gastando. */
92const perDayText = (w: WindowView) =>
93  w.ratePerHour === undefined ? '—' : `${Math.round(w.ratePerHour * 24)} pts/dia`
94
95const isWeekly = (w: WindowView) => w.kind.startsWith('seven_day')
96
97/** "atualizado 09:12" e, se a leitura for velha, de quando ela é e de onde veio. */
98const freshness = (snap: Snapshot) => {
99  const age = readingAge(snap.readAt, snap.updatedAt)
100  const base = `atualizado ${clockTime(snap.updatedAt, snap.updatedAt)}`
101  if (age) return `${base} · leitura ${age}${snap.isSharedReading ? ' (outra sessão)' : ''}: atualiza na próxima resposta`
102  return snap.isSharedReading ? `${base} · leitura de outra sessão` : base
103}
104
105const resetText = (w: WindowView, now: number) =>
106  w.resetsAt === undefined
107    ? '—'
108    : `${hours((w.msToReset ?? 0) / HOUR)} · ${clockTime(w.resetsAt, now)}`
109
110const tokensLine = (w: WindowView) =>
111  w.windowTokens === undefined
112    ? undefined
113    : `${compact(w.windowTokens)} tokens contados nesta janela` +
114      (w.tokensPerPct !== undefined
115        ? ` · ≈${compact(w.tokensPerPct)} por 1% · ≈${compact(w.tokensPerPct * Math.max(0, 100 - w.pct))} restantes`
116        : '')
117
118const projectLine = (p: ProjectShare) =>
119  `${p.name.padEnd(18)} ${bar(p.share * 100, 10)} ${percent(p.share * 100)} do gasto` +
120  (p.points !== undefined ? ` · ≈${p.points.toFixed(1).replace('.', ',')} pts` : '')
121
122/** Quanto cada projeto gastou na janela (até 5). */
123const ProjectList = (ui: BasicUi, w: WindowView, indent: string) => {
124  const { Box, Text } = ui
125  const list = w.projects ?? []
126  if (list.length === 0) return undefined
127
128  return (
129    <Box key="projects" flexDirection="column">
130      <Text dimColor>{indent}Por projeto (esta máquina):</Text>
131      {list.slice(0, 5).map(p => (
132        <Text key={p.name}>
133          {indent}
134          {'  '}
135          {projectLine(p)}
136        </Text>
137      ))}
138    </Box>
139  )
140}
141
142const EMPTY =
143  'Sem dados de limite ainda: eles chegam com a primeira resposta da API e só existem em planos de assinatura (Pro/Max).'
144
145// ---------- sessões e créditos de API ----------
146
147const sessionRow = (r: SessionRecord, totalCost: number, isSelf: boolean) => {
148  const model = r.model ? modelLabel(modelKey(r.model)) : '—'
149  const share = totalCost > 0 ? ` · ${percent((r.costUsd / totalCost) * 100)}` : ''
150
151  return `${isSelf ? '●' : '○'} ${r.project.padEnd(16).slice(0, 16)} ${model.padEnd(11)} ${compact(totalTokens(r.tokens)).padStart(6)} tok  ${usd(r.costUsd)}${share}${isSelf ? '  (esta)' : ''}`
152}
153
154/** As sessões abertas nesta máquina, o total delas e o total de hoje. */
155const SessionsList = (ui: BasicUi, snap: Snapshot) => {
156  const { Box, Text } = ui
157  const view = snap.sessions
158  if (!view) return <Text dimColor>Lista de sessões indisponível nesta máquina.</Text>
159
160  return (
161    <Box key="sessions-list" flexDirection="column">
162      {view.running.map(r => (
163        <Text key={r.id} bold={r.id === snap.selfId}>
164          {sessionRow(r, view.total.costUsd, r.id === snap.selfId)}
165        </Text>
166      ))}
167      <Text bold>
168        Total ({view.total.count} {view.total.count === 1 ? 'sessão aberta' : 'sessões abertas'}): {compact(totalTokens(view.total.tokens))} tok ·{' '}
169        {usd(view.total.costUsd)}
170      </Text>
171      <Text dimColor>
172        Hoje nesta máquina, fechadas inclusive: {view.today.count} sessões · {compact(totalTokens(view.today.tokens))} tok ·{' '}
173        {usd(view.today.costUsd)}
174      </Text>
175      <Text dimColor>Custo equivalente em preço de API; no plano, o que conta são os limites de 5h e semanal.</Text>
176    </Box>
177  )
178}
179
180const dayMonth = (t: number) => {
181  const d = new Date(t)
182  return `${String(d.getDate()).padStart(2, '0')}/${String(d.getMonth() + 1).padStart(2, '0')}`
183}
184
185/** Os créditos de API do Console: gasto, ritmo e quando acabam. */
186const ApiCard = (ui: BasicUi, spend: ApiSpend | null, now: number) => {
187  const { Box, Text } = ui
188  if (!spend) return undefined
189  const pct = spend.creditUsd > 0 ? (spend.spentUsd / spend.creditUsd) * 100 : 0
190  const color = spend.runsOutAt !== undefined ? 'error' : spend.projectedUsd > spend.creditUsd * 0.85 ? 'warning' : 'success'
191
192  return (
193    <Box key="api" flexDirection="column" borderStyle="round" borderColor={spend.problem ? 'warning' : color} paddingX={1}>
194      <Text bold>Créditos de API (Console)</Text>
195      {spend.problem && <Text color="warning">{spend.problem}</Text>}
196      <Text>
197        <Text color={color}>{bar(pct, 20)}</Text> {usd(spend.spentUsd)} de {usd(spend.creditUsd)} · {percent(pct)}
198      </Text>
199      <Text dimColor>
200        Ciclo {dayMonth(spend.cycleStart)} a {dayMonth(spend.cycleEnd)} · {usd(spend.dailyUsd)}/dia · renova em{' '}
201        {Math.max(0, Math.ceil((spend.cycleEnd - now) / 86_400_000))} dias
202      </Text>
203      <Text color={color}>
204        {spend.runsOutAt !== undefined
205          ? `⚠ Nesse ritmo o crédito acaba ~${dayMonth(spend.runsOutAt)}, antes de renovar; depois as chamadas param (ou usam crédito comprado).`
206          : `✓ Nesse ritmo o ciclo fecha com ~${usd(spend.projectedUsd)} gastos.`}
207      </Text>
208      {spend.byModel.slice(0, 5).map(m => (
209        <Text key={m.model} dimColor>
210          {'  '}
211          {m.model}: {usd(m.usd)}
212        </Text>
213      ))}
214      <Text dimColor>Não conta nos limites de 5h e semanal do plano. Atualiza a cada 10 min (o Console leva ~5 min).</Text>
215    </Box>
216  )
217}
218
219/** "3 sessões · 4.2M tokens · US$ 12,40" ou, sozinha, os números desta. */
220const usageSummary = (snap: Snapshot, totals: Totals, api: ApiSpend | null) => {
221  const all = snap.sessions?.total
222  // Sessões gravadas por versões antigas do mod têm custo mas 0 tokens: sem tokens, só o custo.
223  const tokens = (n: number) => (n > 0 ? [`${compact(n)} tokens`] : [])
224  const head = (
225    all && all.count > 1
226      ? [`${all.count} sessões`, ...tokens(totalTokens(all.tokens)), usd(all.costUsd)]
227      : [...tokens(totalTokens(totals)), ...(snap.costUsd !== undefined ? [usd(snap.costUsd)] : [])]
228  ).join(' · ')
229
230  return api && !api.problem ? `${head} · API ${usd(api.spentUsd)}/${Math.round(api.creditUsd)}` : head
231}
232
233// ---------- recomendação de modelo ----------
234
235const adviceColor = (a: Advice) => (a.isFine ? 'success' : a.pick ? 'warning' : 'error')
236
237const setupText = (a: Advice, economy: boolean) =>
238  [
239    `principal ${a.mainModel ? modelLabel(a.mainModel) : '—'}${a.mainEffort ? ` · effort ${a.mainEffort}` : ''}`,
240    a.subShare > 0
241      ? `subagentes ${percent(a.subShare * 100)} do gasto (${a.subModels.map(modelLabel).join(', ')})`
242      : 'sem subagentes nesta janela',
243    `economia ${economy ? 'ligada' : 'desligada'}`,
244  ].join(' · ')
245
246/** Botões que aplicam a recomendação; `always` mostra o liga/desliga da economia mesmo sem recomendação. */
247const AdviceButtons = (ui: BasicUi, a: Advice | undefined, economy: boolean, actions: Actions, always: boolean) => {
248  const { Box, Button } = ui
249  const buttons = []
250  if (!economy && (always || usesSubHaiku(a?.pick))) {
251    buttons.push(
252      <Button key="economy-on" label="Haiku nos subagentes" variant="primary" onPress={actions.toggleEconomy} />,
253    )
254  }
255  if (economy) {
256    buttons.push(<Button key="economy-off" label="Desligar economia" onPress={actions.toggleEconomy} />)
257  }
258  if (a && changesMain(a.pick, a.mainModel)) {
259    buttons.push(<Button key="model-sonnet" label="/model sonnet" onPress={() => actions.fillModel('sonnet')} />)
260  }
261  if (a?.pick === 'all-haiku') {
262    buttons.push(<Button key="model-haiku" label="/model haiku" onPress={() => actions.fillModel('haiku')} />)
263  }
264  if (actions.details) {
265    buttons.push(<Button key="details" label="Detalhes" plain onPress={actions.details} />)
266  }
267  // Na faixa o ↻ fica junto dos outros botões; no painel ele fica no topo.
268  if (actions.reload) {
269    buttons.push(<Button key="reload" label="↻ Atualizar" plain onPress={actions.reload} />)
270  }
271
272  return buttons.length > 0 ? (
273    <Box key="buttons" flexDirection="row" columnGap={2} flexWrap="wrap">
274      {buttons}
275    </Box>
276  ) : undefined
277}
278
279/** Cartão "Qual modelo usar" do painel. */
280const AdviceCard = (ui: BasicUi, a: Advice | undefined, economy: boolean, actions: Actions) => {
281  const { Box, Text } = ui
282
283  return (
284    <Box
285      key="advice"
286      flexDirection="column"
287      borderStyle="round"
288      borderColor={a ? adviceColor(a) : 'subtle'}
289      paddingX={1}
290    >
291      <Text bold>Qual modelo usar</Text>
292      {a === undefined ? (
293        <Text dimColor>A recomendação aparece depois de algumas respostas com os limites medidos.</Text>
294      ) : (
295        <Box flexDirection="column">
296          <Text color={adviceColor(a)}>{a.headline}</Text>
297          <Text dimColor>{setupText(a, economy)}</Text>
298          {a.scenarios.length > 0 && (
299            <Box flexDirection="column" marginTop={1}>
300              <Text dimColor>
301                Se o resto da janela {a.windowLabel.toLowerCase()} seguir assim (pelo gasto{' '}
302                {a.mixBasis === 'recent' ? 'das últimas 3 horas com uso' : 'da janela toda'}):
303              </Text>
304              {a.scenarios.map(s => (
305                <Text key={s.id} bold={s.id === a.pick} color={s.lasts ? 'success' : 'error'}>
306                  {s.id === a.pick ? '› ' : '  '}
307                  {s.label.padEnd(30)} dura {s.hoursLeft === undefined ? '—' : `~${hours(s.hoursLeft)}`} · ~
308                  {percent(s.pctAtReset)} no reset · −{percent((1 - s.factor) * 100)} de gasto
309                </Text>
310              ))}
311            </Box>
312          )}
313          {a.tip !== undefined && <Text dimColor>{a.tip}</Text>}
314        </Box>
315      )}
316      {AdviceButtons(ui, a, economy, { ...actions, reload: undefined }, true)}
317      <Text dimColor>
318        Estimativa pelo preço de API de cada modelo; a assinatura pode pesar os modelos de outro jeito.
319      </Text>
320    </Box>
321  )
322}
323
324// ---------- desktop, VS Code, mobile ----------
325
326/** Um número com o rótulo em cima: "Dura" / "até renovar". */
327const Fact = (ui: RichUi, key: string, label: string, value: string, color?: string) => {
328  const { Box, Text } = ui
329
330  return (
331    <Box key={key} flexDirection="column" minWidth={104}>
332      <Text dimColor>{label}</Text>
333      <Text bold color={color}>
334        {value}
335      </Text>
336    </Box>
337  )
338}
339
340/** "dura até renovar", "~3,2h", "esgotado"… para o cartão do painel. */
341const lastsText = (w: WindowView) => {
342  if (w.isRenewed) return 'renovado'
343  if (w.verdict === 'exhausted') return 'esgotado'
344  if (w.ratePerHour === undefined) return '—'
345  if (w.hoursLeft === undefined) return 'parado'
346  return w.verdict !== 'exhausts' && w.hoursLeft >= (w.msToReset ?? 0) / HOUR ? 'até renovar' : `~${hours(w.hoursLeft)}`
347}
348
349const renewsText = (w: WindowView, now: number) =>
350  w.resetsAt === undefined ? '—' : `${clockTime(w.resetsAt, now)} · em ${duration(w.msToReset ?? 0)}`
351
352/** Quanto cada projeto gastou na janela, com barrinhas. */
353const ProjectBars = (ui: RichUi, w: WindowView) => {
354  const { Box, Text, Svg } = ui
355  const list = (w.projects ?? []).slice(0, 4)
356  if (list.length === 0) return undefined
357
358  return (
359    <Box key="projects" flexDirection="column" rowGap={0}>
360      <Text dimColor>Por projeto, nesta máquina</Text>
361      {list.map(p => (
362        <Box key={p.name} flexDirection="row" columnGap={1} alignItems="center">
363          <Box width={120}>
364            <Text wrap="truncate-end">{p.name}</Text>
365          </Box>
366          <Svg source={shareSvg(p.share, 72, 8, HEX[w.verdict])} alt={`${p.name}: ${percent(p.share * 100)} do gasto`} width={72} height={8} />
367          <Text dimColor>
368            {percent(p.share * 100)}
369            {p.points !== undefined ? ` · ≈${p.points.toFixed(1).replace('.', ',')} pts` : ''}
370          </Text>
371        </Box>
372      ))}
373    </Box>
374  )
375}
376
377/** Cartão de um limite: o anel com o %, os números ao lado e o veredito embaixo. */
378const LimitCard = (ui: RichUi, w: WindowView, now: number) => {
379  const { Box, Text, Svg } = ui
380  const color = w.isRenewed ? 'subtle' : colorOf(w)
381  const work = workDaysText(w)
382
383  return (
384    <Box
385      key={w.kind}
386      flexDirection="column"
387      flexGrow={1}
388      minWidth={300}
389      borderStyle="round"
390      borderColor={w.verdict === 'exhausts' || w.verdict === 'exhausted' ? 'error' : 'subtle'}
391      paddingX={1}
392      paddingY={1}
393      rowGap={1}
394    >
395      <Box flexDirection="row" columnGap={2} alignItems="center">
396        <Svg
397          source={limitRingSvg(w, now, 88)}
398          alt={`${w.label}: ${percent(w.pct)} usado, ${lastsText(w)}`}
399          width={88}
400          height={88}
401        />
402        <Box flexDirection="column" rowGap={1} flexGrow={1}>
403          <Text bold>{w.label}</Text>
404          <Box flexDirection="row" columnGap={2} rowGap={1} flexWrap="wrap">
405            {Fact(ui, 'lasts', 'Dura', lastsText(w), color)}
406            {Fact(ui, 'renews', 'Renova', renewsText(w, now))}
407            {isWeekly(w)
408              ? Fact(ui, 'rate', 'Ritmo da conta', perDayText(w))
409              : Fact(ui, 'rate', 'Ritmo recente', rateText(w.recentRatePerHour))}
410          </Box>
411        </Box>
412      </Box>
413      <Text color={color}>{verdictText(w, now)}</Text>
414      {work !== undefined && <Text dimColor>{work}</Text>}
415      {ProjectBars(ui, w)}
416    </Box>
417  )
418}
419
420/** Uma linha de cenário da recomendação, em colunas alinhadas. */
421const ScenarioRow = (ui: RichUi, a: Advice, s: Advice['scenarios'][number]) => {
422  const { Box, Text } = ui
423  const isPick = s.id === a.pick
424
425  return (
426    <Box key={s.id} flexDirection="row" columnGap={2}>
427      <Box flexGrow={1} minWidth={200}>
428        <Text bold={isPick}>
429          {isPick ? '› ' : '  '}
430          {s.label}
431        </Text>
432      </Box>
433      <Box width={88}>
434        <Text color={s.lasts ? 'success' : 'error'}>{s.hoursLeft === undefined ? '—' : `~${hours(s.hoursLeft)}`}</Text>
435      </Box>
436      <Box width={88}>
437        <Text dimColor>{percent(s.pctAtReset)} no reset</Text>
438      </Box>
439      <Box width={80}>
440        <Text dimColor>−{percent((1 - s.factor) * 100)} gasto</Text>
441      </Box>
442    </Box>
443  )
444}
445
446/** "Qual modelo usar" no desktop: a frase, o que está rodando e os cenários numa tabela. */
447const RichAdviceCard = (ui: RichUi, a: Advice | undefined, economy: boolean, actions: Actions) => {
448  const { Box, Text } = ui
449
450  return (
451    <Box key="advice" flexDirection="column" borderStyle="round" borderColor={a && !a.isFine ? adviceColor(a) : 'subtle'} paddingX={1} paddingY={1} rowGap={1}>
452      <Text bold>Qual modelo usar</Text>
453      {a === undefined ? (
454        <Text dimColor>A recomendação aparece depois de algumas respostas com os limites medidos.</Text>
455      ) : (
456        <Box flexDirection="column" rowGap={1}>
457          <Text color={adviceColor(a)}>{a.headline}</Text>
458          <Text dimColor>{setupText(a, economy)}</Text>
459          {a.scenarios.length > 0 && (
460            <Box flexDirection="column">
461              <Text dimColor>
462                Se o resto da janela {a.windowLabel.toLowerCase()} seguir o gasto{' '}
463                {a.mixBasis === 'recent' ? 'das últimas 3 horas com uso' : 'da janela toda'}:
464              </Text>
465              {a.scenarios.map(s => ScenarioRow(ui, a, s))}
466            </Box>
467          )}
468          {a.tip !== undefined && <Text dimColor>{a.tip}</Text>}
469        </Box>
470      )}
471      {AdviceButtons(ui, a, economy, { ...actions, reload: undefined, details: undefined }, true)}
472    </Box>
473  )
474}
475
476/** As sessões abertas numa tabela, com a parte de cada uma no custo. */
477const SessionsTable = (ui: RichUi, snap: Snapshot) => {
478  const { Box, Text, Svg } = ui
479  const view = snap.sessions
480  if (!view) return <Text dimColor>Lista de sessões indisponível nesta máquina.</Text>
481  const total = view.total.costUsd
482
483  return (
484    <Box key="sessions-table" flexDirection="column">
485      {view.running.map(r => {
486        const share = total > 0 ? r.costUsd / total : 0
487        const isSelf = r.id === snap.selfId
488        const tokens = totalTokens(r.tokens)
489
490        return (
491          <Box key={r.id} flexDirection="row" columnGap={2} alignItems="center">
492            <Box width={150}>
493              <Text bold={isSelf} wrap="truncate-end">
494                {isSelf ? '● ' : '○ '}
495                {r.project}
496              </Text>
497            </Box>
498            <Box width={84}>
499              <Text dimColor>{r.model ? modelLabel(modelKey(r.model)) : '—'}</Text>
500            </Box>
501            <Box width={64}>
502              <Text dimColor>{tokens > 0 ? compact(tokens) : '—'}</Text>
503            </Box>
504            <Box width={96}>
505              <Text>{usd(r.costUsd)}</Text>
506            </Box>
507            <Svg source={shareSvg(share)} alt={`${percent(share * 100)} do custo`} width={64} height={8} />
508            <Text dimColor>{percent(share * 100)}</Text>
509          </Box>
510        )
511      })}
512      <Box flexDirection="row" columnGap={2} marginTop={1}>
513        <Text bold>
514          {view.total.count} {view.total.count === 1 ? 'sessão aberta' : 'sessões abertas'} · {usd(view.total.costUsd)}
515        </Text>
516        <Text dimColor>
517          hoje: {view.today.count} sessões · {usd(view.today.costUsd)}
518        </Text>
519      </Box>
520    </Box>
521  )
522}
523
524/** Sessões da máquina e os tokens desta. */
525const UsageCard = (ui: RichUi, { snap, totals }: ViewData, px: number) => {
526  const { Box, Text, Svg } = ui
527  const tokens = totalTokens(totals)
528  const legend = [
529    ['entrada', totals.input, TOKEN_HEX.input],
530    ['saída', totals.output, TOKEN_HEX.output],
531    ['cache escrito', totals.cacheWrite, TOKEN_HEX.cacheWrite],
532    ['cache lido', totals.cacheRead, TOKEN_HEX.cacheRead],
533  ] as const
534
535  return (
536    <Box key="usage" flexDirection="column" borderStyle="round" borderColor="subtle" paddingX={1} paddingY={1} rowGap={1}>
537      <Text bold>Sessões</Text>
538      {SessionsTable(ui, snap)}
539      <Text bold>Esta sessão</Text>
540      <Box flexDirection="row" columnGap={2} rowGap={1} flexWrap="wrap">
541        {Fact(ui, 'tokens', 'Tokens', compact(tokens))}
542        {Fact(ui, 'cost', 'Custo', snap.costUsd === undefined ? '—' : usd(snap.costUsd))}
543        {Fact(ui, 'turns', 'Turnos', String(totals.turns))}
544        {Fact(ui, 'ctx', 'Contexto', snap.contextPercent === undefined ? '—' : `${snap.contextPercent}%`)}
545      </Box>
546      {tokens > 0 && <Svg source={tokenMixSvg(totals, px, 10)} alt="Composição dos tokens da sessão" width={px} height={10} />}
547      {tokens > 0 && (
548        <Box flexDirection="row" columnGap={2} flexWrap="wrap">
549          {legend.map(([label, n, color]) => (
550            <Text key={label}>
551              <Text color={color}>●</Text> <Text dimColor>{label}</Text> {compact(n)}
552            </Text>
553          ))}
554        </Box>
555      )}
556      <Text dimColor>Custo equivalente em preço de API; no plano, o que conta são os limites de 5h e semanal.</Text>
557    </Box>
558  )
559}
560
561/** Painel `/limites` em superfícies que desenham SVG. */
562export const RichPane = (ui: RichUi, data: ViewData, columns: number, actions: Actions) => {
563  const { Box, Text, Button } = ui
564  const { snap } = data
565  const now = snap.updatedAt
566  const px = Math.max(220, Math.min(760, columns * 7 - 48))
567  const stale = isStale(snap)
568
569  return (
570    <Box flexDirection="column" rowGap={1}>
571      <Box flexDirection="row" justifyContent="space-between" alignItems="center" columnGap={2} flexWrap="wrap">
572        <Text bold>Limites de uso</Text>
573        <Box flexDirection="row" columnGap={2} alignItems="center">
574          <Text color={stale ? 'warning' : undefined} dimColor={!stale}>
575            {freshness(snap)}
576          </Text>
577          {actions.reload && <Button key="reload-top" label="↻ Atualizar" onPress={actions.reload} />}
578        </Box>
579      </Box>
580      {snap.windows.length === 0 && <Text dimColor>{EMPTY}</Text>}
581      <Box flexDirection="row" columnGap={1} rowGap={1} flexWrap="wrap">
582        {snap.windows.map(w => LimitCard(ui, w, now))}
583      </Box>
584      {RichAdviceCard(ui, snap.advice, data.economy, actions)}
585      {UsageCard(ui, data, px)}
586      {ApiCard(ui, data.api, now)}
587      <Text dimColor>
588        Anel cheio: uso · parte clara: projeção até renovar · traço: onde o uso estaria num ritmo uniforme. Estimativas pelo preço de API de
589        cada modelo; a assinatura pode pesar os modelos de outro jeito.
590      </Text>
591    </Box>
592  )
593}
594
595// ---------- terminal ----------
596
597/** Painel `/limites` no terminal: só texto. */
598export const TerminalPane = (ui: TerminalUi, { snap, totals, economy, api }: ViewData, columns: number, actions: Actions) => {
599  const { Box, Text } = ui
600  const now = snap.updatedAt
601  const width = Math.max(10, Math.min(30, columns - 30))
602
603  return (
604    <Box flexDirection="column">
605      <Box flexDirection="row" columnGap={2}>
606        <Text dimColor>{freshness(snap)}</Text>
607        {actions.reload && <ui.Button key="reload-top" label="↻ Atualizar" onPress={actions.reload} />}
608      </Box>
609      {snap.windows.length === 0 && <Text dimColor>{EMPTY}</Text>}
610      {snap.windows.map(w => {
611        const tokens = tokensLine(w)
612
613        return (
614          <Box key={w.kind} flexDirection="column" marginTop={1}>
615            <Text>
616              <Text bold>{w.label.padEnd(10)}</Text>
617              <Text color={colorOf(w)}>{bar(w.pct, width)}</Text> {percent(w.pct)}
618            </Text>
619            <Text bold>
620              {'  '}duração estimada {durationText(w)} · reset em {resetText(w, now)}
621            </Text>
622            <Text dimColor>
623              {'  '}
624              {isWeekly(w)
625                ? `ritmo da conta ${perDayText(w)}${workDaysText(w) ? ` · ${workDaysText(w)}` : ''}`
626                : `ritmo ${rateText(w.recentRatePerHour)} recente · ${rateText(w.windowRatePerHour)} média da janela`}
627            </Text>
628            <Text color={colorOf(w)}>
629              {'  '}
630              {verdictText(w, now)}
631            </Text>
632            {tokens !== undefined && (
633              <Text dimColor>
634                {'  '}
635                {tokens}
636              </Text>
637            )}
638            {ProjectList(ui, w, '  ')}
639          </Box>
640        )
641      })}
642      <Box marginTop={1}>{AdviceCard(ui, snap.advice, economy, actions)}</Box>
643      <Box flexDirection="column" marginTop={1}>
644        <Text bold>Sessões</Text>
645        {SessionsList(ui, snap)}
646      </Box>
647      {ApiCard(ui, api, now) !== undefined && <Box marginTop={1}>{ApiCard(ui, api, now)}</Box>}
648      <Box flexDirection="column" marginTop={1}>
649        <Text bold>Esta sessão</Text>
650        <Text>
651          {'  '}entrada {compact(totals.input)} · saída {compact(totals.output)} · cache lido{' '}
652          {compact(totals.cacheRead)} · cache escrito {compact(totals.cacheWrite)}
653        </Text>
654        <Text>
655          {'  '}total {compact(totalTokens(totals))} em {totals.turns} turno{totals.turns === 1 ? '' : 's'}
656          {snap.costUsd !== undefined && ` · custo ${usd(snap.costUsd)}`}
657          {snap.contextPercent !== undefined && ` · contexto ${snap.contextPercent}%`}
658        </Text>
659      </Box>
660    </Box>
661  )
662}
663
664// ---------- faixa acima do prompt (desktop e terminal) ----------
665
666/** Leitura com mais de 2h: os números podem estar bem atrás da conta. */
667const STALE_MS = 2 * HOUR
668
669const isStale = (snap: Snapshot) => snap.readAt !== undefined && snap.updatedAt - snap.readAt > STALE_MS
670
671/** "Semana" na faixa do desktop, que tem espaço; "Sem" no terminal. */
672const bandLabel = (kind: string, isWide: boolean) =>
673  isWide && kind === 'seven_day' ? 'Semana' : shortLabel(kind)
674
675/** O que vem depois do %: quanto dura e quando renova, sem repetir o óbvio. */
676export const bandDetail = (w: WindowView, now: number): string => {
677  const renews = w.resetsAt === undefined ? '' : `renova ${clockTime(w.resetsAt, now)}`
678  if (w.isRenewed) return 'renovado'
679  if (w.verdict === 'exhausted') return `esgotado · volta ${clockTime(w.resetsAt ?? now, now)}`
680  const toReset = (w.msToReset ?? 0) / HOUR
681  const lasts =
682    w.ratePerHour === undefined
683      ? undefined
684      : w.hoursLeft === undefined
685        ? 'parado'
686        : w.verdict === 'exhausts'
687          ? `acaba em ~${hours(w.hoursLeft)}`
688          : w.hoursLeft >= toReset
689            ? 'dura até renovar'
690            : `dura ~${hours(w.hoursLeft)}`
691
692  return [lasts, renews].filter(Boolean).join(' · ')
693}
694
695/** Marca curta da faixa minimizada. */
696const mark = (w: WindowView) =>
697  w.verdict === 'exhausted' ? ' ⛔' : w.verdict === 'exhausts' ? ' ⚠' : w.verdict === 'tight' ? ' △' : ''
698
699/** "2 sessões · 4,2M tokens · US$ 12,40" e, se for o caso, de quando é a leitura. */
700const metaLine = (data: ViewData) => {
701  const { snap, totals, api } = data
702  const age = readingAge(snap.readAt, snap.updatedAt)
703
704  return {
705    text: usageSummary(snap, totals, api),
706    age: age ? `leitura ${age}${isStale(snap) ? ': atualiza na próxima resposta' : ''}` : undefined,
707  }
708}
709
710/**
711 * A recomendação só aparece na faixa quando um limite acaba antes de renovar e
712 * a leitura é recente; o texto inteiro fica em Detalhes.
713 */
714const bandAdvice = (data: ViewData) => {
715  const a = data.snap.advice
716  const w = data.snap.windows.find(v => v.kind === a?.windowKind)
717  if (!a || !w || w.verdict !== 'exhausts' || isStale(data.snap)) return undefined
718  const when = w.exhaustAt !== undefined ? ` ~${clockTime(w.exhaustAt, data.snap.updatedAt)}` : ''
719
720  return { advice: a, text: `⚠ ${w.label} acaba${when}, antes de renovar` }
721}
722
723/** Botões da recomendação que mudam algo agora. */
724const adviceActions = (ui: BasicUi, a: Advice, economy: boolean, actions: Actions) => {
725  const { Button } = ui
726  const buttons = []
727  if (!economy && usesSubHaiku(a.pick)) {
728    buttons.push(<Button key="economy-on" label="Haiku nos subagentes" variant="primary" onPress={actions.toggleEconomy} />)
729  }
730  if (changesMain(a.pick, a.mainModel)) {
731    buttons.push(<Button key="model-sonnet" label="/model sonnet" onPress={() => actions.fillModel('sonnet')} />)
732  }
733  if (a.pick === 'all-haiku') {
734    buttons.push(<Button key="model-haiku" label="/model haiku" onPress={() => actions.fillModel('haiku')} />)
735  }
736  return buttons
737}
738
739/** Os controles à direita: economia, atualizar, detalhes e minimizar. */
740const bandControls = (ui: BasicUi, economy: boolean, actions: Actions, collapsed: boolean) => {
741  const { Box, Button } = ui
742
743  return (
744    <Box key="controls" flexDirection="row" columnGap={1} alignItems="center">
745      {economy && !collapsed && (
746        <Button key="economy-off" label="Economia ligada ✕" plain onPress={actions.toggleEconomy} />
747      )}
748      {actions.reload && !collapsed && <Button key="reload" label="↻" plain onPress={actions.reload} />}
749      {actions.details && !collapsed && <Button key="details" label="Detalhes" plain onPress={actions.details} />}
750      {actions.toggleBand && (
751        <Button
752          key={collapsed ? 'band-expand' : 'band-collapse'}
753          label={collapsed ? '▴' : '▾'}
754          plain
755          onPress={actions.toggleBand}
756        />
757      )}
758    </Box>
759  )
760}
761
762/** Faixa minimizada: uma linha com os % e o botão de expandir. */
763const CollapsedBand = (ui: BasicUi, data: ViewData, actions: Actions, isWide: boolean) => {
764  const { Box, Text } = ui
765  const { snap } = data
766  const all = snap.sessions?.total
767
768  return (
769    <Box flexDirection="row" justifyContent="space-between" alignItems="center" columnGap={2}>
770      <Box flexDirection="row" columnGap={2} alignItems="center">
771        {snap.windows.map(w => (
772          <Text key={w.kind}>
773            <Text dimColor>{bandLabel(w.kind, isWide)}</Text>{' '}
774            <Text bold color={w.isRenewed ? 'subtle' : colorOf(w)}>
775              {percent(w.pct)}
776              {mark(w)}
777            </Text>
778          </Text>
779        ))}
780        {all && all.count > 1 && (
781          <Text key="cost" dimColor>
782            {usd(all.costUsd)}
783          </Text>
784        )}
785        {isStale(snap) && (
786          <Text key="stale" color="warning">
787            leitura {readingAge(snap.readAt, snap.updatedAt)}
788          </Text>
789        )}
790      </Box>
791      {bandControls(ui, data.economy, actions, true)}
792    </Box>
793  )
794}
795
796/** Faixa acima do prompt no desktop: uma linha por assunto, controles à direita. */
797export const RichBand = (ui: RichUi, data: ViewData, actions: Actions) => {
798  if (data.collapsed) return CollapsedBand(ui, data, actions, true)
799  const { Box, Text, Svg } = ui
800  const { snap } = data
801  const now = snap.updatedAt
802  const meta = metaLine(data)
803  const advice = bandAdvice(data)
804
805  return (
806    <Box flexDirection="column" rowGap={0}>
807      <Box flexDirection="row" columnGap={2}>
808        <Box flexDirection="row" columnGap={4} rowGap={0} alignItems="center" flexWrap="wrap">
809          {snap.windows.map(w => (
810            <Box key={w.kind} flexDirection="row" columnGap={1} alignItems="center">
811              <Text bold>{bandLabel(w.kind, true)}</Text>
812              <Svg
813                source={limitBarSvg(w, now, 72, { height: 10 })}
814                alt={`${w.label}: ${percent(w.pct)} usado`}
815                width={72}
816                height={10}
817              />
818              <Text bold color={w.isRenewed ? 'subtle' : colorOf(w)}>
819                {percent(w.pct)}
820              </Text>
821              <Text dimColor>{bandDetail(w, now)}</Text>
822            </Box>
823          ))}
824        </Box>
825      </Box>
826      {advice && (
827        <Box key="advice" flexDirection="row" columnGap={2} alignItems="center" flexWrap="wrap">
828          <Text color="error">{advice.text}</Text>
829          {adviceActions(ui, advice.advice, data.economy, actions)}
830        </Box>
831      )}
832      <Box flexDirection="row" justifyContent="space-between" alignItems="center" columnGap={2}>
833        <Text dimColor>
834          {meta.text}
835          {meta.age !== undefined && (
836            <Text color={isStale(snap) ? 'warning' : undefined} dimColor={!isStale(snap)}>
837              {' · '}
838              {meta.age}
839            </Text>
840          )}
841        </Text>
842        {bandControls(ui, data.economy, actions, false)}
843      </Box>
844    </Box>
845  )
846}
847
848/** Faixa acima do prompt no terminal: o mesmo desenho, com barras de texto. */
849export const TerminalBand = (ui: TerminalUi, data: ViewData, actions: Actions) => {
850  const term = { ...actions, details: undefined }
851  if (data.collapsed) return CollapsedBand(ui, data, term, false)
852  const { Box, Text } = ui
853  const { snap } = data
854  const now = snap.updatedAt
855  const meta = metaLine(data)
856  const advice = bandAdvice(data)
857
858  return (
859    <Box flexDirection="column">
860      <Box flexDirection="row" justifyContent="space-between" columnGap={2}>
861        <Box flexDirection="row" columnGap={3} flexWrap="wrap">
862          {snap.windows.map(w => (
863            <Text key={w.kind}>
864              <Text bold>{bandLabel(w.kind, false)}</Text>{' '}
865              <Text color={w.isRenewed ? 'subtle' : colorOf(w)}>{bar(w.pct, 8)}</Text>{' '}
866              <Text bold color={w.isRenewed ? 'subtle' : colorOf(w)}>
867                {percent(w.pct)}
868              </Text>{' '}
869              <Text dimColor>{bandDetail(w, now)}</Text>
870            </Text>
871          ))}
872        </Box>
873      </Box>
874      {advice && (
875        <Box key="advice" flexDirection="row" columnGap={2} flexWrap="wrap">
876          <Text color="error">{advice.text}</Text>
877          {adviceActions(ui, advice.advice, data.economy, term)}
878        </Box>
879      )}
880      <Box flexDirection="row" columnGap={2}>
881        <Text dimColor>
882          {meta.text}
883          {meta.age !== undefined && (
884            <Text color={isStale(snap) ? 'warning' : undefined} dimColor={!isStale(snap)}>
885              {' · '}
886              {meta.age}
887            </Text>
888          )}
889          {' · /limites'}
890        </Text>
891        {bandControls(ui, data.economy, term, false)}
892      </Box>
893    </Box>
894  )
895}
896
hooks/svg.ts 158 lines
1import type { Totals, Verdict, WindowView } from '../types'
2import { windowLength } from './projection'
3
4/** Tons médios: leem bem no tema claro e no escuro do app. */
5export const HEX: Record<Verdict, string> = {
6  ok: '#2f9e62',
7  tight: '#d99a00',
8  exhausts: '#e5484d',
9  exhausted: '#e5484d',
10  unknown: '#8a8f98',
11}
12const TRACK = '#8a8f98'
13
14export const TOKEN_HEX = {
15  input: '#5b8def',
16  output: '#b26ad9',
17  cacheWrite: '#e0a458',
18  cacheRead: '#3fb4c4',
19} as const
20
21const clamp = (n: number) => Math.min(100, Math.max(0, n))
22const fixed = (n: number) => Math.round(n * 10) / 10
23
24/**
25 * Barra de um limite: o uso (cheio), o que o ritmo atual projeta até o reset
26 * (hachurado) e um traço onde o uso estaria num ritmo uniforme.
27 */
28export const limitBarSvg = (
29  w: WindowView,
30  now: number,
31  width: number,
32  options: { height?: number; pace?: boolean } = {},
33): string => {
34  const height = options.height ?? 30
35  const barH = Math.max(6, Math.round(height * 0.5))
36  const barY = Math.round((height - barH) / 2)
37  const r = barH / 2
38  const x = (pct: number) => fixed((clamp(pct) / 100) * width)
39  const color = HEX[w.verdict]
40  const used = x(w.pct)
41  const projected = x(w.pctAtReset ?? w.pct)
42
43  const length = windowLength(w.kind)
44  const pace =
45    options.pace !== false && length !== undefined && w.resetsAt !== undefined
46      ? x(((now - (w.resetsAt - length)) / length) * 100)
47      : undefined
48
49  return [
50    `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${width} ${height}" width="${width}" height="${height}">`,
51    '<defs>',
52    `<pattern id="h" width="6" height="6" patternUnits="userSpaceOnUse" patternTransform="rotate(45)">`,
53    `<rect width="3" height="6" fill="${color}" fill-opacity="0.45"/></pattern>`,
54    `<clipPath id="c"><rect x="0" y="${barY}" width="${width}" height="${barH}" rx="${r}"/></clipPath>`,
55    '</defs>',
56    `<rect x="0" y="${barY}" width="${width}" height="${barH}" rx="${r}" fill="${TRACK}" fill-opacity="0.2"/>`,
57    '<g clip-path="url(#c)">',
58    projected > used
59      ? `<rect x="${used}" y="${barY}" width="${fixed(projected - used)}" height="${barH}" fill="url(#h)"/>`
60      : '',
61    `<rect x="0" y="${barY}" width="${used}" height="${barH}" fill="${color}"/>`,
62    '</g>',
63    pace !== undefined
64      ? `<line x1="${pace}" y1="${Math.max(1, barY - 4)}" x2="${pace}" y2="${Math.min(height - 1, barY + barH + 4)}" stroke="${TRACK}" stroke-width="2" stroke-linecap="round"/>`
65      : '',
66    '</svg>',
67  ].join('')
68}
69
70/** Barra empilhada da composição dos tokens da sessão. */
71export const tokenMixSvg = (t: Totals, width: number, height = 12): string => {
72  const parts = [
73    [t.input, TOKEN_HEX.input],
74    [t.output, TOKEN_HEX.output],
75    [t.cacheWrite, TOKEN_HEX.cacheWrite],
76    [t.cacheRead, TOKEN_HEX.cacheRead],
77  ] as const
78  const total = parts.reduce((sum, [n]) => sum + n, 0)
79  let at = 0
80  const rects = parts.map(([n, color]) => {
81    const w = total > 0 ? (n / total) * width : 0
82    const rect = w > 0 ? `<rect x="${fixed(at)}" y="0" width="${fixed(w)}" height="${height}" fill="${color}"/>` : ''
83    at += w
84
85    return rect
86  })
87
88  return [
89    `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${width} ${height}" width="${width}" height="${height}">`,
90    `<clipPath id="c"><rect width="${width}" height="${height}" rx="${height / 2}"/></clipPath>`,
91    `<rect width="${width}" height="${height}" rx="${height / 2}" fill="${TRACK}" fill-opacity="0.2"/>`,
92    `<g clip-path="url(#c)">${rects.join('')}</g>`,
93    '</svg>',
94  ].join('')
95}
96
97const arcPath = (cx: number, cy: number, r: number, from: number, to: number) => {
98  // Ângulos em % do círculo, a partir do topo, no sentido horário.
99  const at = (pct: number) => {
100    const a = (pct / 100) * 2 * Math.PI - Math.PI / 2
101    return `${fixed(cx + r * Math.cos(a))} ${fixed(cy + r * Math.sin(a))}`
102  }
103  const large = to - from > 50 ? 1 : 0
104
105  return `M ${at(from)} A ${r} ${r} 0 ${large} 1 ${at(to)}`
106}
107
108/**
109 * Anel de um limite para o painel: o uso cheio, a projeção até o reset mais
110 * clara, um traço onde estaria o ritmo uniforme e o % grande no meio.
111 */
112export const limitRingSvg = (w: WindowView, now: number, size = 96): string => {
113  const stroke = Math.round(size * 0.1)
114  const r = (size - stroke) / 2 - 1
115  const c = size / 2
116  const color = w.isRenewed ? HEX.unknown : HEX[w.verdict]
117  const used = clamp(w.pct)
118  const projected = clamp(w.pctAtReset ?? w.pct)
119  const length = windowLength(w.kind)
120  const pace =
121    length !== undefined && w.resetsAt !== undefined && !w.isRenewed
122      ? clamp(((now - (w.resetsAt - length)) / length) * 100)
123      : undefined
124  const arc = (from: number, to: number, opacity: number) =>
125    to - from >= 99.9
126      ? `<circle cx="${c}" cy="${c}" r="${fixed(r)}" fill="none" stroke="${color}" stroke-opacity="${opacity}" stroke-width="${stroke}"/>`
127      : to - from > 0.2
128        ? `<path d="${arcPath(c, c, r, from, to)}" fill="none" stroke="${color}" stroke-opacity="${opacity}" stroke-width="${stroke}" stroke-linecap="round"/>`
129        : ''
130  const tick = (pct: number) => {
131    const a = (pct / 100) * 2 * Math.PI - Math.PI / 2
132    const r1 = r - stroke / 2 - 2
133    const r2 = r + stroke / 2 + 2
134    return `<line x1="${fixed(c + r1 * Math.cos(a))}" y1="${fixed(c + r1 * Math.sin(a))}" x2="${fixed(c + r2 * Math.cos(a))}" y2="${fixed(c + r2 * Math.sin(a))}" stroke="${TRACK}" stroke-width="2" stroke-linecap="round"/>`
135  }
136
137  return [
138    `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${size} ${size}" width="${size}" height="${size}">`,
139    `<circle cx="${c}" cy="${c}" r="${fixed(r)}" fill="none" stroke="${TRACK}" stroke-opacity="0.2" stroke-width="${stroke}"/>`,
140    projected > used ? arc(used, projected, 0.3) : '',
141    arc(0, used, 1),
142    pace !== undefined ? tick(pace) : '',
143    `<text x="${c}" y="${fixed(c + size * 0.08)}" text-anchor="middle" font-family="-apple-system, Segoe UI, Helvetica, Arial, sans-serif" font-size="${Math.round(size * 0.24)}" font-weight="700" fill="${color}">${Math.round(w.pct)}%</text>`,
144    '</svg>',
145  ].join('')
146}
147
148/** Barrinha de participação (sessões, projetos). */
149export const shareSvg = (share: number, width = 64, height = 8, color = '#5b8def'): string =>
150  [
151    `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${width} ${height}" width="${width}" height="${height}">`,
152    `<rect width="${width}" height="${height}" rx="${height / 2}" fill="${TRACK}" fill-opacity="0.2"/>`,
153    share > 0
154      ? `<rect width="${fixed(Math.max(height, clamp(share * 100) / 100 * width))}" height="${height}" rx="${height / 2}" fill="${color}"/>`
155      : '',
156    '</svg>',
157  ].join('')
158
types/index.d.ts 187 lines
1export type Totals = {
2  input: number
3  output: number
4  cacheRead: number
5  cacheWrite: number
6  turns: number
7}
8
9/** As quatro contagens de tokens de uma resposta. */
10export type Tokens = {
11  input: number
12  output: number
13  cacheRead: number
14  cacheWrite: number
15}
16
17/** Tokens de uma janela por papel (principal ou subagente) e por modelo. */
18export type Mix = {
19  resetsAt: number
20  main: Record<string, Tokens>
21  sub: Record<string, Tokens>
22}
23
24/** O que a sessão está usando no fio principal. */
25export type Setup = { mainModel?: string; mainEffort?: string }
26
27export type ScenarioId = 'sub-haiku' | 'main-sonnet-sub-haiku' | 'all-sonnet' | 'all-haiku'
28
29export type Scenario = {
30  id: ScenarioId
31  label: string
32  /** Custo do cenário sobre o custo atual (0,4 = 60% mais barato). */
33  factor: number
34  hoursLeft?: number
35  pctAtReset: number
36  lasts: boolean
37}
38
39export type Advice = {
40  windowKind: string
41  windowLabel: string
42  mainModel?: string
43  mainEffort?: string
44  /** Parte do gasto da janela feita por subagentes, 0 a 1. */
45  subShare: number
46  subModels: string[]
47  scenarios: Scenario[]
48  /** O cenário recomendado: o menos disruptivo que faz o limite durar. */
49  pick?: ScenarioId
50  /** true quando nada precisa mudar. */
51  isFine: boolean
52  /** O gasto por modelo das últimas horas (`recent`) ou da janela toda. */
53  mixBasis: 'recent' | 'window'
54  headline: string
55  tip?: string
56}
57
58/** A parte de um projeto no gasto de uma janela. */
59export type ProjectShare = {
60  name: string
61  /** Fração do gasto da janela, 0 a 1. */
62  share: number
63  /** Pontos do limite atribuídos ao projeto, pela fração do gasto. */
64  points?: number
65}
66
67/** Gasto em US$ (preço de API) por projeto numa janela. */
68export type ProjectBucket = { resetsAt: number; firstPct: number; byProject: Record<string, number> }
69
70/** Uma sessão do Claude Code desta máquina, como ela mesma se registra. */
71export type SessionRecord = {
72  id: string
73  project: string
74  model?: string
75  startedAt: number
76  /** O último sinal da sessão (a cada minuto enquanto aberta). */
77  updatedAt: number
78  tokens: Totals
79  /** Custo equivalente em preço de API, como o /cost soma. */
80  costUsd: number
81  ended?: boolean
82}
83
84export type SessionsView = {
85  /** As abertas agora, esta primeiro. */
86  running: SessionRecord[]
87  total: { tokens: Totals; costUsd: number; count: number }
88  /** Todas as de hoje, fechadas inclusive. */
89  today: { tokens: Totals; costUsd: number; count: number }
90}
91
92/** O gasto dos créditos de API no ciclo, lido do relatório de custo do Console. */
93export type ApiSpend = {
94  cycleStart: number
95  cycleEnd: number
96  spentUsd: number
97  creditUsd: number
98  byModel: { model: string; usd: number }[]
99  dailyUsd: number
100  projectedUsd: number
101  /** Quando o crédito acaba no ritmo atual, se for antes do fim do ciclo. */
102  runsOutAt?: number
103  fetchedAt: number
104  problem?: string
105}
106
107export type Verdict = 'ok' | 'tight' | 'exhausts' | 'exhausted' | 'unknown'
108
109export type WindowView = {
110  kind: string
111  label: string
112  pct: number
113  resetsAt?: number
114  msToReset?: number
115  /** % por hora usado na projeção. */
116  ratePerHour?: number
117  /**
118   * De onde vem o ritmo: últimas horas (`recent`), média da janela (`window`)
119   * ou, no semanal, o ritmo de trabalho medido pelo limite de 5h (`work`).
120   */
121  rateSource: 'recent' | 'window' | 'work' | 'none'
122  /**
123   * Horas de consumo até o reset no ritmo de `ratePerHour`: no 5h, o relógio;
124   * no semanal por trabalho, as horas de trabalho que cabem até o reset.
125   */
126  hoursAhead?: number
127  /** Horas de trabalho por dia usadas na projeção do semanal. */
128  activeHoursPerDay?: number
129  /**
130   * Só no semanal: horas de uso que restam no ritmo da última hora de trabalho,
131   * medido pelo limite de 5h. Informação extra; a projeção usa o ritmo da conta.
132   */
133  workHoursLeft?: number
134  /** %/h de uso do semanal no ritmo da última hora de trabalho. */
135  workRatePerHour?: number
136  /** Média de %/h desde o início da janela. */
137  windowRatePerHour?: number
138  /** %/h na última hora (5h) ou nas últimas 24h (semanal). */
139  recentRatePerHour?: number
140  /** Horas até chegar a 100% no ritmo usado; ausente quando parado. */
141  hoursLeft?: number
142  /** Quando chega a 100% no ritmo usado, se antes do reset. */
143  exhaustAt?: number
144  /** % projetado no momento do reset. */
145  pctAtReset?: number
146  verdict: Verdict
147  /** A leitura é de antes do reset: a janela já renovou, o uso é 0 até a próxima resposta. */
148  isRenewed?: boolean
149  /** Tokens contados nesta janela (todas as sessões com o mod). */
150  windowTokens?: number
151  /** Tokens por 1% do limite, medido nesta janela. */
152  tokensPerPct?: number
153  /** Quanto cada projeto gastou nesta janela, nesta máquina. */
154  projects?: ProjectShare[]
155}
156
157export type Snapshot = {
158  updatedAt: number
159  windows: WindowView[]
160  costUsd?: number
161  contextPercent?: number
162  advice?: Advice
163  /** Quando os percentuais foram lidos de uma resposta da API. */
164  readAt?: number
165  /** A leitura veio de outra sessão desta máquina, mais recente que a desta. */
166  isSharedReading?: boolean
167  /** As sessões abertas nesta máquina e o total. */
168  sessions?: SessionsView
169  /** O id desta sessão, para marcá-la na lista. */
170  selfId?: string
171}
172
173declare module 'claude-code' {
174  interface PluginState {
175    'usage-limits': {
176      snapshot: Snapshot | null
177      session: Totals
178      economy: boolean
179      setup: Setup
180      project: string
181      api: ApiSpend | null
182      /** Faixa acima do prompt minimizada numa linha. */
183      bandCollapsed: boolean
184    }
185  }
186}
187