SLOPSHOPPER

limits

Claude Code mod: your 5h/7d quota, context window, prompt-cache time left and session cost on one line above the prompt, with per-subagent cost on hover

bandguardpromptprocesstimeragents
★ 1v0.9.0MITupdated 2026-10-20VaitaR/claude-code-limits
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · limits
› 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 5h ━━━━━━ 31% ctx ━━━━━━ 49% cache ○ cold $0.42 ❯ fix the failing auth test and add an audit … ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Band
5h ━━━━━━ 31% ctx ━━━━━━ 49% cache ○ cold $0.42 ❯ fix the failing auth test and add an audit …
README

limits

License: MIT Claude Code 2.1.287+

Know how much room you have left before the next prompt. A Claude Code mod that puts your 5h and 7d quota, context, prompt-cache time and session cost on one line above the prompt, with the subagents still running and what you last asked. It works in the terminal and the desktop app; hover a segment for details.

<img src="docs/media/demo.gif" alt="A Claude Code session in the terminal. A prompt asks for an Explore subagent; the line above the prompt shows the cache as live during the turn, then the running Explore agent, whose hover reads 1 subagent running. The last prompt has a row under the line. Hovering 5h, 7d, ctx, cache and the cost in turn shows each one's details on the row below, under the segment, the cost split into main thread and subagent" width="760">

<a href="#install">Install</a> · <a href="#what-you-see">What you see</a> · <a href="#configure">Configure</a> · <a href="#make-it-yours">Make it yours</a> · <a href="#what-it-can-reach">What it can reach</a>

Install

Inside Claude Code (2.1.287 or later):

/plugin marketplace add VaitaR/claude-code-limits
/plugin install limits@claude-code-limits
/reload-plugins
git clone https://github.com/VaitaR/claude-code-limits
claude --plugin-dir ./claude-code-limits

Mods are an early-access Claude Code feature and their API can change between releases.

What you see

Terminal
<img src="docs/media/band.png" alt="The band in a terminal: 5h and 7d quota gauges with their resets, the context gauge, the cache dot with minutes left and the session cost, with the last prompt on a row of its own" width="760">
Desktop app
<img src="docs/media/desktop.png" alt="The band in the Claude desktop app above the prompt box: 5h 22% resetting in 2h22m, 7d 49% resetting in 4d19h, context 61% in amber after two compactions, cache live for 59 minutes, $19.51" width="760">

Hovering a segment shows its details: the desktop app lists them as rows, a terminal joins them into one line in a blank row the band keeps under itself, below the segment, or across the segment's row when the band has no row to spare.

SegmentShowsHover, for example
5h 7dhow much of each rate-limit window your plan reports is used, and after ↻ the time to its reset5h · 21% used, 79% left · resets 18:07
ctxcontext against the window Claude Code compacts at; ⟲3 after three compactionsctx · 31k of 258k tokens · 3 compactions
cache● live while a turn runs, then ● 59m, the minutes the prompt cache has left (seconds in its last minute), and ○ cold once it has nonecache · warm until 16:31 (1h TTL)
$0.20the session's cost at API prices, subagents includedsession $0.20 at API prices, subagents included, then the last turn's cost; with a costCommand, rows for the main thread and the subagents
◐ Explorethe subagents running now: the type of one, ◐ 3 agents for several1 subagent running, then per agent its type and task, and a row with how long it has run, its model, its last request's context, its tool calls so far and the latest one: 1m59s · Sonnet 5.5 · 156k ctx · 48 tools · Bash(Find RPC clients)
❯ fix the flaky…your last prompt, in the room the line has left and cut with …; with less than 40 cells left, on a row of its own when there is room for onelast prompt · sent 16:18, then the prompt in full

Quiet until it matters. While all is well the gauges, cache and cost stay in plain text colours. Amber and red mark what needs attention:

AmberRed
5h 7d70% used90% used
ctx60%, and the ⟲N of compactions80%
cacheunder 5 minutes leftexpired: the next prompt rewrites the cache

Model, branch, effort and the like are left to the rest of the app. On a narrow window the line moves whole segments to a second row rather than cutting one; only the last prompt is cut to fit.

Configure

In /config, or under pluginConfigs["limits"].options in settings.json:

OptionDefaultMeaning
cacheTtl1hthe main loop's prompt-cache lifetime: 1h with extended caching, 5m otherwise
palettethemetheme follows your Claude Code theme (light, dark, colour-blind); pastel uses fixed colours tuned for dark terminals
costCommandemptya command that prints the session's cost split as JSON; it is split on spaces into arguments, without quoting

The command gets the session id as its last argument and prints one JSON object:

{ "total_usd": 5.85, "main_usd": 5.75, "unpriced_calls": 0,
  "agents": [{ "agent_type": "Explore", "description": "map the repo", "usd": 0.1 }] }

Only total_usd is required; a missing amount counts as zero. The hover lists agents in the order given, so print the costliest first: it names the first six and sums the rest into one row, and a non-zero unpriced_calls adds a row of its own. For the object above it reads:

session $5.85 at API prices
$5.75 main
$0.10 Explore · map the repo
+$0.42 last turn

The command runs at session start and at the end of each main turn and each subagent, one run at a time, with a 15 s timeout. A non-zero exit, a timeout or output without total_usd keeps the last split. The customize-limits skill explains how to price a transcript.

Make it yours

The plugin ships a skill, customize-limits, that knows where each threshold, colour, gauge and segment lives, how to add one and test it, and the traps of drawing in a terminal. Ask Claude in plain words:

make the context gauge turn amber at 50%

hide the cost segment, or the last prompt while I share my screen

add a segment with the current git branch

wire a costCommand for my sessions

What it can reach

It only watches. No hook denies or rewrites a prompt, a tool call or a subagent; the one drawing hook fills the line above the prompt.

It readsThrough
context, cost and rate-limit readingssession.measure, $.session.usage()
when the main loop's requests are sent and answered; a subagent's model and token counts per requestturn.step
a subagent's tool calls: the tool and the argument that names its target (a Bash call's description or command, a file's name, a search pattern)tool.call
the text of your own prompts: typed, from the desktop app or Remote Control, never a notification's or another plugin'sprompt.submit
compactionssession.compact
subagent spawns and ends: type, description, modelagent.spawn, turn.complete
the tail of this session's transcript, at session start while no request or prompt has been seen yet, to start the cache clock, show the last prompt Claude Code recorded and the context of the last responsesh -c tail -c 400000 ~/.claude/projects/*/<session id>.jsonl
the latest 5h/7d readings of every session under the same config directory, and this session's own into it, every 30 s and at each reading$.fs on <config dir>/state/limits/quota.json (CLAUDE_CONFIG_DIR, else ~/.claude)
your costCommand's output, if you set one$.process.run

It makes no network requests and calls no model; your costCommand runs as you wrote it. State lives in session atoms and ends with the session, except the quota file, which holds only the readings of the windows still open. claude plugin validate . prints exactly what it hooks and calls.

