SLOPSHOPPER

quota-band

Your Claude plan's 5h and weekly usage, the context window and the prompt cache's time left, as one line of bars above the prompt

bandcommandtoastpromptprocesstimer
v0.12.0MITupdated 2026-10-15andras-gyarmati/claude-quota-band
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · quota-band
› fix the failing auth test and add an audit log call ⏺ Read(src/auth.ts) ⎿ Read 6 lines ⏺ Update(src/auth.ts) ⎿ Added 2 lines, removed 1 line ⏺ Bash(bun test) ⎿ 3 pass, 1 fail ● Done. refresh now rejects expired claims and logs an audit event. ✻ Worked for 42s · done 4:20 PM › /quota-weights ⎿ quota-band: 5h: 0 intervals, no fit yet ⎿ quota-band: 7d: 0 intervals, no fit yet ⎿ quota-band: output stays at 2.5 cache writes per token ⎿ quota-band: cost × uses API price ratios until 5h has 20 intervals and a cache read range within ±25% 5h 31% · 09:53 ctx 49% · 97k cache 60m keep-warm 09:50 ──────────────────────────────────────────────────────────────────────────────────────────────────────────────────── ──────────────────────────────────────────────────────────────────────────────────────────────────────────────────── ──────────────────────────────────────────────────────────────────────────────────────────────────────────────────── ──────────────────────────────────────────────────── ⟨Claude Code's own drawing⟩ ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Band
5h 31% · 09:53 ctx 49% · 97k cache 60m keep-warm 09:50 ──────────────────────────────────────────────────────────────────────────────────────────────────── ──────────────────────────────────────────────────────────────────────────────────────────────────── ──────────────────────────────────────────────────────────────────────────────────────────────────── ──────────────────────────────────────────────────────────────────────────────────────────────────── ⟨Claude Code's own drawing⟩
README

quota-band

A Claude Code mod that keeps your plan's usage in view: one line above the prompt with the 5-hour and weekly windows, the context window, the prompt cache's time left and what the context adds to each turn's cost.

5h ▬▬▬▬▬▬▬▬▬ 93% → 100% 23:10    7d ▬▬▬▬▬▬▬ 72% 11:00    ctx ▬▬▬ 37% 370k    cache ▬▬▬ 42m    keep-warm off    cost ×4.5
  • Each bar fills with the percent used. A grey tick marks how much of the window has passed, and the notches are hours (5h) or days (7d).
  • A saved reset claimed in the Claude app zeroes the week but keeps its reset time, so from the first reading after the claim the 7d bar runs from the claim to the reset. A claim made while no session was running shows at the next session's first response.
  • Where the Agent Profiles Mac app is installed, the 7d row also shows the week's last gift reset, who spent it and where (🎁 Sat 23:51 · Andras · Mac), from the file that app writes per account.
  • Colours: red from 95%, orange from 80%, yellow while you are ahead of an even pace, white otherwise.
  • → N% is where the current pace lands by the reset, with a dashed outline on the bar.
  • The time is when the window resets.
  • ctx is how full the context window is; 370k is what the next request re-sends, which a cold cache has to write again.
  • cache drains over the time the prompt cache stays warm after the last response: the length the last response actually wrote, read from the transcript at the end of each turn, so it drops to five minutes in overage. Until the first turn ends (and on Windows, which has no tail) it assumes an hour on a subscription's main thread, five minutes otherwise, or what promptCacheTtl sets. It turns orange in the last five minutes and red once cold. When 50%, 25%, 10% and 5% of the lifetime is left, every thread pings with a toast and, on macOS, a Notification Centre banner titled with the thread's name (osascript, so the banner comes from Script Editor, which macOS may ask to allow once). Set iMessageTo (below) to a phone number or Apple ID to get the same pings on the phone, sent through this Mac's Messages app; macOS asks once to let Claude control Messages.
  • keep-warm says whether this thread is kept warm and when the next ping goes out (below). On the desktop app it is a button that turns it on or off.
  • cost ×4.5 is what the last turn cost over the same turn in a fresh thread. Every request in a turn (one per tool call) resends the context, so a long thread costs more per message even with a warm cache. The fresh thread starts from what the session's first request sent (system prompt, tools, rules). Token kinds are weighed at API price ratios: cache read 0.1, cache write 1.25 (5 minutes) or 2 (1 hour), output 5, against uncached input 1. How the plan's quotas weigh them is not published, so treat it as an estimate.
  • Once the plan's own readings have measured the weights (below), cost uses those and says measured.

Measured quota weights

Each session logs its requests' token counts and the 5h and 7d readings to the plugin's store, kept for eight days. Readings from all sessions are cut into intervals in which a window rose at least one point, and a least-squares fit gives how many cache-write tokens make 1% and what a cache read weighs against a cache write. Output stays at the API ratio of 2.5 cache writes per token: it is about a tenth of the quota use, too little to separate from the noise. /quota-weights prints the fit:

5h: 52 intervals, 3 dropped as usage elsewhere; 1% = 2.0M cache-write tokens; cache read = 0.052 (0.048 to 0.058) of a cache write, API 0.05 to 0.08
7d: 6 intervals; 1% = 14.1M cache-write tokens; cache read = 0.061 (0.030 to 0.090) of a cache write, API 0.05 to 0.08
output stays at 2.5 cache writes per token
cost × uses measured 5h weights

The readings cover the whole account, so usage the log cannot see (claude.ai, another machine, subagents) lands in them too. Intervals that used 30% more than the fit predicts are dropped as such, intervals across a 30-minute silence are skipped, and cost switches to measured weights only after 20 intervals with the cache read's 10th to 90th percentile range within ±25%.

Keep warm

Off for every thread until you turn it on for one with /keep-warm (or /keep-warm on, /keep-warm off; bare flips it), or by clicking keep-warm off in the band on the desktop app. The setting is kept per thread in the plugin's store, so it survives a restart of the app. While it is on and the thread is idle (no turn running, prompt box empty) with about 3 minutes of cache left, the band sends keep-warm: reply with only "ok" as a plugin message, so the next prompt reads the context from the cache instead of writing it again. While it is on the cold pings stay quiet, since the cache does not go cold.

