Context fill, session cost and pace on one line, with a warning before the red line.

<img src="../../brand/pixel-icons/svg/redline.svg" width="64" height="64" alt="">
Context fill, session cost and pace on one line, with a warning before the red line.
context ████████░░ 82% RED, full in ≈7m · 5h █░░░░ 11% · week ████░ 83% AMBER, out in ≈21h · ≈$4.12 · 3.9k tokens/min
/plugin install redline --marketplace modmyclaude/claude-code-mods
context ████████░░ 82%: how full the conversation's context window is, as Claude Code measures it, with the level as a word from 60% (AMBER) and 80% (RED), since the status line has no colour. While the context grows, its pace follows: , full in ≈7m is when it would hit 100% at the rate of the last 10 minutes.5h █░░░░ 11% and week ████░ 83%: your plan's 5-hour and weekly windows, as /usage reports them. A window that will run dry before it resets says so, in amber: week ████░ 83% AMBER, out in ≈21h. A spent window says when it comes back: 5h OUT, resets in 48m, or week OUT, resets Sat 10am once that is ten hours or more away; 5h reset after that time has passed, until the next reply brings a new figure.≈$4.12: the session so far at API list prices, Claude Code's own estimate (what /cost shows) where it keeps one, otherwise redline's price table. On a plan nobody pays it, so it comes after the windows; with an API key it is the limit and comes right after the context.3.9k tokens/min: new tokens over the last 10 minutes, shown only while tokens flow. An idle session shows no rate and no pace, never a 0./compact or a fresh session (/clear), once per crossing. It re-arms only after the context drops under 75% (a compaction, a fresh session), so it never nags on every redraw./redline opens the detail view in a pane, laid out to the collection's UI standard. One line on top names the limit closest to its wall, in its colour (Week runs out in ≈2h 44m, 5-hour ran out · resets in 48m), or says Within limits. Under it, the context, the 5-hour window and the week as aligned 10-cell bars, each with its percentage and when it matters (full in ≈30m, resets in 48m, out in ≈2h 44m, resets Tue 9am), coloured by the band's rule. Then when the session started (Wed 2pm) and its cost: Claude Code's own estimate (what /cost shows) when it keeps one, else the price table's, marked ≈. One footnote. Bolt keeps watch beside the bars when the pane is 60 columns or wider; he sleeps until the first reading and while a 5-hour or weekly window is used up. Before anything is spent, the session rows are not drawn. Buttons: Spending (where the money went), show or hide the band, close. Where no surface places the pane, the same view goes to the transcript as dim rows of its own, which the model does not read./redline spend, or the pane's Spending button, shows where the money went in the same pane. On top, what redline counted (≈$2.36 in 9 requests, plus since 1:47pm when redline started after the session). Below that, the cost by the kind of work each request carried (prompt, reading, editing, shell, search, planning, subagents, answering, other tools, an MCP server by its name), with a share bar, the dollars and the share. Four rows at most: the rest fold into one. Then by model, when more than one model answered, and the costliest turns. A request is charged to what it sent Claude: the results of the previous reply's tool calls, split evenly across their kinds. A turn's first request is the prompt, and a subagent's requests are subagents. A model the price table does not know shows --, never a guess. Every figure is a list-price estimate, marked ≈. Nothing new is stored, and the band does not change. Back returns to the limits./redline band toggles a band above the prompt with the same gauge, in colour, for people who hide the status line: each figure in its own colour (green, amber, red, by its own level), the dollars dim on a plan. Under 80 columns the context bar halves and the windows read in words (week 83% used). Its Hide button turns it off. The choice is remembered across sessions. It shares the band: whatever other mods draw there stays, drawn first, with the gauge on the line after it. It steps aside while a survey holds that space.None. The thresholds (60%, 80%, re-arm under 75%) and the 10-minute window are fixed.
$.session.usage(), the session.measure event), each model request's token counts (turn.step), each turn's prompt text (turn.start, shown only in the spend view's costliest turns), and compactions, /clear and an in-session /resume (each starts the gauge over). Model ids, plan window names and prompt text are cleaned of control characters before anything is drawn.context.tokens and context.percent, the status line's used percentage) whenever it has measured the latest request. Between its measurements the gauge counts the main conversation's last request itself, input side (uncached + cache read + cache write), the same way, so it moves on every request. Subagent requests count toward tokens and cost, never toward the session's context.cost.usd, what /cost shows), labelled as its estimate and marked ≈: it is summed at list prices over the session's responses, not a bill (on a subscription nobody pays it). Where Claude Code keeps no ledger, redline's built-in price table prices the requests it counted, and a model the table does not know shows tokens only, never a guessed price.hooks/prices.ts): list prices per model family as of 2026-10-08, used for the spend view's estimates (by kind, by model, per turn). It leaves out long-context premiums, fast mode, 1-hour cache writes, batch and regional pricing, so every figure from it is marked ≈.≈, and its footnote says it assumes your pace holds. A gateway's spend limit gets an estimate only from its recent rate. A window's colour follows this, never its percentage alone: amber when it is set to run out before it resets, red when spent. Spans of ten hours or more round to the hour (≈21h), and a reset that far off reads as clock time in your machine's zone.reset while you wait). Countdowns in the detail view (resets in 48m) refresh with readings, like the band's.This mod was built from its prompt.
More mods: the full catalogue.
hooks/register.tsx 472 lines1// redline: one glanceable gauge for how close the session is to its limits.
2//
3// Where the figures come from (all read from Claude Code, nothing guessed):
4// - each model request (`turn.step`): its four token counts and model, so the
5// gauge moves on every request, not on a timer;
6// - `$.session.usage()` and the `session.measure` event: the context fill
7// (`context.tokens` and `context.percent`, the status line's own figures),
8// the model's window (`context.window`, so redline keeps no window table),
9// the session cost (`cost.usd`, what /cost shows), and the plan's 5-hour
10// and weekly windows (`rateLimits`: kind, percentUsed, resetsAt);
11// - `turn.start` for each turn's prompt (the costliest-turns list),
12// `session.compact` and a /clear (`session.end`) to start the gauge over.
13
14import { atom, read, update } from 'claude-code'
15import type { EngineInterface, Register, SessionMeasureInput, ThemeKey, Timer } from 'claude-code'
16
17import type { BoxProps, ElementConstructor, RenderElement, TextProps } from 'claude-code'
18
19import { boltSprite } from './bolt-draw'
20import { glyphRow } from './cells'
21import { boltPose, detailChunks, detailLines, FIGURE_CELLS, labelCells } from './detail'
22import type { DetailLine, Tone } from './detail'
23import { EMPTY_GAUGE, FULL_CELLS, gaugeLine, gaugeParts, levelWord, NARROW_CELLS, percentOf, RED_AT, reduce, SPAN_MS, TOAST_TEXT } from './gauge'
24import { kindsCarried } from './spend'
25import type { Figure, Level, Reading } from './gauge'
26import type { RedlineGauge, RedlineView } from '../types'
27
28const PANE = 'redline'
29/** From this width the pane's bar rows and buttons get 2-cell gaps, and Bolt stands beside a head that holds bars. */
30const WIDE_COLUMNS = 60
31/** From this width Bolt stands beside a head of words alone (the empty states). */
32const BOLT_WORDS_COLUMNS = 40
33const BAND_STORE_KEY = 'isBandOn'
34const gauge = atom({ plugin: 'redline', key: 'gauge' } as const, EMPTY_GAUGE)
35const isBandOn = atom({ plugin: 'redline', key: 'isBandOn' } as const, false)
36/** Which view the pane shows; this session's only. `/redline` opens the overview, `/redline spend` and the Spending button the other. */
37const paneView = atom({ plugin: 'redline', key: 'view' } as const, 'overview' as RedlineView)
38/** The tools the main loop's last response called, per turn: what its next request carries. Cleared at each turn's start. */
39const carried = new Map<string, string[]>()
40/** One more per pane drawing: the desktop remounts a Button whose wrapper's key changed, so its press stays live after a redraw. */
41let drawing = 0
42
43const LEVEL_COLOR: Record<Level, ThemeKey> = { unknown: 'inactive', normal: 'success', amber: 'warning', red: 'error' }
44
45type Elements = { Box: ElementConstructor<BoxProps>; Text: ElementConstructor<TextProps> }
46
47/**
48 * One figure of the band as coloured spans: its bar in the level's colour, the
49 * readout and the level word coloured once the level is amber or red (plain
50 * or dim otherwise), its clause bound with a comma. The bar is drawn apart on
51 * the desktop (glyphs change a Text's font there), inline on the terminal.
52 */
53function figureSpans({ Box, Text }: Elements, surface: string, f: Figure): RenderElement[] {
54 const isHot = f.level === 'amber' || f.level === 'red'
55 const color = LEVEL_COLOR[f.level]
56 const word = f.value === 'OUT' ? '' : levelWord(f.level)
57 const words: TextProps = isHot ? { color } : f.isDim ? { dimColor: true } : {}
58 // The readout carries the space after a bar, so the bar's Text holds glyphs alone.
59 const readout = (
60 <Text {...words} {...(f.value === 'OUT' ? { bold: true } : {})}>
61 {`${f.bar === undefined ? '' : ' '}${f.value}`}
62 </Text>
63 )
64 const tail = [
65 word ? <Text color={color} bold>{` ${word}`}</Text> : null,
66 f.clause ? <Text {...(isHot ? { color } : { dimColor: true })}>{`, ${f.clause}`}</Text> : null,
67 ]
68 const label = f.label ? <Text {...words}>{`${f.label} `}</Text> : null
69 const bar = f.bar === undefined ? null : surface === 'desktop' ? glyphRow({ Box, Text }, surface, f.bar, { color }) : <Text color={color}>{f.bar}</Text>
70 return [label, bar, readout, ...tail].filter((s): s is RenderElement => s !== null)
71}
72
73/**
74 * The pane's colour for a tone: amber and red by level, dim parts in subtle, a
75 * calm part in `calm` (the hero and the bars in success, a clause in subtle, a
76 * figure in the default text), and a spend row's parts in the default text.
77 */
78type Paint = Pick<TextProps, 'color'>
79function paintOf(tone: Tone, calm: ThemeKey | undefined): Paint {
80 if (tone === 'amber') return { color: 'warning' }
81 if (tone === 'red') return { color: 'error' }
82 if (tone === 'dim' || tone === 'unknown') return { color: 'subtle' }
83 return tone === 'normal' && calm !== undefined ? { color: calm } : {}
84}
85const heroPaint = (tone: Tone): Paint => paintOf(tone, 'success')
86const barPaint = (tone: Tone): Paint => paintOf(tone, 'success')
87const figurePaint = (tone: Tone): Paint => paintOf(tone, undefined)
88const clausePaint = (tone: Tone): Paint => paintOf(tone, 'subtle')
89
90/** What `$.session.usage()` and `session.measure` share, as a reading. */
91const fromUsage = (u: Pick<SessionMeasureInput, 'context' | 'rateLimits' | 'cost'>) => ({
92 window: u.context.window,
93 ledgerUsd: u.cost?.usd,
94 limits: u.rateLimits,
95})
96
97/**
98 * Folds one reading into the gauge (one write per dispatch), then repaints
99 * the status line and raises the 80% toast when this write crossed it.
100 */
101/** One repaint after the 10-minute window passes with no reading (see apply). */
102let idleRepaint: Timer | undefined
103/** One repaint just after the earliest plan window resets (see apply). */
104let resetRepaint: Timer | undefined
105
106async function apply($: EngineInterface, reading: Reading): Promise<void> {
107 let fire = false
108 // `update` may run the change again on a version miss; the last run is the
109 // one written, so `fire` ends up describing the value that was stored.
110 const g = await update($, gauge, current => {
111 const next = reduce(current, reading)
112 fire = next.fire
113 return next.gauge
114 })
115 $.ui.status(gaugeLine(g, reading.now))
116 if (fire) $.ui.toast(TOAST_TEXT(percentOf(g) ?? RED_AT), { timeoutMs: 10_000 })
117 // The status line is a fixed string and the band and pane cache their
118 // drawing: two moments must repaint them with no reading at all. Once the
119 // session sits idle past the 10-minute window (pace and rate read idle),
120 // and just after the earliest plan window resets (a spent window means no
121 // replies, so nothing else would). One shot each, re-armed by every reading:
122 // nothing ticks while nothing happens.
123 idleRepaint?.cancel()
124 idleRepaint = $.clock.after(SPAN_MS + 1000, () => repaint($))
125 armReset($, g, reading.now)
126}
127
128/** Paints every view again with no reading, then waits for the next reset. */
129function repaint($: EngineInterface): void {
130 void safely($, 'repaint', async () => {
131 const g = await read($, gauge)
132 const now = await $.clock.now()
133 $.ui.status(gaugeLine(g, now))
134 $.ui.invalidate('ui.render')
135 // Each reset re-arms for the next one: the weekly after the 5-hour.
136 armReset($, g, now)
137 })
138}
139
140/** One repaint just after the earliest plan window still to reset. */
141function armReset($: EngineInterface, g: RedlineGauge, now: number): void {
142 resetRepaint?.cancel()
143 const nextReset = Math.min(...g.limits.map(l => Date.parse(l.resetsAt ?? '')).filter(t => t > now))
144 // Held to what a timer holds (2147483647 ms, ~24.8 days): a far reset (a
145 // monthly spend limit) then re-arms once on the way, never in a loop.
146 resetRepaint = Number.isFinite(nextReset)
147 ? $.clock.after(Math.min(nextReset - now + 1000, 2_147_483_647), () => repaint($))
148 : undefined
149}
150
151/** Runs gauge work so a failure is logged and never stands in a turn's way. */
152async function safely($: EngineInterface, what: string, work: () => Promise<void>): Promise<void> {
153 try {
154 await work()
155 } catch (err) {
156 $.ui.log(`redline: ${what} failed: ${err instanceof Error ? err.message : String(err)}`, { to: 'debug' })
157 }
158}
159
160async function setBand($: EngineInterface, value: (was: boolean) => boolean): Promise<boolean> {
161 const now = await update($, isBandOn, value)
162 // Remembered across sessions: the band is for people who keep it on.
163 await $.store.set(BAND_STORE_KEY, now).catch(() => undefined)
164 return now
165}
166
167export const register: Register = on => {
168 on('session.start', async ($, e, next) => {
169 await $.command.register({
170 name: 'redline',
171 description: 'Context, plan limits and cost in detail; "/redline spend" for where the money went, "/redline band" for the gauge above the prompt',
172 argumentHint: '[spend|band]',
173 // Checking the gauge mid-turn is the point: run at once, never queued
174 // behind the turn. The hook reads only the gauge, never turn state.
175 immediate: true,
176 })
177 await safely($, 'start', async () => {
178 const stored = await $.store.get(BAND_STORE_KEY)
179 await update($, isBandOn, () => stored === true)
180 const usage = await $.session.usage()
181 await apply($, {
182 now: await $.clock.now(),
183 sessionStartedAt: usage.startedAt,
184 contextTokens: usage.context.tokens ?? null,
185 contextPercent: usage.context.percent,
186 ...fromUsage(usage),
187 })
188 })
189 return next(e)
190 })
191
192 on('turn.start', async ($, e, next) => {
193 const started = await next(e)
194 carried.clear() // an aborted turn leaves nothing behind
195 await safely($, 'turn start', async () => {
196 await apply($, { now: await $.clock.now(), turnStart: { turnId: e.turnId, text: e.text } })
197 })
198 return started
199 })
200
201 // Every model request, main loop and subagents: the gauge's heartbeat.
202 on('turn.step', async function* ($, e, next) {
203 const response = yield* next(e)
204 const usage = response.usage
205 // What this request carried: the results of the previous response's tool calls in this loop.
206 const loop = `${e.agentId ?? 'main'}:${e.turnId}`
207 const kinds = kindsCarried(e.index, e.agentId, carried.get(loop) ?? [])
208 // Kept for the main loop only: a subagent's requests are one kind whatever they carry.
209 const tools = e.agentId === undefined ? (response.toolUses ?? []).map(use => use.name) : []
210 if (tools.length > 0) carried.set(loop, tools)
211 else carried.delete(loop)
212 if (usage) {
213 await safely($, 'request', async () => {
214 const totals = await $.session.usage().catch(() => undefined)
215 await apply($, {
216 now: await $.clock.now(),
217 ...(totals ? { sessionStartedAt: totals.startedAt, ...fromUsage(totals) } : {}),
218 // Claude Code's percentage, taken only once it counts this request.
219 ...(totals && e.agentId === undefined
220 ? { contextTokens: totals.context.tokens, contextPercent: totals.context.percent }
221 : {}),
222 request: { turnId: e.turnId, agentId: e.agentId, usage, kinds },
223 })
224 })
225 }
226 return response
227 })
228
229 // After each turn, and whenever a plan window moves a whole point.
230 on('session.measure', async ($, e, next) => {
231 await safely($, 'measure', async () => {
232 await apply($, {
233 now: await $.clock.now(),
234 // No count (just compacted, until the next reply): keep what we hold.
235 ...(e.context.tokens === undefined ? {} : { contextTokens: e.context.tokens, contextPercent: e.context.percent }),
236 ...fromUsage(e),
237 })
238 })
239 return next(e)
240 })
241
242 // A compaction shrinks the context at once: show it (and re-arm the toast)
243 // without waiting for the next reply. Observes only, so its catch replays.
244 on('session.compact', async ($, e, next) => {
245 const compacted = await next(e)
246 if (e.agentId === undefined && e.trigger !== 'precompute' && compacted.messages) {
247 await safely($, 'compact', async () => {
248 await apply($, { now: await $.clock.now(), contextTokens: compacted.tokensAfter ?? null })
249 })
250 }
251 return compacted
252 }).catch(($, e, next) => next(e))
253
254 // A /clear or an in-session /resume swaps the conversation: start the gauge
255 // over with it (no session.start follows either). The window and the plan
256 // windows belong to the model and account, so they stay.
257 on('session.end', async ($, e, next) => {
258 if (e.reason === 'clear' || e.reason === 'resume') {
259 await safely($, 'clear', async () => {
260 const now = await $.clock.now()
261 const g = await update($, gauge, was => ({
262 ...EMPTY_GAUGE,
263 window: was.window,
264 limits: was.limits,
265 limitHistory: was.limitHistory,
266 sessionStartedAt: now,
267 trackingSince: now,
268 }))
269 $.ui.status(gaugeLine(g, now))
270 })
271 }
272 return next(e)
273 })
274
275 // A command's text is read by the model, so redline answers {} and speaks
276 // through toasts and its pane; where nothing can draw the pane, the view goes
277 // to the transcript as dim rows of its own, which the model never reads.
278 on('command.run', { command: 'redline' }, async ($, e) => {
279 const arg = e.args.trim().toLowerCase()
280 if (arg === 'band') {
281 const isOn = await setBand($, was => !was)
282 $.ui.toast(isOn ? 'Band is on, above the prompt. /redline band hides it.' : 'Band is off. /redline band shows it.')
283 return {}
284 }
285 if (arg !== '' && arg !== 'spend') {
286 $.ui.toast('Use /redline, /redline spend or /redline band.')
287 return {}
288 }
289 const view: RedlineView = arg === 'spend' ? 'spend' : 'overview'
290 await update($, paneView, () => view)
291 // Tall enough inline for either view at 40 columns without scrolling; the dock ignores it.
292 const opened = await $.ui.open({ id: PANE, title: 'Redline', closeOnEscape: true, rows: 18 })
293 if (opened.isPlaced) return {}
294 // Nothing places the pane here: the same view as transcript rows, never as command text.
295 for (const chunk of detailChunks(await read($, gauge), await $.clock.now(), view)) $.ui.log(chunk)
296 return {}
297 }).catch($ => {
298 $.ui.toast('Could not open its detail view (run with --debug for the reason).')
299 return {}
300 })
301
302 // The band above the prompt: the status line's gauge, in colour, drawn with
303 // whatever other mods draw there (never in their place), after theirs, so a
304 // long gauge never pushes another mod's buttons out of view.
305 on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
306 if (e.props.hasSurvey || !(await read($, isBandOn))) return next(e)
307 const g = await read($, gauge)
308 // Narrower than 80 columns the context bar halves and the plan windows read in words.
309 const p = gaugeParts(g, await $.clock.now(), e.props.bodyColumns >= 80 ? FULL_CELLS : NARROW_CELLS)
310 const { Box, Text, Button } = $.ui.resolve(e)
311 // Each figure in its own colour, ` · ` between them; the figures are already cleaned.
312 const spans: RenderElement[] = []
313 p.figures.forEach((f, i) => {
314 if (i > 0) spans.push(<Text dimColor>{' · '}</Text>)
315 spans.push(...figureSpans({ Box, Text }, e.surface, f))
316 })
317 // What the other mods (and the engine) draw in the band comes first.
318 const below = await next(e).catch(() => null)
319 return (
320 <Box flexDirection="column">
321 {below}
322 <Box flexDirection="row" gap={1}>
323 {e.surface === 'desktop' ? (
324 // The desktop draws a Text with block characters in the code font, words and all:
325 // each bar sits in its own one-cell glyphs between the words, and the line's tail truncates.
326 <Box key="gauge" flexDirection="row" flexShrink={1}>
327 <Text>
328 <Text bold>redline</Text>{' '}
329 </Text>
330 {spans.slice(0, -1)}
331 <Text wrap="truncate-end">{spans[spans.length - 1]}</Text>
332 </Box>
333 ) : (
334 <Box key="gauge" flexShrink={1}>
335 <Text wrap="truncate-end">
336 <Text bold>redline</Text>{' '}
337 {spans}
338 </Text>
339 </Box>
340 )}
341 <Button key="hide" label="Hide" dimColor onPress={() => setBand($, () => false)} />
342 </Box>
343 </Box>
344 )
345 })
346
347 // The /redline pane: one of its two views, laid out after brand/UI-STANDARD.md.
348 on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
349 const g = await read($, gauge)
350 const band = await read($, isBandOn)
351 const view = await read($, paneView)
352 const now = await $.clock.now()
353 const elements = $.ui.resolve(e)
354 const { Box, Text, Button } = elements
355 const lines = detailLines(g, now, view)
356 const labelWidth = labelCells(lines)
357 const wide = e.props.bodyColumns >= WIDE_COLUMNS
358 const gap = wide ? 2 : 1
359 const head = lines.filter(l => l.head)
360 const body = lines.filter(l => !l.head && !l.textOnly)
361 // Bolt stands beside the head from 60 columns when it holds bars (their clauses need the room), from 40 when it holds words alone.
362 const boltMin = head.some(l => l.kind === 'bar') ? WIDE_COLUMNS : BOLT_WORDS_COLUMNS
363 drawing += 1
364 const press = (name: string): { key?: string } => (e.surface === 'desktop' ? { key: `press-${name}-${drawing}` } : {})
365 const top = (l: DetailLine): { marginTop?: number } => (l.gap ? { marginTop: 1 } : {})
366 // Each line by its kind: the hero bold in its colour; a bar row as a label column, the glyphs apart
367 // from the words, right-aligned figure columns and clauses that wrap whole; a label and value row
368 // with the value pushed to the right edge; lines and the footnote in subtle. The engine draws the
369 // pane's title bar, so the title line is left to the text view, as are the links (buttons here).
370 const draw = (line: DetailLine): RenderElement | null => {
371 if (line.textOnly) return null
372 switch (line.kind) {
373 case 'title':
374 return (
375 <Box key={line.key} {...top(line)}>
376 <Text bold>{line.value ?? ''}</Text>
377 </Box>
378 )
379 case 'hero':
380 return (
381 <Box key={line.key}>
382 <Text bold wrap="wrap" {...heroPaint(line.tone)}>
383 {line.value ?? ''}
384 </Text>
385 </Box>
386 )
387 case 'bar': {
388 const clauses = line.clauses ?? []
389 return (
390 <Box key={line.key} flexDirection="row" columnGap={gap} {...top(line)}>
391 <Box key="label" width={labelWidth} flexShrink={0}>
392 <Text color="subtle" wrap="wrap">
393 {line.label ?? ''}
394 </Text>
395 </Box>
396 {/* The bar never shrinks: on the terminal a bare Text would be squeezed before the clauses wrap. */}
397 <Box key="bar" flexShrink={0}>
398 {glyphRow(elements, e.surface, line.bar ?? '', barPaint(line.tone))}
399 </Box>
400 {(line.figures ?? []).map((f, i) => (
401 <Box key={`figure-${i}`} width={FIGURE_CELLS[view][i] ?? 4} flexShrink={0} justifyContent="flex-end">
402 <Text {...figurePaint(line.tone)} {...(f === 'OUT' ? { bold: true } : {})}>
403 {f}
404 </Text>
405 </Box>
406 ))}
407 {clauses.length > 0 ? (
408 <Box key="when" flexDirection="row" flexWrap="wrap" columnGap={1} rowGap={0} flexShrink={1}>
409 {clauses.map((c, i) => (
410 <Text key={`clause-${i}`} {...clausePaint(line.tone)}>
411 {i < clauses.length - 1 ? `${c},` : c}
412 </Text>
413 ))}
414 </Box>
415 ) : null}
416 </Box>
417 )
418 }
419 case 'row':
420 return (
421 <Box key={line.key} flexDirection="row" gap={1} {...top(line)}>
422 <Box key="label" flexGrow={1} flexShrink={1}>
423 <Text color="subtle" wrap="wrap">
424 {line.label ?? ''}
425 </Text>
426 </Box>
427 <Box key="value" flexShrink={0} justifyContent="flex-end">
428 <Text {...figurePaint(line.tone)}>{line.value ?? ''}</Text>
429 </Box>
430 </Box>
431 )
432 default:
433 return (
434 <Box key={line.key} {...top(line)}>
435 <Text wrap="wrap" color="subtle">
436 {line.value ?? ''}
437 </Text>
438 </Box>
439 )
440 }
441 }
442 return (
443 <Box flexDirection="column">
444 {e.props.bodyColumns >= boltMin ? (
445 <Box key="head" flexDirection="row" columnGap={2}>
446 <Box key="bolt-cell" flexShrink={0}>
447 {boltSprite(elements, e.surface, { size: 'small', pose: boltPose(g, now, view) })}
448 </Box>
449 <Box key="head-lines" flexDirection="column" flexShrink={1}>
450 {head.map(draw)}
451 </Box>
452 </Box>
453 ) : (
454 head.map(draw)
455 )}
456 {body.map(draw)}
457 <Box key="actions" flexDirection="row" flexWrap="wrap" columnGap={gap} rowGap={0} marginTop={1}>
458 <Box {...press('view')}>
459 <Button key="view" label={view === 'overview' ? 'Spending' : 'Back'} onPress={() => update($, paneView, v => (v === 'overview' ? 'spend' : 'overview'))} />
460 </Box>
461 <Box {...press('band')}>
462 <Button key="band" label={band ? 'Hide band' : 'Show band'} onPress={() => setBand($, was => !was)} />
463 </Box>
464 <Box {...press('close')}>
465 <Button key="close" label="Close" role="dismiss" onPress={() => $.ui.close({ id: PANE })} />
466 </Box>
467 </Box>
468 </Box>
469 )
470 })
471}
472hooks/bolt-draw.tsx 86 lines1// Draws Bolt, the modmyclaude mascot (brand/bolt-sprites), on the surface a hook draws for.
2// Same file in every mod that shows Bolt: mods install on their own, so they cannot share code.
3// Terminal: one Raster, a cell grid. Desktop: one code-font cell per character, since its Text is
4// proportional and a row of half-blocks would drift. Elsewhere: coloured Text runs.
5// Bolt is static here: no timer, no redraw of its own. Never draw it over a safety hold or in a toast.
6
7import type { BoxProps, ElementConstructor, RasterProps, RenderElement, TextProps } from 'claude-code'
8
9import { boltCells, boltRuns } from './bolt'
10import type { BoltCell, BoltSmallPose, BoltTinyPose } from './bolt'
11
12type Elements = {
13 Box: ElementConstructor<BoxProps>
14 Text: ElementConstructor<TextProps>
15 Raster?: ElementConstructor<RasterProps>
16}
17
18export type BoltPick = { size: 'small'; pose: BoltSmallPose } | { size: 'tiny'; pose: BoltTinyPose }
19
20/** Columns a pose takes: small is 10, tiny is 3. */
21export const BOLT_COLUMNS = { small: 10, tiny: 3 } as const
22
23/** The cells of a pose: half-blocks, two pixel rows per cell. */
24export function boltOf(pick: BoltPick): BoltCell[][] {
25 return pick.size === 'small' ? boltCells('small', pick.pose) : boltCells('tiny', pick.pose)
26}
27
28/** Bolt as one element under `key`, drawn the way `surface` lays out cells. */
29export function boltSprite(elements: Elements, surface: string, pick: BoltPick, key = 'bolt'): RenderElement {
30 const { Box, Text, Raster } = elements
31 const cells = boltOf(pick)
32 const columns = cells[0]?.length ?? 0
33 if (surface === 'terminal' && Raster !== undefined) {
34 return <Raster key={key} columns={columns} rows={cells.length} cells={rasterCells(cells)} />
35 }
36 const paint = (cell: BoltCell): TextProps => ({
37 ...(cell.fg !== undefined ? { color: cell.fg } : {}),
38 ...(cell.bg !== undefined ? { backgroundColor: cell.bg } : {}),
39 })
40 if (surface === 'desktop') {
41 return (
42 <Box key={key} flexDirection="column" flexShrink={0}>
43 {cells.map(line => (
44 <Box flexDirection="row" flexWrap="nowrap">
45 {line.map(cell =>
46 cell.fg === undefined && cell.bg === undefined ? <Box width={1} /> : <Box width={1}><Text {...paint(cell)}>{cell.ch}</Text></Box>,
47 )}
48 </Box>
49 ))}
50 </Box>
51 )
52 }
53 return (
54 <Box key={key} flexDirection="column" flexShrink={0}>
55 {cells.map(line => (
56 <Text>
57 {boltRuns(line).map(run => {
58 const text = run.ch.replace(/ /g, ' ')
59 return run.fg === undefined && run.bg === undefined ? text : <Text {...paint(run)}>{text}</Text>
60 })}
61 </Text>
62 ))}
63 </Box>
64 )
65}
66
67/** RasterProps.cells: standard base64 of little-endian u32 [codePoint, fg, bg] per cell, row-major. */
68export function rasterCells(cells: readonly (readonly BoltCell[])[]): string {
69 const DEFAULT = 0x01000000
70 const count = cells.reduce((sum, line) => sum + line.length, 0)
71 const view = new DataView(new ArrayBuffer(count * 12))
72 let at = 0
73 for (const line of cells) {
74 for (const cell of line) {
75 view.setUint32(at, cell.ch.codePointAt(0) ?? 32, true)
76 view.setUint32(at + 4, cell.fg === undefined ? DEFAULT : parseInt(cell.fg.slice(1), 16), true)
77 view.setUint32(at + 8, cell.bg === undefined ? DEFAULT : parseInt(cell.bg.slice(1), 16), true)
78 at += 12
79 }
80 }
81 let binary = ''
82 const bytes = new Uint8Array(view.buffer)
83 for (let i = 0; i < bytes.length; i += 1) binary += String.fromCharCode(bytes[i] ?? 0)
84 return btoa(binary)
85}
86hooks/cells.tsx 45 lines1// Glyph art (the gauge's bar) on the desktop app. Its Text is proportional, and a Text
2// that holds block characters is drawn in the code font, words and all, so a row with
3// a bar changed font and overflowed. There the bar is drawn one
4// code-font cell per character, apart from the words.
5
6import type { BoxProps, ElementConstructor, RenderElement, TextProps } from 'claude-code'
7
8type Elements = { Box: ElementConstructor<BoxProps>; Text: ElementConstructor<TextProps> }
9
10const GLYPHS = /[▀-▟]+/gu
11
12/** One row of glyph art: a plain Text on the terminal, a row of one-cell Boxes on the desktop. */
13export function glyphRow(elements: Elements, surface: string, text: string, paint: TextProps = {}): RenderElement {
14 const { Box, Text } = elements
15 if (surface !== 'desktop') return <Text {...paint}>{text}</Text>
16 const cells: RenderElement[] = []
17 for (const run of text.match(/ +|[^ ]/gu) ?? []) {
18 cells.push(run.startsWith(' ') ? <Box width={run.length} /> : <Box width={1}><Text {...paint}>{run}</Text></Box>)
19 }
20 return (
21 <Box flexDirection="row" flexWrap="nowrap" flexShrink={0}>
22 {cells}
23 </Box>
24 )
25}
26
27/** A line of words with bars in it: one Text where the surface keeps a cell grid, else words and glyph cells side by side. */
28export function mixedRow(elements: Elements, surface: string, text: string, paint: TextProps = {}): RenderElement {
29 const { Box, Text } = elements
30 if (surface !== 'desktop' || !text.match(GLYPHS)) return <Text {...paint}>{text}</Text>
31 const parts: RenderElement[] = []
32 let at = 0
33 for (const m of text.matchAll(GLYPHS)) {
34 if (m.index > at) parts.push(<Text {...paint}>{text.slice(at, m.index)}</Text>)
35 parts.push(glyphRow(elements, surface, m[0], paint))
36 at = m.index + m[0].length
37 }
38 if (at < text.length) parts.push(<Text wrap="truncate-end" {...paint}>{text.slice(at)}</Text>)
39 return (
40 <Box flexDirection="row" flexWrap="nowrap">
41 {parts}
42 </Box>
43 )
44}
45hooks/detail.ts 293 lines1// The /redline pane as structured lines, each keyed, after brand/UI-STANDARD.md.
2// Two views: the overview (a hero naming the limit closest to its wall, the
3// context and each plan window as aligned bars with one readout each, when the
4// session started and its cost, one footnote) and where the money went (what
5// redline counted, by kind of work, by model, the costliest turns). The pane
6// draws the lines by kind; where no surface places the pane, each line's plain
7// `text` prints as transcript rows, so the two can never disagree.
8
9import type { RedlineGauge, RedlineLimit, RedlineSpend, RedlineTokens, RedlineView } from '../types'
10import { bar, BAR_CELLS, clean, contextReadout, costliest, costText, EMPTY_GAUGE, fmtSince, fmtTokens, fmtUsd, limitReadout, limitRowLabel, percentOf, runOut, verdict } from './gauge'
11import type { Level, Readout } from './gauge'
12import { sumTokens } from './prices'
13import { modelLabel, spendLabel } from './spend'
14
15export type Tone = Level | 'dim' | 'title' | 'plain'
16
17/** How the pane draws a line: a section title, the hero, a standalone dim line, a labelled bar with figures, a label and value row, the footnote. */
18export type Kind = 'title' | 'hero' | 'line' | 'bar' | 'row' | 'note'
19
20export type DetailLine = {
21 key: string
22 /** The line as plain text, for a surface that places no pane. */
23 text: string
24 tone: Tone
25 kind: Kind
26 /** Drawn in the head, beside Bolt. */
27 head?: true
28 /** Starts a block: a blank row before it. */
29 gap?: true
30 /** The text form only; the pane skips it (the title bar names the mod, the links are buttons there). */
31 textOnly?: true
32 /** Bars and rows: the label on the left. */
33 label?: string
34 /** A row's value (drawn right-aligned); the words of a hero, a line, a title, the note. */
35 value?: string
36 /** A bar's ten glyphs, drawn apart from the words on the desktop. */
37 bar?: string
38 /** A bar's right-aligned number columns after it. */
39 figures?: string[]
40 /** A bar's words after the numbers, each wrapping as a whole, joined with a comma. */
41 clauses?: string[]
42}
43
44/** The bar rows' label column: the view's longest bar label, within these bounds. */
45export const LABEL_MIN_CELLS = 7
46export const LABEL_MAX_CELLS = 12
47/** The width of each figure column after a bar, per view: the percent; the dollars and the share. */
48export const FIGURE_CELLS: Record<RedlineView, readonly number[]> = { overview: [4], spend: [7, 4] }
49/** The text form pushes a row's value to this column when the row fits in it. */
50const TEXT_COLUMNS = 40
51/** Rows the standard allows a pane: the spend view's kinds, models and turns share them. */
52const ROW_CAP = 7
53
54type Draft = Omit<DetailLine, 'text'>
55
56/** The bar rows' label column for a view: its longest bar label, at least 7 cells, at most 12. */
57export function labelCells(lines: readonly Pick<DetailLine, 'kind' | 'label'>[]): number {
58 const longest = Math.max(0, ...lines.filter(l => l.kind === 'bar').map(l => l.label?.length ?? 0))
59 return Math.max(LABEL_MIN_CELLS, Math.min(LABEL_MAX_CELLS, longest))
60}
61
62// Model ids, plan window kinds and prompts are outside text: cleaned here, at the one
63// place every line passes, before the pane or the command draws it. Block glyphs are
64// the bars' own: in a word (a progress bar pasted into a prompt) they would switch the
65// desktop's font and clip the row, so there they read as `#`.
66const GLYPHS = /[▀-▟]/gu
67const words = (s: string): string => clean(s).replace(GLYPHS, '#')
68const cleaned = (d: Draft): Draft => ({
69 ...d,
70 ...(d.label === undefined ? {} : { label: words(d.label) }),
71 ...(d.value === undefined ? {} : { value: words(d.value) }),
72 ...(d.figures === undefined ? {} : { figures: d.figures.map(words) }),
73 ...(d.clauses === undefined ? {} : { clauses: d.clauses.map(words) }),
74})
75
76const toneOf = (level: Level): Tone => (level === 'unknown' ? 'dim' : level)
77
78/** Every request redline counted, main loop and subagents: the models' counts, which the 100-turn cap never loses. */
79const requestsOf = (g: RedlineGauge): number => Object.values(g.byModel).reduce((n, e) => n + e.requests, 0)
80
81/** Plan windows in a fixed order: the 5-hour, the week, then any other kind by name. */
82function windowsOf(limits: readonly RedlineLimit[]): RedlineLimit[] {
83 const rank = (kind: string): number => (kind === 'five_hour' ? 0 : kind === 'seven_day' ? 1 : 2)
84 return [...limits].sort((a, b) => rank(a.kind) - rank(b.kind) || a.kind.localeCompare(b.kind))
85}
86
87const barLine = (key: string, label: string, r: Readout): Draft => ({ key, kind: 'bar', tone: toneOf(r.level), head: true, label, bar: r.bar, figures: [r.figure], clauses: r.clauses })
88
89// ---------------------------------------------------------------- overview
90
91function overview(g: RedlineGauge, now: number): Draft[] {
92 const lines: Draft[] = []
93 const add = (d: Draft): void => {
94 lines.push(cleaned(d))
95 }
96 const requests = requestsOf(g)
97 const spent = (g.ledgerUsd ?? 0) > 0 || requests > 0
98 const isEmpty = percentOf(g) === undefined && g.limits.length === 0
99 const state = verdict(g, now)
100
101 // For the text view only: the pane's title bar already names the mod.
102 add({ key: 'title', kind: 'title', tone: 'title', textOnly: true, value: 'Redline - context, plan limits and cost' })
103 add({ key: 'state', kind: 'hero', tone: toneOf(state.level), head: true, value: state.text })
104 if (isEmpty) add({ key: 'empty', kind: 'line', tone: 'dim', head: true, value: "Context and limits show up after Claude's next reply." })
105 else {
106 add(barLine('context', 'Context', contextReadout(g, now)))
107 const windows = windowsOf(g.limits)
108 for (const l of windows) add(barLine(`limit-${l.kind}`, limitRowLabel(l.kind), limitReadout(l, now, g.limitHistory[l.kind])))
109 if (windows.length === 0) add({ key: 'limits-none', kind: 'line', tone: 'dim', head: true, value: 'On a Claude plan, 5-hour and week limits appear after a reply.' })
110 }
111
112 // This session, whole: when it started and what it cost (Claude Code's own figures), once anything is spent.
113 let dollars = false
114 if (spent) {
115 if (g.sessionStartedAt !== null) add({ key: 'session', kind: 'row', tone: 'plain', gap: true, label: 'Started', value: fmtSince(g.sessionStartedAt, now) })
116 const isTokens = g.ledgerUsd === null && g.unpriced.length > 0
117 dollars = !isTokens
118 add({ key: 'cost', kind: 'row', tone: isTokens ? 'dim' : 'plain', ...(g.sessionStartedAt === null ? { gap: true } : {}), label: 'Cost', value: costText(g) })
119 }
120
121 // The footnote: a sentence for each figure on screen that needs one.
122 const estimates = lines.some(l => (l.kind === 'hero' && (l.value ?? '').includes('≈')) || (l.clauses ?? []).some(c => c.includes('≈')))
123 const sentences = [...(dollars ? ['Dollars are API list prices, not a bill.'] : []), ...(estimates ? ['Times with ≈ assume your pace holds.'] : [])]
124 if (sentences.length > 0) add({ key: 'note', kind: 'note', tone: 'dim', gap: true, value: sentences.join(' ') })
125 add({ key: 'spend-link', kind: 'line', tone: 'dim', textOnly: true, value: 'Where the money went: /redline spend' })
126 return lines
127}
128
129// ------------------------------------------------------------- spend view
130
131type Share = { key: string; label: string; entry: RedlineSpend; share: number }
132
133const addTokens = (a: RedlineTokens, b: RedlineTokens): RedlineTokens => ({
134 input: a.input + b.input,
135 output: a.output + b.output,
136 cacheRead: a.cacheRead + b.cacheRead,
137 cacheWrite: a.cacheWrite + b.cacheWrite,
138})
139
140/** Several entries as one: their requests and tokens summed, their dollars summed unless one has no price. */
141function folded(entries: readonly RedlineSpend[]): RedlineSpend {
142 return entries.reduce<RedlineSpend>(
143 (sum, e) => ({ requests: sum.requests + e.requests, tokens: addTokens(sum.tokens, e.tokens), usd: sum.usd === null || e.usd === null ? null : sum.usd + e.usd }),
144 { requests: 0, tokens: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 }, usd: 0 },
145 )
146}
147
148/** By cost; entries with no price last, then by tokens. */
149const byCost = (a: RedlineSpend, b: RedlineSpend): number => (b.usd ?? -1) - (a.usd ?? -1) || sumTokens(b.tokens) - sumTokens(a.tokens)
150
151/**
152 * The rows of a share table: every entry when `max` or fewer, else the `max - 1`
153 * costliest and the rest folded into one; each with its share of the group's dollars.
154 */
155function shareRows(entries: readonly [string, string, RedlineSpend][], max: number, restKey: string): Share[] {
156 const sorted = [...entries].sort(([, , a], [, , b]) => byCost(a, b))
157 const priced = sorted.reduce((sum, [, , e]) => sum + (e.usd ?? 0), 0)
158 const shown: [string, string, RedlineSpend][] = sorted.length > max ? [...sorted.slice(0, max - 1), [restKey, 'The rest', folded(sorted.slice(max - 1).map(([, , e]) => e))]] : sorted
159 return shown.map(([key, label, entry]) => ({ key, label, entry, share: entry.usd !== null && priced > 0 ? Math.round((100 * entry.usd) / priced) : 0 }))
160}
161
162const shareLine = (s: Share, gap?: true): Draft => ({
163 key: s.key,
164 kind: 'bar',
165 tone: 'plain',
166 head: true,
167 ...(gap ? { gap } : {}),
168 label: s.label,
169 bar: bar(s.entry.usd === null ? undefined : s.share, BAR_CELLS),
170 figures: s.entry.usd === null ? ['--', '--'] : [fmtUsd(s.entry.usd), `${s.share}%`],
171 clauses: [],
172})
173
174function spendView(g: RedlineGauge, now: number): Draft[] {
175 const lines: Draft[] = []
176 const add = (d: Draft): void => {
177 lines.push(cleaned(d))
178 }
179 const requests = requestsOf(g)
180
181 add({ key: 'title', kind: 'title', tone: 'title', textOnly: true, value: 'Redline - where the money went' })
182 if (requests === 0) {
183 add({ key: 'spend-total', kind: 'hero', tone: 'dim', head: true, value: 'Nothing spent yet' })
184 add({ key: 'spend-none', kind: 'line', tone: 'dim', head: true, value: "Each kind of work shows up here after Claude's next reply." })
185 } else {
186 // Redline's own count, as the table prices it (tokens once a model had no price), and since when it
187 // counts, when that is not the session's start: a clock time this week, else a span (`over the last 9d`).
188 const total = g.unpriced.length === 0 ? fmtUsd(sumTokens(g.tableUsd)) : `${fmtTokens(sumTokens(g.totals))} tokens`
189 let since = ''
190 if (g.trackingSince !== null && (g.sessionStartedAt === null || g.trackingSince - g.sessionStartedAt > 60_000)) {
191 const at = fmtSince(g.trackingSince, now)
192 since = at.endsWith(' ago') ? ` · over the last ${at.slice(0, -' ago'.length)}` : ` · since ${at}`
193 }
194 add({ key: 'spend-total', kind: 'hero', tone: 'plain', head: true, value: `${total} in ${requests} ${requests === 1 ? 'request' : 'requests'}${since}` })
195 }
196
197 // By kind of work: up to four rows, the three costliest and the rest when there are five or more.
198 const kinds = shareRows(Object.entries(g.spend).map(([kind, e]) => [`spend-${kind}`, spendLabel(kind), e]), 4, 'spend-rest')
199 for (const s of kinds) add(shareLine(s))
200 // By model, only when more than one answered: the costliest and the rest.
201 const models = Object.entries(g.byModel)
202 const modelRows = models.length >= 2 ? shareRows(models.map(([model, e]) => [`model-${model}`, modelLabel(model), e]), 2, 'model-rest') : []
203 modelRows.forEach((s, i) => add(shareLine(s, i === 0 ? true : undefined)))
204
205 // The costliest turns take the rows left under the cap.
206 const slots = Math.max(1, Math.min(3, ROW_CAP - kinds.length - modelRows.length))
207 const turns = costliest(g, slots)
208 if (turns.length > 0) {
209 add({ key: 'busiest-title', kind: 'title', tone: 'title', gap: true, value: 'Costliest turns' })
210 turns.forEach((turn, i) => {
211 const value = turn.usd === null ? `${fmtTokens(sumTokens(turn.tokens))} tokens` : fmtUsd(turn.usd)
212 add({ key: `busiest-${i + 1}`, kind: 'row', tone: 'plain', label: `${i + 1}. ${turn.label}`, value })
213 })
214 }
215 if (requests > 0) add({ key: 'spend-rule', kind: 'note', tone: 'dim', gap: true, value: 'Each request counts toward what it sent Claude. Dollars are API list prices.' })
216 add({ key: 'limits-link', kind: 'line', tone: 'dim', textOnly: true, value: 'Context and plan limits: /redline' })
217 return lines
218}
219
220// ------------------------------------------------------------ the lines
221
222/** A line as plain text: a bar with its label padded to the column, its figures right-aligned, its clauses; a row with its value pushed to the right edge. */
223function textOf(l: Draft, labelWidth: number, view: RedlineView): string {
224 if (l.kind === 'bar') {
225 const figures = (l.figures ?? []).map((f, i) => ` ${f.padStart(FIGURE_CELLS[view][i] ?? 0)}`).join('')
226 const clauses = (l.clauses ?? []).length > 0 ? ` ${(l.clauses ?? []).join(', ')}` : ''
227 return `${(l.label ?? '').padEnd(labelWidth)} ${l.bar ?? ''}${figures}${clauses}`
228 }
229 if (l.kind === 'row') {
230 const label = l.label ?? ''
231 const value = l.value ?? ''
232 return label.length + 2 + value.length <= TEXT_COLUMNS ? `${label}${value.padStart(TEXT_COLUMNS - label.length)}` : `${label} ${value}`
233 }
234 return l.value ?? ''
235}
236
237export function detailLines(kept: RedlineGauge, now: number, view: RedlineView = 'overview'): DetailLine[] {
238 // A gauge kept in session state by an earlier version lacks the newer fields: they read as empty.
239 const g: RedlineGauge = { ...EMPTY_GAUGE, ...kept }
240 const drafts = view === 'spend' ? spendView(g, now) : overview(g, now)
241 const labelWidth = labelCells(drafts)
242 return drafts.map(l => ({ ...l, text: textOf(l, labelWidth, view) }))
243}
244
245/**
246 * Bolt's pose beside the head: asleep while nothing is measured (on the spend
247 * view, while nothing is counted) and while a 5-hour or weekly plan window is
248 * used up with its reset still to come; idle otherwise, a full context
249 * included, since the hero says that.
250 */
251export function boltPose(kept: RedlineGauge, now: number, view: RedlineView = 'overview'): 'idle' | 'sleep' {
252 const g: RedlineGauge = { ...EMPTY_GAUGE, ...kept }
253 if (view === 'spend' ? requestsOf(g) === 0 : verdict(g, now).level === 'unknown') return 'sleep'
254 const isOut = (l: RedlineLimit): boolean => {
255 const reset = Date.parse(l.resetsAt ?? '')
256 return (Number.isNaN(reset) || reset > now) && runOut(l, now)?.kind === 'out'
257 }
258 return g.limits.some(l => (l.kind === 'five_hour' || l.kind === 'seven_day') && isOut(l)) ? 'sleep' : 'idle'
259}
260
261/** The view's lines as text, one per line, each block parted by a blank one. */
262function textLines(g: RedlineGauge, now: number, view: RedlineView): { text: string; gap: boolean }[] {
263 return detailLines(g, now, view).map(l => ({ text: l.text, gap: l.gap === true }))
264}
265
266/** The same view as text, for a surface that places no pane. */
267export function detailText(g: RedlineGauge, now: number, view: RedlineView = 'overview'): string {
268 return textLines(g, now, view)
269 .map(l => (l.gap ? `\n${l.text}` : l.text))
270 .join('\n')
271}
272
273/**
274 * The same view for a surface that places no pane, as transcript log rows:
275 * the terminal draws a row's first 2000 characters, so the lines are grouped
276 * under that, whole lines only; a block's blank line stays with the line it
277 * parts, and a row never opens with one. None of it is command text, so the
278 * model reads none of it.
279 */
280export function detailChunks(g: RedlineGauge, now: number, view: RedlineView = 'overview', max = 1900): string[] {
281 const chunks: string[] = []
282 let chunk = ''
283 for (const { text, gap } of textLines(g, now, view)) {
284 const piece = gap ? `\n${text}` : text
285 if (chunk !== '' && chunk.length + 1 + piece.length > max) {
286 chunks.push(chunk)
287 chunk = text
288 } else chunk = chunk === '' ? text : `${chunk}\n${piece}`
289 }
290 if (chunk !== '') chunks.push(chunk)
291 return chunks
292}
293hooks/gauge.ts 643 lines1// redline's pure logic: no `$`, no clock, no state. Every hook turns what it
2// saw into a Reading, `reduce` folds it into the gauge, and the formatters
3// draw the gauge as text. Kept pure so the thresholds, the toast's hysteresis,
4// the pace and the cost math are table-tested on their own.
5
6import type { TurnUsage } from 'claude-code'
7import type { RedlineGauge, RedlineLimit, RedlineSample, RedlineSpend, RedlineTokens, RedlineTurn } from '../types'
8import { priceRequest, sumTokens } from './prices'
9
10export const AMBER_AT = 60
11export const RED_AT = 80
12/** The 80% toast re-arms only once context drops under this (after /compact). */
13export const REARM_BELOW = 75
14/** Pace and tokens per minute look back this far. */
15export const SPAN_MS = 10 * 60_000
16/** A plan window's current rate looks back this far (it moves in whole points). */
17export const LIMIT_SPAN_MS = 15 * 60_000
18/** Under a minute of growth is too little to extrapolate from. */
19const MIN_PACE_MS = 60_000
20const TURNS_KEPT = 100
21const MINUTE = 60_000
22const HOUR = 60 * MINUTE
23
24export type Level = 'unknown' | 'normal' | 'amber' | 'red'
25
26export const ZERO: RedlineTokens = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 }
27
28export const EMPTY_GAUGE: RedlineGauge = {
29 spend: {},
30 byModel: {},
31 sessionStartedAt: null,
32 trackingSince: null,
33 window: null,
34 contextTokens: null,
35 contextPercent: null,
36 samples: [],
37 flow: [],
38 totals: ZERO,
39 tableUsd: ZERO,
40 unpriced: [],
41 ledgerUsd: null,
42 limits: [],
43 limitHistory: {},
44 turns: [],
45 model: null,
46 isArmed: true,
47}
48
49// ---------------------------------------------------------------- thresholds
50
51/**
52 * Context fill as a whole percentage, as the gauge shows and judges it:
53 * Claude Code's own figure when it gave one for this count, else the count
54 * over the window, rounded as Claude Code rounds it.
55 */
56export function percentOf(g: Pick<RedlineGauge, 'contextTokens' | 'contextPercent' | 'window'>): number | undefined {
57 if (g.contextTokens === null) return undefined
58 if (g.contextPercent !== null) return g.contextPercent
59 if (!g.window) return undefined
60 return Math.round((g.contextTokens * 100) / g.window)
61}
62
63export function levelOf(percent: number | undefined): Level {
64 if (percent === undefined) return 'unknown'
65 if (percent >= RED_AT) return 'red'
66 if (percent >= AMBER_AT) return 'amber'
67 return 'normal'
68}
69
70/**
71 * The 80% toast's hysteresis: fire once on the way up, then stay quiet until
72 * the fill drops under 75% (a /compact, a fresh session) and arms it again.
73 */
74export function alarm(isArmed: boolean, percent: number | undefined): { isArmed: boolean; fire: boolean } {
75 if (percent === undefined) return { isArmed, fire: false }
76 if (isArmed && percent >= RED_AT) return { isArmed: false, fire: true }
77 if (!isArmed && percent < REARM_BELOW) return { isArmed: true, fire: false }
78 return { isArmed, fire: false }
79}
80
81// ---------------------------------------------------------------------- pace
82
83/**
84 * When the context fills at the rate of the last 10 minutes: milliseconds
85 * after the last reading, 0 when already full, undefined with no estimate.
86 *
87 * Only the run since the last drop counts (a compaction starts it over), and
88 * it must span a minute and grow; flat or shrinking context has no estimate.
89 */
90export function paceEta(samples: readonly RedlineSample[], window: number | null, now: number): number | undefined {
91 const growth = contextGrowth(samples, now)
92 if (!window || growth === undefined) return undefined
93 const left = window - growth.last
94 return left <= 0 ? 0 : left / growth.perMs
95}
96
97/**
98 * How fast a reading grew over the last `span` (10 minutes for the context),
99 * counted from the last drop: units per millisecond and the latest value.
100 */
101export function contextGrowth(samples: readonly RedlineSample[], now: number, span = SPAN_MS): { perMs: number; last: number } | undefined {
102 const recent = samples.filter(s => s.t >= now - span)
103 let start = 0
104 for (let i = 1; i < recent.length; i++) {
105 if ((recent[i]?.tokens ?? 0) < (recent[i - 1]?.tokens ?? 0)) start = i
106 }
107 const run = recent.slice(start)
108 const first = run[0]
109 const last = run[run.length - 1]
110 if (!first || !last || run.length < 2) return undefined
111 const covered = last.t - first.t
112 const growth = last.tokens - first.tokens
113 if (covered < MIN_PACE_MS || growth <= 0) return undefined
114 return { perMs: growth / covered, last: last.tokens }
115}
116
117/**
118 * New tokens a minute over the last 10 minutes: uncached input, cache writes
119 * and output. Cache reads are left out: every request re-reads the whole
120 * context, so counting them measures context size, not work.
121 */
122export function tokensPerMinute(flow: readonly RedlineSample[], now: number, since: number | null): number {
123 const from = now - SPAN_MS
124 const sum = flow.filter(s => s.t > from).reduce((n, s) => n + s.tokens, 0)
125 const covered = Math.min(SPAN_MS, now - (since ?? from))
126 return sum / Math.max(1, covered / MINUTE)
127}
128
129// --------------------------------------------------------------- plan limits
130
131// The windows Claude Code reports (SessionRateLimit.kind) and how long each
132// runs; any other kind (a gateway's spend_limit) is shown with no run-out.
133const LIMIT_WINDOWS: Record<string, { label: string; short: string; ms: number }> = {
134 five_hour: { label: '5-hour', short: '5h', ms: 5 * HOUR },
135 seven_day: { label: 'weekly', short: 'week', ms: 7 * 24 * HOUR },
136}
137
138export const limitLabel = (kind: string): string => LIMIT_WINDOWS[kind]?.label ?? kind.replace(/_/g, ' ')
139export const limitShort = (kind: string): string => LIMIT_WINDOWS[kind]?.short ?? kind.replace(/_limit$/, '').replace(/_/g, ' ')
140
141/** A plan window as the pane names it, a row label and the hero's subject: `5-hour`, `Week`, else its short name capitalised (`Spend`). */
142export function limitRowLabel(kind: string): string {
143 if (kind === 'five_hour') return '5-hour'
144 if (kind === 'seven_day') return 'Week'
145 const short = limitShort(kind)
146 return short.charAt(0).toUpperCase() + short.slice(1)
147}
148
149/** What a run-out was judged on: the last 15 minutes, or the window's average. */
150export type RunOutBasis = 'recent' | 'average'
151
152export type RunOut = { kind: 'out' } | { kind: 'at'; ms: number; basis: RunOutBasis } | { kind: 'resets-first'; basis: RunOutBasis }
153
154/**
155 * When a plan window runs out. At its current rate (how far it moved over the
156 * last 15 minutes) when it moved; otherwise at the average pace since it
157 * opened (its start is its reset less its length), so a late burst warns and
158 * a quiet spell does not hide what came before. Undefined with no reset time
159 * or one already past, and for an average that has too little to go on (a
160 * window of unknown length, unused, or opened under 10 minutes ago).
161 */
162export function runOut(limit: RedlineLimit, now: number, history: readonly RedlineSample[] = []): RunOut | undefined {
163 if (limit.percentUsed >= 100) return { kind: 'out' }
164 const reset = Date.parse(limit.resetsAt ?? '')
165 if (Number.isNaN(reset) || reset <= now) return undefined
166 const left = 100 - limit.percentUsed
167 const recent = contextGrowth(history, now, LIMIT_SPAN_MS)
168 let ms: number
169 let basis: RunOutBasis
170 if (recent) {
171 ms = left / recent.perMs
172 basis = 'recent'
173 } else {
174 const length = LIMIT_WINDOWS[limit.kind]?.ms
175 if (length === undefined || limit.percentUsed <= 0) return undefined
176 const elapsed = now - (reset - length)
177 if (elapsed < 10 * MINUTE) return undefined
178 ms = (left * elapsed) / limit.percentUsed
179 basis = 'average'
180 }
181 return now + ms >= reset ? { kind: 'resets-first', basis } : { kind: 'at', ms, basis }
182}
183
184/** Adds this reading of each plan window to its last 15 minutes of readings. */
185export function recordLimits(
186 history: Readonly<Record<string, readonly RedlineSample[]>>,
187 limits: readonly RedlineLimit[],
188 now: number,
189): Record<string, RedlineSample[]> {
190 const out: Record<string, RedlineSample[]> = {}
191 for (const l of limits) {
192 const kept = (history[l.kind] ?? []).filter(s => s.t >= now - LIMIT_SPAN_MS)
193 const last = kept[kept.length - 1]
194 // A reading a minute is plenty while the figure holds still.
195 const isSame = last !== undefined && last.tokens === l.percentUsed && now - last.t < MINUTE
196 out[l.kind] = isSame ? kept : [...kept, { t: now, tokens: l.percentUsed }]
197 }
198 return out
199}
200
201// ------------------------------------------------------------------- reduce
202
203/** What one hook saw. A field left out changes nothing in the gauge. */
204export type Reading = {
205 now: number
206 sessionStartedAt?: number
207 window?: number
208 /** The main loop's context: a count, or null when unknown again. */
209 contextTokens?: number | null
210 /** Claude Code's own percentage for that count, when it gave one. */
211 contextPercent?: number
212 ledgerUsd?: number
213 limits?: readonly RedlineLimit[]
214 /** A main-loop turn began with this prompt. */
215 turnStart?: { turnId: string; text: string }
216 /** One model request finished, in the main loop or a subagent's, and the kinds of work it carried. */
217 request?: { turnId: string; agentId?: string; usage: TurnUsage; kinds?: readonly string[] }
218}
219
220const addTokens = (a: RedlineTokens, b: RedlineTokens): RedlineTokens => ({
221 input: a.input + b.input,
222 output: a.output + b.output,
223 cacheRead: a.cacheRead + b.cacheRead,
224 cacheWrite: a.cacheWrite + b.cacheWrite,
225})
226
227export const tokensOf = (u: TurnUsage): RedlineTokens => ({
228 input: u.input_tokens,
229 output: u.output_tokens,
230 cacheRead: u.cache_read_input_tokens,
231 cacheWrite: u.cache_creation_input_tokens,
232})
233
234/**
235 * A prompt's first line, cut to fit a row: past 60 characters it ends at the
236 * last space at or before the 57th and `...`, never mid-word unless that space
237 * sits before the 40th.
238 */
239export function labelOf(text: string): string {
240 const line = text.trim().split('\n')[0]?.trim() ?? ''
241 if (line === '') return '(no prompt text)'
242 if (line.length <= 60) return line
243 const space = line.lastIndexOf(' ', 57)
244 return `${line.slice(0, space >= 40 ? space : 57)}...`
245}
246
247function withTurn(turns: readonly RedlineTurn[], id: string, make: () => RedlineTurn, change: (t: RedlineTurn) => RedlineTurn): RedlineTurn[] {
248 const found = turns.some(t => t.id === id)
249 const next = found ? turns.map(t => (t.id === id ? change(t) : t)) : [...turns, change(make())]
250 if (next.length <= TURNS_KEPT) return next
251 // Over the cap: drop the least busy, which the busiest list never shows;
252 // never the turn being written (a new turn has no tokens yet).
253 const others = next.filter(t => t.id !== id)
254 const quietest = others.reduce((a, b) => (sumTokens(b.tokens) < sumTokens(a.tokens) ? b : a))
255 return next.filter(t => t !== quietest)
256}
257
258/** Folds a reading into the gauge; `fire` says the 80% toast is due now. */
259export function reduce(g: RedlineGauge, r: Reading): { gauge: RedlineGauge; fire: boolean } {
260 // A gauge kept in session state by an earlier version lacks the newer fields: they start empty.
261 let next: RedlineGauge = { ...EMPTY_GAUGE, ...g }
262 if (r.sessionStartedAt !== undefined) next.sessionStartedAt = r.sessionStartedAt
263 if (next.trackingSince === null) next.trackingSince = r.now
264 if (r.window !== undefined && r.window > 0) next.window = r.window
265 if (r.ledgerUsd !== undefined) next.ledgerUsd = r.ledgerUsd
266 if (r.limits !== undefined) {
267 next.limits = r.limits.map(l => ({ ...l }))
268 next.limitHistory = recordLimits(next.limitHistory, r.limits, r.now)
269 }
270
271 let context = r.contextTokens
272 if (r.turnStart) {
273 const { turnId, text } = r.turnStart
274 const make = (): RedlineTurn => ({ id: turnId, label: '', isSubagent: false, startedAt: r.now, requests: 0, tokens: ZERO, usd: 0 })
275 next.turns = withTurn(next.turns, turnId, make, t => ({ ...t, label: labelOf(text) }))
276 }
277 if (r.request) {
278 const { turnId, agentId, usage, kinds = [] } = r.request
279 const tokens = tokensOf(usage)
280 const usd = priceRequest(usage.model, tokens)
281 next.totals = addTokens(next.totals, tokens)
282 if (usd) next.tableUsd = addTokens(next.tableUsd, usd)
283 else if (!next.unpriced.includes(usage.model)) next.unpriced = [...next.unpriced, usage.model].slice(-5)
284 next.flow = [...next.flow.filter(s => s.t > r.now - SPAN_MS), { t: r.now, tokens: tokens.input + tokens.cacheWrite + tokens.output }]
285 const make = (): RedlineTurn => ({
286 id: turnId,
287 label: agentId === undefined ? '(prompt not seen)' : `subagent ${agentId.slice(0, 8)}`,
288 isSubagent: agentId !== undefined,
289 startedAt: r.now,
290 requests: 0,
291 tokens: ZERO,
292 usd: 0,
293 })
294 next.turns = withTurn(next.turns, turnId, make, t => ({
295 ...t,
296 requests: t.requests + 1,
297 tokens: addTokens(t.tokens, tokens),
298 usd: t.usd === null || !usd ? null : t.usd + sumTokens(usd),
299 }))
300 // Where the money went: the request's tokens and price split evenly across the kinds it carried, and by model.
301 const cost = usd ? sumTokens(usd) : undefined
302 const charge = (entry: RedlineSpend | undefined, t: RedlineTokens, c: number | undefined): RedlineSpend => ({
303 requests: (entry?.requests ?? 0) + 1,
304 tokens: addTokens(entry?.tokens ?? ZERO, t),
305 usd: entry?.usd === null || c === undefined ? null : (entry?.usd ?? 0) + c,
306 })
307 const share = kinds.length > 0 ? 1 / kinds.length : 1
308 const part: RedlineTokens = { input: tokens.input * share, output: tokens.output * share, cacheRead: tokens.cacheRead * share, cacheWrite: tokens.cacheWrite * share }
309 const spend = { ...next.spend }
310 for (const kind of kinds) spend[kind] = charge(spend[kind], part, cost === undefined ? undefined : cost * share)
311 next.spend = spend
312 next.byModel = { ...next.byModel, [usage.model]: charge(next.byModel[usage.model], tokens, cost) }
313 // Only the main loop's requests are the session's context; a subagent
314 // has a window of its own.
315 if (agentId === undefined) {
316 context = tokens.input + tokens.cacheRead + tokens.cacheWrite
317 next.model = usage.model
318 }
319 }
320 if (context !== undefined) {
321 next.contextTokens = context
322 // Claude Code's figure belongs to the count it came with, never to another.
323 next.contextPercent = r.contextPercent !== undefined && context === r.contextTokens ? r.contextPercent : null
324 const last = next.samples[next.samples.length - 1]
325 if (context !== null && last?.tokens !== context) {
326 next.samples = [...next.samples.filter(s => s.t >= r.now - SPAN_MS), { t: r.now, tokens: context }]
327 }
328 }
329
330 const { isArmed, fire } = alarm(next.isArmed, percentOf(next))
331 next.isArmed = isArmed
332 return { gauge: next, fire }
333}
334
335/** The busiest turns first, by every token their requests used. */
336export const busiest = (g: RedlineGauge, n = 5): RedlineTurn[] =>
337 [...g.turns].filter(t => t.requests > 0).sort((a, b) => sumTokens(b.tokens) - sumTokens(a.tokens)).slice(0, n)
338
339/** The costliest turns first, by the price table (a turn with no price last), then by tokens: the spend view's list. */
340export const costliest = (g: RedlineGauge, n = 3): RedlineTurn[] =>
341 [...g.turns]
342 .filter(t => t.requests > 0)
343 .sort((a, b) => (b.usd ?? -1) - (a.usd ?? -1) || sumTokens(b.tokens) - sumTokens(a.tokens))
344 .slice(0, n)
345
346// --------------------------------------------------------------- formatting
347
348// ANSI sequences: CSI (7-bit ESC [ or 8-bit U+009B) and OSC (ESC ] ... BEL or ST).
349const ANSI = /(?:\u001b\[|\u009b)[0-?]*[ -/]*[@-~]|\u001b\][^\u0007\u001b]*(?:\u0007|\u001b\\)?/g
350const CONTROL = /[\u0000-\u001f\u007f-\u009f]/g
351
352/**
353 * Text safe to draw: the engine refuses a whole tree (and the status line's
354 * text) that holds a C0 or C1 control character, hiding every band beneath.
355 * Model ids, plan window kinds and prompt text come from outside, so every
356 * string redline draws passes through here: ANSI sequences go, a tab becomes
357 * a space, and any other control character becomes U+FFFD.
358 */
359export const clean = (s: string): string => s.replace(ANSI, '').replace(/\t/g, ' ').replace(CONTROL, '\ufffd')
360
361export function fmtTokens(n: number): string {
362 if (n < 1000) return String(Math.round(n))
363 if (n < 10_000) return `${(n / 1000).toFixed(1)}k`
364 if (n < 1_000_000) return `${Math.round(n / 1000)}k`
365 return `${(n / 1_000_000).toFixed(1)}M`
366}
367
368/**
369 * Dollars as the gauge writes them, always marked "≈": the price table and
370 * Claude Code's own ledger alike are list-price arithmetic, not a bill (on a
371 * subscription nobody pays them).
372 */
373export function fmtUsd(usd: number): string {
374 if (usd >= 100) return `≈$${Math.round(usd)}`
375 // A real but tiny cost reads as such, not as a suspicious $0.00.
376 if (usd > 0 && usd < 0.005) return '≈<$0.01'
377 return `≈$${usd.toFixed(2)}`
378}
379
380export function fmtDuration(ms: number): string {
381 if (ms < MINUTE) return '<1m'
382 // 59m 40s rounds to the hour, not to "60m".
383 if (ms < HOUR) return Math.round(ms / MINUTE) === 60 ? '1h' : `${Math.round(ms / MINUTE)}m`
384 if (ms < 24 * HOUR) {
385 const h = Math.floor(ms / HOUR)
386 const m = Math.round((ms - h * HOUR) / MINUTE)
387 return m === 0 ? `${h}h` : m === 60 ? `${h + 1}h` : `${h}h ${m}m`
388 }
389 const d = Math.floor(ms / (24 * HOUR))
390 const h = Math.round((ms - d * 24 * HOUR) / HOUR)
391 // 23h 50m rounds up into the next day, as 59m 40s does into the next hour.
392 return h === 0 ? `${d}d` : h === 24 ? `${d + 1}d` : `${d}d ${h}h`
393}
394
395/** A span as the one-line gauge writes it: to the minute under ten hours, to the hour from there (`21h`, not `20h 43m`). */
396export function fmtSpan(ms: number): string {
397 return ms < 10 * HOUR ? fmtDuration(ms) : fmtDuration(Math.round(ms / HOUR) * HOUR)
398}
399
400const DAYS = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']
401
402/**
403 * A moment as clock time, in the machine's own zone: `3:30pm` today, `Sat 10am`
404 * on another day of the coming week, and a span (`in 7d`) further out, where a
405 * weekday would be ambiguous.
406 */
407export function fmtClock(at: number, now: number): string {
408 const d = new Date(at)
409 const n = new Date(now)
410 const h = d.getHours()
411 const m = d.getMinutes()
412 const time = `${h % 12 === 0 ? 12 : h % 12}${m === 0 ? '' : `:${String(m).padStart(2, '0')}`}${h < 12 ? 'am' : 'pm'}`
413 if (d.getFullYear() === n.getFullYear() && d.getMonth() === n.getMonth() && d.getDate() === n.getDate()) return time
414 if (at - now >= 6 * 24 * HOUR) return `in ${fmtSpan(at - now)}`
415 return `${DAYS[d.getDay()] ?? ''} ${time}`
416}
417
418/** When a window resets, as the words after "resets": `in 48m` under ten hours away, else the clock time (`Sat 10am`). */
419export function fmtReset(at: number, now: number): string {
420 return at - now < 10 * HOUR ? `in ${fmtDuration(at - now)}` : fmtClock(at, now)
421}
422
423/**
424 * A past moment as clock time: `1:47pm` today, `Wed 2pm` within the last six
425 * days, and a span (`9d ago`) further back, where a weekday would be ambiguous.
426 */
427export function fmtSince(at: number, now: number): string {
428 return now - at >= 6 * 24 * HOUR ? `${fmtSpan(now - at)} ago` : fmtClock(at, now)
429}
430
431/** The context's pace in words, an estimate marked `≈`: `full in ≈25m`. */
432export function fmtPace(ms: number | undefined): string | undefined {
433 if (ms === undefined) return undefined
434 if (ms <= 0) return 'full now'
435 if (ms < MINUTE) return 'full in <1m'
436 if (ms > 24 * HOUR) return 'full in >1d'
437 return `full in ≈${fmtDuration(ms)}`
438}
439
440export function bar(percent: number | undefined, cells: number): string {
441 const filled = percent === undefined ? 0 : Math.max(0, Math.min(cells, Math.round((percent / 100) * cells)))
442 return '█'.repeat(filled) + '░'.repeat(cells - filled)
443}
444
445/** The level as a word, so the gauge reads the same without colour. */
446export const levelWord = (level: Level): string => (level === 'red' ? 'RED' : level === 'amber' ? 'AMBER' : '')
447
448/**
449 * The session's cost as the gauge shows it: Claude Code's own estimate (what
450 * /cost shows), else the price table's, else tokens.
451 */
452export function costText(g: RedlineGauge): string {
453 if (g.ledgerUsd !== null) return fmtUsd(g.ledgerUsd)
454 if (g.unpriced.length === 0) return fmtUsd(sumTokens(g.tableUsd))
455 return `${fmtTokens(sumTokens(g.totals))} tokens`
456}
457
458/** A run-out in words, an estimate marked `≈`: `out in ≈1h 20m` (`≈21h` from ten hours), `resets first`, `OUT`, or nothing. */
459export function fmtRunOut(r: RunOut | undefined): string | undefined {
460 if (r === undefined) return undefined
461 if (r.kind === 'out') return 'OUT'
462 if (r.kind === 'resets-first') return 'resets first'
463 return r.ms < MINUTE ? 'out in <1m' : `out in ≈${fmtSpan(r.ms)}`
464}
465
466/**
467 * A plan window's level, by whether it is set to hit its wall: red when spent,
468 * amber when it is projected to run out before it resets, normal otherwise,
469 * unknown once its reset time has passed (the figure is stale until the next
470 * reply). A percentage alone says nothing here: a week at 83% is fine when it
471 * resets first, and a week at 40% is not when a burst will empty it by tonight.
472 */
473export function limitLevel(l: RedlineLimit, now: number, history: readonly RedlineSample[] = []): Level {
474 const reset = Date.parse(l.resetsAt ?? '')
475 if (!Number.isNaN(reset) && reset <= now) return 'unknown'
476 const r = runOut(l, now, history)
477 return r?.kind === 'out' ? 'red' : r?.kind === 'at' ? 'amber' : 'normal'
478}
479
480/**
481 * One figure of the one-line gauge: a label, a bar where there is room, the
482 * readout, its level (the band's colour, the status line's word), and a clause
483 * bound to it with a comma (`, full in ~7m`, `, out in ~21h`, `, resets Sat 10am`).
484 * Every string is already cleaned: a window's kind is the engine's.
485 */
486export type Figure = {
487 key: string
488 label: string
489 bar?: string
490 value: string
491 level: Level
492 clause?: string
493 /** Drawn dim in the band: the dollars on a plan, the rate. */
494 isDim: boolean
495}
496
497/**
498 * A plan window as a figure: `week ████░ 83%`, or `week 83% used` where the
499 * band has no room for a bar (the bar says "used" on its own); its run-out
500 * when it runs dry before it resets; when it comes back once spent.
501 */
502export function limitFigure(l: RedlineLimit, now: number, history: readonly RedlineSample[] = [], cells = 5): Figure {
503 const key = `limit-${l.kind}`
504 const label = clean(limitShort(l.kind))
505 const level = limitLevel(l, now, history)
506 const reset = Date.parse(l.resetsAt ?? '')
507 // Past its reset the reading is stale until the next response says more.
508 if (level === 'unknown') return { key, label, value: 'reset', level, isDim: true }
509 const r = runOut(l, now, history)
510 // A spent window: when it comes back is the one figure that matters.
511 if (r?.kind === 'out') return { key, label, value: 'OUT', level, isDim: false, ...(Number.isNaN(reset) ? {} : { clause: `resets ${fmtReset(reset, now)}` }) }
512 const pct = Math.round(l.percentUsed)
513 const readout = cells > 0 ? { bar: bar(Math.min(100, pct), cells), value: `${pct}%` } : { value: `${pct}% used` }
514 // On the one line only a window that runs dry before it resets earns words.
515 return { key, label, ...readout, level, isDim: false, ...(r?.kind === 'at' ? { clause: fmtRunOut(r) ?? '' } : {}) }
516}
517
518/**
519 * A figure as plain text, for the status line: `week ████░ 83% AMBER, out in ~21h`.
520 * The level word follows the readout, except where the readout spells it out (OUT).
521 */
522export function figureText(f: Figure): string {
523 const word = f.value === 'OUT' ? '' : levelWord(f.level)
524 const head = [f.label, f.bar, `${f.value}${word ? ` ${word}` : ''}`].filter(s => s !== undefined && s !== '').join(' ')
525 return f.clause ? `${head}, ${f.clause}` : head
526}
527
528/** One plan window as the status line writes it. */
529export const limitText = (l: RedlineLimit, now: number, history: readonly RedlineSample[] = [], cells = 5): string =>
530 figureText(limitFigure(l, now, history, cells))
531
532/** How many cells each bar of the one-line gauge gets; 0 draws the readout in words. */
533export type Cells = { context: number; limit: number }
534export const FULL_CELLS: Cells = { context: 10, limit: 5 }
535export const NARROW_CELLS: Cells = { context: 5, limit: 0 }
536
537/**
538 * The figures every view of the gauge draws, computed once, in reading order:
539 * the context with its pace, each plan window, the dollars, the rate while
540 * tokens flow. On a plan the windows are the limits and the dollars a
541 * footnote (nobody pays them); with an API key the dollars are the limit.
542 */
543export function gaugeParts(g: RedlineGauge, now: number, cells: Cells = FULL_CELLS) {
544 const percent = percentOf(g)
545 const level = levelOf(percent)
546 const pace = fmtPace(paceEta(g.samples, g.window, now))
547 const figures: Figure[] = [
548 percent === undefined
549 ? { key: 'context', label: 'context', value: '--', level, isDim: false }
550 : { key: 'context', label: 'context', bar: bar(percent, cells.context), value: `${percent}%`, level, isDim: false, ...(pace ? { clause: pace } : {}) },
551 ...g.limits.map(l => limitFigure(l, now, g.limitHistory[l.kind], cells.limit)),
552 { key: 'cost', label: '', value: costText(g), level: 'normal', isDim: g.limits.length > 0 },
553 ]
554 const rate = tokensPerMinute(g.flow, now, g.trackingSince)
555 // An idle session shows no rate: "0 tokens/min" reads like a fault.
556 if (rate > 0) figures.push({ key: 'rate', label: '', value: `${fmtTokens(rate)} tokens/min`, level: 'normal', isDim: true })
557 return { percent, level, figures }
558}
559
560/**
561 * The status line: plain text, each level spelled out since it has no colour,
562 * cleaned since a plan window's kind is the engine's string.
563 */
564export function gaugeLine(g: RedlineGauge, now: number): string {
565 return clean(gaugeParts(g, now).figures.map(figureText).join(' · '))
566}
567
568// ------------------------------------------------------------------ the pane
569
570/** The pane's bars are this wide. */
571export const BAR_CELLS = 10
572
573/** One bar row of the pane: its level (the colour), ten cells, the figure for the right-aligned column, and the words after it. */
574export type Readout = { level: Level; bar: string; figure: string; clauses: string[] }
575
576/** The context as a bar row: its fill and, while it grows, its pace; `--` and `no reading yet` before the first count. */
577export function contextReadout(g: RedlineGauge, now: number): Readout {
578 const percent = percentOf(g)
579 if (percent === undefined) return { level: 'unknown', bar: bar(undefined, BAR_CELLS), figure: '--', clauses: ['no reading yet'] }
580 const pace = fmtPace(paceEta(g.samples, g.window, now))
581 return { level: levelOf(percent), bar: bar(percent, BAR_CELLS), figure: `${percent}%`, clauses: pace ? [pace] : [] }
582}
583
584/**
585 * A plan window as a bar row, coloured by the band's rule (`limitLevel`), never
586 * by its percentage: `OUT` and its reset once spent; its run-out then its reset
587 * when it runs dry first; its reset alone when calm; `--` and `reset 10m ago`
588 * once its reset time has passed, until the next reply brings a new figure.
589 */
590export function limitReadout(l: RedlineLimit, now: number, history: readonly RedlineSample[] = []): Readout {
591 const level = limitLevel(l, now, history)
592 const reset = Date.parse(l.resetsAt ?? '')
593 if (level === 'unknown') return { level, bar: bar(undefined, BAR_CELLS), figure: '--', clauses: [`reset ${fmtDuration(now - reset)} ago`] }
594 const resets = Number.isNaN(reset) ? [] : [`resets ${fmtReset(reset, now)}`]
595 const r = runOut(l, now, history)
596 if (r?.kind === 'out') return { level, bar: bar(100, BAR_CELLS), figure: 'OUT', clauses: resets }
597 const pct = Math.round(l.percentUsed)
598 const out = r?.kind === 'at' ? [fmtRunOut(r) ?? ''] : []
599 return { level, bar: bar(Math.min(100, pct), BAR_CELLS), figure: `${pct}%`, clauses: [...out, ...resets] }
600}
601
602export type Verdict = { text: string; level: Level }
603
604/**
605 * The pane's hero: the limit closest to its wall, in the band's own words. The
606 * first that applies wins: a window used up (of several, the one that resets
607 * last); the context full; the context red; the soonest amber wall, a window's
608 * run-out or the context's pace; else `Within limits`. Unknown while nothing is
609 * measured: no context reading and no window with a current figure.
610 */
611export function verdict(g: RedlineGauge, now: number): Verdict {
612 const percent = percentOf(g)
613 const windows = g.limits
614 .map(l => ({ l, level: limitLevel(l, now, g.limitHistory[l.kind]), reset: Date.parse(l.resetsAt ?? '') }))
615 .filter(w => w.level !== 'unknown')
616 if (percent === undefined && windows.length === 0) return { text: 'Nothing measured yet', level: 'unknown' }
617 // Used up: the window that resets last is the wall; one with no reset time counts as last.
618 const resetAt = (w: { reset: number }): number => (Number.isNaN(w.reset) ? Number.MAX_SAFE_INTEGER : w.reset)
619 const out = windows.filter(w => w.level === 'red').sort((a, b) => resetAt(b) - resetAt(a))[0]
620 if (out) {
621 const label = limitRowLabel(out.l.kind)
622 return { text: Number.isNaN(out.reset) ? `${label} ran out` : `${label} ran out · resets ${fmtReset(out.reset, now)}`, level: 'red' }
623 }
624 if (percent !== undefined && percent >= 100) return { text: 'Context full · run /compact', level: 'red' }
625 const eta = paceEta(g.samples, g.window, now)
626 const pace = fmtPace(eta)
627 const context = `Context ${percent ?? 0}%${pace ? ` · ${pace}` : ''}`
628 if (percent !== undefined && percent >= RED_AT) return { text: context, level: 'red' }
629 // Amber: whichever wall comes first, a window's run-out or the context's pace; no estimate sorts last.
630 const walls: { at: number; text: string }[] = []
631 for (const w of windows) {
632 const r = runOut(w.l, now, g.limitHistory[w.l.kind])
633 if (r?.kind === 'at') walls.push({ at: r.ms, text: `${limitRowLabel(w.l.kind)} runs ${fmtRunOut(r)}` })
634 }
635 if (percent !== undefined && percent >= AMBER_AT) walls.push({ at: eta ?? Number.POSITIVE_INFINITY, text: context })
636 const first = walls.sort((a, b) => (a.at < b.at ? -1 : a.at > b.at ? 1 : 0))[0]
637 return first ? { text: first.text, level: 'amber' } : { text: 'Within limits', level: 'normal' }
638}
639
640/** The 80% toast: redline's own words and a number, no outside text. */
641export const TOAST_TEXT = (percent: number): string =>
642 `Context is ${percent}% full. Run /compact to summarize it, or /clear to start a fresh session.`
643hooks/spend.ts 87 lines1// Where the money went: which kind of work a model request carried. A request's
2// input holds the results of the previous response's tool calls in the same loop,
3// so each request is charged to the kinds of those tools, read off the response
4// stream redline already watches; the first request of a turn carries the prompt,
5// a subagent's requests are one kind. Nothing is guessed from the transcript.
6
7/** The kinds, as the pane labels their rows. */
8export const KIND_WORDS: Readonly<Record<string, string>> = {
9 prompt: 'Prompt',
10 reading: 'Reading',
11 editing: 'Editing',
12 shell: 'Shell',
13 search: 'Search',
14 planning: 'Planning',
15 subagents: 'Subagents',
16 answering: 'Answering',
17 other: 'Other tools',
18}
19
20const READING = new Set(['Read', 'Grep', 'Glob', 'LS', 'NotebookRead'])
21const EDITING = new Set(['Edit', 'MultiEdit', 'Write', 'NotebookEdit'])
22const SHELL = new Set(['Bash', 'BashOutput', 'KillShell'])
23const SEARCH = new Set(['WebSearch', 'WebFetch', 'ToolSearch'])
24const PLANNING = new Set(['TodoWrite', 'TodoRead', 'Task', 'Agent', 'ExitPlanMode', 'EnterPlanMode', 'AskUserQuestion'])
25
26/** The kind a tool's result counts as: one of the words, or `mcp:<server>` for an MCP server's tools. */
27export function kindOf(tool: string): string {
28 if (tool.startsWith('mcp__')) {
29 const [server = '', ...rest] = tool.slice(5).split('__')
30 // A lent plan tool is planning, whichever mod lends it.
31 if (rest.join('__') === 'plan') return 'planning'
32 return `mcp:${server}`
33 }
34 if (READING.has(tool)) return 'reading'
35 if (EDITING.has(tool)) return 'editing'
36 if (SHELL.has(tool)) return 'shell'
37 if (SEARCH.has(tool)) return 'search'
38 if (PLANNING.has(tool)) return 'planning'
39 return 'other'
40}
41
42/**
43 * The kinds one request is charged to: a subagent's request is `subagents`; a turn's
44 * first request is the `prompt`; any other carries the results of the tools the
45 * previous response called (each kind once), or `answering` when it carried none.
46 */
47export function kindsCarried(index: number, agentId: string | undefined, previousTools: readonly string[]): string[] {
48 if (agentId !== undefined) return ['subagents']
49 if (index === 0) return ['prompt']
50 const kinds = [...new Set(previousTools.map(kindOf))]
51 return kinds.length > 0 ? kinds : ['answering']
52}
53
54/** A label column holds this many cells at most. */
55const LABEL_CELLS = 12
56
57/** A kind's row label: a word in sentence case (`Shell`, `Other tools`), or an MCP server's own name, cut to the column. */
58export function spendLabel(kind: string): string {
59 if (kind.startsWith('mcp:')) return kind.slice(4).slice(0, LABEL_CELLS)
60 return KIND_WORDS[kind] ?? kind
61}
62
63// claude-opus-4-1-20250805, us.anthropic.claude-sonnet-4-5-20250929-v1:0,
64// claude-haiku-4-5@20251001, claude-opus-5: the family, then the major, then a
65// one-digit minor when one follows (a date is never a major or a minor).
66const MODEL_ID = /(opus|sonnet|haiku|fable|mythos)-(\d{1,2})(?!\d)(?:-(\d)(?!\d))?/
67// claude-3-5-haiku-20241022, claude-3-opus-20240229: the version before the family.
68const OLDER_MODEL_ID = /claude-(\d)(?:-(\d))?-(opus|sonnet|haiku)/
69
70/**
71 * A model's row label, read from its id: the family and version (`Fable 5.1`,
72 * `Opus 4.6`, `Sonnet 5.5`, `Haiku 3.5`). An id of another shape loses its
73 * `claude-` and a trailing date (`nova-1`), cut to the column.
74 */
75export function modelLabel(model: string): string {
76 const id = model.toLowerCase()
77 const m = MODEL_ID.exec(id)
78 const older = m ? null : OLDER_MODEL_ID.exec(id)
79 const [family, major, minor] = m ? [m[1], m[2], m[3]] : older ? [older[3], older[1], older[2]] : []
80 if (family !== undefined && major !== undefined) return `${family.charAt(0).toUpperCase()}${family.slice(1)} ${major}${minor === undefined ? '' : `.${minor}`}`
81 return model
82 .replace(/^claude-/, '')
83 .replace(/@.*$/, '')
84 .replace(/-\d{8}$/, '')
85 .slice(0, LABEL_CELLS)
86}
87hooks/bolt.ts 109 lines1// Bolt sprites for mods, v1.0.0. GENERATED by brand/bolt-sprites/tools/build.py: edit design.py, not this file.
2// Copy this file into your mod's hooks/ folder (mods install on their own, so they cannot import from brand/).
3// Rules (brand/BRAND.md): pink is the antenna light only, blush the cheeks only. Never recolour, rotate or stretch.
4// Never draw Bolt over a safety hold, and never in a toast (toasts are uncoloured text).
5
6export const BOLT_PALETTE = {
7 B: '#C8F53C',
8 S: '#9BC21A',
9 O: '#FF5C8A',
10 K: '#FF8FB1',
11 E: '#101114',
12 W: '#FBFBF8',
13 G: '#8E95A3',
14} as const
15
16export type BoltSize = 'small' | 'tiny'
17export type BoltSmallPose = 'idle' | 'run1' | 'run2' | 'jump' | 'crash' | 'cheer' | 'sleep' | 'sweat' | 'think' | 'egg' | 'egg-wobble-l' | 'egg-wobble-r' | 'egg-crack-1' | 'egg-crack-2' | 'egg-crack-3' | 'egg-hatch'
18export type BoltTinyPose = 'idle' | 'run1' | 'run2' | 'jump' | 'crash' | 'cheer' | 'sleep'
19export type BoltPose = BoltSmallPose | BoltTinyPose
20
21/** One text cell: a character and its colours (absent = the surface's own). */
22export type BoltCell = { ch: string; fg?: string; bg?: string }
23
24/** Pixel rows: one palette letter per pixel, '.' empty. Heights are even (two pixel rows per cell). */
25export const BOLT_SPRITES = {
26 small: {
27 'idle': ['....OO....', '....SS....', '..BBBBBB..', '.BBBBBBBB.', 'BBWEBBWEBB', 'BBEEBBEEBB', 'BKKBBBBKKB', 'BBBBEEBBBB', '.SSSSSSSS.', '..SS..SS..'],
28 'run1': ['...OO.....', '....SS....', '..BBBBBB..', '.BBBBBBBB.', 'BBBWEBBWEB', 'BBBEEBBEEB', 'BKKBBBBBKB', 'BBBBBEEBBB', '.SSSSSSSS.', 'SS......SS'],
29 'run2': ['....OO....', '....SS....', '..BBBBBB..', '.BBBBBBBB.', 'BBBWEBBWEB', 'BBBEEBBEEB', 'BKKBBBBBKB', 'BBBBBEEBBB', '.SSSSSSSS.', '...SSSS...'],
30 'jump': ['....OO....', '....SS....', '..BBBBBB..', '.BBBBBBBB.', 'BBWEBBWEBB', 'BBEEBBEEBB', 'BKKBBBBKKB', 'BBBBEEBBBB', '.SSSSSSSS.', '...S..S...'],
31 'crash': ['......OO..', '.....S....', '..BBBBBB..', '.BBBBBBBB.', 'BEBEBBEBEB', 'BBEBBBBEBB', 'BEBEBBEBEB', 'BBBBEEBBBB', '.SSSSSSSS.', 'SS......SS'],
32 'cheer': ['S...OO...S', 'S...SS...S', 'SBBBBBBBBS', '.BBBBBBBB.', 'BBWEBBWEBB', 'BBEEBBEEBB', 'BKKBBBBKKB', 'BBBEEEEBBB', '.SSSSSSSS.', '..SS..SS..'],
33 'sleep': ['....SS....', '....SS....', '..BBBBBB..', '.BBBBBBBB.', 'BBBBBBBBBB', 'BBEEBBEEBB', 'BKKBBBBKKB', 'BBBBBBBBBB', '.SSSSSSSS.', '..SS..SS..'],
34 'sweat': ['....OO....', '....SS...G', '..BBBBBB.G', '.BBBBBBBB.', 'BBWEBBWEBB', 'BBEEBBEEBB', 'BKKBBBBKKB', 'BBBBEEEBBB', '.SSSSSSSS.', '..SS..SS..'],
35 'think': ['....OO....', '....SS....', '..BBBBBB..', '.BBWEBWEB.', 'BBBEEBEEBB', 'BBBBBBBBBB', 'BKKBBBBKKB', 'BBBBBEBBBB', '.SSSSSSSS.', '..SS..SS..'],
36 'egg': ['....OO....', '....SS....', '...BWBB...', '..BWBBBB..', '..BBBBBB..', '.BBBBBBBB.', '.BBBBBBBB.', '.BBBBBBBS.', '..BBBBBS..', '...SSSS...'],
37 'egg-wobble-l': ['...OO.....', '...SS.....', '..BWBB....', '.BWBBBB...', '.BBBBBB...', '.BBBBBBBB.', '.BBBBBBBB.', '.BBBBBBBS.', '..BBBBBS..', '...SSSS...'],
38 'egg-wobble-r': ['.....OO...', '.....SS...', '....BWBB..', '...BWBBBB.', '...BBBBBB.', '.BBBBBBBB.', '.BBBBBBBB.', '.BBBBBBBS.', '..BBBBBS..', '...SSSS...'],
39 'egg-crack-1': ['....OO....', '....SS....', '...BWBB...', '..BWBBBB..', '..BBBBBB..', '.BBBBBBBB.', '.BEBBBBBB.', '.BBEBBBBS.', '..BBBBBS..', '...SSSS...'],
40 'egg-crack-2': ['....OO....', '....SS....', '...BWBB...', '..BWBBBB..', '..BBBBBB..', '.BBBBBBBB.', '.BEBEBBBB.', '.BBEBEBBS.', '..BBBBBS..', '...SSSS...'],
41 'egg-crack-3': ['....OO....', '....SS....', '...BWBB...', '..BWBBBB..', '..BBBBBB..', '.BBBBBBBB.', '.BEBEBEBB.', '.BBEBEBES.', '..BBBBBS..', '...SSSS...'],
42 'egg-hatch': ['......OO..', '......SS..', '....BWBBBB', '....B.B.B.', '..........', '..........', '.B.B.B.BB.', '.BSSSSSSB.', '..BBBBBS..', '...SSSS...'],
43 },
44 tiny: {
45 'idle': ['.O.', 'BEB', 'BBB', 'S.S'],
46 'run1': ['.O.', 'BEB', 'BBB', 'S.S'],
47 'run2': ['.O.', 'BEB', 'BBB', '.S.'],
48 'jump': ['.O.', 'BEB', 'BBB', '.S.'],
49 'crash': ['...', '.SO', 'BEB', 'SSS'],
50 'cheer': ['SOS', 'BEB', 'BBB', 'S.S'],
51 'sleep': ['.S.', 'BSB', 'BBB', 'S.S'],
52 },
53} as const
54
55/** Letters drawn over a whole cell (cell coordinates). */
56const GLYPHS: Record<string, readonly { row: number; col: number; ch: string; color: keyof typeof BOLT_PALETTE }[]> = {
57 'small/sleep': [{ row: 0, col: 8, ch: 'z', color: 'G' }],
58}
59
60/** The two run frames, in order. Swap them about every 120 ms while running. */
61export const BOLT_RUN = ['run1', 'run2'] as const
62
63function colour(key: string | undefined): string | undefined {
64 if (key === undefined || key === '.') return undefined
65 return (BOLT_PALETTE as Record<string, string>)[key]
66}
67
68/**
69 * Packs a pose into half-block text cells: rows / 2 lines of `cols` cells.
70 * Terminal: draw with Raster (see hatchling's rasterCells). Desktop: one fixed-width cell per character.
71 */
72export function boltCells(size: 'small', pose: BoltSmallPose): BoltCell[][]
73export function boltCells(size: 'tiny', pose: BoltTinyPose): BoltCell[][]
74export function boltCells(size: BoltSize, pose: BoltPose): BoltCell[][] {
75 const rows: readonly string[] = (BOLT_SPRITES[size] as Record<string, readonly string[]>)[pose] ?? []
76 const out: BoltCell[][] = []
77 for (let r = 0; r + 1 < rows.length; r += 2) {
78 const top = rows[r] ?? ''
79 const bottom = rows[r + 1] ?? ''
80 const line: BoltCell[] = []
81 for (let c = 0; c < top.length; c += 1) {
82 const t = colour(top[c])
83 const b = colour(bottom[c])
84 if (t === undefined && b === undefined) line.push({ ch: ' ' })
85 else if (b === undefined) line.push({ ch: '\u2580', fg: t })
86 else if (t === undefined) line.push({ ch: '\u2584', fg: b })
87 else if (t === b) line.push({ ch: '\u2588', fg: t })
88 else line.push({ ch: '\u2580', fg: t, bg: b })
89 }
90 out.push(line)
91 }
92 for (const glyph of GLYPHS[`${size}/${pose}`] ?? []) {
93 const line = out[glyph.row]
94 if (line !== undefined && glyph.col < line.length) line[glyph.col] = { ch: glyph.ch, fg: BOLT_PALETTE[glyph.color] }
95 }
96 return out
97}
98
99/** Merges a row of cells into runs of one style, for coloured Text spans. */
100export function boltRuns(line: readonly BoltCell[]): BoltCell[] {
101 const runs: BoltCell[] = []
102 for (const cell of line) {
103 const last = runs[runs.length - 1]
104 if (last !== undefined && last.fg === cell.fg && last.bg === cell.bg) last.ch += cell.ch
105 else runs.push({ ...cell })
106 }
107 return runs
108}
109hooks/prices.ts 75 lines1// The built-in price table: USD per million tokens, per model family, as the
2// published list prices stood on 2026-10-08.
3//
4// Claude Code's own cost ledger (what /cost shows) is preferred for the session
5// total wherever it exists; this table prices the breakdowns (per category, per
6// turn) and stands in for the total where no ledger is kept. Everything priced
7// here is shown with "≈": it leaves out long-context premiums, fast mode,
8// 1-hour cache writes, batch and regional pricing. A model with no row gets no
9// price at all (tokens only), never a guess.
10
11import type { RedlineTokens } from '../types'
12
13export type Price = RedlineTokens
14
15type Row = {
16 label: string
17 families: readonly string[]
18 /** "major.minor", as the model id spells it (claude-opus-4-1 is 4.1). */
19 versions: readonly string[]
20 price: Price
21 /** A second rate card for requests whose prompt is over 100k tokens. */
22 above100k?: Price
23}
24
25// Cache writes are the 5-minute rate (1.25x input); cache reads 0.1x input
26// unless the model's list price says otherwise.
27const rates = (input: number, output: number, readX = 0.1): Price => ({
28 input,
29 output,
30 cacheWrite: input * 1.25,
31 cacheRead: input * readX,
32})
33
34export const PRICE_TABLE: readonly Row[] = [
35 { label: 'Fable 5.1', families: ['fable', 'mythos'], versions: ['5.1'], price: rates(10, 50, 0.025) },
36 { label: 'Fable 5', families: ['fable', 'mythos'], versions: ['5.0'], price: rates(10, 50) },
37 { label: 'Opus 5.5', families: ['opus'], versions: ['5.5'], price: rates(4, 20, 0.05) },
38 { label: 'Opus 4.5 - 5', families: ['opus'], versions: ['4.5', '4.6', '4.7', '4.8', '5.0'], price: rates(5, 25) },
39 { label: 'Opus 4 - 4.1', families: ['opus'], versions: ['4.0', '4.1'], price: rates(15, 75) },
40 { label: 'Sonnet 5 - 5.5', families: ['sonnet'], versions: ['5.0', '5.5'], price: rates(2, 10) },
41 { label: 'Sonnet 4 - 4.6', families: ['sonnet'], versions: ['4.0', '4.5', '4.6'], price: rates(3, 15) },
42 { label: 'Haiku 5.5', families: ['haiku'], versions: ['5.5'], price: rates(0.1, 0.5), above100k: rates(0.5, 2.5) },
43 { label: 'Haiku 4.5', families: ['haiku'], versions: ['4.5'], price: rates(1, 5) },
44]
45
46// claude-opus-4-1-20250805, us.anthropic.claude-sonnet-4-5-20250929-v1:0,
47// claude-haiku-4-5@20251001, claude-opus-5: the family, then the major, then a
48// one-digit minor when one follows (a date is never a minor).
49const MODEL_ID = /(opus|sonnet|haiku|fable|mythos)-(\d+)(?:-(\d)(?!\d))?/
50
51/** The price row for a model id, or undefined when the table has none. */
52export function priceRow(model: string): Row | undefined {
53 const m = MODEL_ID.exec(model.toLowerCase())
54 if (!m) return undefined
55 const family = m[1] ?? ''
56 const version = `${m[2]}.${m[3] ?? '0'}`
57 return PRICE_TABLE.find(row => row.families.includes(family) && row.versions.includes(version))
58}
59
60/** What one request cost per category, USD; undefined for an unpriced model. */
61export function priceRequest(model: string, t: RedlineTokens): RedlineTokens | undefined {
62 const row = priceRow(model)
63 if (!row) return undefined
64 const prompt = t.input + t.cacheRead + t.cacheWrite
65 const p = row.above100k && prompt > 100_000 ? row.above100k : row.price
66 return {
67 input: (t.input * p.input) / 1e6,
68 output: (t.output * p.output) / 1e6,
69 cacheRead: (t.cacheRead * p.cacheRead) / 1e6,
70 cacheWrite: (t.cacheWrite * p.cacheWrite) / 1e6,
71 }
72}
73
74export const sumTokens = (t: RedlineTokens): number => t.input + t.output + t.cacheRead + t.cacheWrite
75types/index.d.ts 97 lines1// The values redline keeps in $.state: the gauge every drawing reads, and
2// whether the band above the prompt is on. Self-contained on purpose: no
3// import, every name led by "Redline".
4
5/** The four token counts of a model request, as the API reports them. */
6export type RedlineTokens = {
7 input: number
8 output: number
9 cacheRead: number
10 cacheWrite: number
11}
12
13/** One reading over time: context tokens, or new tokens of one request. */
14export type RedlineSample = { t: number; tokens: number }
15
16/** One plan rate-limit window as Claude Code reports it. */
17export type RedlineLimit = {
18 kind: string
19 percentUsed: number
20 resetsAt?: string
21}
22
23/** One turn (or one subagent run) and what its requests used. */
24export type RedlineTurn = {
25 id: string
26 label: string
27 isSubagent: boolean
28 startedAt: number
29 requests: number
30 tokens: RedlineTokens
31 /** USD by the built-in price table; null once a request had no price. */
32 usd: number | null
33}
34
35/** What the requests charged to one kind of work, or to one model, used. */
36export type RedlineSpend = {
37 requests: number
38 tokens: RedlineTokens
39 /** USD by the built-in price table; null once a request charged here had no price. */
40 usd: number | null
41}
42
43export type RedlineGauge = {
44 /** When the session began (Claude Code's own figure), epoch ms. */
45 sessionStartedAt: number | null
46 /** When redline began counting tokens, epoch ms. */
47 trackingSince: number | null
48 /** The model's context window in tokens, from Claude Code. */
49 window: number | null
50 /** Input side of the main loop's last request; null while unknown. */
51 contextTokens: number | null
52 /**
53 * Claude Code's own fill percentage (the status line's used_percentage)
54 * when it reported one for this reading; null to compute it from tokens.
55 */
56 contextPercent: number | null
57 /** Main-loop context readings of the last 10 minutes (pace). */
58 samples: RedlineSample[]
59 /** New tokens per request of the last 10 minutes (tokens per minute). */
60 flow: RedlineSample[]
61 /** Every request counted since trackingSince, main loop and subagents. */
62 totals: RedlineTokens
63 /** The same requests priced by the built-in table, per category, USD. */
64 tableUsd: RedlineTokens
65 /** Models seen with no row in the price table. */
66 unpriced: string[]
67 /** Claude Code's own cost ledger for the session, USD; null where absent. */
68 ledgerUsd: number | null
69 limits: RedlineLimit[]
70 /** Each plan window's readings of the last 15 minutes, by kind (run-out). */
71 limitHistory: Record<string, RedlineSample[]>
72 turns: RedlineTurn[]
73 /**
74 * This session's requests by the kind of work each carried (the results of the
75 * previous response's tool calls: reading, editing, shell, search, planning; a
76 * subagent's requests as subagents; a turn's first request as prompt; one with no
77 * results as answering; an MCP server's tools as mcp:<server>), a request carrying
78 * several kinds split evenly across them.
79 */
80 spend: Record<string, RedlineSpend>
81 /** The same requests by the model that answered. */
82 byModel: Record<string, RedlineSpend>
83 /** The model of the main loop's last request. */
84 model: string | null
85 /** The 80% toast may fire; false until context drops under 75%. */
86 isArmed: boolean
87}
88
89/** Which of the pane's two views is open: the limits, or where the money went. */
90export type RedlineView = 'overview' | 'spend'
91
92declare module 'claude-code' {
93 interface PluginState {
94 redline: { gauge: RedlineGauge; isBandOn: boolean; view: RedlineView }
95 }
96}
97