A rev limiter for Claude Code: past the redline you set on your plan's windows, it shifts the session down to Sonnet or low effort until the window resets, and…

A rev limiter for Claude Code. Set a redline on your plan's five-hour and seven-day windows; past it, every request this session makes goes out on Sonnet, or at low effort, until the window resets. It never stops you working, it stops you spending the last of a window at Opus prices on the easy parts. One dim line above the prompt shows the two windows, the context, and which of your other sessions are waiting on you.
5h 62% · 7d 31% · ctx 44% · 1 session needs you · 2 working
Shifted down, the line leads with the gear:
⇣ Sonnet 5.5 · 5h 84% · 7d 31% · ctx 44% · 2 working
Add the marketplace:
/plugin marketplace add jamubc/toolbox
Install the plugin:
/plugin install redline@toolbox
| Command | What it does |
|---|---|
/redline | Opens and closes the dash: the three dials, the readouts, the limiter and every session. |
/redline shift | Shifts down now, until the five-hour window resets. |
/redline lift | Lifts the limiter until the five-hour window resets, when you need the big model past the redline. |
/redline auto | Hands the lever back to the limiter. |
The dash:
⡴⠋⠉⠉⠳⡄ ⡴⠋⠉⠉⠳⡄ ⡴⠋⠉⠉⠳⡄
⣇⠀⠀5H⠀⠀⣸ ⣇⠀⠀7D⠀⠀⣸ ⣇⠀⠀CTX⠀⣸
F ⠈⠁ E F ⠈⠁ E E ⠈⠁ F
5h 62% resets 20:00 · 4h left · runs out 19:10 at this pace
7d 31% resets Thu 09:00 · 2d 3h left
ctx 44% $1.20 this session
Limiter in gear · shifts at 80% of 5h, 90% of 7d
shift now
Sessions 3
! fennec needs you · approve Bash · 2m · ctx 61% · $0.40
● toolbox working · 4m · ctx 44% · $1.20 · this one
○ jam idle
On the plan dials the needle swings from F to E as the window drains and turns red in the reserve; the context dial fills, E to F. The plan readings need a subscription; the context works for everyone. A dial the engine has no reading for stays dim.
/config, or the plugin's settings:
| Setting | Default | What it does |
|---|---|---|
| Shift down when the 5-hour window is this % used | 80 | The redline on the five-hour window. |
| Shift down when the 7-day window is this % used | 90 | The redline on the seven-day window. |
| What shifting down does | switch to Sonnet | switch to Sonnet sends requests to the model below instead of the session's model, subagents too. lower effort sets the effort to low. Sonnet and lower effort does both. warn only changes nothing and just shows the line. |
| The model to shift down to | claude-sonnet-5-5 | A full model id, as /model lists it; Claude Code takes an id here, not an alias. Haiku works too. |
| The line above the prompt | one line, always | only when it matters keeps the line blank until the limiter shifts, a session needs you, or a window is within twenty points of its redline. never draws nothing above the prompt; /redline still opens the dash. |
A request already on Sonnet or Haiku, or on the model you chose, is left alone. The limiter lifts itself when the window resets, and says so in a toast each time it shifts or lifts.
Every Claude Code session on this machine with redline installed writes a small heartbeat; the dash reads them all, so it can say exactly what a session is waiting for: a permission prompt, with the tool's name, or a question. A session without redline still appears, from Claude Code's own list of running sessions, as working or idle. In the line above the prompt only the sessions that need you, and the count working, are shown.
redline runs one read-only program on your machine and sends nothing anywhere. It makes no network requests.
| Program | Exactly what it runs | When | Why |
|---|---|---|---|
claude | claude agents --json | Every five seconds, in an interactive session only | Claude Code's own list of your running sessions: each one's id, working directory, name and whether it is busy or idle. |
session.usage at start and the session.measure event after each turn): the context fill, your plan's rate-limit percentages and reset times, and the session's cost, the same figures the status line has. The limiter decides from them and the dash draws them.~/.claude/plugins/store/ that every session on this machine shares: the session id, working directory, state (working, waiting or idle) and what it waits for, when that changed, the turn count, the context fill, the cost so far, the model, and whether the limiter is shifted. It is written at start, on every change of state, and every thirty seconds, and removed when the session ends. It reads the other sessions' heartbeats every five seconds; one older than a day is removed.turn.step to change the model, or the effort, of a request while shifted, and agent.spawn to send a subagent to the same model while shifted. In gear it passes both through unchanged.tool.check only to read the decision: when a tool is going to ask you, the heartbeat says so. It never changes a decision. It hooks tool.call to notice AskUserQuestion and to clear the waiting state once the call goes through.command.run only for its own /redline command, ui.close to notice when you close its pane, and session.start, session.end and session.measure to keep its figures right across /clear.hooks/register.tsx 467 lines1// redline: a rev limiter for Claude Code. It watches your plan's five-hour and seven-day windows
2// and, once one is past the redline you set, shifts this session down (Sonnet, low effort, or
3// both) on every model request until the window resets. One quiet line above the prompt says
4// where the windows stand and which of your other sessions need you; /redline opens the dash.
5//
6// State lives in this module: it survives /clear (which empties `$.state`) and is rebuilt on a
7// hot reload by `session.start`. Each session running redline writes a heartbeat to the shared
8// `$.store`, so every session can list the others with their exact state.
9
10import type { EngineInterface, Register } from 'claude-code'
11
12import type { RedlineBeat, RedlineUsage } from '../types'
13import { type Segment, bandSegments, bandLine, matters } from './band'
14import { type Agent, type Row, agentsIn, fleet } from './fleet'
15import { BIG, Needle, SCALE, type Tanks, dashCanvas, dashLayout, tanksNow, usageFrom } from './fuel'
16import { DEFAULT_MODEL, type Gear, LENGTH, type LimiterConfig, type Manual, clock, gearFor, paceOf, shiftFor, shiftWords, span, spawnModel, stepChange, windowNow } from './limiter'
17
18const PANE = 'redline'
19const FPS = 10
20const POLL_MS = 5000
21const BEAT_MS = 30_000
22const EMPTY_USAGE: RedlineUsage = { fiveHour: null, sevenDay: null, context: null }
23
24type BandMode = 'always' | 'matters' | 'never'
25const BAND_OPTIONS: Record<string, BandMode> = { 'one line, always': 'always', 'only when it matters': 'matters', never: 'never' }
26
27type View = { requestId: string; columns: number }
28
29// What this process knows. A hot reload starts it over; session.start refills it.
30let config: LimiterConfig = { redlineAt: 80, weeklyRedlineAt: 90, shift: 'sonnet', model: DEFAULT_MODEL }
31let bandMode: BandMode = 'always'
32let usage: RedlineUsage = EMPTY_USAGE
33let manual: Manual = { mode: 'auto' }
34let wasShifted: boolean | null = null // the gear the last check saw; null before the first
35let agents: Agent[] = []
36let beats: RedlineBeat[] = []
37let rows: Row[] = []
38let lastFleet = ''
39let myId = ''
40let myModel = ''
41let myState: RedlineBeat['state'] = 'idle'
42let myWaitingFor = ''
43let mySince = 0
44let myTurns = 0
45let myUsd: number | null = null
46let isPaneOpen = false
47let isInteractive = false
48let views: View[] = []
49const needles: Record<keyof Tanks, Needle> = { fiveHour: new Needle(), sevenDay: new Needle(), context: new Needle() }
50const reads: Record<keyof Tanks, number | null> = { fiveHour: null, sevenDay: null, context: null }
51
52const RED = '#ff3b30'
53const AMBER = '#ffaf00'
54const toneColor = (tone: Segment['tone']) => (tone === 'red' ? RED : tone === 'amber' ? AMBER : undefined)
55
56/** The engine's clock, read as `now()` plus the offset the last `sync` measured. */
57let skew = 0
58const now = () => Date.now() + skew
59async function sync($: EngineInterface): Promise<void> {
60 try {
61 skew = (await $.clock.now()) - Date.now()
62 } catch {
63 // the wall clock then
64 }
65}
66
67const gearNow = (at = now()): Gear => gearFor(usage, config, manual, at)
68
69/** What the dials draw: the sprung needle positions, in 0-1, or null while a tank has no reading. */
70function drawnTanks(): Tanks {
71 const at = (key: keyof Tanks) => (reads[key] === null ? null : reads[key] / SCALE)
72 return { fiveHour: at('fiveHour'), sevenDay: at('sevenDay'), context: at('context') }
73}
74
75function mounted(view: View): void {
76 views = [...views.filter(v => v.requestId !== view.requestId), view]
77}
78
79/** One frame of the dials: step every needle and repaint the mounted rasters. */
80async function frame($: EngineInterface): Promise<void> {
81 if (views.length === 0) return
82 const tanks = tanksNow(usage, now())
83 for (const key of ['fiveHour', 'sevenDay', 'context'] as const) {
84 const frac = tanks[key]
85 reads[key] = frac === null ? null : needles[key].step(frac * SCALE, 1 / FPS)
86 }
87 await Promise.all(
88 views.map(async v => {
89 const res = await $.ui.blit({ requestId: v.requestId, key: 'dash', cells: dashCanvas(drawnTanks(), dashLayout(v.columns)).encode() })
90 if (res.deny !== undefined) views = views.filter(w => w !== v)
91 }),
92 )
93}
94
95/** This session's heartbeat, as the other sessions read it. */
96function myBeat(cwd: string, now: number): RedlineBeat {
97 return {
98 id: myId,
99 cwd,
100 state: myState,
101 waitingFor: myWaitingFor,
102 since: mySince,
103 at: now,
104 turns: myTurns,
105 context: usage.context,
106 usd: myUsd,
107 model: myModel,
108 isShifted: gearNow(now).isShifted,
109 }
110}
111
112async function beat($: EngineInterface): Promise<void> {
113 await sync($)
114 try {
115 const id = await $.session.id()
116 if (id !== myId) {
117 if (myId) await $.store.delete(`session:${myId}`)
118 myId = id
119 }
120 await $.store.set(`session:${myId}`, myBeat(await $.session.cwd(), now()))
121 } catch {
122 // the store is best effort: the dash still draws
123 }
124}
125
126function setState($: EngineInterface, state: RedlineBeat['state'], waitingFor = ''): void {
127 if (state === myState && waitingFor === myWaitingFor) return
128 myState = state
129 myWaitingFor = waitingFor
130 mySince = now()
131 void beat($).then(() => refleet($))
132}
133
134/** Reads the other sessions' heartbeats; a stale one is removed from the store. */
135async function readBeats($: EngineInterface): Promise<RedlineBeat[]> {
136 const found: RedlineBeat[] = []
137 const at = now()
138 for (const key of await $.store.keys()) {
139 if (!key.startsWith('session:')) continue
140 const value = (await $.store.get(key)) as RedlineBeat | undefined
141 if (!value || typeof value !== 'object' || typeof value.id !== 'string') continue
142 if (at - value.at > 24 * 3600_000) {
143 await $.store.delete(key)
144 continue
145 }
146 found.push(value)
147 }
148 return found
149}
150
151/** Folds the two sources into the rows, and redraws when they changed. */
152function refleet($: EngineInterface): void {
153 rows = fleet(agents, beats, myId, now())
154 const key = JSON.stringify(rows.map(r => [r.id, r.state, r.waitingFor, r.folder, Math.floor((r.forMs ?? 0) / 60_000)]))
155 if (key === lastFleet) return
156 lastFleet = key
157 $.ui.invalidate('ui.render')
158}
159
160async function poll($: EngineInterface): Promise<void> {
161 await sync($)
162 try {
163 const res = await $.process.run(['claude', 'agents', '--json'], { timeoutMs: 5000 })
164 if (res.exitCode === 0) agents = agentsIn(res.stdout)
165 } catch {
166 // keep the last listing
167 }
168 beats = await readBeats($).catch(() => beats)
169 refleet($)
170 checkGear($)
171}
172
173/** Notices the gear changing on its own (a window crossing the redline, or resetting) and says so. */
174function checkGear($: EngineInterface): void {
175 const at = now()
176 const gear = gearNow(at)
177 if (wasShifted === gear.isShifted) return
178 const wasKnown = wasShifted !== null
179 wasShifted = gear.isShifted
180 if (!wasKnown) return
181 if (gear.isShifted) {
182 const until = gear.until === null ? '' : ` until ${clock(gear.until, at)}`
183 $.ui.toast(config.shift === 'warn' ? `${gear.reason}: past the redline` : `shifted down to ${shiftWords(config)}${until}: ${gear.reason}`)
184 } else {
185 $.ui.toast('back in gear')
186 }
187 $.ui.invalidate('ui.render')
188 void beat($)
189}
190
191/** The engine's figures; null when the engine has none to give. */
192async function readUsage($: EngineInterface): Promise<RedlineUsage | null> {
193 try {
194 const { rateLimits, context, cost } = await $.session.usage()
195 if (cost) myUsd = cost.usd
196 return usageFrom(rateLimits, context.percent ?? null)
197 } catch {
198 return null
199 }
200}
201
202/** The pane's rows: the dash, the readouts, the limiter and the sessions. */
203function paneRows(): number {
204 return dashLayout(Infinity).rows + 9 + Math.max(1, rows.length)
205}
206
207export const register: Register = (on, options) => {
208 const num = (v: unknown, d: number) => (typeof v === 'number' && Number.isFinite(v) ? Math.max(1, Math.min(100, v)) : d)
209 const model = typeof options.model === 'string' && options.model.trim() ? options.model.trim() : DEFAULT_MODEL
210 config = { redlineAt: num(options.redlineAt, 80), weeklyRedlineAt: num(options.weeklyRedlineAt, 90), shift: shiftFor(options.shift), model }
211 bandMode = BAND_OPTIONS[String(options.band)] ?? 'always'
212
213 on('session.start', async ($, e, next) => {
214 const result = await next(e)
215 await sync($)
216 mySince = now()
217 isInteractive = e.isInteractive
218 try {
219 await $.command.register({ name: 'redline', description: 'The dash: your plan windows, the limiter, and every session', argumentHint: '[shift|lift|auto]', immediate: true })
220 } catch {
221 // a reload registers it again
222 }
223 myModel = await $.session.model().catch(() => '')
224 const found = await readUsage($)
225 if (found) usage = found
226 isPaneOpen = await $.ui.panes().then(panes => panes.some(p => p.id === PANE), () => false)
227 wasShifted = gearNow().isShifted
228 await beat($)
229 $.clock.every(1000 / FPS, () => void frame($).catch(() => {}))
230 $.clock.every(BEAT_MS, () => void beat($))
231 if (isInteractive) {
232 void poll($)
233 $.clock.every(POLL_MS, () => void poll($))
234 }
235 return result
236 })
237
238 // The engine measures after every turn and whenever a window moves a whole point.
239 on('session.measure', async ($, e, next) => {
240 const result = await next(e)
241 await sync($)
242 usage = usageFrom(e.rateLimits, e.context.percent ?? null)
243 if (e.cost) myUsd = e.cost.usd
244 checkGear($)
245 $.ui.invalidate('ui.render')
246 return result
247 })
248
249 on('session.end', async ($, e, next) => {
250 const result = await next(e)
251 if (e.reason !== 'clear' && myId) await $.store.delete(`session:${myId}`).catch(() => {})
252 return result
253 })
254
255 on('turn.start', async ($, e, next) => {
256 setState($, 'working')
257 return next(e)
258 })
259
260 on('turn.complete', async ($, e, next) => {
261 const result = await next(e)
262 if (e.agentId === undefined) {
263 myTurns += 1
264 setState($, 'idle')
265 }
266 return result
267 })
268
269 // The limiter: while shifted, every request goes out on the cheaper setting.
270 on('turn.step', async function* ($, e, next) {
271 const change = gearNow().isShifted ? stepChange(e, config) : null
272 return yield* next(change ? { ...e, ...change } : e)
273 })
274
275 on('agent.spawn', async ($, e, next) => {
276 const model = gearNow().isShifted ? spawnModel(e, config) : null
277 return next(model ? { ...e, model } : e)
278 })
279
280 // A permission prompt is the main way a session waits on you: tool.check answers `ask` for
281 // it, inside the tool.call that then waits for your answer.
282 on('tool.check', async ($, e, next) => {
283 const decided = await next(e)
284 if (decided.decision === 'ask' && e.tool_use_id !== undefined) setState($, 'waiting', `approve ${e.tool}`)
285 return decided
286 })
287
288 on('tool.call', async ($, e, next) => {
289 if (e.tool === 'AskUserQuestion') setState($, 'waiting', 'a question')
290 const result = await next(e)
291 if (myState === 'waiting') setState($, 'working')
292 return result
293 })
294
295 on('command.run', { command: 'redline' }, async ($, e) => {
296 await sync($)
297 const arg = e.args.trim().toLowerCase()
298 const at = now()
299 const five = windowNow(usage.fiveHour, at)
300 const until = five?.resetsAt ?? at + LENGTH.fiveHour
301 if (arg === 'shift') {
302 manual = { mode: 'shift', until }
303 checkGear($)
304 return { text: `Shifted down to ${shiftWords(config)} until ${clock(until, at)}. /redline auto hands it back to the limiter.` }
305 }
306 if (arg === 'lift') {
307 const gear = gearNow(at)
308 const liftUntil = gear.until ?? until
309 manual = { mode: 'lift', until: liftUntil }
310 checkGear($)
311 return { text: `Limiter lifted until ${clock(liftUntil, at)}. /redline auto hands it back.` }
312 }
313 if (arg === 'auto') {
314 manual = { mode: 'auto' }
315 checkGear($)
316 const gear = gearNow(at)
317 return { text: gear.isShifted ? `Automatic again: shifted, ${gear.reason}.` : 'Automatic again: in gear.' }
318 }
319 if (arg !== '') return { text: 'Usage: /redline, /redline shift, /redline lift, /redline auto' }
320
321 if (isPaneOpen) {
322 await $.ui.close({ id: PANE })
323 isPaneOpen = false
324 return {}
325 }
326 const opened = await $.ui.open({ id: PANE, title: 'Redline', rows: paneRows() })
327 isPaneOpen = true
328 if (isInteractive) void poll($)
329 return opened.isPlaced ? {} : { text: 'Redline opened; widen the terminal to see it.' }
330 })
331
332 on('ui.close', async ($, e, next) => {
333 const result = await next(e)
334 if (e.id === PANE) {
335 isPaneOpen = false
336 views = []
337 }
338 return result
339 })
340
341 on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
342 if (e.props.hasSurvey || bandMode === 'never' || isPaneOpen) return next(e)
343 await sync($)
344 const segments = bandSegments({ usage, gear: gearNow(), shift: config, redlineAt: config.redlineAt, weeklyRedlineAt: config.weeklyRedlineAt, rows, now: now() })
345 if (segments.length === 0 || (bandMode === 'matters' && !matters(segments))) return next(e)
346 const { Box, Text } = $.ui.resolve(e)
347 const theirs = await next(e)
348 const line = (
349 <Text wrap="truncate">
350 {segments.map((s, i) => (
351 <Text key={`seg-${i}`} color={toneColor(s.tone)} dimColor={s.tone === 'dim'} bold={s.tone === 'red'}>
352 {i === 0 ? s.text : ` · ${s.text}`}
353 </Text>
354 ))}
355 </Text>
356 )
357 if (e.props.bodyColumns < bandLine(segments, Infinity).length) {
358 return <Box flexDirection="column"><Text dimColor wrap="truncate">{bandLine(segments, e.props.bodyColumns)}</Text>{theirs}</Box>
359 }
360 return <Box flexDirection="column">{line}{theirs}</Box>
361 })
362
363 on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
364 await sync($)
365 const at = now()
366 const gear = gearNow(at)
367 const elements = $.ui.resolve(e)
368 const { Box, Text, Button } = elements
369 const width = e.props.bodyColumns
370
371 const five = windowNow(usage.fiveHour, at)
372 const week = windowNow(usage.sevenDay, at)
373 const fivePace = paceOf(five, LENGTH.fiveHour, at)
374 const weekPace = paceOf(week, LENGTH.sevenDay, at)
375 const percentColor = (percent: number, redlineAt: number) => (percent >= redlineAt ? RED : percent >= redlineAt - 20 ? AMBER : undefined)
376 const readout = (label: string, tank: { percent: number; resetsAt: number | null } | null, redlineAt: number, pace: ReturnType<typeof paceOf>) => {
377 if (!tank) return <Text dimColor>{`${label.padEnd(4)} no reading yet`}</Text>
378 const resets = tank.resetsAt === null ? '' : `resets ${clock(tank.resetsAt, at)} · ${span(tank.resetsAt - at)} left`
379 const runsOut = pace?.runsOutAt ? ` · runs out ${clock(pace.runsOutAt, at)} at this pace` : ''
380 return (
381 <Text wrap="truncate">
382 <Text dimColor>{label.padEnd(4)}</Text>
383 <Text color={percentColor(tank.percent, redlineAt)} bold={tank.percent >= redlineAt}>{`${String(Math.round(tank.percent)).padStart(3)}%`}</Text>
384 <Text dimColor>{` ${resets}`}</Text>
385 {runsOut ? <Text color={AMBER}>{runsOut}</Text> : null}
386 </Text>
387 )
388 }
389 const readouts = (
390 <Box flexDirection="column" paddingX={1}>
391 {readout('5h', five, config.redlineAt, fivePace)}
392 {readout('7d', week, config.weeklyRedlineAt, weekPace)}
393 {usage.context === null ? (
394 <Text dimColor>{'ctx no reading yet'}</Text>
395 ) : (
396 <Text wrap="truncate">
397 <Text dimColor>{'ctx '}</Text>
398 <Text color={percentColor(usage.context, 85)}>{`${String(Math.round(usage.context)).padStart(3)}%`}</Text>
399 <Text dimColor>{myUsd === null ? '' : ` $${myUsd.toFixed(2)} this session`}</Text>
400 </Text>
401 )}
402 </Box>
403 )
404
405 const limiterWords = gear.isShifted
406 ? `⇣ ${config.shift === 'warn' ? 'past the redline' : `shifted down to ${shiftWords(config)}`} · ${gear.reason}${gear.until === null ? '' : ` · lifts ${clock(gear.until, at)}`}`
407 : `in gear · shifts at ${config.redlineAt}% of 5h, ${config.weeklyRedlineAt}% of 7d${manual.mode === 'lift' ? ' · lifted by hand' : ''}`
408 const limiter = (
409 <Box flexDirection="column" paddingX={1}>
410 <Text wrap="truncate">
411 <Text bold color={gear.isShifted ? RED : undefined}>{'Limiter '}</Text>
412 <Text color={gear.isShifted ? RED : undefined} dimColor={!gear.isShifted}>{limiterWords}</Text>
413 </Text>
414 <Box gap={2}>
415 {!gear.isShifted && <Button key="shift" plain hotkey="s" label="shift at" onPress={() => void $.command.run({ command: 'redline', args: 'shift' })} />}
416 {gear.isShifted && <Button key="lift" plain hotkey="l" label="lift" onPress={() => void $.command.run({ command: 'redline', args: 'lift' })} />}
417 {manual.mode !== 'auto' && <Button key="auto" plain hotkey="a" label="auto" onPress={() => void $.command.run({ command: 'redline', args: 'auto' })} />}
418 </Box>
419 </Box>
420 )
421
422 const mark = (r: Row) => (r.state === 'waiting' ? '!' : r.state === 'working' ? '●' : r.state === 'done' ? '✓' : '○')
423 const words = (r: Row) => {
424 const ago = r.forMs === null ? '' : ` · ${span(r.forMs)}`
425 const detail =
426 r.state === 'waiting' ? `needs you · ${r.waitingFor}${ago}`
427 : r.state === 'working' ? `working${ago}`
428 : r.state === 'done' ? `done${ago} ago`
429 : `idle${ago}`
430 const extra = r.beat ? [r.beat.context === null ? '' : `ctx ${Math.round(r.beat.context)}%`, r.beat.usd === null ? '' : `$${r.beat.usd.toFixed(2)}`, r.beat.isShifted ? '⇣' : ''].filter(Boolean).join(' · ') : ''
431 return `${detail}${extra ? ` · ${extra}` : ''}${r.isThis ? ' · this one' : ''}`
432 }
433 const nameWidth = Math.min(24, Math.max(8, ...rows.map(r => r.folder.length)))
434 const sessions = (
435 <Box flexDirection="column" paddingX={1}>
436 <Text bold>{rows.length === 0 ? 'Sessions' : `Sessions ${rows.length}`}</Text>
437 {rows.length === 0 && <Text dimColor>none found yet</Text>}
438 {rows.map(r => (
439 <Text key={`row-${r.id}`} wrap="truncate" color={r.state === 'waiting' ? RED : undefined} dimColor={r.state === 'idle'} bold={r.state === 'waiting'}>
440 {`${mark(r)} ${r.folder.slice(0, nameWidth).padEnd(nameWidth)} ${words(r)}`}
441 </Text>
442 ))}
443 </Box>
444 )
445
446 const gap = <Text> </Text>
447 if (!('Raster' in elements) || width < BIG.cols) {
448 return <Box flexDirection="column" paddingTop={1}>{readouts}{gap}{limiter}{gap}{sessions}</Box>
449 }
450 const layout = dashLayout(width)
451 mounted({ requestId: e.requestId, columns: width })
452 return (
453 <Box flexDirection="column" paddingTop={1}>
454 <Box paddingX={Math.max(0, Math.floor((width - layout.cols) / 2))}>
455 <elements.Raster key="dash" columns={layout.cols} rows={layout.rows} cells={dashCanvas(drawnTanks(), layout).encode()} />
456 </Box>
457 {readouts}
458 {gap}
459 {limiter}
460 {gap}
461 {sessions}
462 </Box>
463 )
464 })
465}
466
467hooks/band.ts 58 lines1// The one line above the prompt: the gear when shifted, the windows, the context, and who
2// needs you. Each piece is a segment with a tone; the renderer colors them. Pure.
3
4import type { RedlineUsage } from '../types'
5import type { Row } from './fleet'
6import { tally } from './fleet'
7import { type Gear, type LimiterConfig, shiftWords, windowNow } from './limiter'
8
9export type Tone = 'dim' | 'plain' | 'amber' | 'red'
10export type Segment = { text: string; tone: Tone }
11
12export type BandInput = {
13 usage: RedlineUsage
14 gear: Gear
15 shift: Pick<LimiterConfig, 'shift' | 'model'>
16 redlineAt: number
17 weeklyRedlineAt: number
18 rows: readonly Row[]
19 now: number
20}
21
22/** The tone a percent reads in, against its redline: red at it, amber within 20 points of it. */
23export function toneFor(percent: number, redlineAt: number): Tone {
24 if (percent >= redlineAt) return 'red'
25 if (percent >= redlineAt - 20) return 'amber'
26 return 'dim'
27}
28
29export const CONTEXT_REDLINE = 85
30
31/** The band's segments, in order; empty when there is nothing to say. */
32export function bandSegments(input: BandInput): Segment[] {
33 const out: Segment[] = []
34 if (input.gear.isShifted) out.push({ text: `⇣ ${shiftWords(input.shift)}`, tone: 'red' })
35 const five = windowNow(input.usage.fiveHour, input.now)
36 if (five) out.push({ text: `5h ${Math.round(five.percent)}%`, tone: toneFor(five.percent, input.redlineAt) })
37 const week = windowNow(input.usage.sevenDay, input.now)
38 if (week) out.push({ text: `7d ${Math.round(week.percent)}%`, tone: toneFor(week.percent, input.weeklyRedlineAt) })
39 if (input.usage.context !== null) {
40 out.push({ text: `ctx ${Math.round(input.usage.context)}%`, tone: toneFor(input.usage.context, CONTEXT_REDLINE) })
41 }
42 const { needYou, working } = tally(input.rows)
43 if (needYou) out.push({ text: needYou === 1 ? '1 session needs you' : `${needYou} sessions need you`, tone: 'red' })
44 if (working) out.push({ text: `${working} working`, tone: 'dim' })
45 return out
46}
47
48/** True when the band has something worth a line: the gear, a session that needs you, or a tank near its redline. */
49export function matters(segments: readonly Segment[]): boolean {
50 return segments.some(s => s.tone === 'red' || s.tone === 'amber')
51}
52
53/** The segments as one line, cut to `columns`. */
54export function bandLine(segments: readonly Segment[], columns: number): string {
55 const line = segments.map(s => s.text).join(' · ')
56 return line.length <= columns ? line : `${line.slice(0, Math.max(0, columns - 1))}…`
57}
58hooks/fleet.ts 93 lines1// The other Claude sessions on this machine, and which of them need you. Two sources: what
2// `claude agents --json` lists (every interactive session, busy or idle), and the heartbeat each
3// session running redline writes to the shared store (exact state: working, waiting on you and
4// for what, idle since when, context, cost, gear). Pure functions: the wiring is in register.tsx.
5
6import type { RedlineBeat } from '../types'
7
8
9/** A heartbeat older than this is a session that has gone. */
10export const STALE_MS = 3 * 60_000
11/** An idle session that finished its turn within this long is shown as done, not idle. */
12export const DONE_MS = 10 * 60_000
13
14export type Agent = { sessionId: string; pid: number | null; cwd: string; name: string; status: 'busy' | 'idle' | 'waiting' | '' }
15
16/** The interactive sessions in what `claude agents --json` printed; nothing for anything else. */
17export function agentsIn(json: string): Agent[] {
18 let rows: unknown
19 try {
20 rows = JSON.parse(json)
21 } catch {
22 return []
23 }
24 if (!Array.isArray(rows)) return []
25 const out: Agent[] = []
26 for (const row of rows as Record<string, unknown>[]) {
27 if (!row || typeof row !== 'object' || row.kind !== 'interactive' || typeof row.sessionId !== 'string') continue
28 const status = row.status === 'busy' || row.status === 'idle' || row.status === 'waiting' ? row.status : ''
29 out.push({
30 sessionId: row.sessionId,
31 pid: typeof row.pid === 'number' ? row.pid : null,
32 cwd: typeof row.cwd === 'string' ? row.cwd : '',
33 name: typeof row.name === 'string' ? row.name : '',
34 status,
35 })
36 }
37 return out
38}
39
40export type RowState = 'waiting' | 'working' | 'done' | 'idle'
41
42export type Row = {
43 id: string
44 folder: string
45 name: string
46 state: RowState
47 /** What it waits for, or '' */
48 waitingFor: string
49 /** How long it has been in this state, in ms; null when unknown. */
50 forMs: number | null
51 isThis: boolean
52 beat: RedlineBeat | null
53}
54
55export const folder = (cwd: string) => cwd.slice(cwd.lastIndexOf('/') + 1) || cwd || '?'
56
57const ORDER: Record<RowState, number> = { waiting: 0, working: 1, done: 2, idle: 3 }
58
59/** Every session, merged from the two sources, those that need you first. */
60export function fleet(agents: readonly Agent[], beats: readonly RedlineBeat[], selfId: string, now: number): Row[] {
61 const fresh = new Map(beats.filter(b => now - b.at < STALE_MS).map(b => [b.id, b]))
62 const rows = new Map<string, Row>()
63 for (const a of agents) {
64 const beat = fresh.get(a.sessionId) ?? null
65 rows.set(a.sessionId, rowFor(a.sessionId, a.cwd, a.name, beat, a.status, selfId, now))
66 }
67 for (const b of fresh.values()) {
68 if (!rows.has(b.id)) rows.set(b.id, rowFor(b.id, b.cwd, '', b, '', selfId, now))
69 }
70 // The session that has waited on you longest comes first; among the rest, the most recent change.
71 const byTime = (x: Row, y: Row) => (x.forMs === null || y.forMs === null ? 0 : x.state === 'waiting' ? y.forMs - x.forMs : x.forMs - y.forMs)
72 return [...rows.values()].sort((x, y) => ORDER[x.state] - ORDER[y.state] || byTime(x, y) || x.folder.localeCompare(y.folder))
73}
74
75function rowFor(id: string, cwd: string, name: string, beat: RedlineBeat | null, status: Agent['status'], selfId: string, now: number): Row {
76 const base = { id, folder: folder(beat?.cwd || cwd), name, isThis: id === selfId, beat }
77 if (beat) {
78 const forMs = now - beat.since
79 if (beat.state === 'waiting') return { ...base, state: 'waiting', waitingFor: beat.waitingFor, forMs }
80 if (beat.state === 'working') return { ...base, state: 'working', waitingFor: '', forMs }
81 return { ...base, state: beat.turns > 0 && forMs < DONE_MS ? 'done' : 'idle', waitingFor: '', forMs }
82 }
83 if (status === 'waiting') return { ...base, state: 'waiting', waitingFor: 'you', forMs: null }
84 if (status === 'busy') return { ...base, state: 'working', waitingFor: '', forMs: null }
85 return { ...base, state: 'idle', waitingFor: '', forMs: null }
86}
87
88/** The counts the band shows, this session left out. */
89export function tally(rows: readonly Row[]): { needYou: number; working: number } {
90 const others = rows.filter(r => !r.isThis)
91 return { needYou: others.filter(r => r.state === 'waiting').length, working: others.filter(r => r.state === 'working').length }
92}
93hooks/fuel.ts 156 lines1// The three dials on the dash: the plan's five-hour and seven-day windows, and this session's
2// context. Each is a shallow arc with F at the left and E at the right, a red reserve at the E
3// end, drawn in braille with the dial library. The plan windows drain, so their needles swing
4// from F to E as the window is used; the context fills, so its dial reads E to F.
5
6import type { SessionRateLimit } from 'claude-code'
7
8import type { RedlineTank, RedlineUsage } from '../types'
9import type { Canvas } from './canvas'
10import { dial, shallow } from './dial'
11import { Dots } from './dots'
12
13export const DIAL = 0x6c6c6c
14export const DIAL_DIM = 0x4a4a4a
15export const TICK = 0xd0d0d0
16export const AMBER_C = 0xffaf00
17export const RED_C = 0xff3b30
18export const NEEDLE = 0xff875f
19export const HUB = 0xeeeeee
20
21/** The needle's scale: a tank's fill in 0-1 is drawn at `frac * SCALE`. */
22export const SCALE = 25
23
24/**
25 * A damped spring: a needle swings to a new reading with a little overshoot and settles on it,
26 * never past the pin at `SCALE` or below 0.
27 */
28export class Needle {
29 value = 0
30 private velocity = 0
31
32 /** Moves `dt` seconds toward `target`; returns where the needle reads now. */
33 step(target: number, dt: number): number {
34 const goal = Math.max(0, Math.min(target, SCALE))
35 this.velocity += (18 * (goal - this.value) - 5 * this.velocity) * dt
36 this.value += this.velocity * dt
37 if (this.value > SCALE) {
38 this.value = SCALE
39 this.velocity = -Math.abs(this.velocity) * 0.6
40 }
41 if (this.value < 0) {
42 this.value = 0
43 this.velocity = Math.abs(this.velocity) * 0.3
44 }
45 return this.value
46 }
47}
48
49/** How much of each tank is used, 0 to 1; null while that tank has no reading. */
50export type Tanks = { fiveHour: number | null; sevenDay: number | null; context: number | null }
51
52export type FuelFace = { cols: number; rows: number }
53
54/** One dial in the pane: 6 rows, labelled F and E. */
55export const BIG: FuelFace = { cols: 15, rows: 6 }
56
57const GAP = 2
58const FROM = (150 / 180) * Math.PI
59const SWEEP = (120 / 180) * Math.PI
60const RESERVE = 0.85 // the red band starts here, as a fraction of the tank used
61
62/**
63 * `fills` is for a tank that fills as it is used, the context: it reads E at the left and F at the
64 * red end. The plan windows drain, F at the left and E at the red end. Either way the needle
65 * swings right, into the red, as the tank is used.
66 */
67export function fuelDial(face: FuelFace, frac: number | null, label: string, fills = false): Dots {
68 const dots = new Dots(face.cols, face.rows)
69 const dim = frac === null
70 const reserve = (t: number) => t >= RESERVE
71 dial(dots, {
72 dial: shallow(face.cols, face.rows, FROM, SWEEP),
73 arc: {
74 colorAt: t => (dim ? DIAL_DIM : reserve(t) ? RED_C : DIAL),
75 widthAt: t => (!dim && reserve(t) ? 1 : 0),
76 },
77 ticks: {
78 count: 8,
79 majorEvery: 4,
80 length: 2,
81 majorLength: 3,
82 rank: 2,
83 colorAt: t => (dim ? DIAL_DIM : reserve(t) ? RED_C : TICK),
84 },
85 needle: dim
86 ? undefined
87 : {
88 t: frac,
89 color: reserve(frac) ? RED_C : NEEDLE,
90 inner: 4,
91 tail: 2.5,
92 width: 1.4,
93 hub: { color: HUB },
94 },
95 })
96
97 dots.text(0, Math.round(face.cols / 2 - label.length / 2), label, dim ? DIAL_DIM : TICK)
98 const [start, end] = fills ? ['E', 'F'] : ['F', 'E']
99 dots.text(face.rows - 2, 0, start, dim ? DIAL_DIM : TICK)
100 dots.text(face.rows - 2, face.cols - 1, end, dim ? DIAL_DIM : RED_C)
101 return dots
102}
103
104export const LABELS = ['5H', '7D', 'CTX'] as const
105
106/** How the dash fits the three dials into `columns`: as many to a row as fit, 1 to 3. */
107export type DashLayout = { perRow: number; cols: number; rows: number }
108
109export function dashLayout(columns: number): DashLayout {
110 const perRow = Math.max(1, Math.min(3, Math.floor((columns + GAP) / (BIG.cols + GAP))))
111 const lines = Math.ceil(3 / perRow)
112 return { perRow, cols: perRow * BIG.cols + (perRow - 1) * GAP, rows: lines * BIG.rows + (lines - 1) }
113}
114
115/** The dash at its widest: the three dials in one row. */
116export const WIDE = dashLayout(Infinity)
117
118/** The dash: the three dials, `layout.perRow` to a row, each row centered. */
119export function dashCanvas(tanks: Tanks, layout: DashLayout = WIDE): Canvas {
120 const out = new Dots(layout.cols, layout.rows)
121 const dials = [tanks.fiveHour, tanks.sevenDay, tanks.context].map((frac, i) => fuelDial(BIG, frac, LABELS[i]!, i === 2))
122 dials.forEach((panel, i) => {
123 const line = Math.floor(i / layout.perRow)
124 const inLine = Math.min(layout.perRow, dials.length - line * layout.perRow)
125 const left = Math.floor((layout.cols - (inLine * BIG.cols + (inLine - 1) * GAP)) / 2)
126 out.blit(panel, line * (BIG.rows + 1), left + (i % layout.perRow) * (BIG.cols + GAP))
127 })
128 return out.toCanvas()
129}
130
131/** A tank's fill from its last reading: emptied once its reset time has passed. */
132export function tankFrac(tank: RedlineTank | null, now: number): number | null {
133 if (tank === null) return null
134 if (tank.resetsAt !== null && now >= tank.resetsAt) return 0
135 return Math.max(0, Math.min(1, tank.percent / 100))
136}
137
138/** A bare percentage, clamped, as a fill; null stays null. */
139export const fracOf = (percent: number | null): number | null => (percent === null ? null : Math.max(0, Math.min(1, percent / 100)))
140
141/** Where each tank sits now, from the last figures: the plan windows empty once they reset. */
142export function tanksNow(usage: RedlineUsage, now: number): Tanks {
143 return { fiveHour: tankFrac(usage.fiveHour, now), sevenDay: tankFrac(usage.sevenDay, now), context: fracOf(usage.context) }
144}
145
146/** The two plan windows and the context, from what a measurement reported. */
147export function usageFrom(rateLimits: readonly SessionRateLimit[], contextPercent: number | null): RedlineUsage {
148 const tank = (kind: string): RedlineTank | null => {
149 const limit = rateLimits.find(l => l.kind === kind)
150 if (!limit) return null
151 const parsed = limit.resetsAt === undefined ? NaN : Date.parse(limit.resetsAt)
152 return { percent: limit.percentUsed, resetsAt: Number.isFinite(parsed) ? parsed : null }
153 }
154 return { fiveHour: tank('five_hour'), sevenDay: tank('seven_day'), context: contextPercent }
155}
156hooks/limiter.ts 145 lines1// The rev limiter: where the redline sits on each plan window, whether the needle is past it,
2// and what to do about a model request when it is. Pure functions: the wiring is in register.tsx.
3
4import type { RedlineTank, RedlineUsage } from '../types'
5
6/** What the limiter does to a request once it is engaged. */
7export type Shift = 'effort' | 'sonnet' | 'both' | 'warn'
8
9export type LimiterConfig = {
10 /** Percent of the five-hour window used at which the limiter engages. */
11 redlineAt: number
12 /** Percent of the seven-day window used at which the limiter engages. */
13 weeklyRedlineAt: number
14 shift: Shift
15 /** The full id of the model a shift sends requests to; an alias is refused by the engine. */
16 model: string
17}
18
19export const DEFAULT_MODEL = 'claude-sonnet-5-5'
20
21/** A model id as a short name: `claude-sonnet-5-5` reads Sonnet 5.5. */
22export function modelWords(id: string): string {
23 const m = /^claude-([a-z]+)-(\d+)(?:-(\d+))?/i.exec(id)
24 if (!m) return id
25 const family = m[1]![0]!.toUpperCase() + m[1]!.slice(1)
26 return m[3] === undefined ? `${family} ${m[2]}` : `${family} ${m[2]}.${m[3]}`
27}
28
29/** The person's say over the automatic limiter: `shift` holds it on, `lift` holds it off, until `until`. */
30export type Manual = { mode: 'auto' } | { mode: 'shift' | 'lift'; until: number | null }
31
32export type Gear = { isShifted: boolean; reason: string; until: number | null }
33
34export const SHIFT_OPTIONS = {
35 'switch to Sonnet': 'sonnet',
36 'lower effort': 'effort',
37 'Sonnet and lower effort': 'both',
38 'warn only': 'warn',
39} as const satisfies Record<string, Shift>
40
41/** The `shift` option's label as the manifest lists it, to what it means; an unknown label switches to Sonnet. */
42export function shiftFor(label: unknown): Shift {
43 return (SHIFT_OPTIONS as Record<string, Shift>)[String(label)] ?? 'sonnet'
44}
45
46export const LENGTH = { fiveHour: 5 * 3600_000, sevenDay: 7 * 86_400_000 } as const
47
48/** A window's reading as it stands now: empty once its reset time has passed. */
49export function windowNow(tank: RedlineTank | null, now: number): RedlineTank | null {
50 if (tank === null) return null
51 if (tank.resetsAt !== null && now >= tank.resetsAt) return null
52 return tank
53}
54
55/**
56 * Whether the limiter is engaged now: by hand (`manual`), or because a window is at or past
57 * its redline. `until` is when the engaging window resets, so the pane can say when it lifts.
58 */
59export function gearFor(usage: RedlineUsage, config: LimiterConfig, manual: Manual, now: number): Gear {
60 if (manual.mode !== 'auto' && (manual.until === null || now < manual.until)) {
61 return manual.mode === 'shift'
62 ? { isShifted: true, reason: 'shifted by hand', until: manual.until }
63 : { isShifted: false, reason: 'lifted by hand', until: manual.until }
64 }
65 const five = windowNow(usage.fiveHour, now)
66 if (five && five.percent >= config.redlineAt) {
67 return { isShifted: true, reason: `5h window at ${Math.round(five.percent)}%`, until: five.resetsAt }
68 }
69 const week = windowNow(usage.sevenDay, now)
70 if (week && week.percent >= config.weeklyRedlineAt) {
71 return { isShifted: true, reason: `7d window at ${Math.round(week.percent)}%`, until: week.resetsAt }
72 }
73 return { isShifted: false, reason: '', until: null }
74}
75
76const CHEAP = /haiku|sonnet/i
77
78/** True for a model the limiter would not shift any lower: the one it shifts to, or any Sonnet or Haiku. */
79export const isCheap = (model: string | undefined, to: string) => model !== undefined && (model === to || CHEAP.test(model))
80
81/** What to rewrite on a model request while shifted: nothing when the request is already there. */
82export function stepChange(e: { model: string; effort?: string | number }, config: Pick<LimiterConfig, 'shift' | 'model'>): { model?: string; effort?: 'low' } | null {
83 const { shift, model } = config
84 const change: { model?: string; effort?: 'low' } = {}
85 if ((shift === 'sonnet' || shift === 'both') && !isCheap(e.model, model)) change.model = model
86 if ((shift === 'effort' || shift === 'both') && e.effort !== undefined && e.effort !== 'low') change.effort = 'low'
87 return Object.keys(change).length ? change : null
88}
89
90/** The model a subagent spawned while shifted should run on: null leaves the spawn alone. */
91export function spawnModel(e: { model?: string; parentModel: string }, config: Pick<LimiterConfig, 'shift' | 'model'>): string | null {
92 if (config.shift !== 'sonnet' && config.shift !== 'both') return null
93 if (isCheap(e.model ?? e.parentModel, config.model)) return null
94 return config.model
95}
96
97/** The words for a shift, as the band and the pane say it. */
98export function shiftWords(config: Pick<LimiterConfig, 'shift' | 'model'>): string {
99 switch (config.shift) {
100 case 'sonnet': return modelWords(config.model)
101 case 'effort': return 'low effort'
102 case 'both': return `${modelWords(config.model)} · low effort`
103 case 'warn': return 'past the redline'
104 }
105}
106
107export type Pace = {
108 /** When the window runs out at the pace so far; null when it lasts to the reset, or there is no pace yet. */
109 runsOutAt: number | null
110 /** Percent used per hour so far. */
111 perHour: number
112}
113
114/** How a window is being spent: from its reset time and length, when it started, and how fast it is going. */
115export function paceOf(tank: RedlineTank | null, length: number, now: number): Pace | null {
116 if (tank === null || tank.resetsAt === null) return null
117 const startedAt = tank.resetsAt - length
118 const elapsed = now - startedAt
119 if (elapsed < length * 0.02 || tank.percent <= 0) return null // too early to say
120 const perMs = tank.percent / elapsed
121 const runsOutAt = now + (100 - tank.percent) / perMs
122 return { runsOutAt: runsOutAt < tank.resetsAt ? runsOutAt : null, perHour: perMs * 3600_000 }
123}
124
125const DAYS = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']
126
127/** A time of day, with the weekday when it is not today's: `14:10`, `Thu 09:00`. */
128export function clock(at: number, now: number): string {
129 const d = new Date(at)
130 const hhmm = `${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}`
131 const today = new Date(now)
132 const sameDay = d.getFullYear() === today.getFullYear() && d.getMonth() === today.getMonth() && d.getDate() === today.getDate()
133 return sameDay ? hhmm : `${DAYS[d.getDay()]} ${hhmm}`
134}
135
136/** A span in words: `48m`, `1h 48m`, `2d 3h`. */
137export function span(ms: number): string {
138 const m = Math.max(0, Math.round(ms / 60_000))
139 if (m < 60) return `${m}m`
140 const h = Math.floor(m / 60)
141 if (h < 24) return m % 60 ? `${h}h ${m % 60}m` : `${h}h`
142 const d = Math.floor(h / 24)
143 return h % 24 ? `${d}d ${h % 24}h` : `${d}d`
144}
145hooks/canvas.ts 37 lines1// A grid of terminal cells, encoded as a `Raster` takes them: row-major little-endian u32
2// triplets [codePoint, foreground, background], base64.
3
4const DEFAULT = 0x01000000 // the terminal's own color
5
6export class Canvas {
7 readonly cells: Uint32Array
8
9 constructor(
10 readonly rows: number,
11 readonly cols: number,
12 ) {
13 this.cells = new Uint32Array(rows * cols * 3)
14 for (let i = 0; i < rows * cols; i++) this.cells.set([0x20, DEFAULT, DEFAULT], i * 3)
15 }
16
17 /** Writes `s` from (r, c) in color `fg`; characters off the grid are dropped. */
18 put(r: number, c: number, s: string, fg: number): void {
19 if (r < 0 || r >= this.rows) return
20 let x = c
21 for (const ch of s) {
22 if (x >= 0 && x < this.cols) this.cells.set([ch.codePointAt(0)!, fg, DEFAULT], (r * this.cols + x) * 3)
23 x++
24 }
25 }
26
27 line(r: number): string {
28 let s = ''
29 for (let c = 0; c < this.cols; c++) s += String.fromCodePoint(this.cells[(r * this.cols + c) * 3] ?? 0x20)
30 return s
31 }
32
33 encode(): string {
34 return new Uint8Array(this.cells.buffer).toBase64()
35 }
36}
37hooks/dial.ts 123 lines1// The dial standard library: the parts every gauge in redline is built from. A dial is a pivot,
2// a radius, and the arc its scale sweeps clockwise from `from`; callers work in `t`, 0 at the
3// start of the sweep and 1 at its end, and supply the colors. The braille grid is in `dots.ts`.
4
5import { Dots } from './dots'
6
7/** A dial's scale: where the pivot sits and the arc it sweeps. */
8export type Dial = { cx: number; cy: number; r: number; from: number; sweep: number }
9
10/** A shallow dial whose pivot sits at the bottom edge of a `cols` × `rows` panel. */
11export function shallow(cols: number, rows: number, from: number, sweep: number): Dial {
12 const cx = cols - 0.5 // the panel's middle, between two dot columns, so the dial rounds the same both sides
13 const cy = rows * 4 - 2
14 const reach = Math.max(Math.abs(Math.cos(from)), Math.abs(Math.cos(from - sweep)))
15 const r = Math.floor(Math.min((cols - 2) / reach, cy - 5))
16 return { cx, cy, r, from, sweep }
17}
18
19export const angleAt = (d: Dial, t: number) => d.from - t * d.sweep
20
21/** The point `r` from the pivot at angle `a`. */
22export const polar = (d: Dial, a: number, r: number): [number, number] => [d.cx + r * Math.cos(a), d.cy - r * Math.sin(a)]
23
24/** The point at `t` on a circle of radius `r`. */
25export const at = (d: Dial, t: number, r = d.r): [number, number] => polar(d, angleAt(d, t), r)
26
27export type ArcSpec = {
28 colorAt: (t: number) => number
29 /** Extra dots drawn outward at `t`, for a painted zone. */
30 widthAt?: (t: number) => number
31 radius?: number
32 rank?: number
33}
34
35/** The scale arc, in fine steps so it reads as a line. */
36export function arc(dots: Dots, d: Dial, spec: ArcSpec): void {
37 const r = spec.radius ?? d.r
38 const rank = spec.rank ?? 1
39 const widthAt = spec.widthAt ?? (() => 0)
40 const n = Math.ceil(d.sweep * r * 1.6)
41 for (let i = 0; i <= n; i++) {
42 const t = i / n
43 const color = spec.colorAt(t)
44 const [x, y] = at(d, t, r)
45 dots.dot(x, y, color, rank)
46 for (let k = 1, w = widthAt(t); k <= w; k++) {
47 const [wx, wy] = at(d, t, r + k)
48 dots.dot(wx, wy, color, rank)
49 }
50 }
51}
52
53export type TickSpec = {
54 count: number
55 colorAt: (t: number) => number
56 length?: number
57 majorLength?: number
58 /** Every `majorEvery`-th tick is a major one, one rank above the rest; 0 (the default) makes none. */
59 majorEvery?: number
60 rank?: number
61 /** How far inside the arc the ticks start. */
62 inner?: number
63}
64
65/** The ticks along the scale. */
66export function ticks(dots: Dots, d: Dial, spec: TickSpec): void {
67 const length = spec.length ?? 2
68 const majorLength = spec.majorLength ?? length + 1
69 const rank = spec.rank ?? 2
70 const inner = spec.inner ?? 1
71 for (let k = 0; k <= spec.count; k++) {
72 const t = k / spec.count
73 const major = spec.majorEvery ? k % spec.majorEvery === 0 : false
74 const [x0, y0] = at(d, t, d.r - inner)
75 const [x1, y1] = at(d, t, d.r - (major ? majorLength : length))
76 dots.line(x0, y0, x1, y1, spec.colorAt(t), major ? rank + 1 : rank)
77 }
78}
79
80export type NeedleSpec = {
81 t: number
82 color: number
83 /** The tip stops this far inside the arc. */
84 inner?: number
85 /** How far past the pivot the tail runs. */
86 tail?: number
87 /** The needle's width at the pivot; it tapers to the tip. */
88 width?: number
89 hub?: { color: number; ringRadius?: number; ringColor?: number }
90}
91
92/** The needle at `t`, with its tail and hub. */
93export function needle(dots: Dots, d: Dial, spec: NeedleSpec): void {
94 const a = angleAt(d, spec.t)
95 const [tipX, tipY] = polar(d, a, d.r - (spec.inner ?? 4))
96 const [tailX, tailY] = polar(d, a + Math.PI, spec.tail ?? 2)
97 dots.needle(d.cx, d.cy, tipX, tipY, spec.width ?? 1.2, spec.color, 3)
98 dots.line(tailX, tailY, tipX, tipY, spec.color, 3)
99 if (spec.hub) {
100 if (spec.hub.ringRadius) {
101 for (let i = 0; i < 18; i++) {
102 const ha = (i / 18) * 2 * Math.PI
103 dots.dot(d.cx + spec.hub.ringRadius * Math.cos(ha), d.cy - spec.hub.ringRadius * Math.sin(ha), spec.hub.ringColor ?? spec.hub.color, 4)
104 }
105 }
106 for (const [dx, dy] of [[0, 0], [1, 0], [-1, 0], [0, 1], [0, -1]] as const) dots.dot(d.cx + dx, d.cy + dy, spec.hub.color, 5)
107 }
108}
109
110export type DialSpec = {
111 dial: Dial
112 arc?: ArcSpec
113 ticks?: TickSpec
114 needle?: NeedleSpec
115}
116
117/** Draws a dial from its parts, the needle last. */
118export function dial(dots: Dots, spec: DialSpec): void {
119 if (spec.arc) arc(dots, spec.dial, spec.arc)
120 if (spec.ticks) ticks(dots, spec.dial, spec.ticks)
121 if (spec.needle) needle(dots, spec.dial, spec.needle)
122}
123hooks/dots.ts 105 lines1// The braille dot grid the gauges draw into: each terminal cell is a 2 × 4 grid of dots, so the
2// arcs stay round and the needles thin. A cell takes the color of the highest-ranked dot drawn in
3// it; text cells sit above every dot.
4
5import { Canvas } from './canvas'
6
7const BIT = [[0x01, 0x08], [0x02, 0x10], [0x04, 0x20], [0x40, 0x80]] as const // braille dot bits by [row][column]
8
9export class Dots {
10 readonly bits: Uint8Array
11 readonly color: Int32Array
12 readonly rank: Int8Array
13 private readonly chars = new Map<number, string>()
14
15 constructor(readonly cols: number, readonly rows: number) {
16 this.bits = new Uint8Array(cols * rows)
17 this.color = new Int32Array(cols * rows)
18 this.rank = new Int8Array(cols * rows).fill(-1)
19 }
20
21 dot(x: number, y: number, color: number, rank: number): void {
22 const [px, py] = [Math.round(x), Math.round(y)]
23 const [c, r] = [Math.floor(px / 2), Math.floor(py / 4)]
24 if (px < 0 || py < 0 || c >= this.cols || r >= this.rows) return
25 const i = r * this.cols + c
26 this.bits[i]! |= BIT[py % 4]![px % 2]!
27 if (rank >= this.rank[i]!) {
28 this.rank[i] = rank
29 this.color[i] = color
30 }
31 }
32
33 line(x0: number, y0: number, x1: number, y1: number, color: number, rank: number): void {
34 const n = Math.ceil(Math.max(Math.abs(x1 - x0), Math.abs(y1 - y0)) * 1.5) || 1
35 for (let i = 0; i <= n; i++) this.dot(x0 + ((x1 - x0) * i) / n, y0 + ((y1 - y0) * i) / n, color, rank)
36 }
37
38 /** A needle from the hub to the tip, `wBase` dots wide at the hub and a point at the tip. */
39 needle(hubX: number, hubY: number, tipX: number, tipY: number, wBase: number, color: number, rank: number): void {
40 const dx = tipX - hubX
41 const dy = tipY - hubY
42 const len = Math.hypot(dx, dy) || 1
43 const px = -dy / len
44 const py = dx / len
45 const n = Math.ceil(len * 2)
46 for (let i = 0; i <= n; i++) {
47 const t = i / n
48 const w = wBase * (1 - t)
49 const x = hubX + dx * t
50 const y = hubY + dy * t
51 for (let o = -w; o <= w; o += 0.5) this.dot(x + px * o, y + py * o, color, rank)
52 }
53 }
54
55 /** Writes `s` as text cells from (r, c); characters off the grid are dropped. */
56 text(r: number, c: number, s: string, color: number): void {
57 if (r < 0 || r >= this.rows) return
58 let x = c
59 for (const ch of s) {
60 if (x >= 0 && x < this.cols) {
61 const i = r * this.cols + x
62 this.bits[i] = 0
63 this.rank[i] = 99
64 this.color[i] = color
65 this.chars.set(i, ch)
66 }
67 x++
68 }
69 }
70
71 /** Pastes `other` at (r, c): dots merge by rank, text stays text. */
72 blit(other: Dots, r: number, c: number): void {
73 for (let i = 0; i < other.bits.length; i++) {
74 const or = Math.floor(i / other.cols) + r
75 const oc = (i % other.cols) + c
76 if (or < 0 || or >= this.rows || oc < 0 || oc >= this.cols) continue
77 const to = or * this.cols + oc
78 const ch = other.chars.get(i)
79 if (ch !== undefined) {
80 this.bits[to] = 0
81 this.rank[to] = 99
82 this.color[to] = other.color[i]!
83 this.chars.set(to, ch)
84 continue
85 }
86 if (!other.bits[i]) continue
87 this.bits[to]! |= other.bits[i]!
88 if (other.rank[i]! >= this.rank[to]!) {
89 this.rank[to] = other.rank[i]!
90 this.color[to] = other.color[i]!
91 }
92 }
93 }
94
95 toCanvas(): Canvas {
96 const cv = new Canvas(this.rows, this.cols)
97 for (let i = 0; i < this.bits.length; i++) {
98 const ch = this.chars.get(i)
99 if (ch !== undefined) cv.put(Math.floor(i / this.cols), i % this.cols, ch, this.color[i]!)
100 else if (this.bits[i]) cv.put(Math.floor(i / this.cols), i % this.cols, String.fromCharCode(0x2800 + this.bits[i]!), this.color[i]!)
101 }
102 return cv
103 }
104}
105types/index.d.ts 31 lines1/** One rate-limit window's last reading: how much is used, and when it refills. */
2export type RedlineTank = { percent: number; resetsAt: number | null }
3
4/** The figures behind the dials; each null until the engine has a reading. */
5export type RedlineUsage = {
6 fiveHour: RedlineTank | null
7 sevenDay: RedlineTank | null
8 /** This session's context fill, percent used; null until a response reports one. */
9 context: number | null
10}
11
12/** What one session running redline writes to the shared store, so the others can list it. */
13export type RedlineBeat = {
14 /** The session's id, as `claude agents --json` lists it. */
15 id: string
16 cwd: string
17 state: 'working' | 'waiting' | 'idle'
18 /** What it waits for while `waiting`: `approve Bash`, `a question`. */
19 waitingFor: string
20 /** When it entered this state. */
21 since: number
22 /** When this beat was written; one older than a few minutes is a session that has gone. */
23 at: number
24 /** Turns completed this session: an idle session with none has not started yet. */
25 turns: number
26 context: number | null
27 usd: number | null
28 model: string
29 isShifted: boolean
30}
31