The band's segment, one state at a time:

  • keep-warm off: not on for this thread.
  • keep-warm 13:47 · 2 sent: the local time of the next ping, and the pings since your last prompt. A time already past means the ping waits for the turn to end or the prompt box to empty.
  • keep-warm pinging: a ping was sent and its turn has not ended yet.
  • keep-warm stopped · 3 pings without a prompt (or · 2h without a prompt): keepWarmMaxIdle was reached; your next prompt starts it again.
  • keep-warm paused · overage: the cache lives five minutes, so no pings (below).
  • keep-warm on · cache cold: the cache went cold before a ping could go out (you were typing, or a turn ran); the next response arms it again.
  • keep-warm on: no response yet in this session to time from.
  • One ping costs a cache read of the whole context, about 0.05 of a cache write by the band's own fit (0.1 of uncached input at API prices), plus a few tokens of output. Letting it go cold costs re-writing the whole context at the next prompt: 1.25x (5-minute write) to 2x (1-hour write) of uncached input. On a 400k thread that is about 20k cache-write tokens per ping against 400k to rebuild, so up to about 20 pings cost what one cold rebuild does.
  • keepWarmMaxIdle stops it so an abandoned thread does not burn quota: 3 (the default) stops after three pings in a row with no prompt of yours, 2h two hours after your last prompt. Any prompt you send starts the count again.
  • It stands down in overage, where the cache lives five minutes: a ping every four minutes costs more than the rebuild it saves.
  • A ping's turn is logged for the quota fit but does not replace the last turn's cost.
"pluginConfigs": {
  "quota-band@claude-quota-band": { "options": { "keepWarmMaxIdle": "3" } }
}

Phone pings

The cache pings can also go to your phone as an iMessage from this Mac. Set iMessageTo in /config under the plugin's options, or in settings.json:

"pluginConfigs": {
  "quota-band@claude-quota-band": { "options": { "iMessageTo": "" } }
}

The close and rename buttons moved to prompt-buttons.

It reads the figures Claude Code already receives with each response (session.measure), and the ends of the session's transcript at the end of each turn, so it sends no requests of its own. It writes to its own plugin store and, where the Agent Profiles Mac app is installed, the latest figures per account to ~/Library/Application Support/Agent Profiles/mod-readings/, which that app shows instead of asking Anthropic. The figures appear after the first response of a session, on Pro, Max and Team plans.

Install

Needs Claude Code 2.1.287 or later (Claude Mods). In Claude Code:

/plugin marketplace add andras-gyarmati/claude-quota-band
/plugin install quota-band@claude-quota-band

To pick up new versions on each start, set "autoUpdate": true for this marketplace under extraKnownMarketplaces in settings.json.

Bars draw in the desktop app's Code tab; the terminal shows the same line as text.

