SLOPSHOPPER

limits-meter

Plan limits, cache clock and context above the prompt: model and effort, 5-hour and weekly windows with reset times, a countdown of the prompt cache with an…

panebandrowscommandtoastprompt
★ 11v0.5.0MITupdated 2026-10-25ice-lfernandes/claude-code-mods/limits-meter
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · limits-meter
│ ┃ Limits & context ✕ › fix the failing auth test and add an audit log call │ ┃ Figures the engine reports after each │ ┃ turn. Tokens and percent, never money. ⏺ Read(src/auth.ts) │ ┃ ⎿ Read 6 lines │ ┃ Plan windows ⏺ Update(src/auth.ts) │ ┃ 5h ███████░░░░░░░░░░░░░░░░░ 31% ⎿ Added 2 lines, removed 1 line │ ┃ ⏺ Bash(bun test) │ ┃ Cache ⎿ 3 pass, 1 fail │ ┃ Cache TTL unknown. It shows after a model │ ┃ switch, or after a one-request turn that ● Done. refresh now rejects expired claims and logs an audit event. │ ┃ follows more than 5 min idle. │ ┃ last turn hit rate: 93% ✻ Worked for 42s · done 4:20 PM │ ┃ │ ┃ Context › /limits │ ┃ ctx ████████████░░░░░░░░░░░░ 49% 97k │ ┃ of 200k │ ┃ │ ┃ Model │ ┃ opus 5.5 │ ┃ │ ┃ Costly switch warning │ ┃ Toast on a switch to a bigger model or │ ┃ effort max with 5h from: │ ┃ 50% · 60% · 70% · 80% · 90% │ ┃ order: haiku < sonnet < opus < fable │ ┃ opus 5.5 5h ██░░░░ 31% ctx ███░░░ 49% cache 93% details hide ⟨Claude Code's own drawing⟩ ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Band
opus 5.5 5h ██░░░░ 31% ctx ███░░░ 49% cache 93% details hide ⟨Claude Code's own drawing⟩
Pane · Limits &amp; context
Figures the engine reports after each turn. Tokens and percent, never money. Plan windows 5h ███████░░░░░░░░░░░░░░░░░ 31% Cache Cache TTL unknown. It shows after a model switch, or after a one-request turn that follows more than 5 min idle. last turn hit rate: 93% Context ctx ████████████░░░░░░░░░░░░ 49% 97k of 200k Model opus 5.5 Costly switch warning Toast on a switch to a bigger model or effort max with 5h from: 50% · 60% · 70% · 80% · 90% order: haiku < sonnet < opus < fable Turns (main thread) in out cache time model #1 97k 1.5k 93% 42s opus 5.5 /limits hide · show · keep-warm on · keep-warm off · help
README

limits-meter

Plan limits and context above the prompt, in tokens and percent. Never money.