What is inferred, not measured

  • The cache clock starts when the main loop's last answered request was sent and runs for cacheTtl. The engine reports no TTL, so a wrong cacheTtl gives a wrong clock. A compaction sets the cache to cold.
  • Quotas are account-wide. Parallel sessions spend the same windows, so every session shows the latest reading any of them received (the hover says when it was read): an idle session lags by up to 30 s behind a busy one, and with no session busy the figure is as old as the last response. A window past its reset is not drawn until the next reading. Sessions share readings through their config directory, so two accounts under two directories never mix.
  • After a restart (the desktop app stops a hidden session's process after a while idle, and starts it again when you come back) the context gauge shows the transcript's last response until the next one; the compaction count starts from zero.
  • Cost is the engine's API-price figure. On a subscription it is what the session would cost at API prices, not a bill.

Develop

claude --plugin-dir .            # load it; edits hot-reload
claude plugin validate .
claude plugin test .
npx -p typescript tsc -p .       # after the first load, which writes .claude-plugin/types/
FileHolds
hooks/register.tsxthe event hooks and the band
hooks/core.tsconfig, formatting and readings as pure functions
hooks/countdown.tsxa surface module: the reset and cache countdowns tick on the surface's own clock
types/index.d.tsthe state contract
skills/customize-limits/the skill for tuning and extending the band

See CONTRIBUTING.md. Changes are listed in CHANGELOG.md.

License

MIT. Started as a fork of claude-flightdeck by Stephen Casella.

Source 4 files
hooks/register.tsx 594 lines
1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, Register, RenderChildren } from 'claude-code'
3
4import type { LastPrompt, Running, Usage } from '../types'
5
6type Limit = Usage['limits'][number]
7import {
8  DEFAULT_USAGE,
9  PALETTES,
10  activityOf,
11  agentLines,
12  contextOf,
13  contextTokens,
14  fmtAgo,
15  fmtAt,
16  fmtCacheLeft,
17  fmtLeft,
18  fmtUsd,
19  freshLimits,
20  gaugeCells,
21  kTokens,
22  lastContextOf,
23  lastPromptOf,
24  lastRequestAt,
25  limitLabel,
26  limitsOf,
27  listOf,
28  mergeLimits,
29  newestLimits,
30  normalize,
31  parseConfig,
32  parseCostSplit,
33  parseQuota,
34  plural,
35  promptLine,
36  quotaLevel,
37  shorten,
38  splitLines,
39} from './core'
40import type { Config } from './core'
41
42// ---------------------------------------------------------------- state
43
44const usage = atom({ plugin: 'limits', key: 'usage' } as const, DEFAULT_USAGE)
45const cacheAt = atom({ plugin: 'limits', key: 'cacheAt' } as const, 0)
46const running = atom({ plugin: 'limits', key: 'running' } as const, [])
47const costAtStart = atom({ plugin: 'limits', key: 'costAtStart' } as const, null)
48const lastTurnUsd = atom({ plugin: 'limits', key: 'lastTurnUsd' } as const, null)
49const split = atom({ plugin: 'limits', key: 'split' } as const, null)
50const prompts = atom({ plugin: 'limits', key: 'prompts' } as const, [])
51
52// Every read goes through these, so a value saved under an older shape still reads.
53async function getUsage($: EngineInterface): Promise<Usage> {
54  return normalize(DEFAULT_USAGE, await read($, usage))
55}
56async function getRunning($: EngineInterface): Promise<Running[]> {
57  return listOf<Running>(await read($, running))
58}
59/** Changes one running agent; an id not in the list (spawned before a reload) changes nothing. */
60async function touch($: EngineInterface, id: string, f: (a: Running) => Running) {
61  await update($, running, list => listOf<Running>(list).map(a => (a.id === id ? f(a) : a)))
62}
63const promptsOf = (v: unknown): LastPrompt[] =>
64  listOf<Partial<LastPrompt>>(v).flatMap(p =>
65    p && typeof p.text === 'string' && p.text ? [{ text: p.text, at: typeof p.at === 'number' ? p.at : null }] : [],
66  )
67async function getPrompts($: EngineInterface): Promise<LastPrompt[]> {
68  return promptsOf(await read($, prompts))
69}
70const PROMPTS_KEPT = 10
71const PROMPT_HOVER_CHARS = 70
72const PROMPT_MIN = 40
73const PROMPT_FLOOR = 12
74const numOr = <T,>(v: unknown, d: T): number | T => (typeof v === 'number' && Number.isFinite(v) ? v : d)
75
76/**
77 * A module loaded mid-session (a reload, a resume, a later install) has seen no request and no prompt:
78 * the cache clock starts from the transcript's last main-loop request, and the last prompt is the one
79 * Claude Code recorded there. The transcript is found by session id, so no project-folder naming is
80 * assumed; only its tail is read.
81 */
82async function seedFromTranscript($: EngineInterface) {
83  const needCache = numOr(await read($, cacheAt), 0) <= 0
84  const needPrompt = (await getPrompts($)).length === 0
85  const needCtx = (await getUsage($)).tokens === null
86  if (!needCache && !needPrompt && !needCtx) return
87  const id = await $.session.id().catch(() => null)
88  if (!id || !/^[\w-]+$/.test(id)) return
89  const out = await $.process
90    .run(['sh', '-c', 'tail -c 400000 "$HOME"/.claude/projects/*/"$1".jsonl 2>/dev/null', 'sh', id], { timeoutMs: 5000 })
91    .then(r => r.stdout)
92    .catch(() => '')
93  const at = needCache ? lastRequestAt(out) : null
94  if (at) await update($, cacheAt, x => (numOr(x, 0) > 0 ? x : at))
95  const text = needPrompt ? lastPromptOf(out) : null
96  if (text) await update($, prompts, x => (promptsOf(x).length > 0 ? x : [{ text, at: null }]))
97  const tokens = needCtx ? lastContextOf(out) : null
98  if (tokens) await update($, usage, x => (normalize(DEFAULT_USAGE, x).tokens === null ? { ...normalize(DEFAULT_USAGE, x), tokens } : x))
99}
100
101// ---------------------------------------------------------------- shared quota
102
103/**
104 * Quotas are account-wide, but a session reads them only from its own responses: an idle one shows what it
105 * last heard, and a restarted one (the desktop app stops a hidden session's process after a while idle)
106 * nothing until its first response. Every session of one config directory keeps the latest reading of each
107 * window in one file and takes the others' from it.
108 */
109const QUOTA_TICK_MS = 30_000
110let quotaTick: { cancel: () => void } | null = null
111
112async function quotaPath($: EngineInterface): Promise<string | null> {
113  // `$.env.get` takes literal names only: `claude plugin validate` lists what a mod reads.
114  const config = await $.env.get('CLAUDE_CONFIG_DIR').catch(() => undefined)
115  const home = await $.env.get('HOME').catch(() => undefined)
116  const dir = config || (home ? `${home}/.claude` : '')
117  return dir ? `${dir}/state/limits/quota.json` : null
118}
119
120const sameLimits = (a: readonly Limit[], b: readonly Limit[]) => JSON.stringify(a) === JSON.stringify(b)
121
122/** Ours into the file where newer than what it holds, the others' into ours. A failure leaves both as they were. */
123async function syncQuota($: EngineInterface) {
124  const path = await quotaPath($)
125  if (!path) return
126  const [text, own, now] = await Promise.all([$.fs.read(path).catch(() => ''), getUsage($), $.clock.now()])
127  const shared = parseQuota(text)
128  const merged = newestLimits(own.limits, shared, now)
129  if (!sameLimits(merged, freshLimits(shared, now))) await $.fs.write(path, JSON.stringify({ limits: merged }))
130  if (!sameLimits(merged, freshLimits(own.limits, now))) {
131    await update($, usage, x => {
132      const u = normalize(DEFAULT_USAGE, x)
133      return { ...u, limits: newestLimits(u.limits, merged, now) }
134    })
135  }
136}
137const syncSoon = ($: EngineInterface) => void syncQuota($).catch(() => undefined)
138
139/**
140 * The window Claude Code compacts against: `autoCompactWindow` from settings, or the model's own limit.
141 * A `summary` breakdown is estimated locally and sends no request.
142 */
143async function readCompactWindow($: EngineInterface) {
144  const u = await $.session.usage({ breakdown: 'summary', columns: 40 }).catch(() => null)
145  const raw = u?.context.breakdown?.rawMaxTokens
146  if (raw) await update($, usage, x => ({ ...normalize(DEFAULT_USAGE, x), compactWindow: raw }))
147}
148
149/**
150 * One run at a time: a turn end and a subagent's end often land together. A request during a run
151 * queues one more, since the running one may have read the transcript before that end was written.
152 */
153let splitRunning = false
154let splitAgain = false
155
156/** The session's cost by transcript, from the person's `costCommand`; a failure keeps the last split. */
157async function refreshSplit($: EngineInterface, cfg: Config) {
158  if (cfg.costCommand.length === 0) return
159  if (splitRunning) {
160    splitAgain = true
161    return
162  }
163  splitRunning = true
164  try {
165    do {
166      splitAgain = false
167      const sid = await $.session.id().catch(() => null)
168      if (!sid) return
169      const r = await $.process.run([...cfg.costCommand, sid], { timeoutMs: 15_000 }).catch(() => null)
170      const s = r && r.exitCode === 0 ? parseCostSplit(r.stdout, await $.clock.now()) : null
171      if (s) await update($, split, () => s)
172    } while (splitAgain)
173  } finally {
174    splitRunning = false
175  }
176}
177
178/** The session's cost read fresh, not from the last measurement: the last turn's cost subtracts two of these. */
179async function costNow($: EngineInterface): Promise<number | null> {
180  const u = await $.session.usage().catch(() => null)
181  return u?.cost?.usd ?? null
182}
183
184async function resetAll($: EngineInterface) {
185  await update($, cacheAt, () => 0)
186  await update($, running, () => [])
187  await update($, costAtStart, () => null)
188  await update($, lastTurnUsd, () => null)
189  await update($, split, () => null)
190  await update($, prompts, () => [])
191  // The context gauge waits for the next measurement rather than showing the pre-clear fill.
192  await update($, usage, x => ({ ...normalize(DEFAULT_USAGE, x), pct: null, tokens: null, compactions: 0 }))
193}
194
195// ---------------------------------------------------------------- hooks
196
197export const register: Register = (on, options) => {
198  const cfg = parseConfig(options)
199  const C = PALETTES[cfg.palette]
200
201  on('session.start', async ($, e, next) => {
202    // A host without usage (headless, an SDK host, a session not yet bound) just starts without it.
203    const u = await $.session.usage().catch(() => null)
204    if (u) {
205      const at = await $.clock.now()
206      await update($, usage, x => ({
207        ...normalize(DEFAULT_USAGE, x),
208        pct: u.context.percent ?? null,
209        tokens: u.context.tokens ?? null,
210        window: u.context.window,
211        costUsd: u.cost?.usd ?? null,
212        limits: mergeLimits(normalize(DEFAULT_USAGE, x).limits, limitsOf(u.rateLimits, at), at),
213      }))
214    }
215    await Promise.all([seedFromTranscript($), readCompactWindow($)])
216    syncSoon($)
217    // A hot reload loads the module again and cancels its timers; session.start runs for the new one.
218    quotaTick?.cancel()
219    quotaTick = $.clock.every(QUOTA_TICK_MS, () => syncSoon($))
220    void refreshSplit($, cfg).catch(() => undefined)
221    return next(e)
222  })
223
224  on('session.end', async ($, e, next) => {
225    if (e.reason === 'clear') await resetAll($)
226    return next(e)
227  })
228
229  // The person's own words: typed, through Remote Control, from an SDK host such as the desktop app, or
230  // sent by a plugin as theirs. A task's notification, a peer session or a schedule is not their prompt.
231  on('prompt.submit', async ($, e, next) => {
232    const done = await next(e)
233    const o = e.origin
234    const own = o.kind === 'composer' || o.kind === 'bridge' || o.kind === 'sdk' || (o.kind === 'plugin' && o.asUser === true)
235    const text = promptLine(e.text)
236    // The prompt has entered by now: a failure here must not reach the person as an error on it.
237    if (own && text && !('drop' in done)) {
238      await $.clock
239        .now()
240        .then(at => update($, prompts, x => [...promptsOf(x), { text, at }].slice(-PROMPTS_KEPT)))
241        .catch(() => undefined)
242    }
243    return done
244  })
245
246  on('turn.start', async ($, e, next) => {
247    const cost = await costNow($)
248    await update($, costAtStart, () => cost)
249    return next(e)
250  })
251
252  on('turn.step', async function* ($, e, next) {
253    const id = e.agentId
254    const sentAt = id ? 0 : await $.clock.now()
255    const done = yield* next(e)
256    const u = done.usage
257    if (u && id) await touch($, id, a => ({ ...a, model: u.model || a.model, tokens: contextTokens(u) }))
258    else if (u) await update($, cacheAt, () => sentAt)
259    return done
260  })
261
262  // Counted when a call starts, so the activity is what the agent is doing now. A failed write must not
263  // fail the agent's tool.
264  on('tool.call', async ($, e, next) => {
265    const id = e.agentId
266    if (id) {
267      await touch($, id, a => ({ ...a, tools: (a.tools ?? 0) + 1, activity: activityOf(e.tool, e as unknown as Record<string, unknown>) })).catch(
268        () => undefined,
269      )
270    }
271    return next(e)
272  })
273
274  on('session.measure', async ($, e, next) => {
275    const before = await getUsage($)
276    const at = await $.clock.now()
277    await update($, usage, x => ({
278      ...normalize(DEFAULT_USAGE, x),
279      pct: e.context.percent ?? null,
280      tokens: e.context.tokens ?? null,
281      window: e.context.window,
282      costUsd: e.cost?.usd ?? null,
283      limits: mergeLimits(normalize(DEFAULT_USAGE, x).limits, limitsOf(e.rateLimits, at), at),
284    }))
285    if (e.rateLimits.length > 0) syncSoon($)
286    // A model switch changes the window; the compaction window follows it.
287    if (before.window !== e.context.window) await readCompactWindow($)
288    return next(e)
289  })
290
291  on('session.compact', async ($, e, next) => {
292    const done = await next(e)
293    if (!e.agentId && e.trigger !== 'precompute') {
294      await update($, usage, x => {
295        const u = normalize(DEFAULT_USAGE, x)
296        return { ...u, compactions: u.compactions + 1 }
297      })
298      // The compacted context is a new prefix: nothing of it is cached until the next request.
299      await update($, cacheAt, () => 0)
300    }
301    return done
302  })
303
304  on('agent.spawn', async ($, e, next) => {
305    const started = await next(e)
306    if (started.deny !== undefined || !started.agentId) return started
307    const agent: Running = {
308      id: started.agentId,
309      type: e.name ?? e.subagentType,
310      description: e.description || undefined,
311      model: started.model || undefined,
312      startedAt: await $.clock.now(),
313    }
314    await update($, running, list => [...listOf<Running>(list).filter(a => a.id !== agent.id), agent].slice(-24))
315    return started
316  })
317
318  on('turn.complete', async ($, e, next) => {
319    const done = await next(e)
320    const id = e.agentId
321    if (id) {
322      await update($, running, list => listOf<Running>(list).filter(a => a.id !== id))
323      // A subagent's transcript is final once it ends: price it while the main turn may still run.
324      void refreshSplit($, cfg).catch(() => undefined)
325      return done
326    }
327    const [start, cost] = await Promise.all([read($, costAtStart), costNow($)])
328    const from = numOr(start, null)
329    await update($, lastTurnUsd, () => (from !== null && cost !== null ? Math.max(0, cost - from) : null))
330    void refreshSplit($, cfg).catch(() => undefined)
331    return done
332  })
333
334  // ---------------------------------------------------------------- drawing
335
336  // What the rest of the app does not show, on one line above the prompt: quotas, context, cache, cost,
337  // running agents. Calm while all is well: colour marks only what needs attention. Hovering a segment
338  // shows its details.
339  on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
340    if (e.props.hasSurvey) return next(e)
341    const els = $.ui.resolve(e)
342    const { Box, Text } = els
343    const hasClient = 'Client' in els
344    const [u, agents, cache, now, lastTurn, sp, ps] = await Promise.all([
345      getUsage($),
346      getRunning($),
347      read($, cacheAt),
348      $.clock.now(),
349      read($, lastTurnUsd),
350      read($, split),
351      getPrompts($),
352    ])
353    const lp = ps[ps.length - 1] ?? null
354    const cx = contextOf(u)
355    const sentAt = numOr(cache, 0)
356    const last = numOr(lastTurn, null)
357    const levelColor = { ok: C.text, warn: C.amber, hot: C.warn }
358    // `plain` is the segment as text, for its width in a terminal's cells.
359    const segments: { key: string; node: RenderChildren; detail: string[]; cells: number }[] = []
360    const add = (key: string, node: RenderChildren, detail: string | string[], plain: string) =>
361      segments.push({ key, node, detail: typeof detail === 'string' ? [detail] : detail, cells: [...plain].length })
362    const gauge = (label: string, pct: number) => `${label} ${'━'.repeat(6)} ${Math.round(pct)}%`
363    // One glyph for both parts keeps every gauge the same width in a proportional font.
364    const meter = (label: string, pct: number, color: string) => {
365      const filled = gaugeCells(pct, 6)
366      return [
367        <Text dimColor>{`${label} `}</Text>,
368        <Text color={color === C.text ? C.dim : color}>{'━'.repeat(filled)}</Text>,
369        <Text color={C.faint}>{'━'.repeat(6 - filled)}</Text>,
370        <Text color={color} bold>{` ${Math.round(pct)}%`}</Text>,
371      ]
372    }
373
374    for (const l of freshLimits(u.limits, now).filter(l => l.kind === 'five_hour' || l.kind === 'seven_day')) {
375      const label = limitLabel(l.kind)
376      add(
377        `quota-${l.kind}`,
378        <Box>
379          {meter(label, l.pct, levelColor[quotaLevel(l.pct)])}
380          {l.resetsAt ? <Text dimColor> ↻</Text> : null}
381          {!l.resetsAt ? null : hasClient ? (
382            <els.Client key={`band-reset-${l.kind}`} module="./countdown.tsx" props={{ until: l.resetsAt, now, kind: 'left', color: C.dim, warn: C.amber, hot: C.warn }} />
383          ) : (
384            <Text dimColor>{fmtLeft(l.resetsAt - now)}</Text>
385          )}
386        </Box>,
387        `${label} · ${Math.round(l.pct)}% used, ${Math.round(100 - l.pct)}% left${l.resetsAt ? ` · resets ${fmtAt(l.resetsAt, now)}` : ''}${l.at ? ` · read ${fmtAt(l.at, now)}` : ''}`,
388        `${gauge(label, l.pct)}${l.resetsAt ? ` ↻${fmtLeft(l.resetsAt - now)}` : ''}`,
389      )
390    }
391    if (cx.pct !== null) {
392      add(
393        'ctx',
394        <Box>
395          {meter('ctx', cx.pct, cx.pct >= 80 ? C.warn : cx.pct >= 60 ? C.amber : C.text)}
396          {u.compactions > 0 ? <Text color={C.amber}>{` ⟲${u.compactions}`}</Text> : null}
397        </Box>,
398        `ctx · ${u.tokens !== null ? `${kTokens(u.tokens)} of ${kTokens(cx.limit)} tokens` : `${Math.round(cx.pct)}%`}${u.compactions > 0 ? ` · ${plural(u.compactions, 'compaction')}` : ''}`,
399        `${gauge('ctx', cx.pct)}${u.compactions > 0 ? ` ⟲${u.compactions}` : ''}`,
400      )
401    }
402    const until = sentAt + cfg.cacheTtlMs
403    const ttl = cfg.cacheTtlMs >= 3_600_000 ? '1h' : '5m'
404    add(
405      'cache',
406      <Box>
407        <Text dimColor>cache </Text>
408        {e.props.isWorking ? (
409          <Text color={C.text}>● live</Text>
410        ) : sentAt <= 0 ? (
411          <Text dimColor>○ cold</Text>
412        ) : hasClient ? (
413          <els.Client key="band-cache" module="./countdown.tsx" props={{ until, now, kind: 'cache', color: C.text, warn: C.amber, hot: C.warn }} />
414        ) : (
415          <Text color={until - now <= 0 ? C.warn : until - now < 5 * 60_000 ? C.amber : C.text}>
416            {until - now <= 0 ? '○ cold' : `● ${fmtCacheLeft(until - now)}`}
417          </Text>
418        )}
419      </Box>,
420      // Every request of a running turn re-arms the cache; the countdown starts once the turn ends.
421      e.props.isWorking
422        ? 'cache · live: each request of this turn refreshes it'
423        : sentAt <= 0
424          ? 'cache · cold: the next prompt rewrites it'
425          : until <= now
426            ? `cache · cold since ${fmtAt(until, now)}: the next prompt rewrites it`
427            : `cache · warm until ${fmtAt(until, now)} (${ttl} TTL)`,
428      `cache ${e.props.isWorking ? '● live' : sentAt <= 0 || until <= now ? '○ cold' : `● ${fmtCacheLeft(until - now)}`}`,
429    )
430
431    // The engine prices every response of the session, its subagents' included; on a plan it is the API-price equivalent.
432    if (u.costUsd !== null) {
433      add(
434        'cost',
435        <Text color={C.text}>{fmtUsd(u.costUsd)}</Text>,
436        [
437          `session ${fmtUsd(u.costUsd)} at API prices${sp ? '' : ', subagents included'}`,
438          ...(sp ? splitLines(sp) : []),
439          ...(last !== null ? [`+${fmtUsd(last)} last turn`] : []),
440        ],
441        fmtUsd(u.costUsd),
442      )
443    }
444
445    // A segment like the rest, so a narrow band wraps it whole: squeezed at the right edge it read as `◐…`.
446    if (agents.length > 0) {
447      const label = agents.length === 1 ? `◐ ${agents[0]?.type}` : `◐ ${agents.length} agents`
448      add(
449        'agents',
450        <Text color={C.agent}>{label}</Text>,
451        agentLines(agents, now),
452        label,
453      )
454    }
455
456    const width = Math.max(20, e.props.bodyColumns)
457    const hoverWidth = (rows: string[]) => Math.min(Math.max(...rows.map(l => l.length)) + 2, width)
458    const card = (key: string, rows: string[]) =>
459      rows.map((l, j) => (
460        <Text key={`${key}-${j}`} color={j === 0 ? C.text : C.dim} wrap="truncate">
461          {l}
462        </Text>
463      ))
464
465    // A terminal paints in tree order, so a hover drawn inside its segment lay under the segments after
466    // it, and it clips a hover to the band's own rows, so none can sit above the band. There the band keeps
467    // a blank row under its segments, and a hover is drawn in it under its segment, shifted left to fit:
468    // laid over the band's row it sat flush on the neighbours' text, and revealed as a row in the flow it
469    // made the band jump. With no row to spare under `maxRows` the hover covers its segment's whole row.
470    // Both places come from the band's wrap (its cells are known in a terminal). The segment lights its
471    // hover through a scope.
472    const terminal = e.surface === 'terminal'
473    const placed: { row: number; col: number }[] = []
474    let row = 0
475    let col = 0
476    for (const s of segments) {
477      const room = s.cells + 2
478      if (col > 0 && col + room > width) {
479        row += 1
480        col = 0
481      }
482      placed.push({ row, col })
483      col += room
484    }
485
486    // The last prompt takes what its row has left, cut with `…`; with less than PROMPT_MIN cells left it
487    // starts a row of its own. Its cells are set here, not by its text, so it is placed last. A band
488    // taller than `maxRows` is folded into an `n more` row, hiding every segment: the prompt then stays
489    // in what its row has left, or is left out.
490    const plain = lp ? `❯ ${lp.text}` : ''
491    const full = [...plain].length
492    if (lp && col > 0 && width - col - 2 < Math.min(full, PROMPT_MIN) && row + 2 <= e.props.maxRows) {
493      row += 1
494      col = 0
495    }
496    const cells = Math.min(full, width - col - 2)
497    // PROMPT_FLOOR bounds a cut prompt; a short one that fits whole always shows.
498    if (lp && cells >= Math.min(full, PROMPT_FLOOR)) {
499      segments.push({
500        key: 'prompt',
501        node: (
502          <Box key="band-prompt" width={cells}>
503            <Text color={C.dim} wrap="truncate">
504              {plain}
505            </Text>
506          </Box>
507        ),
508        // Newest first; elapsed time, not wall time, so no clock arithmetic is needed to read it.
509        detail: [
510          ps.length === 1 ? 'last prompt' : `last ${ps.length} prompts`,
511          ...[...ps].reverse().map(p => `${p.at !== null ? fmtAgo(now - p.at) : 'earlier'} · ${shorten(p.text, PROMPT_HOVER_CHARS)}`),
512        ],
513        cells,
514      })
515      placed.push({ row, col })
516    }
517    const under = row + 2 <= e.props.maxRows
518
519    return (
520      <Box width={width} flexDirection={terminal ? 'column' : 'row'}>
521        <Box flexWrap="wrap" flexShrink={1}>
522          {/* The gap trails each segment: a wrapped row then starts flush, where a leading `│` read as a stray mark. */}
523          {segments.map(s =>
524            terminal ? (
525              <Box key={s.key} marginRight={2} hover={{ scope: `limits-${s.key}` }}>
526                {s.node}
527              </Box>
528            ) : (
529              <Box key={s.key} marginRight={2}>
530                {s.node}
531                {/* Shown while the pointer is on the segment. Sized to its longest row: unsized, it took the
532                    segment's width and truncated. */}
533                <Box
534                  position="absolute"
535                  top={0}
536                  left={0}
537                  width={hoverWidth(s.detail)}
538                  flexDirection="column"
539                  display="none"
540                  hover={{ display: 'flex' }}
541                  backgroundColor={C.faint}
542                  paddingX={1}
543                >
544                  {card(s.key, s.detail)}
545                </Box>
546              </Box>
547            ),
548          )}
549        </Box>
550        {terminal && under ? (
551          <Box key="hover-row" height={1} width={width}>
552            {segments.map((s, i) => {
553              const line = s.detail.join(' · ')
554              const w = Math.min([...line].length, width)
555              return (
556                <Box
557                  key={`hover-${s.key}`}
558                  position="absolute"
559                  top={0}
560                  left={Math.max(0, Math.min(placed[i]?.col ?? 0, width - w))}
561                  width={w}
562                  display="none"
563                  hover={{ scope: `limits-${s.key}`, display: 'flex' }}
564                >
565                  <Text color={C.dim} wrap="truncate">
566                    {line}
567                  </Text>
568                </Box>
569              )
570            })}
571          </Box>
572        ) : null}
573        {terminal && !under
574          ? segments.map((s, i) => (
575                <Box
576                  key={`hover-${s.key}`}
577                  position="absolute"
578                  top={placed[i]?.row ?? 0}
579                  left={0}
580                  width={width}
581                  display="none"
582                  hover={{ scope: `limits-${s.key}`, display: 'flex' }}
583                  backgroundColor={C.faint}
584                  paddingX={1}
585                >
586                  {card(s.key, [s.detail.join(' · ')])}
587                </Box>
588            ))
589          : null}
590      </Box>
591    )
592  })
593}
594
hooks/core.ts 362 lines
1// Pure data: defaults, config, formatting. Nothing here touches `$`, so every behaviour is testable directly.
2import type { CostSplit, Running, Usage } from '../types'
3
4// ---------------------------------------------------------------- defaults
5
6export const DEFAULT_USAGE: Usage = {
7  pct: null,
8  tokens: null,
9  window: 0,
10  costUsd: null,
11  limits: [],
12  compactions: 0,
13  compactWindow: null,
14}
15
16/** Context against the window Claude Code compacts at, not the model's whole window. */
17export const contextOf = (u: Usage) => {
18  const limit = u.compactWindow ?? u.window
19  const pct = u.tokens !== null && limit > 0 ? (u.tokens / limit) * 100 : u.pct
20  return { limit, pct }
21}
22
23const isObject = (v: unknown): v is Record<string, unknown> => typeof v === 'object' && v !== null && !Array.isArray(v)
24
25/** A stored object merged over its defaults, so a value saved under an older shape still reads. */
26export const normalize = <T extends object>(def: T, stored: unknown): T =>
27  isObject(stored) ? ({ ...def, ...stored } as T) : def
28
29/** A stored list, or empty when what is stored is not a list. */
30export const listOf = <T>(stored: unknown): T[] => (Array.isArray(stored) ? (stored as T[]) : [])
31
32// ---------------------------------------------------------------- config
33
34export type Config = {
35  palette: Palette
36  /** argv the session id is appended to; it prints the JSON the README describes. Empty: no split. */
37  costCommand: string[]
38  /** The prompt cache's lifetime: the engine reports no 5m/1h split, so the person names theirs. */
39  cacheTtlMs: number
40}
41
42/** The plugin's `/config` values, read leniently: anything malformed falls back to the default. */
43export const parseConfig = (o: Readonly<Record<string, unknown>>): Config => {
44  const str = (k: string, d: string) => (typeof o[k] === 'string' && o[k] !== '' ? (o[k] as string) : d)
45  return {
46    palette: str('palette', 'theme') === 'pastel' ? 'pastel' : 'theme',
47    costCommand: str('costCommand', '').trim().split(/\s+/).filter(Boolean),
48    cacheTtlMs: str('cacheTtl', '1h') === '5m' ? 300_000 : 3_600_000,
49  }
50}
51
52// ---------------------------------------------------------------- palette
53
54export type Palette = 'theme' | 'pastel'
55export type Colors = Record<'agent' | 'amber' | 'warn' | 'dim' | 'faint' | 'text', string>
56
57/**
58 * `theme` names the person's own theme colours (they follow light, dark and colour-blind themes);
59 * `pastel` is fixed hex tuned for dark terminals.
60 */
61export const PALETTES: Record<Palette, Colors> = {
62  theme: { agent: 'suggestion', amber: 'warning', warn: 'error', dim: 'inactive', faint: 'subtle', text: 'text' },
63  pastel: { agent: '#93c5fd', amber: '#fcd34d', warn: '#fca5a5', dim: '#6b7280', faint: '#3f4654', text: '#e5e7eb' },
64}
65
66// ---------------------------------------------------------------- formatting
67
68export const shorten = (s: string, n: number) => {
69  const one = s.replace(/\s+/g, ' ').trim()
70  return n <= 0 ? '' : one.length > n ? `${one.slice(0, Math.max(0, n - 1)).trimEnd()}…` : one
71}
72
73export const kTokens = (n: number) =>
74  n >= 1_000_000 ? `${(n / 1_000_000).toFixed(1)}M` : n >= 1000 ? `${Math.round(n / 1000)}k` : String(n)
75
76/** `1 call`, `2 calls`. */
77export const plural = (n: number, word: string) => `${n} ${word}${n === 1 ? '' : 's'}`
78
79export const fmtUsd = (n: number) => (n >= 100 ? `$${Math.round(n)}` : `$${n.toFixed(2)}`)
80
81/** Filled cells of a `width`-cell gauge; never none while anything is used: 4% of a quota is not 0%. */
82export const gaugeCells = (pct: number, width: number) => {
83  const round = Math.max(0, Math.min(width, Math.round((pct / 100) * width)))
84  return pct > 0 ? Math.max(1, round) : round
85}
86
87/** Colour band of a quota by what is used so far. */
88export const quotaLevel = (pct: number): 'ok' | 'warn' | 'hot' => (pct >= 90 ? 'hot' : pct >= 70 ? 'warn' : 'ok')
89
90/** `2h05m`, `45m`; with days, `2d00h`. */
91export const fmtLeft = (ms: number) => {
92  const m = Math.max(0, Math.floor(ms / 60_000))
93  const d = Math.floor(m / 1440)
94  const h = Math.floor((m % 1440) / 60)
95  if (d > 0) return `${d}d${String(h).padStart(2, '0')}h`
96  return h > 0 ? `${h}h${String(m % 60).padStart(2, '0')}m` : `${m}m`
97}
98
99/** The cache in whole minutes, then seconds in its last minute: the moment to send one more prompt. */
100export const fmtCacheLeft = (ms: number) =>
101  ms <= 0 ? 'cold' : ms < 60_000 ? `${Math.min(59, Math.ceil(ms / 1000))}s` : `${Math.floor(ms / 60_000)}m`
102
103/** How long ago: `just now`, `5m ago`, `1h05m ago`, `2d03h ago`. */
104export const fmtAgo = (ms: number) => (ms < 60_000 ? 'just now' : `${fmtLeft(ms)} ago`)
105
106const DAYS = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']
107
108/** A moment as local wall time: `18:40` within a day of `now`, `Thu 14:00` further out. */
109export const fmtAt = (ms: number, now: number) => {
110  const d = new Date(ms)
111  const hm = `${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}`
112  return Math.abs(ms - now) < 86_400_000 ? hm : `${DAYS[d.getDay()]} ${hm}`
113}
114
115// ---------------------------------------------------------------- rate limits
116
117type Limit = Usage['limits'][number]
118const LIMIT_ORDER = ['five_hour', 'seven_day']
119
120/** `readAt`: when the response carrying the reading arrived, so readings of several sessions can be ordered. */
121export const limitsOf = (rateLimits: readonly { kind: string; percentUsed: number; resetsAt?: string }[], readAt?: number): Limit[] =>
122  rateLimits.map(r => {
123    const at = r.resetsAt ? Date.parse(r.resetsAt) : NaN
124    return { kind: r.kind, pct: r.percentUsed, resetsAt: Number.isFinite(at) ? at : null, ...(readAt !== undefined ? { at: readAt } : {}) }
125  })
126
127const rank = (k: string) => (LIMIT_ORDER.includes(k) ? LIMIT_ORDER.indexOf(k) : LIMIT_ORDER.length)
128const byRank = (a: Limit, b: Limit) => rank(a.kind) - rank(b.kind)
129const live = (l: Limit, now: number) => l.resetsAt == null || l.resetsAt > now
130
131/**
132 * A reading without a window keeps the last one until it resets: some responses carry no rate-limit
133 * headers, and an empty reading would otherwise blank the quotas until the next one that does.
134 */
135export const mergeLimits = (prev: readonly Limit[], next: readonly Limit[], now: number): Limit[] => {
136  const seen = new Set(next.map(l => l.kind))
137  const kept = prev.filter(l => !seen.has(l.kind) && live(l, now))
138  return [...next, ...kept].sort(byRank)
139}
140
141/** Windows still open at `now`: past its reset a reading says nothing about the new window. */
142export const freshLimits = (limits: readonly Limit[], now: number): Limit[] => limits.filter(l => live(l, now))
143
144/**
145 * Quotas are account-wide, so the latest reading of any session is the right one: per window, the reading
146 * read last wins (one without `at` loses to any with it), and windows past their reset are dropped.
147 */
148export const newestLimits = (a: readonly Limit[], b: readonly Limit[], now: number): Limit[] => {
149  const best = new Map<string, Limit>()
150  for (const l of [...a, ...b]) {
151    if (!live(l, now)) continue
152    const prev = best.get(l.kind)
153    if (!prev || (l.at ?? 0) > (prev.at ?? 0)) best.set(l.kind, l)
154  }
155  return [...best.values()].sort(byRank)
156}
157
158/** The shared quota file's readings, read leniently: a malformed file or entry is no reading. */
159export const parseQuota = (text: string): Limit[] => {
160  let o: unknown
161  try {
162    o = JSON.parse(text)
163  } catch {
164    return []
165  }
166  const list = isObject(o) && Array.isArray(o.limits) ? o.limits : []
167  const num = (v: unknown) => typeof v === 'number' && Number.isFinite(v)
168  return list.flatMap((l: unknown) =>
169    isObject(l) && typeof l.kind === 'string' && num(l.pct) && num(l.at)
170      ? [{ kind: l.kind, pct: l.pct as number, resetsAt: num(l.resetsAt) ? (l.resetsAt as number) : null, at: l.at as number }]
171      : [],
172  )
173}
174
175/** A rate-limit window's short name: `five_hour` → `5h`, `seven_day_opus` → `7d opus`. */
176export const limitLabel = (kind: string) =>
177  kind
178    .replace(/five[_ -]?hours?/i, '5h')
179    .replace(/seven[_ -]?days?/i, '7d')
180    .replace(/[_-]+/g, ' ')
181    .trim()
182
183// ---------------------------------------------------------------- cost split
184
185/** A `costCommand` answer, read leniently: anything without a total is no split. */
186export const parseCostSplit = (stdout: string, at: number): CostSplit | null => {
187  let o: Record<string, unknown>
188  try {
189    o = JSON.parse(stdout)
190  } catch {
191    return null
192  }
193  const num = (v: unknown) => (typeof v === 'number' && Number.isFinite(v) ? v : 0)
194  if (typeof o?.total_usd !== 'number') return null
195  return {
196    at,
197    totalUsd: num(o.total_usd),
198    mainUsd: num(o.main_usd),
199    unpriced: num(o.unpriced_calls),
200    agents: listOf<Record<string, unknown>>(o.agents).map(a => ({
201      type: String(a.agent_type ?? 'agent'),
202      description: String(a.description ?? ''),
203      usd: num(a.usd),
204    })),
205  }
206}
207
208/**
209 * One row per part: the main thread, the costliest agents by name, the rest summed, then unpriced calls.
210 * The amount leads: the desktop sets rows in a proportional font, so a row sized by its character count
211 * can still be truncated, and that must cut the description, never the amount.
212 */
213export const splitLines = (s: CostSplit, max = 6) => {
214  const named = s.agents.slice(0, max).map(a => `${fmtUsd(a.usd)} ${a.type}${a.description ? ` · ${shorten(a.description.toLowerCase(), 28)}` : ''}`)
215  const rest = s.agents.slice(max)
216  const more = rest.length > 0 ? [`${fmtUsd(rest.reduce((n, a) => n + a.usd, 0))} +${rest.length} more`] : []
217  const miss = s.unpriced > 0 ? [`${plural(s.unpriced, 'call')} unpriced`] : []
218  return [`${fmtUsd(s.mainUsd)} main`, ...named, ...more, ...miss]
219}
220
221// ---------------------------------------------------------------- running agents
222
223const cap = (s: string) => s.charAt(0).toUpperCase() + s.slice(1)
224
225/** `claude-sonnet-5-5` → `Sonnet 5.5`, `claude-haiku-4-5-20251001` → `Haiku 4.5`; an alias capitalised; any other id as given. */
226export const modelLabel = (id: string) => {
227  const m = /claude-([a-z]+)-(\d+)(?:-(\d{1,2}))?(?!\d)/i.exec(id)
228  if (m?.[1] && m[2]) return `${cap(m[1].toLowerCase())} ${m[2]}${m[3] ? `.${m[3]}` : ''}`
229  return /^[a-z]+$/.test(id) ? cap(id) : id
230}
231
232/** `45s`, `1m59s`, `1h02m`. */
233export const fmtElapsed = (ms: number) => {
234  const s = Math.max(0, Math.floor(ms / 1000))
235  if (s < 60) return `${s}s`
236  const m = Math.floor(s / 60)
237  return m < 60 ? `${m}m${String(s % 60).padStart(2, '0')}s` : `${Math.floor(m / 60)}h${String(m % 60).padStart(2, '0')}m`
238}
239
240/** A tool call as Claude Code shows one: `Bash(run the tests)`, `Read(core.ts)`, `Grep(fmtAt)`; the tool alone when no argument names it. */
241export const activityOf = (tool: string, args: Readonly<Record<string, unknown>>) => {
242  const s = (k: string) => (typeof args[k] === 'string' ? (args[k] as string) : '')
243  const file = s('file_path') || s('notebook_path')
244  const what =
245    tool === 'Bash'
246      ? s('description') || s('command')
247      : file
248        ? (file.split('/').filter(Boolean).pop() ?? file)
249        : s('description') || s('pattern') || s('query') || s('url') || s('path')
250  return what ? `${tool}(${shorten(what, 40)})` : tool
251}
252
253/** A request's context: what it sent plus what it got back, as the desktop app's agent card counts tokens. */
254export const contextTokens = (u: { input_tokens: number; output_tokens: number; cache_read_input_tokens: number; cache_creation_input_tokens: number }) =>
255  u.input_tokens + u.cache_read_input_tokens + u.cache_creation_input_tokens + u.output_tokens
256
257/**
258 * Two rows per agent: what it is doing, then how far it got. Each part is left out until its event has
259 * been seen, so an agent spawned before a reload reads as its type alone.
260 */
261export const agentLines = (agents: readonly Running[], now: number, max = 4) => {
262  const rows = agents.slice(0, max).flatMap(a => {
263    const facts = [
264      typeof a.startedAt === 'number' ? fmtElapsed(now - a.startedAt) : '',
265      a.model ? modelLabel(a.model) : '',
266      a.tokens ? `${kTokens(a.tokens)} ctx` : '',
267      a.tools ? plural(a.tools, 'tool') : '',
268      a.activity ?? '',
269    ].filter(Boolean)
270    return [`${a.type}${a.description ? ` · ${shorten(a.description, 48)}` : ''}`, ...(facts.length > 0 ? [facts.join(' · ')] : [])]
271  })
272  return [`${plural(agents.length, 'subagent')} running`, ...rows, ...(agents.length > max ? [`+${agents.length - max} more`] : [])]
273}
274
275// ---------------------------------------------------------------- cache clock
276
277type Row = { type?: string; subtype?: string; isSidechain?: boolean; timestamp?: string; message?: { id?: string; usage?: unknown } }
278
279/**
280 * When the main loop's last answered request was sent, read from the tail of the session's transcript:
281 * the last timed row before the last main-loop response (its own first row when none precedes it). The first
282 * line of a tail is cut and skipped. null when no response is there or a compaction came after it.
283 */
284export const lastRequestAt = (tail: string): number | null => {
285  const rows: Row[] = []
286  for (const line of tail.split('\n').slice(1)) {
287    try {
288      rows.push(JSON.parse(line) as Row)
289    } catch {
290      // a cut or blank line
291    }
292  }
293  const main = rows.filter(r => !r.isSidechain)
294  let last = -1
295  for (let i = main.length - 1; i >= 0; i--) {
296    const r = main[i]
297    if (r?.subtype === 'compact_boundary') return null
298    if (r?.type === 'assistant' && r.message?.usage && r.message.id) {
299      last = i
300      break
301    }
302  }
303  if (last < 0) return null
304  const id = main[last]?.message?.id
305  let first = last
306  while (first > 0 && main[first - 1]?.type === 'assistant' && main[first - 1]?.message?.id === id) first--
307  // The request went out after the last row written before its response: a tool result, a prompt, an attachment.
308  const before = main.slice(0, first).filter(r => r.timestamp).pop()
309  const at = Date.parse((before ?? main[first])?.timestamp ?? '')
310  return Number.isFinite(at) ? at : null
311}
312
313/**
314 * The main loop's context at its last response, read from the transcript's tail like `lastRequestAt`: what a
315 * restarted process shows until its first response. null when no response is there or a compaction came after it.
316 */
317export const lastContextOf = (tail: string): number | null => {
318  const lines = tail.split('\n').slice(1)
319  for (let i = lines.length - 1; i >= 0; i--) {
320    let r: Row
321    try {
322      r = JSON.parse(lines[i] ?? '') as Row
323    } catch {
324      continue
325    }
326    if (r.isSidechain) continue
327    if (r.subtype === 'compact_boundary') return null
328    const u = r.type === 'assistant' ? (r.message?.usage as Record<string, unknown> | undefined) : undefined
329    if (u && typeof u.input_tokens === 'number') {
330      const n = (k: string) => (typeof u[k] === 'number' ? (u[k] as number) : 0)
331      return contextTokens({
332        input_tokens: n('input_tokens'),
333        output_tokens: n('output_tokens'),
334        cache_read_input_tokens: n('cache_read_input_tokens'),
335        cache_creation_input_tokens: n('cache_creation_input_tokens'),
336      })
337    }
338  }
339  return null
340}
341
342// ---------------------------------------------------------------- last prompt
343
344/** A prompt as one line: line breaks and runs of spaces read as one space; a long paste keeps its head. */
345export const promptLine = (text: string) => text.replace(/\s+/g, ' ').trim().slice(0, 1000)
346
347/** The person's last prompt as Claude Code records it in the transcript's `last-prompt` rows; null when the tail has none. */
348export const lastPromptOf = (tail: string): string | null => {
349  const lines = tail.split('\n').slice(1)
350  for (let i = lines.length - 1; i >= 0; i--) {
351    const line = lines[i] ?? ''
352    if (!line.includes('"last-prompt"')) continue
353    try {
354      const r = JSON.parse(line) as { type?: string; lastPrompt?: unknown }
355      if (r.type === 'last-prompt' && typeof r.lastPrompt === 'string') return promptLine(r.lastPrompt) || null
356    } catch {
357      // a cut line
358    }
359  }
360  return null
361}
362
hooks/countdown.tsx 36 lines
1// A countdown ticking on the surface's frame clock, so the cache TTL and reset times move between redraws.
2import type { ClientModule } from 'claude-code'
3import { fmtCacheLeft, fmtLeft } from './core'
4
5type Props = { until: number; now: number; kind: 'cache' | 'left'; color: string; warn: string; hot: string }
6type Ref = { left: number; lastNow: number }
7type State = { ref: Ref }
8
9const text = (props: Props, left: number) => (props.kind === 'left' ? fmtLeft(left) : left <= 0 ? '○ cold' : `● ${fmtCacheLeft(left)}`)
10
11const Countdown: ClientModule<Props, State> = (props, surface) => {
12  const { Text } = surface.elements
13  const ref = surface.state?.ref ?? { left: 0, lastNow: -1 }
14  if (props.now !== ref.lastNow) {
15    ref.lastNow = props.now
16    ref.left = props.until - props.now
17  }
18  if (surface.state === undefined) {
19    surface.setState({ ref })
20    // A tick a minute would drift, so it ticks each second but repaints only when the shown text
21    // changes: each minute, then each second of the cache's last one.
22    surface.every(1000, () => {
23      if (ref.left <= 0) return
24      const was = text(props, ref.left)
25      ref.left -= 1000
26      if (text(props, ref.left) !== was) surface.setState({ ref })
27    })
28  }
29  if (props.kind === 'left') return <Text color={props.color}>{fmtLeft(ref.left)}</Text>
30  // Amber with time left to send one more prompt.
31  const color = ref.left <= 0 ? props.hot : ref.left < 5 * 60_000 ? props.warn : props.color
32  return <Text color={color}>{text(props, ref.left)}</Text>
33}
34
35export default Countdown
36
types/index.d.ts 70 lines
1export type Usage = {
2  pct: number | null
3  tokens: number | null
4  window: number
5  costUsd: number | null
6  /** `resetsAt` in ms; null when the window reported none. `at`: when the reading arrived, in ms. */
7  limits: { kind: string; pct: number; resetsAt?: number | null; at?: number }[]
8  compactions: number
9  /**
10   * The window Claude Code compacts against (`autoCompactWindow` in settings, or the model's own limit),
11   * read from the session's context breakdown; null until read. Context is measured against it.
12   */
13  compactWindow: number | null
14}
15
16/**
17 * A subagent running now, by the id its spawn returned. The rest is optional: a value saved before they
18 * existed still reads, and each is set only once its event was seen.
19 */
20export type Running = {
21  id: string
22  type: string
23  /** The Agent call's few-word `description`. */
24  description?: string
25  /** The model its last request was answered by, else the one its spawn resolved. */
26  model?: string
27  startedAt?: number
28  /** Its last request's context: sent plus answered tokens. */
29  tokens?: number
30  /** Tool calls its loop has started. */
31  tools?: number
32  /** Its latest tool call, as `activityOf` names it. */
33  activity?: string
34}
35
36/** A session's cost split by transcript, as the `costCommand` priced it when `at`. */
37export type CostSplit = {
38  at: number
39  totalUsd: number
40  mainUsd: number
41  /** Calls no price covered: while above 0 the figures are a lower bound. */
42  unpriced: number
43  agents: { type: string; description: string; usd: number }[]
44}
45
46/** The person's last prompt as one line; `at` is when it was sent, null when read back from the transcript. */
47export type LastPrompt = { text: string; at: number | null }
48
49declare module 'claude-code' {
50  interface PluginState {
51    'limits': {
52      usage: Usage
53      /**
54       * When the main loop last sent a request that got a response: each request reads (or writes) the
55       * prompt cache and restarts its TTL. The request's start, not its end, so a long response never
56       * overstates the time left. 0: none since load, /clear or a compaction.
57       */
58      cacheAt: number
59      running: Running[]
60      /** The session's cost when the current main turn started; null when the host reports none. */
61      costAtStart: number | null
62      /** What the last main turn cost; null before one ends or without a cost. */
63      lastTurnUsd: number | null
64      split: CostSplit | null
65      /** The person's prompts since load or /clear, oldest first, the last PROMPTS_KEPT. */
66      prompts: LastPrompt[]
67    }
68  }
69}
70