Source 2 files
hooks/register.tsx 806 lines
1import { atom, read, update } from 'claude-code'
2import type { Register } from 'claude-code'
3
4import type { Limit, Multiplier, Turn, Warm } from '../types'
5
6const limits = atom({ plugin: 'quota-band', key: 'limits' } as const, [] as Limit[])
7const turn = atom({ plugin: 'quota-band', key: 'turn' } as const, null as Turn | null)
8const multiplier = atom({ plugin: 'quota-band', key: 'multiplier' } as const, null as Multiplier | null)
9const tick = atom({ plugin: 'quota-band', key: 'tick' } as const, 0)
10const weekClaim = atom({ plugin: 'quota-band', key: 'weekClaim' } as const, null as number | null)
11const gift = atom({ plugin: 'quota-band', key: 'gift' } as const, null as Gift | null)
12const warm = atom({ plugin: 'quota-band', key: 'warm' } as const, null as Warm | null)
13
14const HOUR = 3600e3
15const FIVE_MINUTES = 5 * 60e3
16const COLD_SOON = FIVE_MINUTES
17/** Shares of the cache lifetime left at which a thread pings, warmest first. */
18export const COLD_STEPS = [0.5, 0.25, 0.1, 0.05]
19const COLD_CHECK_MS = 10e3
20const TRANSCRIPT_TAIL_BYTES = '524288'
21
22/** The fallback before a transcript has been read: subscribers' main thread
23 * caches for an hour, everyone else for five minutes, unless `promptCacheTtl`
24 * says otherwise. */
25async function cacheTtl($: any, subscriber: boolean): Promise<number> {
26  const setting = (await $.settings.read())?.promptCacheTtl
27  if (setting === '1h') return HOUR
28  if (setting === '5m') return FIVE_MINUTES
29  return subscriber ? HOUR : FIVE_MINUTES
30}
31
32/** `$.fs.read` stops at 4 MiB, so transcript ends come from `head` and `tail`;
33 * null where that cannot be read. */
34async function transcriptEnd($: any, tool: 'head' | 'tail', transcriptPath: string): Promise<string[] | null> {
35  const run = await $.process.run([`/usr/bin/${tool}`, '-c', TRANSCRIPT_TAIL_BYTES, transcriptPath]).catch(() => null)
36  return run && run.exitCode === 0 ? run.stdout.split('\n') : null
37}
38
39/** The cache lifetime the last response actually wrote, which drops to five
40 * minutes in overage. */
41function writtenTtl(lines: string[]): number | null {
42  for (let i = lines.length - 1; i >= 0; i--) {
43    if (!lines[i].includes('"cache_creation"')) continue
44    try {
45      const creation = JSON.parse(lines[i])?.message?.usage?.cache_creation
46      if (creation?.ephemeral_1h_input_tokens) return HOUR
47      if (creation?.ephemeral_5m_input_tokens) return FIVE_MINUTES
48    } catch {}
49  }
50  return null
51}
52
53/** The thread's title as the app last set it, from a transcript's end. */
54function threadTitle(lines: string[]): string | null {
55  for (let i = lines.length - 1; i >= 0; i--) {
56    if (!lines[i].includes('"custom-title"')) continue
57    try {
58      const title = JSON.parse(lines[i])?.customTitle
59      if (typeof title === 'string' && title) return title
60    } catch {}
61  }
62  return null
63}
64
65/** The coldest step `left` of `ttlMs` has passed, as an index into
66 * `COLD_STEPS`; -1 above the first, null once cold. */
67export function coldStep(left: number, ttlMs: number): number | null {
68  if (left <= 0) return null
69  let step = -1
70  COLD_STEPS.forEach((share, i) => { if (left <= share * ttlMs) step = i })
71  return step
72}
73
74/** A Notification Centre banner, so a ping reaches him outside the thread. The
75 * text goes in as arguments, never into the script. macOS only. */
76async function notify($: any, title: string, text: string) {
77  await $.process.run(['/usr/bin/osascript',
78    '-e', 'on run argv', '-e', 'display notification (item 2 of argv) with title (item 1 of argv)', '-e', 'end run',
79    title, text]).catch(() => null)
80}
81
82/** An iMessage from this Mac's Messages account, which reaches the phone. */
83async function sendIMessage($: any, to: string, text: string) {
84  await $.process.run(['/usr/bin/osascript',
85    '-e', 'on run argv', '-e', 'tell application "Messages" to send (item 2 of argv) to participant (item 1 of argv) of (1st account whose service type = iMessage)', '-e', 'end run',
86    to, text]).catch(() => null)
87}
88
89/** How long before the cache goes cold a keep-warm ping is sent: a few cold
90 * checks of margin plus the ping's own turn. A guess. */
91export const WARM_LEAD_MS = 3 * 60e3
92export const KEEP_WARM_PROMPT = 'keep-warm: reply with only "ok"'
93
94/** `keepWarmMaxIdle`: `3` stops after three pings in a row with no prompt of
95 * his between them, `2h` after two hours without one. */
96export type WarmLimit = { pings: number } | { hours: number }
97
98export function parseMaxIdle(value: unknown): WarmLimit {
99  const text = String(value ?? '').trim().toLowerCase()
100  const hours = /^(\d+(?:\.\d+)?)\s*h$/.exec(text)
101  if (hours) return { hours: Number(hours[1]) }
102  const pings = Number(text)
103  return Number.isFinite(pings) && pings >= 0 && text !== '' ? { pings: Math.floor(pings) } : { pings: 3 }
104}
105
106export function warmSpent(w: Warm, limit: WarmLimit, now: number): boolean {
107  return 'pings' in limit ? w.sent >= limit.pings : now - w.idleSince >= limit.hours * HOUR
108}
109
110const pad = (n: number) => String(n).padStart(2, '0')
111
112/** Keep-warm stands down in overage: a five-minute cache would need a ping
113 * every four minutes, which costs more than one cold rewrite saves. */
114export function warmArmed(ttlMs: number, w: Warm, limit: WarmLimit, now: number): boolean {
115  return ttlMs > FIVE_MINUTES && !warmSpent(w, limit, now)
116}
117
118export const freshWarm = (now: number): Warm => ({ sent: 0, idleSince: now, pingedFor: null })
119
120const clock = (at: number) => { const d = new Date(at); return `${pad(d.getHours())}:${pad(d.getMinutes())}` }
121
122/** The band's keep-warm segment: off, the local time of the next ping, or why none is coming. */
123export function warmLabel(w: Warm | null, last: Turn | null, limit: WarmLimit, now: number): string {
124  if (!w) return 'keep-warm off'
125  const sent = w.sent ? ` · ${w.sent} sent` : ''
126  if (!last) return 'keep-warm on'
127  if (last.ttlMs <= FIVE_MINUTES) return 'keep-warm paused · overage'
128  if (warmSpent(w, limit, now)) return `keep-warm stopped · ${'pings' in limit ? `${w.sent} pings` : `${limit.hours}h`} without a prompt`
129  if (w.pingedFor === last.at) return `keep-warm pinging${sent}`
130  if (last.at + last.ttlMs <= now) return `keep-warm on · cache cold${sent}`
131  return `keep-warm ${clock(last.at + last.ttlMs - WARM_LEAD_MS)}${sent}`
132}
133
134/** `/keep-warm` with `on`, `off`, or nothing to flip it. */
135export function warmWanted(args: string, isOn: boolean): boolean | null {
136  const word = args.trim().toLowerCase()
137  if (word === '') return !isOn
138  if (word === 'on') return true
139  if (word === 'off') return false
140  return null
141}
142
143export type WarmCheck = { now: number; last: Turn | null; running: boolean; draft: string; warm: Warm; limit: WarmLimit }
144
145/** Whether to send a keep-warm ping now, or why not. */
146export function keepWarmDue(c: WarmCheck): 'ping' | 'no-turn' | 'overage' | 'spent' | 'sent' | 'early' | 'cold' | 'busy' | 'typed' {
147  if (!c.last) return 'no-turn'
148  if (c.last.ttlMs <= FIVE_MINUTES) return 'overage'
149  if (warmSpent(c.warm, c.limit, c.now)) return 'spent'
150  if (c.warm.pingedFor === c.last.at) return 'sent'
151  const left = c.last.at + c.last.ttlMs - c.now
152  if (left <= 0) return 'cold'
153  if (left > WARM_LEAD_MS) return 'early'
154  if (c.running) return 'busy'
155  if (c.draft.trim() !== '') return 'typed'
156  return 'ping'
157}
158
159type Usage = {
160  input_tokens?: number
161  cache_creation_input_tokens?: number
162  cache_read_input_tokens?: number
163  output_tokens?: number
164  cache_creation?: { ephemeral_1h_input_tokens?: number; ephemeral_5m_input_tokens?: number }
165}
166
167/** API prices relative to uncached input. How the plan's quotas weigh token
168 * kinds is not published, so the multiplier assumes the same ratios. */
169const READ_RATE = 0.1
170const WRITE_5M_RATE = 1.25
171const WRITE_1H_RATE = 2
172const OUTPUT_RATE = 5
173
174const sentTokens = (u: Usage) => (u.input_tokens ?? 0) + (u.cache_creation_input_tokens ?? 0) + (u.cache_read_input_tokens ?? 0)
175
176function writeRate(u: Usage): number {
177  const hour = u.cache_creation?.ephemeral_1h_input_tokens ?? 0
178  const five = u.cache_creation?.ephemeral_5m_input_tokens ?? 0
179  return hour + five > 0 ? (hour * WRITE_1H_RATE + five * WRITE_5M_RATE) / (hour + five) : WRITE_5M_RATE
180}
181
182/** Quota used per token kind, relative to a cache write: measured by
183 * `fitWeights`; null means the API price ratios. */
184type Weights = { write: number; read: number; output: number }
185
186function cost(u: Usage, w: Weights | null): number {
187  const written = (u.input_tokens ?? 0) + (u.cache_creation_input_tokens ?? 0)
188  if (w) return written * w.write + (u.cache_read_input_tokens ?? 0) * w.read + (u.output_tokens ?? 0) * w.output
189  return (u.input_tokens ?? 0) + (u.cache_creation_input_tokens ?? 0) * writeRate(u)
190    + (u.cache_read_input_tokens ?? 0) * READ_RATE + (u.output_tokens ?? 0) * OUTPUT_RATE
191}
192
193/** What resending `old` tokens of earlier context cost this request: read from
194 * the cache first, then written to it, then sent uncached. */
195function carried(u: Usage, old: number, w: Weights | null): number {
196  const read = Math.min(old, u.cache_read_input_tokens ?? 0)
197  const written = Math.min(old - read, u.cache_creation_input_tokens ?? 0)
198  return read * (w?.read ?? READ_RATE) + written * (w?.write ?? writeRate(u)) + (old - read - written) * (w?.write ?? 1)
199}
200
201type Entry = { type?: string; timestamp?: string; isMeta?: boolean; isSidechain?: boolean; message?: { id?: string; content?: unknown; usage?: Usage } }
202
203type Request = { at: number; usage: Usage }
204
205const parse = (line: string): Entry | null => { try { return JSON.parse(line) } catch { return null } }
206
207const isPrompt = (e: Entry) => e.type === 'user' && !e.isMeta && !e.isSidechain
208  && !(Array.isArray(e.message?.content) && e.message!.content.some((b: any) => b?.type === 'tool_result'))
209
210/** Context the session's first request sent: system prompt, tools, rules and
211 * the first prompt, the floor a fresh thread starts from. */
212function baselineTokens(head: string[]): number | null {
213  for (const line of head) {
214    if (!line.includes('"usage"')) continue
215    const e = parse(line)
216    if (e?.type === 'assistant' && !e.isSidechain && e.message?.usage) return sentTokens(e.message.usage)
217  }
218  return null
219}
220
221/** The last turn's requests, newest first. A response spans several transcript
222 * lines that repeat its usage, so each message id counts once. */
223function lastTurn(tail: string[]): Request[] {
224  const seen = new Set<string>()
225  const requests: Request[] = []
226  for (let i = tail.length - 1; i >= 0; i--) {
227    const e = parse(tail[i])
228    if (!e || e.isSidechain) continue
229    if (isPrompt(e)) break
230    const id = e.message?.id
231    if (e.type !== 'assistant' || !e.message?.usage || !id || seen.has(id)) continue
232    seen.add(id)
233    requests.push({ at: Date.parse(e.timestamp ?? '') || 0, usage: e.message.usage })
234  }
235  return requests
236}
237
238/** The turn's cost over what the same turn costs on a fresh thread: every
239 * request in it resends the context the turn started with beyond `baseline`. */
240function turnMultiplier(turn: Request[], baseline: number, w: Weights | null): number | null {
241  if (turn.length === 0) return null
242  const old = Math.max(0, sentTokens(turn[turn.length - 1].usage) - baseline)
243  const actual = turn.reduce((sum, r) => sum + cost(r.usage, w), 0)
244  const fresh = turn.reduce((sum, r) => sum + cost(r.usage, w) - carried(r.usage, old, w), 0)
245  return fresh > 0 ? actual / fresh : null
246}
247
248/** One session's calibration record in `$.store`: requests as [unix s, tokens
249 * written or sent uncached, cache read, output], quota readings as [unix s,
250 * 5h %, 7d %]. */
251type Log = { updated: number; requests: number[][]; readings: (number | null)[][] }
252
253const LOG_PREFIX = 'calibration/'
254const KEEP_MS = 8 * 86400e3
255const READING_EVERY_S = 300
256const REFIT_MS = 10 * 60e3
257/** Guesses: a quota step large enough that the one-decimal reading and request
258 * timing are noise, a gap after which usage elsewhere (claude.ai, another
259 * machine) is likely, and enough intervals to fit two weights. */
260const MIN_STEP = 1
261const MAX_GAP_S = 30 * 60
262const MIN_INTERVALS = 20
263
264const requestRow = (r: Request): number[] => [
265  Math.round(r.at / 1e3),
266  (r.usage.input_tokens ?? 0) + (r.usage.cache_creation_input_tokens ?? 0),
267  r.usage.cache_read_input_tokens ?? 0,
268  r.usage.output_tokens ?? 0,
269]
270
271/** Output per cache-write token at API prices with hour-long writes. Output is
272 * about a tenth of a turn's quota use, below what the readings can resolve, so
273 * it stays at this ratio and only writes and reads are measured. */
274const OUTPUT_PER_WRITE = OUTPUT_RATE / WRITE_1H_RATE
275/** Guesses: an interval using this much more than the fit predicts had usage
276 * this log cannot see; the read weight is trusted once its resampled 10th to
277 * 90th percentile range stays within this share of it. */
278const OUTLIER = 1.3
279const MAX_SPREAD = 0.25
280const RESAMPLES = 100
281
282type Fit = { kind: string; intervals: number; dropped: number; writePerPoint: number | null; weights: Weights | null; readRange: [number, number] | null }
283
284const usable = (fit: Fit | null): fit is Fit & { weights: Weights; readRange: [number, number] } =>
285  !!fit?.weights && !!fit.readRange && fit.intervals >= MIN_INTERVALS
286  && fit.readRange[1] - fit.readRange[0] <= 2 * MAX_SPREAD * fit.weights.read
287
288/** Intervals in which a window rose at least `MIN_STEP`, as rows of [written +
289 * weighted output, cache read] in millions of tokens and the points used. */
290function quotaIntervals(logs: Log[], column: 1 | 2): { rows: number[][]; ys: number[] } {
291  const readings = logs.flatMap(l => l.readings)
292    .filter(r => typeof r[column] === 'number')
293    .map(r => [r[0] as number, r[column] as number])
294    .sort((a, b) => a[0] - b[0])
295  const requests = logs.flatMap(l => l.requests)
296  const rows: number[][] = []
297  const ys: number[] = []
298  let start = readings[0]
299  for (let i = 1; i < readings.length; i++) {
300    const [t, p] = readings[i]
301    const [prevT, prevP] = readings[i - 1]
302    if (p < prevP || t - prevT > MAX_GAP_S) { start = readings[i]; continue }
303    if (p - start[1] < MIN_STEP) continue
304    const row = [0, 0]
305    for (const q of requests) {
306      if (q[0] <= start[0] || q[0] > t) continue
307      row[0] += (q[1] + q[3] * OUTPUT_PER_WRITE) / 1e6
308      row[1] += q[2] / 1e6
309    }
310    rows.push(row)
311    ys.push(p - start[1])
312    start = readings[i]
313  }
314  return { rows, ys }
315}
316
317/** Least squares for points = rows·[W, R] with W > 0 and R ≥ 0. */
318function leastSquares(rows: number[][], ys: number[]): [number, number] | null {
319  let aa = 0, ab = 0, bb = 0, ay = 0, by = 0
320  rows.forEach(([a, b], i) => { aa += a * a; ab += a * b; bb += b * b; ay += a * ys[i]; by += b * ys[i] })
321  const det = aa * bb - ab * ab
322  if (det > 1e-12) {
323    const w = (ay * bb - by * ab) / det
324    const r = (by * aa - ay * ab) / det
325    if (w > 0 && r >= 0) return [w, r]
326  }
327  return aa > 0 && ay > 0 ? [ay / aa, 0] : null
328}
329
330/** Fits the points each interval used, drops intervals well above the fit as
331 * usage elsewhere (claude.ai, another machine) and fits again; the read weight's
332 * range comes from refitting resampled intervals. */
333function fitWeights(logs: Log[], column: 1 | 2, kind: string): Fit {
334  const { rows, ys } = quotaIntervals(logs, column)
335  const none: Fit = { kind, intervals: rows.length, dropped: 0, writePerPoint: null, weights: null, readRange: null }
336  const first = leastSquares(rows, ys)
337  if (!first) return none
338  const kept = rows.map((r, i) => i).filter(i => ys[i] <= OUTLIER * (rows[i][0] * first[0] + rows[i][1] * first[1]))
339  const keptRows = kept.map(i => rows[i])
340  const keptYs = kept.map(i => ys[i])
341  const fit = leastSquares(keptRows, keptYs)
342  if (!fit) return none
343  let seed = 1
344  const random = () => (seed = (seed * 1103515245 + 12345) % 2147483648) / 2147483648
345  const reads: number[] = []
346  for (let n = 0; n < RESAMPLES; n++) {
347    const pick = keptRows.map(() => Math.floor(random() * keptRows.length))
348    const again = leastSquares(pick.map(i => keptRows[i]), pick.map(i => keptYs[i]))
349    if (again) reads.push(again[1] / again[0])
350  }
351  reads.sort((a, b) => a - b)
352  return {
353    kind,
354    intervals: kept.length,
355    dropped: rows.length - kept.length,
356    writePerPoint: 1e6 / fit[0],
357    weights: { write: 1, read: fit[1] / fit[0], output: OUTPUT_PER_WRITE },
358    readRange: reads.length >= RESAMPLES / 2 ? [reads[Math.floor(reads.length * 0.1)], reads[Math.floor(reads.length * 0.9)]] : null,
359  }
360}
361
362function fitText(fit: Fit): string {
363  const head = `${fit.kind}: ${fit.intervals} intervals` + (fit.dropped ? `, ${fit.dropped} dropped as usage elsewhere` : '')
364  if (!fit.weights) return `${head}, no fit yet`
365  const range = fit.readRange ? ` (${fit.readRange[0].toFixed(3)} to ${fit.readRange[1].toFixed(3)})` : ''
366  return `${head}; 1% = ${tokensText(fit.writePerPoint)} cache-write tokens; cache read = ${fit.weights.read.toFixed(3)}${range} of a cache write, API 0.05 to 0.08`
367}
368
369function tokensText(tokens: number | null): string {
370  if (tokens === null) return ''
371  return tokens >= 1e6 ? `${(tokens / 1e6).toFixed(1)}M` : `${Math.round(tokens / 1e3)}k`
372}
373
374const windowMs: Record<string, number> = { five_hour: 5 * 3600e3, seven_day: 7 * 86400e3 }
375const labels: Record<string, string> = { five_hour: '5h', seven_day: '7d', spend_limit: 'spend' }
376const days = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']
377
378
379function resetText(limit: Limit, now: number): string {
380  if (!limit.resetsAt) return ''
381  const at = new Date(limit.resetsAt)
382  const time = `${pad(at.getHours())}:${pad(at.getMinutes())}`
383  return at.getTime() - now < 20 * 3600e3 ? time : `${days[at.getDay()]} ${time}`
384}
385
386type Gift = { at: number; by?: string; device?: string | null }
387
388/** `🎁 Sat 23:51 · Andras · Mac`: the week's last gift reset as Agent Profiles writes it per account, where installed. */
389export function giftText(g: Gift): string {
390  const at = new Date(g.at)
391  const who = g.by === 'Andras' ? `${g.by} · ${g.device ?? 'device?'}` : g.by ?? 'gift'
392  return `🎁 ${days[at.getDay()]} ${pad(at.getHours())}:${pad(at.getMinutes())} · ${who}`
393}
394
395async function readGift($: any): Promise<Gift | null> {
396  const home = await $.env.get('HOME')
397  const email = (await $.env.get('CLAUDE_CODE_USER_EMAIL'))?.toLowerCase()
398  if (!home || !email) return null
399  const path = `${home}/Library/Application Support/Agent Profiles/resets/${email}.json`
400  if (!(await $.fs.exists(path))) return null
401  try {
402    const gifts = (JSON.parse(await $.fs.read(path))?.gifts ?? []) as Gift[]
403    return gifts.sort((a, b) => b.at - a.at)[0] ?? null
404  } catch { return null }
405}
406
407/** Weekly use never falls by itself within a week, so a drop this large under the same reset time is a claimed reset. */
408const CLAIM_DROP = 10
409/** The reset time read back moves by a second between reads. */
410const RESET_JITTER_MS = HOUR
411
412export type WeekReading = { resetsAt: string; percent: number; claimedAt: number | null }
413
414/** The account's weekly reading after `limit` arrives at `at`. A Claude saved reset zeroes the weekly use and keeps
415 * the weekly reset time (Personal, 2026-10-10 21:51Z: 91% to 0%, reset still Oct 14 16:00Z), so the week then runs
416 * from the claim to the reset, not from seven days before it. */
417export function nextWeek(last: WeekReading | null, limit: Limit, at: number): WeekReading | null {
418  if (limit.kind !== 'seven_day' || !limit.resetsAt) return last
419  const sameWeek = last !== null && Math.abs(new Date(last.resetsAt).getTime() - new Date(limit.resetsAt).getTime()) <= RESET_JITTER_MS
420  const claimedAt = !sameWeek ? null : last!.percent - limit.percentUsed >= CLAIM_DROP ? at : last!.claimedAt
421  return { resetsAt: limit.resetsAt, percent: limit.percentUsed, claimedAt }
422}
423
424/** Where the window started: a claim that refilled it, else its length before the reset. */
425function windowStart(limit: Limit, claimedAt: number | null): number | null {
426  const length = windowMs[limit.kind]
427  if (!length || !limit.resetsAt) return null
428  const end = new Date(limit.resetsAt).getTime()
429  return limit.kind === 'seven_day' && claimedAt !== null && claimedAt < end && end - claimedAt < length ? claimedAt : end - length
430}
431
432/** Share of the window gone, 0 to 1, or null without a running window. */
433export function elapsed(limit: Limit, now: number, claimedAt: number | null = null): number | null {
434  const start = windowStart(limit, claimedAt)
435  if (start === null) return null
436  const end = new Date(limit.resetsAt!).getTime()
437  const left = end - now
438  return left > 0 && now >= start ? 1 - left / (end - start) : null
439}
440
441/** Red from 95%, orange from 80%, yellow while ahead of an even pace, else white. */
442function tint(percent: number, gone: number | null): string {
443  if (percent >= 95) return '#ff453a'
444  if (percent >= 80) return '#ff8c00'
445  return gone !== null && percent / 100 > gone + 0.05 ? '#ffd60a' : '#f5f5f7'
446}
447
448/** Where the current rate lands by the reset; none in the first tenth of the window. */
449function projected(limit: Limit, now: number, claimedAt: number | null): number | null {
450  const gone = elapsed(limit, now, claimedAt)
451  if (gone === null || gone < 0.1 || limit.percentUsed <= 0) return null
452  return Math.min(Math.round(limit.percentUsed / gone), 100)
453}
454
455/** Hour notches for the 5h window, midnights for the week. */
456function notches(limit: Limit, claimedAt: number | null): number[] {
457  const start = windowStart(limit, claimedAt)
458  if (start === null) return []
459  const end = new Date(limit.resetsAt!).getTime()
460  const length = end - start
461  const step = windowMs[limit.kind] > 86400e3 ? 'day' : 'hour'
462  const line = new Date(start)
463  if (step === 'day') line.setHours(0, 0, 0, 0)
464  else line.setMinutes(0, 0, 0)
465  const marks: number[] = []
466  for (;;) {
467    if (step === 'day') line.setDate(line.getDate() + 1)
468    else line.setHours(line.getHours() + 1)
469    if (line.getTime() >= end) return marks
470    marks.push((line.getTime() - start) / length)
471  }
472}
473
474function bar(limit: Limit, now: number, width: number, height: number, claimedAt: number | null): string {
475  const x = (share: number) => (Math.min(Math.max(share, 0), 1) * width).toFixed(1)
476  const used = limit.percentUsed / 100
477  const gone = elapsed(limit, now, claimedAt)
478  const color = tint(limit.percentUsed, gone)
479  const ahead = projected(limit, now, claimedAt)
480  let svg = `<svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="${height}" viewBox="0 0 ${width} ${height}">`
481    + `<rect width="${width}" height="${height}" rx="2" fill="#000" fill-opacity="0.4"/>`
482  if (ahead !== null && ahead > limit.percentUsed) {
483    svg += `<rect x="${x(used)}" y="0.5" width="${(Number(x(ahead / 100)) - Number(x(used))).toFixed(1)}" height="${height - 1}" fill="none" stroke="${color}" stroke-opacity="0.5" stroke-dasharray="2 2"/>`
484  }
485  svg += `<rect width="${x(used)}" height="${height}" rx="2" fill="${color}"/>`
486  for (const mark of notches(limit, claimedAt)) svg += `<rect x="${x(mark)}" y="0" width="1" height="${height}" fill="#000" fill-opacity="0.35"/>`
487  if (gone !== null) svg += `<rect x="${(Number(x(gone)) - 1).toFixed(1)}" y="0" width="2" height="${height}" fill="#8b8d98"/>`
488  return svg + `</svg>`
489}
490
491type Options = { iMessageTo?: string; keepWarmMaxIdle?: string }
492
493/** A plain filled bar for a share of 0 to 1. */
494function meter(share: number, color: string, width: number, height: number): string {
495  const fill = (Math.min(Math.max(share, 0), 1) * width).toFixed(1)
496  return `<svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="${height}" viewBox="0 0 ${width} ${height}">`
497    + `<rect width="${width}" height="${height}" rx="2" fill="#000" fill-opacity="0.4"/>`
498    + `<rect width="${fill}" height="${height}" rx="2" fill="${color}"/></svg>`
499}
500
501/** The Agent Profiles Mac app shows each account's quota; the figures every response carries
502 * spare it a request to Anthropic's rate-limited usage endpoint. Written only where that app is
503 * installed, one file per account (Desktop sessions name it) or per CLI config folder. */
504async function handOff($: any, rateLimits: unknown[]): Promise<void> {
505  const home = await $.env.get('HOME')
506  if (!home) return
507  const root = home + '/Library/Application Support/Agent Profiles'
508  if (!(await $.fs.exists(root))) return
509  const account = await $.env.get('CLAUDE_CODE_ACCOUNT_UUID')
510  const configDir = await $.env.get('CLAUDE_CONFIG_DIR')
511  const name = await accountName($)
512  const email = await $.env.get('CLAUDE_CODE_USER_EMAIL')
513  await $.fs.write(`${root}/mod-readings/${name}.json`, JSON.stringify({ at: new Date().toISOString(), account, email, configDir, rateLimits }))
514}
515
516/** One name per account (Desktop sessions name it) or per CLI config folder; every profile shares this store. */
517async function accountName($: any): Promise<string> {
518  const account = await $.env.get('CLAUDE_CODE_ACCOUNT_UUID')
519  const configDir = await $.env.get('CLAUDE_CONFIG_DIR')
520  return account ? 'account-' + account : 'config-' + (configDir ?? 'default').replace(/[^A-Za-z0-9]+/g, '-')
521}
522
523/** Keeps the account's weekly reading in the store, so a claim seen in one session reaches the others. */
524async function trackWeek($: any, rateLimits: Limit[], at: number) {
525  const seven = rateLimits.find(l => l.kind === 'seven_day')
526  if (!seven) return
527  const key = 'week:' + await accountName($)
528  const last = ((await $.store.get(key)) as WeekReading | undefined) ?? null
529  const next = nextWeek(last, seven, at)
530  if (next && (next.percent !== last?.percent || next.claimedAt !== last?.claimedAt || next.resetsAt !== last?.resetsAt)) await $.store.set(key, next)
531  await update($, weekClaim, () => next?.claimedAt ?? null)
532}
533
534type Calibration = { own: { key: string; log: Log } | null; fits: Fit[]; fittedAt: number }
535
536async function ownLog($: any, c: Calibration): Promise<{ key: string; log: Log }> {
537  const key = LOG_PREFIX + await $.session.id()
538  if (c.own?.key !== key) c.own = { key, log: ((await $.store.get(key)) as Log | undefined) ?? { updated: 0, requests: [], readings: [] } }
539  return c.own
540}
541
542/** Expired session logs are dropped; when the store refuses a write as
543 * over its 4 MiB, the oldest other log goes and the write is tried again. */
544async function calibrationLogs($: any): Promise<{ key: string; log: Log }[]> {
545  const now = await $.clock.now()
546  const found: { key: string; log: Log }[] = []
547  for (const key of (await $.store.keys()) as string[]) {
548    if (!key.startsWith(LOG_PREFIX)) continue
549    const log = (await $.store.get(key)) as Log | undefined
550    if (!log || now - log.updated > KEEP_MS) await $.store.delete(key)
551    else found.push({ key, log })
552  }
553  return found.sort((a, b) => a.log.updated - b.log.updated)
554}
555
556async function saveLog($: any, mine: { key: string; log: Log }) {
557  for (let attempt = 0; attempt < 3; attempt++) {
558    try {
559      await $.store.set(mine.key, mine.log)
560      return
561    } catch {
562      const oldest = (await calibrationLogs($)).find(l => l.key !== mine.key)
563      if (!oldest) break
564      await $.store.delete(oldest.key)
565    }
566  }
567  $.ui.toast('quota-band: calibration log not saved')
568}
569
570/** Keep-warm is per thread: the session ids it is on for, in the store so a restart keeps them. */
571const WARM_PREFIX = 'keep-warm/'
572
573async function setKeepWarm($: any, on: boolean) {
574  const key = WARM_PREFIX + await $.session.id()
575  const now = await $.clock.now()
576  if (on) await $.store.set(key, { since: now })
577  else await $.store.delete(key)
578  await update($, warm, () => (on ? freshWarm(now) : null))
579}
580
581async function refit($: any, c: Calibration) {
582  const all = (await calibrationLogs($)).map(l => (l.key === c.own?.key ? c.own.log : l.log))
583  if (c.own && !all.includes(c.own.log)) all.push(c.own.log)
584  c.fits = [fitWeights(all, 1, '5h'), fitWeights(all, 2, '7d')]
585  c.fittedAt = await $.clock.now()
586}
587
588export const register: Register = (on, options: Options = {}) => {
589  let pinged = { at: 0, step: -1 }
590  let title: string | null = null
591  let observedTtl: number | null = null
592  let baseline: { path: string; tokens: number } | null = null
593  const calibration: Calibration = { own: null, fits: [], fittedAt: 0 }
594  const warmLimit = parseMaxIdle(options.keepWarmMaxIdle)
595  // Main-loop turns in flight, from turn.start to turn.complete. A reload mid-turn
596  // starts it empty; $.prompt.submit still waits for the session to be idle.
597  const running = new Set<string>()
598  let warmTurn = false
599
600  on('command.run', { command: 'quota-weights' }, async $ => {
601    await refit($, calibration)
602    const used = usable(calibration.fits[0]) ? 'measured 5h weights' : `API price ratios until 5h has ${MIN_INTERVALS} intervals and a cache read range within ±${MAX_SPREAD * 100}%`
603    return { text: [...calibration.fits.map(fitText), `output stays at ${OUTPUT_PER_WRITE} cache writes per token`, `cost × uses ${used}`].join('\n') }
604  })
605
606  on('command.run', { command: 'keep-warm' }, async ($, e) => {
607    const wanted = warmWanted(e.args, (await read($, warm)) !== null)
608    if (wanted === null) return { text: 'Usage: /keep-warm [on|off]' }
609    await setKeepWarm($, wanted)
610    return { text: wanted ? 'keep-warm on for this thread' : 'keep-warm off for this thread' }
611  })
612
613  on('session.start', async ($, e, next) => {
614    const result = await next(e)
615    await $.command.register({ name: 'quota-weights', description: 'How much of the 5h and 7d quota cache reads and output use, measured against cache writes' })
616    await $.command.register({ name: 'keep-warm', description: 'Ping this thread before its prompt cache goes cold', argumentHint: '[on|off]', immediate: true })
617    await ownLog($, calibration)
618    await refit($, calibration)
619    const usage = await $.session.usage()
620    if (usage.rateLimits.length > 0) await update($, limits, () => usage.rateLimits)
621    const stored = (await $.store.get('week:' + await accountName($))) as WeekReading | undefined
622    await update($, weekClaim, () => stored?.claimedAt ?? null)
623    if (await $.store.get(WARM_PREFIX + await $.session.id())) {
624      const now = await $.clock.now()
625      await update($, warm, w => w ?? freshWarm(now))
626    } else await update($, warm, () => null)
627    $.clock.every(60e3, () => { update($, tick, n => n + 1) })
628    $.clock.every(COLD_CHECK_MS, () => {
629      read($, turn).then(async last => {
630        if (!last) return
631        const now = Date.now()
632        const w = await read($, warm)
633        if (w) {
634          const draft = (await $.prompt.read()).text
635          if (keepWarmDue({ now, last, running: running.size > 0, draft, warm: w, limit: warmLimit }) === 'ping') {
636            await update($, warm, v => ({ ...(v ?? w), sent: (v ?? w).sent + 1, pingedFor: last.at }))
637            void $.prompt.submit({ text: KEEP_WARM_PROMPT })
638            return
639          }
640          // An armed keep-warm pings before the cache goes cold, so the cold pings would only be noise.
641          if (warmArmed(last.ttlMs, w, warmLimit, now)) return
642        }
643        const left = last.at + last.ttlMs - now
644        const step = coldStep(left, last.ttlMs)
645        if (step === null || step < 0) return
646        if (pinged.at === last.at && pinged.step >= step) return
647        pinged = { at: last.at, step }
648        const minutes = left >= 60e3 ? `${Math.round(left / 60e3)} min` : `${Math.round(left / 1e3)} s`
649        const text = `Prompt cache ${COLD_STEPS[step] * 100}% warm · cold in ${minutes} · ${tokensText(last.tokens)} to rebuild`
650        $.ui.toast(text, { timeoutMs: 10e3 })
651        const folder = (await $.session.cwd().catch(() => '')).split('/').pop()
652        await notify($, title ?? folder ?? 'Claude', text)
653        if (options.iMessageTo) await sendIMessage($, String(options.iMessageTo), `${title ?? folder ?? 'Claude'}: ${text}`)
654      })
655    })
656    return result
657  })
658
659  on('turn.start', async ($, e, next) => {
660    running.add(e.turnId)
661    warmTurn = e.text.includes(KEEP_WARM_PROMPT)
662    return next(e)
663  })
664
665  on('turn.complete', async ($, e, next) => {
666    try { return await next(e) } finally { running.delete(e.turnId) }
667  })
668
669  // Every prompt but this plugin's own pings (a hook never sees its plugin's own submit) restarts the idle count.
670  on('prompt.submit', async ($, e, next) => {
671    if (!e.agentId && (await read($, warm))) {
672      const now = await $.clock.now()
673      await update($, warm, w => (w ? freshWarm(now) : w))
674    }
675    return next(e)
676  })
677
678  on('session.measure', async ($, e, next) => {
679    if (e.rateLimits.length > 0) {
680      await update($, limits, () => e.rateLimits)
681      handOff($, e.rateLimits).catch(() => {})
682    }
683    const ttlMs = observedTtl ?? await cacheTtl($, e.rateLimits.length > 0)
684    const at = await $.clock.now()
685    if (e.rateLimits.length > 0) await trackWeek($, e.rateLimits, at).catch(() => {})
686    const found = await readGift($).catch(() => null)
687    await update($, gift, () => found)
688    await update($, turn, () => ({ at, tokens: e.context.tokens ?? null, window: e.context.window ?? null, ttlMs }))
689    const five = e.rateLimits.find(l => l.kind === 'five_hour')?.percentUsed ?? null
690    const seven = e.rateLimits.find(l => l.kind === 'seven_day')?.percentUsed ?? null
691    if (five !== null || seven !== null) {
692      const { log } = await ownLog($, calibration)
693      const last = log.readings[log.readings.length - 1]
694      const t = Math.round(at / 1e3)
695      if (!last || last[1] !== five || last[2] !== seven || t - (last[0] as number) >= READING_EVERY_S) log.readings.push([t, five, seven])
696    }
697    return next(e)
698  })
699
700  on('classic.Stop', async ($, e, next) => {
701    const result = await next(e)
702    const path: string | undefined = (e as any).transcript_path
703    if (!path) return result
704    const tail = await transcriptEnd($, 'tail', path)
705    if (!tail) return result
706    title = threadTitle(tail) ?? title
707    const ttlMs = writtenTtl(tail)
708    if (ttlMs !== null) {
709      observedTtl = ttlMs
710      await update($, turn, last => (last ? { ...last, ttlMs } : last))
711    }
712    if (baseline?.path !== path) {
713      const head = await transcriptEnd($, 'head', path)
714      const tokens = head ? baselineTokens(head) : null
715      baseline = tokens === null ? null : { path, tokens }
716    }
717    const requests = lastTurn(tail)
718    const mine = await ownLog($, calibration)
719    const loggedUntil = mine.log.requests[mine.log.requests.length - 1]?.[0] ?? 0
720    mine.log.requests.push(...requests.map(requestRow).filter(r => r[0] > loggedUntil).reverse())
721    mine.log.updated = await $.clock.now()
722    await saveLog($, mine)
723    if (mine.log.updated - calibration.fittedAt >= REFIT_MS) await refit($, calibration)
724    if (baseline && !warmTurn) {
725      const fit = calibration.fits[0] ?? null
726      const weights = usable(fit) ? fit.weights : null
727      const value = turnMultiplier(requests, baseline.tokens, weights)
728      await update($, multiplier, () => (value === null ? null : { value, measured: weights !== null }))
729    }
730    return result
731  })
732
733  on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
734    const shown = await read($, limits)
735    const last = await read($, turn)
736    const times = await read($, multiplier)
737    const claimedAt = await read($, weekClaim)
738    const lastGift = await read($, gift)
739    const w = await read($, warm)
740    await read($, tick)
741    const below = await next(e)
742    if (e.props.hasSurvey || (shown.length === 0 && !last)) return below
743    const now = await $.clock.now()
744    const ui = $.ui.resolve(e)
745    const { Box, Text, Button } = ui
746    const left = last ? last.at + last.ttlMs - now : null
747    const cache = left === null || !last ? null
748      : left > 0 ? { text: `${Math.ceil(left / 60e3)}m`, share: left / last.ttlMs, color: left <= COLD_SOON ? '#ff8c00' : '#f5f5f7' }
749      : { text: 'cold', share: 0, color: '#ff453a' }
750    const warmText = warmLabel(w, last, warmLimit, now)
751    const context = last?.tokens && last.window ? { share: last.tokens / last.window, percent: Math.round((last.tokens / last.window) * 100) } : null
752    const line = shown.map(l => `${labels[l.kind] ?? l.kind} ${Math.round(l.percentUsed)}%` + (l.resetsAt ? ` · ${resetText(l, now)}` : '')
753      + (l.kind === 'seven_day' && lastGift ? ` · ${giftText(lastGift)}` : '')).join('   ')
754      + (context ? `   ctx ${context.percent}% · ${tokensText(last!.tokens)}` : '')
755      + (cache ? `   cache ${cache.text}` : '')
756      + `   ${warmText}`
757      + (times ? `   cost ×${times.value.toFixed(1)}${times.measured ? ' measured' : ''}` : '')
758    // Wider than any terminal; the divider row clips it to the band's width.
759    const divider = below ? <Box height={1} overflow="hidden"><Text dimColor>{'─'.repeat(400)}</Text></Box> : null
760    if (e.surface !== 'desktop' || !('Svg' in ui)) return <Box flexDirection="column"><Text dimColor>{line}</Text>{divider}{below}</Box>
761    const { Svg } = ui as any
762
763    return (
764      <Box flexDirection="column">
765      <Box flexDirection="row" alignItems="center" columnGap={2}>
766        {shown.map(l => (
767          <Box key={l.kind} flexDirection="row" alignItems="center" columnGap={1}>
768            <Text dimColor>{labels[l.kind] ?? l.kind}</Text>
769            <Svg source={bar(l, now, 120, 8, claimedAt)} alt={`${l.kind} ${l.percentUsed}%`} width={120} height={8} />
770            <Text>{Math.round(l.percentUsed)}%</Text>
771            {projected(l, now, claimedAt) !== null && projected(l, now, claimedAt)! > Math.round(l.percentUsed) ? <Text dimColor>→ {projected(l, now, claimedAt)}%</Text> : null}
772            {l.resetsAt ? <Text dimColor>{resetText(l, now)}</Text> : null}
773            {l.kind === 'seven_day' && lastGift ? <Text dimColor>{giftText(lastGift)}</Text> : null}
774          </Box>
775        ))}
776        {context ? (
777          <Box flexDirection="row" alignItems="center" columnGap={1}>
778            <Text dimColor>ctx</Text>
779            <Svg source={meter(context.share, tint(context.percent, null), 60, 8)} alt={`context ${context.percent}%`} width={60} height={8} />
780            <Text>{context.percent}%</Text>
781            <Text dimColor>{tokensText(last!.tokens)}</Text>
782          </Box>
783        ) : null}
784        {cache ? (
785          <Box flexDirection="row" alignItems="center" columnGap={1}>
786            <Text dimColor>cache</Text>
787            <Svg source={meter(cache.share, cache.color, 60, 8)} alt={`cache ${cache.text}`} width={60} height={8} />
788            <Text color={cache.color === '#f5f5f7' ? undefined : cache.color}>{cache.text}</Text>
789          </Box>
790        ) : null}
791        <Button key="keep-warm" label={warmText} dimColor={w === null} onPress={() => setKeepWarm($, w === null)} />
792        {times ? (
793          <Box flexDirection="row" alignItems="center" columnGap={1}>
794            <Text dimColor>cost</Text>
795            <Text>×{times.value.toFixed(1)}</Text>
796            {times.measured ? <Text dimColor>measured</Text> : null}
797          </Box>
798        ) : null}
799      </Box>
800      {divider}
801      {below}
802      </Box>
803    )
804  })
805}
806
types/index.d.ts 16 lines
1export type Limit = { kind: string; percentUsed: number; resetsAt?: string }
2
3export type Multiplier = { value: number; measured: boolean }
4
5/** Keep-warm pings since his last prompt, when that prompt came, and the
6 * response (`Turn.at`) the last ping was sent for. */
7export type Warm = { sent: number; idleSince: number; pingedFor: number | null }
8
9export type Turn = { at: number; tokens: number | null; window: number | null; ttlMs: number }
10
11declare module 'claude-code' {
12  interface PluginState {
13    'quota-band': { limits: Limit[]; turn: Turn | null; multiplier: Multiplier | null; tick: number; weekClaim: number | null; gift: { at: number; by?: string; device?: string | null } | null; warm: Warm | null }
14  }
15}
16