limits-meter: band above the prompt, the /limits pane and its toasts

  • Band above the prompt: the main thread's model, in the accent color, and its effort as a five-step gauge, opus 5.5 ▰▰▰▱▱ high (low to max, max in the warning color), the 5-hour and weekly plan windows with their reset times, the context window's fill, and the cache clock (below; the last turn's hit rate until the TTL is known). With format: compact it is one line of numbers: sonnet 5.5 ▰▰▰▱▱ high · ctx 8% · 5h 34% · wk 31%. The effort comes from each request, else the turn's end on the main thread, else /config at the start; a weaker source never overwrites a stronger one, so the band does not flip between max and its downgrade. Colors follow the theme: warning at 70%, error at 90% (the warnAt and dangerAt options). Below 90 columns each bar shrinks to one cell. details opens the pane, hide hides the band, and from 85% context compact puts /compact [focus] in the prompt, with the blank marked: nothing runs until you send it.
  • Cache clock: the cache cell counts the prompt cache down from the end of the last request, ⏱ 52:10, in the warning color for the last 10 minutes (the last minute of a 5-minute cache), then ❄ cold and one toast. The TTL comes from cache_ttl on a model switch, else from a turn of one request after more than 5 minutes idle (a high hit means 1 hour, a near-zero one 5 minutes). Until it is known, the cell shows the last turn's hit rate. The TTL and the clock are the engine's; a model switch empties the clock until the next request.
  • Keep warm: keep warm on the band (while the cache cools) or /limits keep-warm on asks first, then sends one short message about 5 minutes before a 1-hour cache goes cold (30 seconds before a 5-minute one). It is a real turn: the model reads "Keep-warm ping from limits-meter. Reply with a single "."" and the transcript draws one dim row. It spends plan (each send re-reads the whole context from the cache) and is the only way this mod calls a model. It stops at your next prompt, after 2 hours, or when the cache goes cold before a send; stop on the band or /limits keep-warm off ends it. Off by default.
  • Context groups: the context bar is split by the engine's own categories (the /context breakdown, estimated locally and free): █ system (prompt, tools, memory files, skills) in blue, █ MCP in orange, █ messages in the context's color, ░ free. A legend under the band names each color with its share of the window. With no breakdown from the engine, the band keeps its single bar. format: compact has no legend.
  • /limits opens a pane with the same figures at full width, context in tokens (116k of 200k), and the last main-thread turns that fit, under column heads: input, output, cache hit, duration, model. The turn with the most input stands out. Its footer has the verbs and a close button. The command runs mid-turn.
  • Pace: each window's readings since it last reset draw a line; when that line reaches 100% before the reset, the pane says so: at this pace, 5h reaches 100% in ~1h20, before it resets.
  • Cache: the clock, what it means in tokens, and keep warm.
  • Context trend: a sparkline of the context fill at the end of each turn, and the table of every category and MCP server with tokens and share of the window.
  • Model and its effort gauge.
  • Costly switch warning: the threshold for the toast below, 50% · 60% · 70% · 80% · 90%, one click each; the choice is kept for later sessions.
  • Toasts, once each: a window at 80, 90 and 100% (re-armed when the window resets), and context at 85% with a hint to /compact (re-armed once it drops below 50%). And once per costly switch, a model up haiku < sonnet < opus < fable or effort turning to max, with the 5-hour window at the threshold or more (70% by default):
  • 5h at 82%: at this pace the window runs out in ~18 min · /limits, from the window's readings since the first of the last 3 turns started;
  • 5h at 85%: resets in 12m, before it runs out · /limits when the window resets first;
  • 5h at 82%: opus uses the window faster · /limits with fewer than 3 turns, no number.

The effort is read as each request goes out, so the max warning comes with the first request after /effort max. A resumed session's model is no switch. The pace comes from turns at the previous model, so right after a switch it tends to be optimistic. If the hook fails, the switch goes on (fail-open): it is a warning, not a guard.

/limits          open the pane
/limits hide     hide the band above the prompt, in later sessions too
/limits show     bring the band back
/limits keep-warm on|off  keep the cache warm: asks first, spends plan
/limits warn N   warn on a costly switch with the 5-hour window from N%, 1 to 100 (default 70)
/limits help     list the commands

Options

Set them in /config, under the plugin.

OptionValuesDefault
iconsauto, emoji, symbol. symbol draws the cache glyphs in one cell (◷ * ↺); auto uses it in a JetBrains terminalauto
languageauto, pt-BR, en. auto follows the system's LANG: Portuguese for pt_*, English otherwiseauto
formatfull draws the band with bars; compact one line of numbers: model · effort · ctx · 5h · wkfull
cellsThe band's cells, comma-separated, from model, 5h, wk, spend, ctx, cache. all shows them allall
densityauto sizes the bars to the terminal and shrinks each to one cell (▁ to █) below 90 columns; bars always draws 10 cells; mini always one; numbers no barauto
warnAtPercent from which a window or the context turns to the warning color70
dangerAtPercent from which it turns to the error color90

Figures come from the engine's session.measure event, pushed after each turn, so nothing polls. Plan windows appear on a subscription after the first response; with an API key the band shows context only.

Install

/plugin install limits-meter --marketplace ice-lfernandes/claude-code-mods

Or for one session: claude --plugin-dir ./limits-meter

What it reaches

ModNetworkRuns processesFilesCalls a modelSends data anywhere
limits-meterNoNoNoOnly if you turn on keep-warm: one short message per cache lap, until your next prompt or 2 hoursNo

It stores these values in the session's plugin state: the latest figures, recent turns, whether the band is hidden, which alerts fired, each window's readings for the pace, the model, the effort and the costly-switch threshold. Across sessions it keeps two values in the plugin's store: whether you hid the band, and the costly-switch threshold.

Source 5 files
hooks/register.tsx 811 lines
1// limits-meter: plan limits and context, above the prompt and in a pane.
2//
3//   band   AbovePrompt: the main thread's model and effort, 5-hour and weekly windows with reset
4//          times, context fill, last turn's cache hit rate. Tokens and percent only, never money.
5//          `details` opens the pane, `hide` hides the band, and from 85% context `compact` puts
6//          /compact in the prompt. The `format`, `cells`, `density`, `warnAt` and `dangerAt`
7//          options shape it; below 90 columns each bar shrinks to one cell, and `format: compact`
8//          draws one line of numbers.
9//   cache  the band's cache cell counts down the prompt cache (⏱ 52:10, warning when it cools, ❄ cold
10//          when it lapsed) from the end of the last request and its TTL (`cache_ttl` on a model
11//          switch, else inferred from a one-request turn after a gap); without a TTL it shows the
12//          last turn's hit rate. Keep-warm (/limits keep-warm on|off, or the band's button) asks, then
13//          sends a short message just before the cache goes cold; it stops at the person's next
14//          prompt or after 2 h. It is a real turn the transcript draws as one dim row.
15//   ctx    the context bar is split by the engine's categories (system, MCP, messages, free), with a
16//          legend under the band; the pane lists every category. $.session.usage({ breakdown: 'summary' }).
17//   pace   each window's readings since its reset; when their pace reaches 100% before the
18//          reset, the pane says when.
19//   /limits  opens a pane with the same figures at full width and the last turns' tokens;
20//          /limits hide | show toggles the band, and the choice is kept across sessions.
21//   toasts once per threshold: a window at 80, 90 and 100%, context at 85%. And once per costly
22//          switch (a model up haiku < sonnet < opus < fable, or effort turning to max) with the
23//          5-hour window at /limits warn N or more (70 by default): the minutes left at the pace
24//          of the last 3 turns, or when the window resets first, or no number without a pace.
25//
26// Figures come from `session.measure` (pushed by the engine after each turn and when a window
27// moves a point), so nothing polls. Reads nothing from disk, runs no process, calls no model.
28
29import { atom, read, update } from 'claude-code'
30import type { Elements, EngineInterface, Register } from 'claude-code'
31
32import type { CacheClock, ContextGroups, KeepWarm, Samples, Snapshot, Turn, Ttl } from '../types'
33import type { Setting } from './meter'
34import { addSamples, alerts, bar, barCells, clockOf, contextSpark, effortLevel, gauge, groupContext, heaviest, inferTtl, keepMargin, KEEP_WARM_MAX_MS, KEEP_WARM_TEXT, label, mini, mmss, needsCompact, pace, pct, resetIn, splitOf, summary, switchWarning, toSnapshot, toTurn, tone as toneOf, TTL_MS, TURNS_KEPT } from './meter'
35import type { IconStyle, Lang, Verb } from './ui'
36import { clip, fillArgs, glyph, langOf, linesOf, shortModel, styleOf, tokens, verbRow } from './ui'
37import { COMMAND, WORDS } from './words'
38
39const PANE = 'limits'
40const KEY_HIDDEN = 'hidden'
41const KEY_SWITCH = 'switchWarnAt'
42const SWITCH_AT = 70
43/** The thresholds the pane offers for the costly-switch toast; /limits warn takes any 1 to 100. */
44const SWITCH_CHOICES = [50, 60, 70, 80, 90]
45
46const EMPTY: Snapshot = { limits: [], contextPercent: null, contextTokens: null, contextWindow: 0 }
47
48const snapshot = atom({ plugin: 'limits-meter', key: 'snapshot' } as const, EMPTY)
49const turns = atom({ plugin: 'limits-meter', key: 'turns' } as const, [] as Turn[])
50const isHidden = atom({ plugin: 'limits-meter', key: 'isHidden' } as const, false)
51const fired = atom({ plugin: 'limits-meter', key: 'fired' } as const, [] as string[])
52const samples = atom({ plugin: 'limits-meter', key: 'samples' } as const, {} as Samples)
53const model = atom({ plugin: 'limits-meter', key: 'model' } as const, null as string | null)
54const effort = atom({ plugin: 'limits-meter', key: 'effort' } as const, null as string | number | null)
55const switchAt = atom({ plugin: 'limits-meter', key: 'switchAt' } as const, SWITCH_AT)
56const cache = atom({ plugin: 'limits-meter', key: 'cache' } as const, { lastAt: null, ttl: null } as CacheClock)
57const keepWarm = atom({ plugin: 'limits-meter', key: 'keepWarm' } as const, null as KeepWarm | null)
58const groups = atom({ plugin: 'limits-meter', key: 'groups' } as const, null as ContextGroups | null)
59
60// Set by register from the options, and by session.start from the system's LANG.
61let lang: Lang = 'en'
62let warnAt = 70
63let dangerAt = 90
64/** The band's cells by id (5h, wk, spend, ctx, cache); null shows them all. */
65let cells: Set<string> | null = null
66let density: 'auto' | 'bars' | 'mini' | 'numbers' = 'auto'
67/** `full`, the band with bars, or `compact`, one line of numbers. */
68let format: 'full' | 'compact' = 'full'
69let style: IconStyle = 'emoji'
70/** The cache cell's glyphs: ⏱ counting, ❄ cold, ♻ kept warm; one cell each in the symbol style. */
71const ICONS = {
72  clock: { emoji: '⏱', symbol: '◷' },
73  cold: { emoji: '❄', symbol: '*' },
74  keep: { emoji: '♻', symbol: '↺' },
75}
76/** Model requests so far in the main thread's running turn: a turn of one has a hit rate the TTL can be read from. */
77let steps = 0
78/** A keep-warm message is on its way: the turn that ends next is its own, not the person's. */
79let keepSending = false
80let ticker: { cancel: () => void } | null = null
81
82const tone = (percent: number | null) => toneOf(percent, warnAt, dangerAt)
83
84const CELL_IDS: Record<string, string> = { five_hour: '5h', seven_day: 'wk', spend_limit: 'spend' }
85const shows = (id: string) => cells === null || cells.has(id)
86
87/** The `cells` option: names from model, 5h, wk, spend, ctx, cache, comma-separated; `all` or nothing known shows them all. */
88const cellsOf = (option: unknown): Set<string> | null => {
89  const names = String(option ?? '')
90    .toLowerCase()
91    .split(/[\s,]+/)
92    .filter(n => ['model', '5h', 'wk', 'spend', 'ctx', 'cache'].includes(n))
93  return names.length ? new Set(names) : null
94}
95
96/** Bar cells for the band: by the terminal's width on `auto`, 0 for one cell, -1 for none. */
97const barWidth = (columns: number) =>
98  density === 'bars' ? 10 : density === 'mini' ? 0 : density === 'numbers' ? -1 : columns >= 120 ? 10 : columns >= 90 ? 6 : 0
99
100const take = async ($: EngineInterface, next: Snapshot) => {
101  await update($, snapshot, () => next)
102  const now = await $.clock.now()
103  await update($, samples, list => addSamples(list, next, now))
104  const result = alerts(next, await read($, fired), now, lang)
105  if (result.raised.length === 0) return
106  await update($, fired, () => result.fired)
107  for (const a of result.raised) $.ui.toast(a.text, { timeoutMs: 8000 })
108}
109
110/** Hides or shows the band, and keeps the choice for later sessions. */
111const setHidden = async ($: EngineInterface, hidden: boolean) => {
112  await update($, isHidden, () => hidden)
113  await $.store.set(KEY_HIDDEN, hidden)
114}
115
116/** Sets the costly-switch threshold, and keeps it for later sessions. */
117const setSwitchAt = async ($: EngineInterface, percent: number) => {
118  await update($, switchAt, () => percent)
119  await $.store.set(KEY_SWITCH, percent)
120}
121
122/** The window by the engine's categories, grouped for the band; null when the engine gives none. */
123const takeGroups = async ($: EngineInterface) => {
124  try {
125    const b = (await $.session.usage({ breakdown: 'summary' })).context.breakdown
126    await update($, groups, () => (b ? groupContext(b) : null))
127  } catch {
128    // No breakdown: the band keeps its single bar.
129  }
130}
131
132/** When the last keep-warm message went out, or null: until that turn ends the next one is its own. */
133let keepSentAt: number | null = null
134/** The last request for which the cold toast fired, so it comes once per lapse. */
135let coldFor: number | null = null
136/** Seconds a sent keep-warm may wait for its turn to end before the next one is tried. */
137const KEEP_PATIENCE_MS = 120_000
138
139const stopTicker = () => {
140  ticker?.cancel()
141  ticker = null
142}
143
144/** Ends keep-warm; every reason but the person's own stop says why in a toast. */
145const stopKeep = async ($: EngineInterface, why: 'prompt' | 'time' | 'cold' | 'failed' | 'manual') => {
146  if ((await read($, keepWarm)) === null) return
147  await update($, keepWarm, () => null)
148  if (why !== 'manual') $.ui.toast(WORDS[lang].keepStopped(why), { timeoutMs: 8000 })
149}
150
151/** Sends the keep-warm message: a real turn, once the session is idle; the turn's end refreshes the clock. */
152const sendKeep = async ($: EngineInterface) => {
153  keepSentAt = await $.clock.now()
154  try {
155    await $.prompt.submit({ text: KEEP_WARM_TEXT }).catch(() => {
156      keepSentAt = null
157      return stopKeep($, 'failed')
158    })
159  } catch {
160    keepSentAt = null
161    await stopKeep($, 'failed')
162  }
163}
164
165/** Once a second while a clock counts: redraws the band, sends keep-warm when due, toasts when the cache lapses. */
166const tick = async ($: EngineInterface) => {
167  const now = await $.clock.now()
168  const c = await read($, cache)
169  const clock = clockOf(c, now)
170  const kept = await read($, keepWarm)
171  const waiting = keepSentAt !== null && now - keepSentAt < KEEP_PATIENCE_MS
172  if (kept && now >= kept.until) await stopKeep($, 'time')
173  else if (kept && clock && c.ttl && !waiting) {
174    if (clock.state === 'cold') await stopKeep($, 'cold')
175    else if (clock.left <= keepMargin(c.ttl)) await sendKeep($)
176  }
177  if (clock?.state === 'cold' && coldFor !== c.lastAt) {
178    coldFor = c.lastAt
179    $.ui.toast(WORDS[lang].coldToast(tokens((await read($, snapshot)).contextTokens ?? 0)), { timeoutMs: 8000 })
180  }
181  if (!clock || clock.state === 'cold') stopTicker()
182  $.ui.invalidate('ui.render')
183}
184
185/** Starts the one-second tick while a clock is counting. */
186const ensureTicker = ($: EngineInterface) => {
187  if (ticker === null) ticker = $.clock.every(1000, () => void tick($).catch(() => undefined))
188}
189
190/** Asks, then turns keep-warm on; the answer is the line to show. It spends plan, so it waits for a yes. */
191const startKeep = async ($: EngineInterface): Promise<string> => {
192  const w = WORDS[lang]
193  if ((await read($, keepWarm)) !== null) return w.keepOn
194  if ((await read($, cache)).ttl === null) return w.keepNeedsTtl
195  const re = (await read($, snapshot)).contextTokens ?? 0
196  const answer = await $.ui.ask(w.keepAsk(tokens(re)), [w.keepYes, w.keepNo]).catch(() => w.keepNo)
197  if (answer !== w.keepYes) return w.keepOff
198  const now = await $.clock.now()
199  await update($, keepWarm, () => ({ until: now + KEEP_WARM_MAX_MS }))
200  ensureTicker($)
201  return w.keepOn
202}
203
204/** A costly switch with the 5-hour window at the threshold or more raises one toast. */
205const warnIfCostly = async ($: EngineInterface, from: Setting, to: Setting) => {
206  const s = await read($, snapshot)
207  const five = s.limits.find(l => l.kind === 'five_hour')
208  const readings = five && five.resetsAt !== null ? (await read($, samples))[five.kind] : undefined
209  const points = readings && five && readings.resetsAt === five.resetsAt ? readings.points : []
210  const text = switchWarning(from, to, five, await read($, switchAt), points, await read($, turns), await $.clock.now(), lang)
211  if (text) $.ui.toast(text, { timeoutMs: 8000 })
212}
213
214/**
215 * Where the effort came from, best first: a request (`turn.step`, the setting it asks for), the
216 * turn's end (`classic.Stop`, after any downgrade for the model), /config (the stored setting).
217 * The sources can disagree, so a weaker one never overwrites a stronger one, and only a change
218 * within one source counts as a switch: the band does not flip between a request's max and the
219 * high it was downgraded to, and no toast fires for it. A module variable: a reload starts over.
220 */
221const SOURCES = { request: 2, turnEnd: 1, config: 0 } as const
222let effortFrom: keyof typeof SOURCES | null = null
223
224/**
225 * An effort seen on the main thread, from `source`: kept for the band when no stronger source
226 * gave one, and a change within the same source to max may warn (never from /config). A source
227 * with no effort (a request that carries none) keeps the one known.
228 */
229const seeEffort = async ($: EngineInterface, level: string | number | null | undefined, source: keyof typeof SOURCES, id?: string | null) => {
230  if (level == null || level === '') return
231  if (effortFrom !== null && SOURCES[source] < SOURCES[effortFrom]) return
232  const was = effortFrom === source ? await read($, effort) : null
233  effortFrom = source
234  if (was === level) return
235  await update($, effort, () => level)
236  if (was !== null && source !== 'config') {
237    const current = id ?? (await read($, model))
238    await warnIfCostly($, { model: current, effort: was }, { model: current, effort: level })
239  }
240}
241
242/** The session's effort from /config: the first row named for effort whose value is a level. */
243const effortOfConfig = (rows: readonly { key: string; label: string; value: unknown }[]) => {
244  for (const r of rows) {
245    if (!/effort/i.test(r.key) && !/^(effort|esforço)/i.test(r.label)) continue
246    const level = effortLevel(r.value)
247    if (level) return level
248  }
249  return null
250}
251
252/** The effort drawn, band and pane alike: its gauge and its name, max in the warning color. */
253const effortView = (Text: Elements[keyof Elements]['Text'], level: string | number) => {
254  const max = level === 'max'
255  return [
256    ...(gauge(level) !== '' ? [<Text key="gauge" color={max ? 'warning' : undefined} dimColor={!max}>{`${gauge(level)} `}</Text>] : []),
257    <Text key="level" color={max ? 'warning' : undefined} bold={max}>{String(level)}</Text>,
258  ]
259}
260
261/** A threshold from /limits warn: a whole number from 1 to 100, else null. */
262const percentOf = (arg: string) => (/^\d{1,3}%?$/.test(arg) && Number.parseInt(arg, 10) >= 1 && Number.parseInt(arg, 10) <= 100 ? Number.parseInt(arg, 10) : null)
263
264/** The group colors: system and MCP have their own, messages take the context's tone. */
265const groupColor = (group: 'system' | 'mcp' | 'messages', percent: number | null) => (group === 'system' ? 'suggestion' : group === 'mcp' ? 'claude' : tone(percent))
266
267/** The cache cell's figure: the countdown, or `cold`; kept warm draws it in the accent. */
268const clockView = (Text: Elements[keyof Elements]['Text'], clock: { left: number; state: 'warm' | 'cooling' | 'cold' }, kept: boolean) => {
269  const w = WORDS[lang]
270  if (clock.state === 'cold') {
271    return (
272      <Text key="clock" color="error" bold>
273        {`${glyph(style, ICONS.cold)} ${w.coldWord}`}
274      </Text>
275    )
276  }
277  const color = kept ? 'claude' : clock.state === 'cooling' ? 'warning' : 'success'
278  return (
279    <Text key="clock" color={color} bold>
280      {`${glyph(style, kept ? ICONS.keep : ICONS.clock)} ${mmss(clock.left)}`}
281    </Text>
282  )
283}
284
285/** Presses of the keep-warm buttons: ask and say the answer, or stop. */
286const pressKeep = ($: EngineInterface) => startKeep($).then(text => $.ui.toast(text, { timeoutMs: 6000 }), () => $.ui.toast(WORDS[lang].failedToRun(`/${COMMAND} keep-warm on`)))
287
288const open = ($: EngineInterface) => $.ui.open({ id: PANE, title: WORDS[lang].pane, focus: true, closeOnEscape: true }).catch(() => null)
289
290/** /limits and its arguments: what the command answers, and what the pane's verbs run. */
291const runCommand = async ($: EngineInterface, args: string): Promise<{ text?: string }> => {
292  const w = WORDS[lang]
293  const [verb = '', arg = ''] = args.trim().toLowerCase().split(/\s+/)
294  if (verb === 'warn') {
295    if (arg === '') return { text: w.warnIs(await read($, switchAt)) }
296    const percent = percentOf(arg)
297    if (percent === null) return { text: w.help }
298    await setSwitchAt($, percent)
299    return { text: w.warnSet(percent) }
300  }
301  if (verb === 'keep-warm') {
302    if (arg === 'on') return { text: await startKeep($) }
303    if (arg === 'off') {
304      await stopKeep($, 'manual')
305      return { text: w.keepOff }
306    }
307    return { text: (await read($, keepWarm)) ? w.keepOn : w.keepOff }
308  }
309  switch (args.trim().toLowerCase()) {
310    case 'hide':
311      await setHidden($, true)
312      return { text: w.hidden }
313    case 'show':
314      await setHidden($, false)
315      return { text: w.shown }
316    case 'help':
317      return { text: w.help }
318    case '': {
319      const opened = await open($)
320      if (opened?.isPlaced) return {}
321      const list = await read($, turns)
322      return { text: summary(await read($, snapshot), list[list.length - 1], await $.clock.now(), lang) }
323    }
324    default:
325      return { text: w.help }
326  }
327}
328
329/** Puts a text in the prompt for the person to send; runs nothing. */
330const fill = async ($: EngineInterface, text: string) => {
331  await $.prompt.fill(fillArgs(text))
332}
333
334/** The pane's verbs: each one is undone by another, so all of them run. */
335const VERBS: readonly Verb[] = [{ verb: 'hide' }, { verb: 'show' }, { verb: 'keep-warm on' }, { verb: 'keep-warm off' }, { verb: 'help' }]
336
337/** A verb pressed in the pane: runs and writes its answer to the transcript. */
338const pressVerb = async ($: EngineInterface, v: Verb) => {
339  try {
340    if (v.fill) return await fill($, v.fill)
341    const { text } = await runCommand($, v.verb)
342    for (const line of linesOf(text)) $.ui.log(line)
343  } catch {
344    $.ui.toast(WORDS[lang].failedToRun(`/${COMMAND} ${v.verb}`))
345  }
346}
347
348export const register: Register = (on, options) => {
349  lang = langOf(options.language)
350  const num = (v: unknown, d: number) => (Number.isFinite(Number(v)) && v !== '' && v != null ? Math.max(1, Math.min(100, Number(v))) : d)
351  warnAt = num(options.warnAt, 70)
352  dangerAt = Math.max(warnAt, num(options.dangerAt, 90))
353  cells = cellsOf(options.cells)
354  density = options.density === 'bars' || options.density === 'mini' || options.density === 'numbers' ? options.density : 'auto'
355  format = options.format === 'compact' ? 'compact' : 'full'
356  style = styleOf(options.icons)
357
358  on('session.start', async ($, e, next) => {
359    const result = await next(e)
360    lang = langOf(options.language, await $.env.get('LANG').catch(() => undefined))
361    style = styleOf(options.icons, await $.env.get('TERMINAL_EMULATOR').catch(() => undefined))
362    steps = 0
363    keepSentAt = null
364    await $.command.register({
365      name: COMMAND,
366      description: WORDS[lang].description,
367      argumentHint: '[hide|show|keep-warm on|off|warn N|help]',
368      immediate: true,
369    })
370    const hidden = (await $.store.get(KEY_HIDDEN).catch(() => undefined)) === true
371    await update($, isHidden, () => hidden)
372    const kept = await $.store.get(KEY_SWITCH).catch(() => undefined)
373    await update($, switchAt, () => (typeof kept === 'number' && kept >= 1 && kept <= 100 ? kept : SWITCH_AT))
374    try {
375      const id = await $.session.model()
376      await update($, model, () => id || null)
377    } catch {
378      // The first turn.step brings it.
379    }
380    try {
381      await seeEffort($, effortOfConfig(await $.config.list()), 'config')
382    } catch {
383      // The first request or turn end brings it.
384    }
385    try {
386      const usage = await $.session.usage()
387      await update($, snapshot, () => toSnapshot(usage.context, usage.rateLimits))
388    } catch {
389      // No figures yet; the first session.measure brings them.
390    }
391    await takeGroups($)
392    return result
393  })
394
395  on('session.measure', async ($, e, next) => {
396    const result = await next(e)
397    await take($, toSnapshot(e.context, e.rateLimits))
398    await takeGroups($)
399    return result
400  })
401
402  on('turn.complete', async ($, e, next) => {
403    const result = await next(e)
404    if (!e.agentId && e.usage) {
405      const now = await $.clock.now()
406      // A keep-warm turn refreshes the cache but is no turn of the person's: it stays out of the table.
407      const kept = keepSentAt !== null
408      keepSentAt = null
409      const turn = { ...toTurn(e.usage, e.durationMs), contextPercent: (await read($, snapshot)).contextPercent, endedAt: now, steps }
410      steps = 0
411      const ttl = kept ? null : inferTtl((await read($, turns)).at(-1), turn)
412      await update($, cache, c => ({ lastAt: now, ttl: ttl ?? c.ttl }))
413      if (!kept) await update($, turns, list => [...list, turn].slice(-TURNS_KEPT))
414      if ((await read($, cache)).ttl !== null) ensureTicker($)
415    }
416    return result
417  })
418
419  // A switch to a costlier model: the band's model and, near the 5-hour limit, a toast. A resumed
420  // session restores its model, which is no switch. The new model may take no effort, or another
421  // default: the effort starts over and the next source fills it. Fail-open: the switch goes on.
422  on('classic.PostModelSwitch', async ($, e, next) => {
423    const result = await next(e)
424    await update($, model, () => e.to_model)
425    // The new model has no cache yet; the TTL is what the engine says it will use.
426    await update($, cache, c => ({ lastAt: null, ttl: e.cache_ttl ?? c.ttl }))
427    if (e.source !== 'resume') {
428      const now = await read($, effort)
429      await warnIfCostly($, { model: e.from_model, effort: now }, { model: e.to_model, effort: now })
430    }
431    if (e.from_model !== e.to_model) {
432      effortFrom = null
433      await update($, effort, () => null)
434    }
435    return result
436  }).catch(($, e, next) => next(e))
437
438  // The main loop's model and effort as each request goes out; effort turning to max warns here,
439  // on the first request at max, since a /effort command raises no event of its own.
440  on('turn.step', async function* ($, e, next) {
441    if (!e.agentId) {
442      steps += 1
443      try {
444        await update($, model, () => e.model)
445        await seeEffort($, e.effort, 'request', e.model)
446      } catch {
447        // The band keeps what it had; the request goes on.
448      }
449    }
450    return yield* next(e)
451  })
452
453  // The turn's end carries its effort too (`effort.level`), where the requests carry none. One a
454  // turn on main, in order: unlike PostToolUse, which may run in parallel and toast twice.
455  on('classic.Stop', async ($, e, next) => {
456    const result = await next(e)
457    if (!e.agent_id) await seeEffort($, e.effort?.level, 'turnEnd')
458    return result
459  }).catch(($, e, next) => next(e))
460
461  // The person's own prompt refreshes the cache, so keep-warm has nothing left to do.
462  on('prompt.submit', async ($, e, next) => {
463    if (e.origin?.kind !== 'plugin') await stopKeep($, 'prompt')
464    return next(e)
465  })
466
467  // The keep-warm message is a real turn; the transcript draws it as one dim row.
468  on('ui.render', { component: 'UserMessage' }, async ($, e, next) => {
469    if (e.props.origin.kind !== 'plugin' || !e.props.text.includes('Keep-warm ping from limits-meter')) return next(e)
470    const { Text } = $.ui.resolve(e)
471    return <Text dimColor>{WORDS[lang].keepRow}</Text>
472  })
473
474  on('command.run', { command: COMMAND }, ($, e) => runCommand($, e.args))
475
476  on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
477    if (e.props.hasSurvey || (await read($, isHidden))) return next(e)
478    const s = await read($, snapshot)
479    if (s.limits.length === 0 && s.contextPercent === null) return next(e)
480
481    const { Box, Text, Button } = $.ui.resolve(e)
482    const w = WORDS[lang]
483    const now = await $.clock.now()
484    const list = await read($, turns)
485    const last = list[list.length - 1]
486    const clock = clockOf(await read($, cache), now)
487    const kept = (await read($, keepWarm)) !== null
488    const g = await read($, groups)
489    const parts = g && s.contextPercent !== null ? splitOf(s.contextPercent, g) : null
490    const columns = e.props.bodyColumns || e.viewport?.columns || 80
491    const width = barWidth(columns)
492    const meter = (percent: number) =>
493      width > 0 ? <Text color={tone(percent)}>{`${bar(width, percent)} `}</Text> : width === 0 ? <Text color={tone(percent)}>{mini(percent)}</Text> : null
494    // The context bar split by group when the engine gave a breakdown: solid cells per group, free shaded.
495    const ctxMeter = (percent: number) => {
496      if (!parts || width <= 0) return meter(percent)
497      const c = barCells(width, parts)
498      return (
499        <Text>
500          <Text color={groupColor('system', percent)}>{'█'.repeat(c.system)}</Text>
501          <Text color={groupColor('mcp', percent)}>{'█'.repeat(c.mcp)}</Text>
502          <Text color={groupColor('messages', percent)}>{'█'.repeat(c.messages)}</Text>
503          <Text dimColor>{`${'░'.repeat(c.free)} `}</Text>
504        </Text>
505      )
506    }
507    const id = await read($, model)
508    const level = await read($, effort)
509    // The model in the accent color; the effort as a five-step gauge and its name, max in warning.
510    const setting =
511      (id || level !== null) && shows('model') ? (
512        <Text key="model">
513          {id && <Text color="claude" bold>{shortModel(id)}</Text>}
514          {id && level !== null && <Text> </Text>}
515          {level !== null && effortView(Text, level)}
516        </Text>
517      ) : null
518
519    const verbs = [
520      ...(clock?.state === 'cooling' && !kept ? [<Button key="keep" label={w.keepWarm} plain color="warning" onPress={() => void pressKeep($)} />] : []),
521      ...(kept ? [<Button key="keep-stop" label={w.keepStop} plain dimColor onPress={() => void stopKeep($, 'manual')} />] : []),
522      ...(needsCompact(s) ? [<Button key="compact" label={w.compact} plain color="warning" onPress={() => fill($, w.compactFill)} />] : []),
523      <Button key="details" label={w.details} plain dimColor onPress={() => open($)} />,
524      <Button key="hide" label={w.hide} plain dimColor onPress={() => setHidden($, true)} />,
525    ]
526
527    if (format === 'compact') {
528      // model · effort · ctx 8% · 5h 34% · wk 31%: numbers only, one line.
529      const cell = (key: string, name: string, percent: number | null) => (
530        <Text key={key}>
531          <Text dimColor>{`${name} `}</Text>
532          <Text color={tone(percent)} bold>{pct(percent)}</Text>
533        </Text>
534      )
535      const parts = [
536        ...(setting ? [setting] : []),
537        ...(shows('ctx') ? [cell('ctx', 'ctx', s.contextPercent)] : []),
538        ...s.limits.filter(l => shows(CELL_IDS[l.kind] ?? l.kind)).map(l => cell(l.kind, label(l.kind, lang), l.percent)),
539      ]
540      const line = (
541        <Box key="limits-meter" flexDirection="row" flexWrap="wrap" gap={2} paddingX={1}>
542          <Text key="numbers">{parts.flatMap((p, i) => (i > 0 ? [<Text key={`sep-${i}`} dimColor> · </Text>, p] : [p]))}</Text>
543          {verbs}
544        </Box>
545      )
546      const beneath = await next(e)
547      return beneath ? (
548        <Box flexDirection="column">
549          {line}
550          {beneath}
551        </Box>
552      ) : (
553        line
554      )
555    }
556
557    const band = [
558      ...(setting ? [setting] : []),
559      ...s.limits
560        .filter(l => shows(CELL_IDS[l.kind] ?? l.kind))
561        .map(l => {
562          const reset = resetIn(l.resetsAt, now, lang)
563          return (
564            <Text key={l.kind}>
565              <Text dimColor>{`${label(l.kind, lang)} `}</Text>
566              {meter(l.percent)}
567              <Text color={tone(l.percent)} bold>{pct(l.percent)}</Text>
568              {reset !== '' && <Text dimColor>{` ↻${reset}`}</Text>}
569            </Text>
570          )
571        }),
572      ...(shows('ctx')
573        ? [
574            <Text key="ctx">
575              <Text dimColor>ctx </Text>
576              {s.contextPercent !== null && ctxMeter(s.contextPercent)}
577              <Text color={tone(s.contextPercent)} bold>{pct(s.contextPercent)}</Text>
578            </Text>,
579          ]
580        : []),
581      ...((clock || last?.cacheHit != null) && shows('cache')
582        ? [
583            <Text key="cache">
584              <Text dimColor>cache </Text>
585              {clock ? clockView(Text, clock, kept) : <Text>{pct(last!.cacheHit! * 100)}</Text>}
586            </Text>,
587          ]
588        : []),
589    ]
590
591    // The legend under the cells: which color is which group, with its share of the window.
592    const legend =
593      parts && g && shows('ctx') ? (
594        <Box key="legend" flexDirection="row" paddingX={1}>
595          <Text>
596            <Text dimColor>{`${w.ctxLabel}  `}</Text>
597            <Text color={groupColor('system', s.contextPercent)}>{`█ ${w.groups.system} ${parts.system}%`}</Text>
598            {g.mcp > 0 && <Text dimColor> · </Text>}
599            {g.mcp > 0 && <Text color={groupColor('mcp', s.contextPercent)}>{`█ ${w.groups.mcp} ${parts.mcp}%`}</Text>}
600            <Text dimColor> · </Text>
601            <Text color={groupColor('messages', s.contextPercent)}>{`█ ${w.groups.messages} ${parts.messages}%`}</Text>
602            <Text dimColor>{` · ░ ${w.groups.free} ${parts.free}%`}</Text>
603          </Text>
604        </Box>
605      ) : null
606
607    const row = (
608      <Box key="band" flexDirection="row" flexWrap="wrap" gap={2} paddingX={1}>
609        {band}
610        {verbs}
611      </Box>
612    )
613    const mine = legend ? (
614      <Box key="limits-meter" flexDirection="column">
615        {row}
616        {legend}
617      </Box>
618    ) : (
619      row
620    )
621    const theirs = await next(e)
622    return theirs ? (
623      <Box flexDirection="column">
624        {mine}
625        {theirs}
626      </Box>
627    ) : (
628      mine
629    )
630  })
631
632  on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
633    const { Box, Text, Button } = $.ui.resolve(e)
634    const w = WORDS[lang]
635    const s = await read($, snapshot)
636    const list = await read($, turns)
637    const readings = await read($, samples)
638    const now = await $.clock.now()
639    const columns = Math.max(30, (e.props.bodyColumns || e.viewport?.columns || 80) - 2)
640    const width = Math.max(10, Math.min(40, columns - 30))
641    const paces = s.limits.map(l => {
642      const points = readings[l.kind]
643      return l.resetsAt !== null && points && points.resetsAt === l.resetsAt ? pace(points.points, now, l.resetsAt) : null
644    })
645    const trend = list.filter(t => t.contextPercent != null)
646    const top = heaviest(list)
647    const id = await read($, model)
648    const level = await read($, effort)
649    const at = await read($, switchAt)
650    const choices = [...new Set([...SWITCH_CHOICES, at])].sort((a, b) => a - b)
651    const c = await read($, cache)
652    const clock = clockOf(c, now)
653    const keep = await read($, keepWarm)
654    const g = await read($, groups)
655    const parts = g && s.contextPercent !== null ? splitOf(s.contextPercent, g) : null
656    const lastTurn = list[list.length - 1]
657    const re = tokens(s.contextTokens ?? 0)
658    // The cache sentence of the state: kept warm, or warm, cooling or cold.
659    const sentence = keep ? w.cacheKeeping(resetIn(keep.until, now, lang)) : clock?.state === 'cold' ? w.cacheCold(re) : clock?.state === 'cooling' ? w.cacheCooling(re) : w.cacheWarm(re)
660    const share = (n: number) => `${((n / (g?.window || 1)) * 100).toFixed(n / (g?.window || 1) < 0.1 ? 1 : 0)}%`
661    const usedTokens = g ? g.system + g.mcp + g.messages : 0
662    // Rows besides the turns: the hint, three headings, the context row, the table head, the
663    // footer, the gaps, a pace line per window that has one and the trend line; then the
664    // costly-switch section (heading, hint, choices, order, gap) and the model's (heading, row, gap).
665    const fixed = 12 + (g ? g.rows.length + 4 : 0) + 5 + Math.max(1, s.limits.length) + paces.filter(p => p !== null).length + (trend.length > 1 ? 1 : 0) + 5 + (id || level !== null ? 3 : 0)
666    const room = Math.max(3, (e.props.scroll?.bodyRows ?? e.viewport?.rows ?? 30) - fixed)
667    const [cIn, cOut, cCache, cTime, cModel] = w.columns
668
669    return (
670      <Box flexDirection="column" paddingX={1} gap={1}>
671        <Text dimColor>{w.hint}</Text>
672
673        <Box flexDirection="column">
674          <Text bold>{w.planWindows}</Text>
675          {s.limits.length === 0 && <Text dimColor>{w.noWindows}</Text>}
676          {s.limits.map((l, i) => {
677            const left = paces[i]
678            return (
679              <Box key={l.kind} flexDirection="column">
680                <Text>
681                  <Text dimColor>{label(l.kind, lang).padEnd(6)}</Text>
682                  <Text color={tone(l.percent)}>{bar(width, l.percent)}</Text>
683                  <Text bold>{` ${pct(l.percent).padStart(4)}`}</Text>
684                  <Text dimColor>{l.resetsAt !== null ? `  ${w.resetsIn(resetIn(l.resetsAt, now, lang))}` : ''}</Text>
685                </Text>
686                {left != null && <Text color="warning">{`      ${w.pace(label(l.kind, lang), resetIn(now + left, now, lang))}`}</Text>}
687              </Box>
688            )
689          })}
690        </Box>
691
692        <Box flexDirection="column">
693          <Text bold>{w.cacheHeading}</Text>
694          {clock && c.ttl ? (
695            <Box flexDirection="column">
696              <Box flexDirection="row" flexWrap="wrap" gap={2}>
697                <Text>
698                  {clockView(Text, clock, keep !== null)}
699                  <Text dimColor>{`  ${w.cacheOf(c.ttl === '1h' ? '1 h' : '5 min')}`}</Text>
700                </Text>
701                {keep === null && clock.state !== 'cold' && <Button key="keep" label={w.keepWarm} plain color="warning" onPress={() => void pressKeep($)} />}
702                {keep !== null && <Button key="keep-stop" label={w.keepStop} plain dimColor onPress={() => void stopKeep($, 'manual')} />}
703              </Box>
704              <Text dimColor>{sentence}</Text>
705            </Box>
706          ) : (
707            <Text dimColor>{w.cacheUnknown}</Text>
708          )}
709          {lastTurn?.cacheHit != null && <Text dimColor>{w.hitRate(pct(lastTurn.cacheHit * 100))}</Text>}
710        </Box>
711
712        <Box flexDirection="column">
713          <Text bold>{w.contextHeading}</Text>
714          <Box flexDirection="row" flexWrap="wrap" gap={2}>
715            <Text>
716              <Text dimColor>{'ctx   '}</Text>
717              {parts && s.contextPercent !== null ? (
718                <Text>
719                  <Text color={groupColor('system', s.contextPercent)}>{'█'.repeat(barCells(width, parts).system)}</Text>
720                  <Text color={groupColor('mcp', s.contextPercent)}>{'█'.repeat(barCells(width, parts).mcp)}</Text>
721                  <Text color={groupColor('messages', s.contextPercent)}>{'█'.repeat(barCells(width, parts).messages)}</Text>
722                  <Text dimColor>{'░'.repeat(barCells(width, parts).free)}</Text>
723                </Text>
724              ) : (
725                <Text color={tone(s.contextPercent)}>{bar(width, s.contextPercent ?? 0)}</Text>
726              )}
727              <Text bold>{` ${pct(s.contextPercent).padStart(4)}`}</Text>
728              <Text dimColor>{s.contextTokens !== null ? `  ${w.ofWindow(tokens(s.contextTokens), tokens(s.contextWindow))}` : ''}</Text>
729            </Text>
730            {needsCompact(s) && <Button key="compact" label={w.compact} plain color="warning" onPress={() => fill($, w.compactFill)} />}
731          </Box>
732          {trend.length > 1 && (
733            <Text>
734              <Text dimColor>{'      '}</Text>
735              <Text color={tone(s.contextPercent)}>{contextSpark(list.slice(-width))}</Text>
736              <Text dimColor>{`  ${w.trend(Math.min(list.length, width))}`}</Text>
737            </Text>
738          )}
739          {g && (
740            <Box flexDirection="column">
741              <Text dimColor>{`      ${w.breakdownHead}`}</Text>
742              {g.rows.map(r => (
743                <Text key={`row-${r.name}`}>
744                  <Text color={groupColor(r.group, s.contextPercent)}>{'      █ '}</Text>
745                  <Text>{clip(r.name, 22).padEnd(22)}</Text>
746                  <Text>{tokens(r.tokens).padStart(6)}</Text>
747                  <Text dimColor>{share(r.tokens).padStart(7)}</Text>
748                </Text>
749              ))}
750              <Text dimColor>{`      ░ ${w.groups.free.padEnd(22)}${tokens(Math.max(0, g.window - usedTokens)).padStart(6)}${share(Math.max(0, g.window - usedTokens)).padStart(7)}`}</Text>
751              <Text dimColor>{`      ${w.breakdownNote}`}</Text>
752            </Box>
753          )}
754        </Box>
755
756        {(id || level !== null) && (
757          <Box flexDirection="column">
758            <Text bold>{w.modelHeading}</Text>
759            <Text>
760              {id && <Text color="claude" bold>{shortModel(id)}</Text>}
761              {level !== null && <Text dimColor>{`${id ? '   ' : ''}${w.effort} `}</Text>}
762              {level !== null && effortView(Text, level)}
763            </Text>
764          </Box>
765        )}
766
767        <Box flexDirection="column">
768          <Text bold>{w.warnHeading}</Text>
769          <Text dimColor>{w.warnHint}</Text>
770          <Box flexDirection="row" flexWrap="wrap">
771            {choices.map((n, i) => (
772              <Box key={`warn-${n}`} flexDirection="row">
773                {i > 0 && <Text dimColor> · </Text>}
774                {n === at ? (
775                  <Text color="claude" bold>{`${n}%`}</Text>
776                ) : (
777                  <Button key={`warn:${n}`} plain dimColor label={`${n}%`} onPress={() => setSwitchAt($, n).then(() => $.ui.toast(w.warnSet(n)), () => $.ui.toast(w.failedToRun(`/${COMMAND} warn ${n}`)))} />
778                )}
779              </Box>
780            ))}
781          </Box>
782          <Text dimColor>{w.warnOrder}</Text>
783        </Box>
784
785        <Box flexDirection="column">
786          <Text bold>{w.turns}</Text>
787          {list.length === 0 && <Text dimColor>{w.noTurns}</Text>}
788          {list.length > 0 && <Text dimColor>{`    ${cIn.padStart(8)}${cOut.padStart(8)}${cCache.padStart(7)}${cTime.padStart(7)}  ${cModel}`}</Text>}
789          {list.slice(-room).map((t, i, shown) => {
790            const isTop = list.length > 1 && t === top
791            return (
792              <Text key={`turn-${list.length - shown.length + i}`}>
793                <Text dimColor>{`#${list.length - shown.length + i + 1}`.padEnd(4)}</Text>
794                <Text color={isTop ? 'claude' : undefined} bold={isTop}>{tokens(t.input).padStart(8)}</Text>
795                <Text>{tokens(t.output).padStart(8)}</Text>
796                <Text color={t.cacheHit !== null && t.cacheHit < 0.5 ? 'warning' : undefined}>{pct(t.cacheHit === null ? null : t.cacheHit * 100).padStart(7)}</Text>
797                <Text dimColor>{`${`${Math.round(t.durationMs / 1000)}s`.padStart(7)}  ${shortModel(t.model)}`}</Text>
798              </Text>
799            )
800          })}
801        </Box>
802
803        <Box flexDirection="row" flexWrap="wrap" gap={2}>
804          {verbRow({ Box, Text, Button }, COMMAND, VERBS, v => pressVerb($, v))}
805          <Button key="close" role="dismiss" label={w.close} onPress={() => $.ui.close({ id: PANE })} />
806        </Box>
807      </Box>
808    )
809  })
810}
811
hooks/meter.ts 354 lines
1import type { CacheClock, ContextGroups, ContextRow, Limit, Samples, Snapshot, Ttl, Turn } from '../types'
2import type { Lang } from './ui'
3import { WORDS } from './words'
4
5export const LIMIT_ALERTS = [80, 90, 100]
6export const CONTEXT_ALERT = 85
7/** Below this the context alert re-arms (after a compaction or /clear). */
8export const CONTEXT_REARM = 50
9export const TURNS_KEPT = 20
10/** Readings kept per plan window for the pace, and how far apart they need to be. */
11export const SAMPLES_KEPT = 60
12const SAMPLE_GAP_MS = 60_000
13/** The pace needs readings over this long before it says anything. */
14const PACE_SPAN_MS = 10 * 60_000
15
16export const label = (kind: string, lang: Lang = 'en') => WORDS[lang].labels[kind] ?? kind
17
18/** Context full enough that the band and the pane offer /compact. */
19export const needsCompact = (s: Snapshot) => s.contextPercent !== null && s.contextPercent >= CONTEXT_ALERT
20
21type RateLimitIn = { kind: string; percentUsed: number; resetsAt?: string }
22type ContextIn = { tokens?: number; window: number; percent?: number }
23
24export const toSnapshot = (context: ContextIn, rateLimits: readonly RateLimitIn[]): Snapshot => ({
25  limits: rateLimits.map(r => {
26    const at = r.resetsAt ? Date.parse(r.resetsAt) : NaN
27    return { kind: r.kind, percent: r.percentUsed, resetsAt: Number.isFinite(at) ? at : null }
28  }),
29  contextPercent: context.percent ?? null,
30  contextTokens: context.tokens ?? null,
31  contextWindow: context.window,
32})
33
34/** "3d4h", "1h12", "7m", "now"; "" when unknown. */
35export const resetIn = (at: number | null, now: number, lang: Lang = 'en') => {
36  if (at === null) return ''
37  const minutes = Math.max(0, Math.round((at - now) / 60_000))
38  if (minutes === 0) return WORDS[lang].now
39  if (minutes < 60) return `${minutes}m`
40  const hours = Math.floor(minutes / 60)
41  if (hours < 24) return `${hours}h${String(minutes % 60).padStart(2, '0')}`
42  return `${Math.floor(hours / 24)}d${hours % 24}h`
43}
44
45export const pct = (n: number | null) => (n === null ? '–' : `${Math.round(n)}%`)
46
47export const bar = (width: number, percent: number) => {
48  const filled = Math.round((Math.max(0, Math.min(100, percent)) / 100) * width)
49  return '█'.repeat(filled) + '░'.repeat(width - filled)
50}
51
52/** The theme's colors: error from `dangerAt` (90%), warning from `warnAt` (70%), success below. */
53export const tone = (percent: number | null, warnAt = 70, dangerAt = 90) =>
54  percent === null ? undefined : percent >= dangerAt ? 'error' : percent >= warnAt ? 'warning' : 'success'
55
56const CELLS = '▁▂▃▄▅▆▇█'
57
58/** One cell for a percent, ▁ empty to █ full: the bar of a narrow terminal. */
59export const mini = (percent: number) => CELLS[Math.round((Math.max(0, Math.min(100, percent)) / 100) * 7)]!
60
61/** Context fill per turn, oldest first, on the 0 to 100 scale; a turn with no reading is a space. */
62export const contextSpark = (turns: readonly Turn[]) => turns.map(t => (t.contextPercent == null ? ' ' : mini(t.contextPercent))).join('')
63
64/** The turn with the most input, the one to look at first; undefined with no turns. */
65export const heaviest = (turns: readonly Turn[]) => turns.reduce<Turn | undefined>((top, t) => (!top || t.input > top.input ? t : top), undefined)
66
67/**
68 * The readings with the snapshot's added: one per window a minute apart at least, dropped when
69 * the window resets (its reset time moves), at most SAMPLES_KEPT.
70 */
71export const addSamples = (samples: Samples, s: Snapshot, now: number): Samples => {
72  const next: Samples = { ...samples }
73  for (const l of s.limits) {
74    if (l.resetsAt === null) continue
75    const was = samples[l.kind]
76    const points = was && was.resetsAt === l.resetsAt ? was.points : []
77    const last = points[points.length - 1]
78    if (last && now - last[0] < SAMPLE_GAP_MS && last[1] === l.percent) continue
79    const kept = last && now - last[0] < SAMPLE_GAP_MS ? points.slice(0, -1) : points
80    next[l.kind] = { resetsAt: l.resetsAt, points: [...kept, [now, l.percent] as [number, number]].slice(-SAMPLES_KEPT) }
81  }
82  return next
83}
84
85/**
86 * Milliseconds until the window reaches 100% at the pace of its readings (a least-squares
87 * line), or null: too few readings, too short a span, a flat or falling pace, or a window that
88 * resets first.
89 */
90export const pace = (points: readonly (readonly [number, number])[], now: number, resetsAt: number): number | null => {
91  if (points.length < 3) return null
92  const first = points[0]![0]
93  const last = points[points.length - 1]!
94  if (last[0] - first < PACE_SPAN_MS) return null
95  const n = points.length
96  const mx = points.reduce((a, p) => a + (p[0] - first), 0) / n
97  const my = points.reduce((a, p) => a + p[1], 0) / n
98  const sxx = points.reduce((a, p) => a + (p[0] - first - mx) ** 2, 0)
99  const sxy = points.reduce((a, p) => a + (p[0] - first - mx) * (p[1] - my), 0)
100  const slope = sxx > 0 ? sxy / sxx : 0
101  if (slope <= 0) return null
102  const at = first + mx + (100 - my) / slope
103  const left = Math.max(0, at - now)
104  return now + left < resetsAt ? left : null
105}
106
107export const toTurn = (
108  usage: { input_tokens: number; output_tokens: number; cache_read_input_tokens: number; cache_creation_input_tokens: number; model: string },
109  durationMs: number,
110): Turn => {
111  const input = usage.input_tokens + usage.cache_read_input_tokens + usage.cache_creation_input_tokens
112  return {
113    input,
114    output: usage.output_tokens,
115    cacheHit: input > 0 ? usage.cache_read_input_tokens / input : null,
116    model: usage.model,
117    durationMs,
118  }
119}
120
121export type Alert = { key: string; text: string }
122
123/**
124 * Alerts the snapshot raises that have not fired yet. A limit alert is keyed by its window's
125 * reset time, so a new window re-arms it; the context alert re-arms once the fill drops below
126 * CONTEXT_REARM. Returns the alerts and the fired list to store.
127 */
128export const alerts = (s: Snapshot, fired: readonly string[], now: number, lang: Lang = 'en'): { raised: Alert[]; fired: string[] } => {
129  const w = WORDS[lang]
130  let next = [...fired]
131  const raised: Alert[] = []
132  for (const limit of s.limits) {
133    const hit = LIMIT_ALERTS.filter(t => limit.percent >= t)
134    const top = hit[hit.length - 1]
135    if (top === undefined) continue
136    const keys = hit.map(t => `${limit.kind}:${limit.resetsAt ?? '-'}:${t}`)
137    if (keys.every(k => next.includes(k))) continue
138    next = [...next, ...keys.filter(k => !next.includes(k))]
139    raised.push({ key: keys[keys.length - 1]!, text: w.windowAlert(label(limit.kind, lang), pct(limit.percent), resetIn(limit.resetsAt, now, lang)) })
140  }
141  const contextKey = `context:${CONTEXT_ALERT}`
142  if (s.contextPercent !== null && s.contextPercent < CONTEXT_REARM) next = next.filter(k => k !== contextKey)
143  if (s.contextPercent !== null && s.contextPercent >= CONTEXT_ALERT && !next.includes(contextKey)) {
144    next = [...next, contextKey]
145    raised.push({ key: contextKey, text: w.contextAlert(pct(s.contextPercent)) })
146  }
147  return { raised, fired: next }
148}
149
150/** One-line text summary, for the command's answer where no pane can open. */
151export const summary = (s: Snapshot, last: Turn | undefined, now: number, lang: Lang = 'en') => {
152  const w = WORDS[lang]
153  const parts = s.limits.map(l => `${label(l.kind, lang)} ${pct(l.percent)}${l.resetsAt !== null ? ` (${w.resetsIn(resetIn(l.resetsAt, now, lang))})` : ''}`)
154  parts.push(`${w.context} ${pct(s.contextPercent)}`)
155  if (last?.cacheHit != null) parts.push(`cache ${pct(last.cacheHit * 100)}`)
156  if (s.limits.length === 0) parts.push(w.noReadings)
157  return parts.join(' · ')
158}
159
160/** Effort levels from least to most thinking, the gauge's five steps. */
161export const EFFORT_LEVELS = ['low', 'medium', 'high', 'xhigh', 'max'] as const
162
163/** The level an effort value names, or null: a string from EFFORT_LEVELS, any case. */
164export const effortLevel = (v: unknown) => {
165  const level = typeof v === 'string' ? v.toLowerCase() : ''
166  return (EFFORT_LEVELS as readonly string[]).includes(level) ? level : null
167}
168
169/** Effort as a five-step gauge, low ▰▱▱▱▱ to max ▰▰▰▰▰; "" for a level outside the list. */
170export const gauge = (level: string | number | null | undefined) => {
171  const n = EFFORT_LEVELS.indexOf(String(level) as (typeof EFFORT_LEVELS)[number]) + 1
172  return n > 0 ? '▰'.repeat(n) + '▱'.repeat(EFFORT_LEVELS.length - n) : ''
173}
174
175/** Models from cheapest to costliest; a switch up this list is a costly one. */
176export const MODEL_ORDER = ['haiku', 'sonnet', 'opus', 'fable'] as const
177
178/** A model's place in MODEL_ORDER, or -1 for a model it does not name. */
179export const rankOf = (model: string | null | undefined) => {
180  const name = (model ?? '').toLowerCase()
181  return MODEL_ORDER.findIndex(family => name.includes(family))
182}
183
184/** Whether going from one model to another climbs MODEL_ORDER; an unknown model never does. */
185export const isCostlier = (from: string | null | undefined, to: string | null | undefined) => {
186  const a = rankOf(from)
187  const b = rankOf(to)
188  return a >= 0 && b > a
189}
190
191/** Turns the toast's pace reads: the last few, as the plan item says. */
192export const PACE_TURNS = 3
193
194/**
195 * Minutes until the 5-hour window reaches 100% at the pace of the last PACE_TURNS main-thread
196 * turns, or null: fewer turns than that, or no rise. The pace comes from the window's own
197 * timestamped readings (`points`, as addSamples keeps them) since the first of those turns
198 * started; the turns only bound the span, so a reading that lands after its turn still counts.
199 */
200export const minutesLeft = (five: Limit, points: readonly (readonly [number, number])[], recentTurns: readonly Turn[]): number | null => {
201  const ended = recentTurns.filter(t => t.endedAt != null)
202  if (ended.length < PACE_TURNS) return null
203  const first = ended[ended.length - PACE_TURNS]!
204  const since = first.endedAt! - first.durationMs
205  const span = points.filter(p => p[0] >= since)
206  if (span.length < 2) return null
207  const [t0, p0] = span[0]!
208  const [t1, p1] = span[span.length - 1]!
209  if (t1 <= t0 || p1 <= p0) return null
210  return Math.max(0, Math.round(((100 - five.percent) * (t1 - t0)) / (p1 - p0) / 60_000))
211}
212
213/** What the session runs: a model id and the effort of its last request. */
214export type Setting = { model: string | null; effort: string | number | null }
215
216/**
217 * The toast for a costly switch (a model up MODEL_ORDER, or effort turning to max) with the
218 * 5-hour window at `threshold` or more, or null when there is nothing to say. With a pace, the
219 * minutes left; when the window resets before that, its reset time; with no pace, no number.
220 */
221export const switchWarning = (
222  from: Setting,
223  to: Setting,
224  five: Limit | undefined,
225  threshold: number,
226  points: readonly (readonly [number, number])[],
227  recentTurns: readonly Turn[],
228  now: number,
229  lang: Lang = 'en',
230): string | null => {
231  const toModel = isCostlier(from.model, to.model)
232  const toMax = to.effort === 'max' && from.effort !== 'max'
233  if (!toModel && !toMax) return null
234  if (!five || five.percent < threshold) return null
235  const w = WORDS[lang]
236  const percent = pct(five.percent)
237  const minutes = minutesLeft(five, points, recentTurns)
238  if (minutes !== null) {
239    const runsOutAt = now + minutes * 60_000
240    if (five.resetsAt !== null && runsOutAt >= five.resetsAt) return w.switchResets(percent, resetIn(five.resetsAt, now, lang))
241    return w.switchPace(percent, minutes < 60 ? `${minutes} min` : resetIn(runsOutAt, now, lang))
242  }
243  return w.switchFaster(percent, toModel ? MODEL_ORDER[rankOf(to.model)]! : 'effort max')
244}
245
246/** How long each cache lives after the request that refreshed it. */
247export const TTL_MS: Record<Ttl, number> = { '5m': 5 * 60_000, '1h': 60 * 60_000 }
248
249/** The cache is "cooling" this long before it goes cold: 10 minutes of the hour, a fifth of the 5 minutes. */
250export const coolMs = (ttl: Ttl) => Math.min(10 * 60_000, TTL_MS[ttl] / 5)
251
252export type Clock = { left: number; state: 'warm' | 'cooling' | 'cold' }
253
254/** Time left on the cache and its state; null while the last request or the TTL is unknown. */
255export const clockOf = (c: CacheClock, now: number): Clock | null => {
256  if (c.lastAt === null || c.ttl === null) return null
257  const left = Math.max(0, c.lastAt + TTL_MS[c.ttl] - now)
258  return { left, state: left === 0 ? 'cold' : left <= coolMs(c.ttl) ? 'cooling' : 'warm' }
259}
260
261/** 52:10; the seconds round up, so a cache with 1 ms left still reads 00:01. */
262export const mmss = (ms: number) => {
263  const s = Math.ceil(Math.max(0, ms) / 1000)
264  return `${String(Math.floor(s / 60)).padStart(2, '0')}:${String(s % 60).padStart(2, '0')}`
265}
266
267/** Keep-warm sends this long before the cache goes cold: 5 minutes of the hour, 30 seconds of the 5 minutes. */
268export const keepMargin = (ttl: Ttl) => Math.min(5 * 60_000, TTL_MS[ttl] / 10)
269
270/** Keep-warm stops by itself after this long. */
271export const KEEP_WARM_MAX_MS = 2 * 60 * 60_000
272
273/** What keep-warm sends. The model reads it framed as a plugin's message; the transcript draws a dim row instead. */
274export const KEEP_WARM_TEXT = 'Keep-warm ping from limits-meter. Reply with a single "." and nothing else.'
275
276/**
277 * The TTL a turn shows, or null. Only a turn of one request counts (its hit rate is that
278 * request's own): after more than 5 minutes idle, a high hit means the cache lived past 5
279 * minutes (1h); a near-zero hit within the hour means it lapsed (5m). A compaction or a changed
280 * prompt also reads near zero, so a later `cache_ttl` or turn overrides it.
281 */
282export const inferTtl = (prev: Turn | undefined, cur: Turn): Ttl | null => {
283  if (prev?.endedAt == null || cur.endedAt == null || cur.steps !== 1 || cur.cacheHit === null) return null
284  const gap = cur.endedAt - cur.durationMs - prev.endedAt
285  if (gap <= TTL_MS['5m'] + 30_000) return null
286  if (cur.cacheHit >= 0.5) return '1h'
287  return gap < TTL_MS['1h'] - 60_000 && cur.cacheHit < 0.2 ? '5m' : null
288}
289
290/** Whole numbers from `weights` that add up to `total` (largest remainder); a weight above 0 gets 1 at least when `total` allows. */
291export const apportion = (total: number, weights: readonly number[]): number[] => {
292  const sum = weights.reduce((a, b) => a + b, 0)
293  if (sum <= 0 || total <= 0) return weights.map(() => 0)
294  const exact = weights.map(w => (w / sum) * total)
295  const out = exact.map(Math.floor)
296  let left = total - out.reduce((a, b) => a + b, 0)
297  for (const [, i] of exact.map((x, i) => [x - Math.floor(x), i] as const).sort((a, b) => b[0] - a[0])) {
298    if (left <= 0) break
299    out[i]!++
300    left--
301  }
302  if (total >= weights.filter(w => w > 0).length) {
303    weights.forEach((w, i) => {
304      if (w > 0 && out[i] === 0) {
305        out[out.indexOf(Math.max(...out))]!--
306        out[i] = 1
307      }
308    })
309  }
310  return out
311}
312
313type CategoryIn = { name: string; tokens: number; kind: string }
314type McpToolIn = { serverName: string; tokens: number; isLoaded: boolean }
315
316/**
317 * The engine's breakdown rows in the band's groups: MCP (one row per server with a loaded tool),
318 * messages, and everything else in use as system. Free space, the compaction buffer and deferred
319 * schemas are not in use. Null without a window to measure against.
320 */
321export const groupContext = (b: { categories: readonly CategoryIn[]; maxTokens: number; mcpTools?: readonly McpToolIn[] }): ContextGroups | null => {
322  if (!(b.maxTokens > 0)) return null
323  const servers = new Map<string, number>()
324  for (const t of b.mcpTools ?? []) if (t.isLoaded) servers.set(t.serverName, (servers.get(t.serverName) ?? 0) + t.tokens)
325  const rows: ContextRow[] = []
326  for (const c of b.categories) {
327    if (c.kind !== 'used' || c.tokens <= 0) continue
328    if (/mcp/i.test(c.name)) {
329      if (servers.size === 0) rows.push({ name: c.name, tokens: c.tokens, group: 'mcp' })
330      else for (const [server, tokens] of servers) rows.push({ name: `MCP · ${server}`, tokens, group: 'mcp' })
331      continue
332    }
333    rows.push({ name: c.name, tokens: c.tokens, group: /^messages$/i.test(c.name) ? 'messages' : 'system' })
334  }
335  const sum = (g: ContextRow['group']) => rows.filter(r => r.group === g).reduce((a, r) => a + r.tokens, 0)
336  return { window: b.maxTokens, system: sum('system'), mcp: sum('mcp'), messages: sum('messages'), rows }
337}
338
339export type Split = { system: number; mcp: number; messages: number; free: number }
340
341/** The window's percent in groups: the groups share `percent` by their tokens, free is the rest; whole numbers adding to 100. */
342export const splitOf = (percent: number, g: ContextGroups): Split => {
343  const used = Math.max(0, Math.min(100, Math.round(percent)))
344  const [system = 0, mcp = 0, messages = 0] = apportion(used, [g.system, g.mcp, g.messages])
345  return { system, mcp, messages: g.system + g.mcp + g.messages === 0 ? used : messages, free: 100 - used }
346}
347
348/** Bar cells per group for a bar `width` cells wide: the used share of it, split by the groups; the rest is free. */
349export const barCells = (width: number, split: Split): Split => {
350  const used = Math.round(((100 - split.free) / 100) * width)
351  const [system = 0, mcp = 0, messages = 0] = apportion(used, [split.system, split.mcp, split.messages])
352  return { system, mcp, messages, free: width - used }
353}
354
hooks/ui.tsx 114 lines
1// Shared UI helpers, after launchpad's patterns. The same file in every mod that has one: a mod
2// installs alone and cannot import another's code, so scripts/check-shared.sh keeps the copies
3// equal. Change one, copy it to the others.
4//
5// Nothing here takes `$`: the engine follows `$` only into functions of the file that uses it,
6// never across an import. A call on `$` stays in register.tsx; this file gives it its arguments.
7//
8//   language and icons  the `language` and `icons` options, else the system's LANG and terminal.
9//   prompt              the arguments of $.prompt.fill: a text with its first `[blank]` marked.
10//   lists               the window of a long list a pane shows, for ui.scroll.
11//   verbs               a row of a command's arguments, one press each.
12//   numbers             tokens, elapsed time, clipped text and short model names.
13
14import type { Elements, PromptFillArgs } from 'claude-code'
15
16export type Lang = 'pt-BR' | 'en'
17export type IconStyle = 'emoji' | 'symbol'
18
19/** The language: the `language` option when it names one, else Portuguese for a pt LANG, else English. */
20export const langOf = (option: unknown, systemLang?: string | null): Lang =>
21  option === 'en' || option === 'pt-BR' ? option : /^pt([_.@-]|$)/i.test(systemLang ?? '') ? 'pt-BR' : 'en'
22
23/**
24 * The icon style: the `icons` option when it names one; on `auto` (or none), symbols in a
25 * JetBrains IDE's terminal (TERMINAL_EMULATOR=JetBrains-JediTerm), which gives many emoji one
26 * column where Claude Code counts two, and emoji everywhere else.
27 */
28export const styleOf = (option: unknown, terminal?: string | null): IconStyle =>
29  option === 'emoji' || option === 'symbol' ? option : /^JetBrains/i.test(terminal ?? '') ? 'symbol' : 'emoji'
30
31/** An icon in the style: its emoji, or the one-cell symbol that stands in for it. */
32export const glyph = (style: IconStyle, icon: { emoji: string; symbol: string }) => icon[style]
33
34const BLANK = /\[[^\]\n]+\]/
35
36/** The first `[blank]` in a text, as offsets, so the prompt can mark what to replace. */
37export const blankIn = (text: string): { start: number; end: number } | null => {
38  const m = BLANK.exec(text)
39  return m ? { start: m.index, end: m.index + m[0].length } : null
40}
41
42/** What `$.prompt.fill` takes to put a text in the prompt, its `[blank]` marked to replace. */
43export const fillArgs = (text: string): PromptFillArgs => {
44  const blank = blankIn(text)
45  return blank ? { text, decorations: [{ ...blank, bold: true, underline: true }] } : { text }
46}
47
48/** The rows of a list of `total` a pane shows from `offset`, kept inside the list. */
49export const windowOf = (total: number, offset: number, rows: number): { start: number; end: number } => {
50  const size = Math.max(1, rows)
51  const start = Math.max(0, Math.min(offset, total - size))
52  return { start, end: Math.min(total, start + size) }
53}
54
55/**
56 * One of a command's arguments in a verb row. `fill` is the text the prompt waits with, for a
57 * verb that takes an argument or undoes something: a stray click then loses nothing. A verb with
58 * no `fill` runs, and its answer goes to the transcript a line at a time (`linesOf`).
59 */
60export type Verb = { verb: string; label?: string; fill?: string }
61
62/** A command's answer as the lines `$.ui.log` writes, one row each; blank lines dropped. */
63export const linesOf = (text: string | undefined) => (text ?? '').split('\n').filter(line => line.trim() !== '')
64
65/** `/command verb · verb · verb`, each verb a plain button; `lead` goes dim before the command. */
66export function verbRow(
67  ui: Pick<Elements[keyof Elements], 'Box' | 'Text' | 'Button'>,
68  command: string,
69  verbs: readonly Verb[],
70  onPress: (v: Verb) => void,
71  lead = '',
72) {
73  const { Box, Text, Button } = ui
74  return (
75    <Box flexDirection="row" flexWrap="wrap">
76      {lead !== '' && <Text dimColor>{`${lead} · `}</Text>}
77      <Text dimColor>{`/${command} `}</Text>
78      {verbs.map((v, i) => (
79        <Box key={`verbrow:${v.verb}`} flexDirection="row">
80          {i > 0 && <Text dimColor> · </Text>}
81          <Button key={`verb:${v.verb}`} plain dimColor label={v.label ?? v.verb} onPress={() => onPress(v)} />
82        </Box>
83      ))}
84    </Box>
85  )
86}
87
88/** 950, 1.2k, 46k, 1.2M. */
89export const tokens = (n: number) => {
90  if (n < 1000) return String(n)
91  if (n < 1_000_000) return `${(n / 1000).toFixed(n < 10_000 ? 1 : 0)}k`
92  return `${(n / 1_000_000).toFixed(1)}M`
93}
94
95/** 42s, 6m 05s, 1h 02m. */
96export const elapsed = (ms: number) => {
97  const s = Math.max(0, Math.round(ms / 1000))
98  if (s < 60) return `${s}s`
99  const m = Math.floor(s / 60)
100  if (m < 60) return `${m}m ${String(s % 60).padStart(2, '0')}s`
101  return `${Math.floor(m / 60)}h ${String(m % 60).padStart(2, '0')}m`
102}
103
104/** The text cut to `n` characters, an ellipsis last when it was longer. */
105export const clip = (s: string, n: number) => (s.length > n ? `${s.slice(0, n - 1)}…` : s)
106
107/** claude-haiku-4-5-20251001 -> haiku 4.5 */
108export const shortModel = (m?: string) => {
109  if (!m) return ''
110  const hit = /(opus|sonnet|haiku|fable)[-\s]?(\d+(?:[-.]\d+)?)?/i.exec(m)
111  if (!hit) return m.length > 14 ? `${m.slice(0, 13)}…` : m
112  return `${hit[1]!.toLowerCase()}${hit[2] ? ` ${hit[2].replace('-', '.')}` : ''}`
113}
114
hooks/words.ts 241 lines
1// What limits-meter says, in Portuguese and English. The language comes from the `language`
2// option, else the system's LANG (ui.tsx's langOf).
3
4import type { Lang } from './ui'
5
6export const COMMAND = 'limits'
7
8type Words = {
9  description: string
10  pane: string
11  hint: string
12  /** Short names of the plan windows, for the band and the pane's first column. */
13  labels: Record<string, string>
14  now: string
15  resetsIn: (reset: string) => string
16  /** Toasts, once per threshold. */
17  windowAlert: (label: string, percent: string, reset: string) => string
18  contextAlert: (percent: string) => string
19  /** The one-line answer where no pane can open. */
20  context: string
21  noReadings: string
22  planWindows: string
23  noWindows: string
24  contextHeading: string
25  ofWindow: (used: string, window: string) => string
26  turns: string
27  noTurns: string
28  /** The turns table's column heads: input, output, cache, time, model. */
29  columns: readonly [string, string, string, string, string]
30  /** Under a plan window: when it reaches 100% at the current pace, before it resets. */
31  pace: (label: string, span: string) => string
32  /** After the context sparkline. */
33  trend: (turns: number) => string
34  /** Band and pane buttons. */
35  compact: string
36  /** What `compact` puts in the prompt, its blank marked to replace. */
37  compactFill: string
38  details: string
39  hide: string
40  close: string
41  hidden: string
42  shown: string
43  help: string
44  failedToRun: (what: string) => string
45  /** Toasts on a costly switch: with a pace, with the window resetting first, with no pace. */
46  switchPace: (percent: string, span: string) => string
47  switchResets: (percent: string, reset: string) => string
48  switchFaster: (percent: string, what: string) => string
49  /** The pane's model section. */
50  modelHeading: string
51  effort: string
52  /** The pane's costly-switch section and /limits warn. */
53  warnHeading: string
54  warnHint: string
55  warnOrder: string
56  warnSet: (percent: number) => string
57  warnIs: (percent: number) => string
58  /** The cache clock: pane section, the sentence of each state, the unknown TTL and the hit rate. */
59  cacheHeading: string
60  cacheOf: (ttl: string) => string
61  cacheWarm: (tokens: string) => string
62  cacheCooling: (tokens: string) => string
63  cacheCold: (tokens: string) => string
64  cacheKeeping: (until: string) => string
65  cacheUnknown: string
66  hitRate: (percent: string) => string
67  coldWord: string
68  coldToast: (tokens: string) => string
69  /** Keep-warm: buttons, the question and its answers, why it stopped, the transcript row. */
70  keepWarm: string
71  keepStop: string
72  keepAsk: (tokens: string) => string
73  keepYes: string
74  keepNo: string
75  keepOn: string
76  keepOff: string
77  keepNeedsTtl: string
78  keepStopped: (why: 'prompt' | 'time' | 'cold' | 'failed') => string
79  keepRow: string
80  /** The context groups on the band's legend and in the pane's table. */
81  ctxLabel: string
82  groups: { system: string; mcp: string; messages: string; free: string }
83  breakdownHead: string
84  breakdownNote: string
85}
86
87export const WORDS: Record<Lang, Words> = {
88  'pt-BR': {
89    description: 'Limites do plano, relógio do cache e contexto: /limits abre o painel; hide, show, keep-warm, warn, help',
90    pane: 'Limites e contexto',
91    hint: 'Números que o engine informa a cada turno. Tokens e percentual, nunca dinheiro.',
92    labels: { five_hour: '5h', seven_day: 'sem', spend_limit: 'gasto' },
93    now: 'agora',
94    resetsIn: reset => `reinicia em ${reset}`,
95    windowAlert: (label, percent, reset) => `Janela ${label} em ${percent}${reset ? `, reinicia em ${reset}` : ''}`,
96    contextAlert: percent => `Contexto ${percent} cheio: bom momento para /compact com um foco`,
97    context: 'contexto',
98    noReadings: 'sem leituras de limite do plano (chave de API, ou antes da primeira resposta)',
99    planWindows: 'Janelas do plano',
100    noWindows: 'Sem leituras: uma chave de API não tem janelas do plano, e uma assinatura as mostra depois da primeira resposta.',
101    contextHeading: 'Contexto',
102    ofWindow: (used, window) => `${used} de ${window}`,
103    turns: 'Turnos (thread principal)',
104    noTurns: 'Nenhum turno terminado ainda.',
105    columns: ['entrada', 'saída', 'cache', 'tempo', 'modelo'],
106    pace: (label, span) => `no ritmo atual, ${label} chega a 100% em ~${span}, antes de reiniciar`,
107    trend: n => `contexto ao fim ${n === 1 ? 'do último turno' : `dos últimos ${n} turnos`}`,
108    compact: 'compactar',
109    compactFill: '/compact [foco]',
110    details: 'detalhes',
111    hide: 'ocultar',
112    close: 'Fechar',
113    hidden: 'Banda oculta. /limits show traz de volta.',
114    shown: 'Banda visível.',
115    help: [
116      '/limits          abre o painel: janelas do plano, contexto em tokens, os últimos 20 turnos',
117      '/limits hide     oculta a banda acima do prompt, também nas próximas sessões',
118      '/limits show     traz a banda de volta',
119      '/limits keep-warm on|off  mantém o cache quente (gasta plano; pergunta antes)',
120      '/limits warn N   avisa na troca cara com a janela de 5h a partir de N% (padrão 70)',
121    ].join('\n'),
122    failedToRun: what => `Não deu para rodar: ${what}`,
123    switchPace: (percent, span) => `5h em ${percent}: neste ritmo a janela acaba em ~${span} · /limits`,
124    switchResets: (percent, reset) => `5h em ${percent}: reinicia em ${reset}, antes de acabar · /limits`,
125    switchFaster: (percent, what) => `5h em ${percent}: ${what} gasta a janela mais rápido · /limits`,
126    modelHeading: 'Modelo',
127    effort: 'effort',
128    warnHeading: 'Aviso de troca cara',
129    warnHint: 'Toast ao trocar para modelo maior ou effort max com 5h a partir de:',
130    warnOrder: 'ordem: haiku < sonnet < opus < fable',
131    warnSet: percent => `Aviso de troca cara a partir de ${percent}%. Vale nas próximas sessões.`,
132    warnIs: percent => `Aviso de troca cara a partir de ${percent}%. /limits warn N muda (1 a 100).`,
133    cacheHeading: 'Cache',
134    cacheOf: ttl => `de ${ttl} (TTL da última resposta)`,
135    cacheWarm: tokens => `Responda agora e ${tokens} tokens saem do cache: ~10% do que custaria reler a frio.`,
136    cacheCooling: tokens => `Esfriando: responda ou mantenha quente. Frio, ${tokens} tokens são relidos sem cache.`,
137    cacheCold: tokens => `Cache frio: a próxima resposta relê ${tokens} tokens sem cache. /compact antes gasta menos.`,
138    cacheKeeping: until => `Mantendo quente: uma mensagem curta antes de esfriar. Para no seu próximo prompt ou em ${until}.`,
139    cacheUnknown: 'TTL do cache desconhecido. Ele aparece depois de uma troca de modelo, ou de um turno de uma só chamada depois de mais de 5 min parado.',
140    hitRate: percent => `taxa de acerto do último turno: ${percent}`,
141    coldWord: 'frio',
142    coldToast: tokens => `Cache frio: a próxima resposta relê ${tokens} tokens sem cache`,
143    keepWarm: 'manter quente',
144    keepStop: 'parar',
145    keepAsk: tokens => `Manter o cache quente? Cada envio relê ${tokens} tokens do cache e gasta plano (sem estimativa em %: depende do contexto). Para no seu próximo prompt ou em 2 h.`,
146    keepYes: 'sim, manter',
147    keepNo: 'não',
148    keepOn: 'Manter quente ligado. Para no seu próximo prompt ou em 2 h.',
149    keepOff: 'Manter quente desligado.',
150    keepNeedsTtl: 'Ainda não sei o TTL do cache, então não dá para saber quando enviar. Tente depois do próximo turno.',
151    keepStopped: why =>
152      ({
153        prompt: 'Manter quente parou: o seu prompt já renova o cache.',
154        time: 'Manter quente parou: passaram 2 h.',
155        cold: 'Manter quente parou: o cache esfriou antes do envio.',
156        failed: 'Manter quente parou: o envio falhou.',
157      })[why],
158    keepRow: '♻ manter quente (mensagem do limits-meter)',
159    ctxLabel: 'ctx',
160    groups: { system: 'sistema', mcp: 'MCP', messages: 'mensagens', free: 'livre' },
161    breakdownHead: 'categoria                tokens  janela',
162    breakdownNote: '≈ estimativa local do engine, os mesmos números do /context',
163  },
164  en: {
165    description: 'Plan limits, cache clock and context: /limits opens the pane; hide, show, keep-warm, warn, help',
166    pane: 'Limits & context',
167    hint: 'Figures the engine reports after each turn. Tokens and percent, never money.',
168    labels: { five_hour: '5h', seven_day: 'wk', spend_limit: 'spend' },
169    now: 'now',
170    resetsIn: reset => `resets in ${reset}`,
171    windowAlert: (label, percent, reset) => `${label} window at ${percent}${reset ? `, resets in ${reset}` : ''}`,
172    contextAlert: percent => `Context ${percent} full: a good moment for /compact with a focus`,
173    context: 'context',
174    noReadings: 'no plan-limit readings (API key, or before the first response)',
175    planWindows: 'Plan windows',
176    noWindows: 'No readings: an API key has no plan windows, and a subscription shows them after the first response.',
177    contextHeading: 'Context',
178    ofWindow: (used, window) => `${used} of ${window}`,
179    turns: 'Turns (main thread)',
180    noTurns: 'No finished turns yet.',
181    columns: ['in', 'out', 'cache', 'time', 'model'],
182    pace: (label, span) => `at this pace, ${label} reaches 100% in ~${span}, before it resets`,
183    trend: n => `context at the end of the last ${n} turn${n === 1 ? '' : 's'}`,
184    compact: 'compact',
185    compactFill: '/compact [focus]',
186    details: 'details',
187    hide: 'hide',
188    close: 'Close',
189    hidden: 'Band hidden. /limits show brings it back.',
190    shown: 'Band shown.',
191    help: [
192      '/limits          open the pane: plan windows, context in tokens, the last 20 turns',
193      '/limits hide     hide the band above the prompt, in later sessions too',
194      '/limits show     bring the band back',
195      '/limits keep-warm on|off  keep the cache warm (spends plan; asks first)',
196      '/limits warn N   warn on a costly switch with the 5-hour window from N% (default 70)',
197    ].join('\n'),
198    failedToRun: what => `Could not run: ${what}`,
199    switchPace: (percent, span) => `5h at ${percent}: at this pace the window runs out in ~${span} · /limits`,
200    switchResets: (percent, reset) => `5h at ${percent}: resets in ${reset}, before it runs out · /limits`,
201    switchFaster: (percent, what) => `5h at ${percent}: ${what} uses the window faster · /limits`,
202    modelHeading: 'Model',
203    effort: 'effort',
204    warnHeading: 'Costly switch warning',
205    warnHint: 'Toast on a switch to a bigger model or effort max with 5h from:',
206    warnOrder: 'order: haiku < sonnet < opus < fable',
207    warnSet: percent => `Costly switch warning from ${percent}%. Kept for later sessions.`,
208    warnIs: percent => `Costly switch warning from ${percent}%. /limits warn N changes it (1 to 100).`,
209    cacheHeading: 'Cache',
210    cacheOf: ttl => `of ${ttl} (TTL of the last reply)`,
211    cacheWarm: tokens => `Reply now and ${tokens} tokens come from cache: ~10% of what a cold re-read would cost.`,
212    cacheCooling: tokens => `Cooling: reply or keep it warm. Cold, ${tokens} tokens are re-read with no cache.`,
213    cacheCold: tokens => `Cache cold: the next reply re-reads ${tokens} tokens with no cache. /compact first spends less.`,
214    cacheKeeping: until => `Keeping warm: a short message before it cools. Stops at your next prompt or in ${until}.`,
215    cacheUnknown: 'Cache TTL unknown. It shows after a model switch, or after a one-request turn that follows more than 5 min idle.',
216    hitRate: percent => `last turn hit rate: ${percent}`,
217    coldWord: 'cold',
218    coldToast: tokens => `Cache cold: the next reply re-reads ${tokens} tokens with no cache`,
219    keepWarm: 'keep warm',
220    keepStop: 'stop',
221    keepAsk: tokens => `Keep the cache warm? Each send re-reads ${tokens} tokens from cache and spends plan (no estimate in %: it depends on the context). Stops at your next prompt or in 2 h.`,
222    keepYes: 'yes, keep warm',
223    keepNo: 'no',
224    keepOn: 'Keep-warm on. Stops at your next prompt or in 2 h.',
225    keepOff: 'Keep-warm off.',
226    keepNeedsTtl: 'The cache TTL is not known yet, so there is no telling when to send. Try after the next turn.',
227    keepStopped: why =>
228      ({
229        prompt: 'Keep-warm stopped: your prompt already refreshes the cache.',
230        time: 'Keep-warm stopped: 2 h passed.',
231        cold: 'Keep-warm stopped: the cache went cold before the send.',
232        failed: 'Keep-warm stopped: the send failed.',
233      })[why],
234    keepRow: '♻ keep-warm (message from limits-meter)',
235    ctxLabel: 'ctx',
236    groups: { system: 'system', mcp: 'MCP', messages: 'messages', free: 'free' },
237    breakdownHead: 'category                 tokens  window',
238    breakdownNote: '≈ local engine estimate, the same figures as /context',
239  },
240}
241
types/index.d.ts 80 lines
1/** One rate-limit window as the meter draws it. */
2export type Limit = {
3  /** `five_hour`, `seven_day`, or a gateway's `spend_limit`. */
4  kind: string
5  /** 0 to 100, past 100 on an exceeded spend limit. */
6  percent: number
7  /** When the window resets, in epoch milliseconds; null when unknown. */
8  resetsAt: number | null
9}
10
11/** The live figures the band draws, pushed by `session.measure`. */
12export type Snapshot = {
13  limits: Limit[]
14  /** Context window fill, 0 to 100; null before the first response. */
15  contextPercent: number | null
16  /** Input tokens the last response was answered over. */
17  contextTokens: number | null
18  /** The model's context window in tokens. */
19  contextWindow: number
20}
21
22/** One finished main-thread turn. */
23export type Turn = {
24  /** Input tokens: uncached, cache-read and cache-written together. */
25  input: number
26  output: number
27  /** Share of input the prompt cache served, 0 to 1; null when no input. */
28  cacheHit: number | null
29  model: string
30  durationMs: number
31  /** Context fill when the turn ended, 0 to 100; null when unknown. */
32  contextPercent?: number | null
33  /** When the turn ended, in epoch milliseconds: the costly-switch pace spans the last turns. */
34  endedAt?: number
35  /** Model requests the turn made; 1 means its cache hit rate is its first request's, which the cache TTL inference needs. */
36  steps?: number
37}
38
39/** How long the prompt cache lives after a request: `cache_ttl` on a model switch, or inferred from the turns. */
40export type Ttl = '5m' | '1h'
41
42/** When the main thread's last request ended, and the TTL of the cache it refreshed; null while unknown. */
43export type CacheClock = { lastAt: number | null; ttl: Ttl | null }
44
45/** Keep-warm is on until this time (epoch ms), or at the person's next prompt. */
46export type KeepWarm = { until: number }
47
48/** One row of the window's breakdown, in the group the band draws it in. */
49export type ContextRow = { name: string; tokens: number; group: 'system' | 'mcp' | 'messages' }
50
51/** The context window by the engine's categories (`$.session.usage({ breakdown: 'summary' })`), grouped for the band. */
52export type ContextGroups = { window: number; system: number; mcp: number; messages: number; rows: ContextRow[] }
53
54/** Readings of each plan window since it last reset, for the pace: [epoch ms, percent]. */
55export type Samples = Record<string, { resetsAt: number; points: [number, number][] }>
56
57declare module 'claude-code' {
58  interface PluginState {
59    'limits-meter': {
60      snapshot: Snapshot
61      turns: Turn[]
62      isHidden: boolean
63      fired: string[]
64      samples: Samples
65      /** The main thread's model id, from session.model, PostModelSwitch and turn.step. */
66      model: string | null
67      /** The main thread's effort, from the best source seen; null when unknown or the model has none. */
68      effort: string | number | null
69      /** The 5-hour percent from which a costly switch raises a toast; kept in $.store. */
70      switchAt: number
71      /** The cache clock: last request end and TTL. */
72      cache: CacheClock
73      /** Keep-warm while on; null when off. */
74      keepWarm: KeepWarm | null
75      /** The latest context breakdown, grouped; null before the first or when the engine gives none. */
76      groups: ContextGroups | null
77    }
78  }
79}
80