Status band above the Claude Code prompt: prompt-cache countdown, today's cost and plan limits, open PRs, queued Actions runs and the coord-bus seat

A status band above the Claude Code prompt, drawn as one row when it fits and stacked when it does not:
████████████░░░░░░░░ 52:10 until prompt cache expires (1h detected) │ $4.12 today · 5h 63% 7d 21% │ ⎇ 2 open PRs │ ▶ 1 queued · 2 running │ ● worker-2 · #groundwork · 3 unread
| Segment | Shows |
|---|---|
| Cache countdown | Time left before the prompt cache expires (when the next prompt costs more). Green, yellow, then red as it drains; a red "Cache expired" line afterwards. The TTL (5m or 1h) is detected from the cache's behaviour and labelled assumed, detected or set. |
| Cost and limits | Today's cost across all your sessions, and your plan-limit windows (5h, 7d) as percentages, coloured by how full they are. |
| Open PRs | Open PRs in the current repo (gh pr list), with drafts counted. |
| Actions runs | GitHub Actions runs queued (queued, waiting, pending) and running in the current repo, from the latest 100 (gh run list). |
| Coord bus | This session's seat on an agent-coord bus: id, rooms, unread count. Hidden when there is no bus. |
When the terminal is narrow the segments shorten ($4.12 · 7d 22%, ⎇ 2 PRs), then stack.
/plugin marketplace add davidbalzan/status-band
/plugin install status-band@status-band
From a local clone, use its path instead of davidbalzan/status-band.
Set under /plugin configure status-band@status-band.
| Option | Default | |
|---|---|---|
ttl | auto | auto detects the cache lifetime; 5m or 1h forces it. |
showUsage | on | Cost and plan limits. |
showPrs | on | Open PRs. Needs the gh CLI, signed in. |
showRuns | on | Queued and running Actions runs. Needs the gh CLI, signed in. |
showBus | on | Coord-bus row. |
whoami tool (agent-coord-mcp 0.26.46 and later; older servers fall back to status and list_rooms). With no bus on the machine it backs off to every 10 minutes.gh pr list call every 5 minutes, sooner after this session runs gh pr or git push. A failing call backs off.gh run list call every minute, sooner after this session runs gh pr or git push. A failing call backs off.assumed.claude plugin validate .
claude plugin test .
Logic lives in small modules under hooks/ (cache, usage, prs, bus, pieces for layout, schedule), with register.tsx wiring them to the engine. Tests are beside them.
hooks/register.tsx 404 lines1import type { Register, Timer } from 'claude-code'
2
3import { busSegment, findJoin, parseJsonBlock, type Bus, type WhoamiView } from './bus'
4import { cacheSegment, describeCheck, isTtl, judgeTtl, TTL_MS, type CacheState, type Ttl } from './cache'
5import { layoutRows } from './pieces'
6import { parsePrs, prSegment, type PrCount } from './prs'
7import { parseRuns, runSegment, type RunCount } from './runs'
8import { backoff } from './schedule'
9import { costDelta, localDay, usageSegment, type PlanLimit } from './usage'
10
11const STORE_TTL_KEY = 'detected-ttl'
12const STORE_COST_PREFIX = 'usage-cost:'
13const COST_KEEP_DAYS = 14
14
15// One display tick (while a countdown is on screen) and one slow poll; each source below keeps its own due time.
16const POLL_MS = 15_000
17const BUS_MS = 15_000
18const BUS_IDLE_MS = 60_000
19const USAGE_MS = 30_000
20const OTHER_SESSIONS_MS = 120_000
21const PR_REFRESH_MS = 5 * 60_000
22const PR_SETTLE_MS = 10_000
23const RUNS_REFRESH_MS = 60_000
24const BACKOFF_MAX_MS = 10 * 60_000
25
26export const register: Register = (on, options) => {
27 const configured = isTtl(options.ttl) ? options.ttl : null
28 const showBus = options.showBus !== false
29 const showPrs = options.showPrs !== false
30 const showRuns = options.showRuns !== false
31 const showUsage = options.showUsage !== false
32
33 // Cache: every API response refreshes it, so the clock restarts at each one.
34 let lastResponseAt: number | null = null
35 let previousTokens = 0
36 let gapBeforeTurn: number | null = null
37 let detected: Ttl | null = null
38 let isDetectedLoaded = false
39 let lastCheck: string | null = null
40
41 // Redraw: the 1s tick only draws while a countdown is showing; the poll draws only when a value changed.
42 let tick: Timer | undefined
43 let poll: Timer | undefined
44 let isTicking = false
45 let hasPolledOnce = false
46
47 // Bus
48 let bus: Bus | null = null
49 let isBusChecked = false
50 let hasWhoami: boolean | null = null
51 let busDueAt = 0
52 let busDelayMs = BUS_MS
53
54 // Usage: today's cost is every session's spend since midnight, one store key per session so concurrent
55 // sessions never overwrite each other. Spend before the mod loaded in a session is not counted.
56 let todayUsd: number | null = null
57 let limits: readonly PlanLimit[] = []
58 let usageDueAt = 0
59 let lastSessionUsd: number | null = null
60 let ownDay = ''
61 let ownUsd = 0
62 let othersUsd = 0
63 let othersDay = ''
64 let othersDueAt = 0
65 let isUsagePruned = false
66
67 // Open PRs
68 let prs: PrCount | null = null
69 let prsDueAt = 0
70 let prsDelayMs = PR_REFRESH_MS
71
72 // GitHub Actions runs waiting for or occupying a runner
73 let runs: RunCount | null = null
74 let runsDueAt = 0
75 let runsDelayMs = RUNS_REFRESH_MS
76
77 on('classic.SessionStart', async ($, e, next) => {
78 if (e.seconds_since_last_response !== undefined) {
79 lastResponseAt = (await $.clock.now()) - e.seconds_since_last_response * 1000
80 previousTokens = e.context_tokens ?? 0
81 }
82
83 return next(e)
84 })
85
86 on('session.end', ($, e, next) => {
87 tick?.cancel()
88 tick = undefined
89 poll?.cancel()
90 poll = undefined
91 bus = null
92
93 return next(e)
94 })
95
96 on('classic.PostModelSwitch', async ($, e, next) => {
97 detected = e.cache_ttl
98 await $.store.set(STORE_TTL_KEY, detected)
99
100 return next(e)
101 })
102
103 // `e.agentId` on a tool.call is the subagent loop's id, not the tool's own `agentId` argument, so the
104 // identity is never read off the event: a join only says to look again, soon.
105 on('tool.call', { tool: 'mcp__agent-coord__join' }, async ($, e, next) => {
106 const ran = await next(e)
107
108 if (ran.deny === undefined && ran.isError !== true) {
109 bus = null
110 isBusChecked = false
111 busDueAt = 0
112 busDelayMs = BUS_MS
113 }
114
115 return ran
116 })
117
118 on('tool.call', { tool: 'mcp__agent-coord__unregister' }, ($, e, next) => {
119 bus = null
120
121 return next(e)
122 })
123
124 // A PR changes when this agent pushes or runs gh, so that is when the count is worth refetching early.
125 on('tool.call', { tool: 'Bash' }, async ($, e, next) => {
126 if (/\bgh\s+pr\b|\bgit\s+push\b/.test(e.command)) {
127 const soon = (await $.clock.now()) + PR_SETTLE_MS
128
129 prsDueAt = Math.min(prsDueAt, soon)
130 runsDueAt = Math.min(runsDueAt, soon)
131 }
132
133 return next(e)
134 })
135
136 on('prompt.submit', async ($, e, next) => {
137 gapBeforeTurn = lastResponseAt === null ? null : (await $.clock.now()) - lastResponseAt
138
139 return next(e)
140 })
141
142 on('turn.step', async function* ($, e, next) {
143 for await (const chunk of next(e)) {
144 if (chunk.kind === 'stop' && chunk.usage) {
145 const { usage } = chunk
146
147 if (gapBeforeTurn !== null) {
148 const verdict = judgeTtl(gapBeforeTurn, previousTokens, usage)
149 lastCheck = describeCheck(gapBeforeTurn, previousTokens, usage)
150 gapBeforeTurn = null
151
152 if (verdict && verdict !== detected) {
153 detected = verdict
154 await $.store.set(STORE_TTL_KEY, verdict)
155 }
156 }
157
158 previousTokens = usage.input_tokens + usage.cache_read_input_tokens + usage.cache_creation_input_tokens
159 lastResponseAt = await $.clock.now()
160 $.ui.invalidate('ui.render')
161 }
162
163 yield chunk
164 }
165 })
166
167 on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
168 if (e.props.hasSurvey) {
169 return next(e)
170 }
171
172 // Drawing must not depend on the timers, so a failure to start them is not a failure to draw.
173 try {
174 tick ??= $.clock.every(1000, () => {
175 if (isTicking) {
176 $.ui.invalidate('ui.render')
177 }
178 })
179
180 const runPoll = async () => {
181 const now = await $.clock.now()
182 let isChanged = false
183
184 if (showBus && now >= busDueAt) {
185 const seen = JSON.stringify(bus)
186 let outcome: 'ok' | 'none' | 'failed' = 'failed'
187
188 // `whoami` answers in one read-only call; a server without it falls back to the id in this session's
189 // own `join` call (read once from the transcript) plus `status` and `list_rooms`.
190 if (hasWhoami !== false) {
191 const call = await $.mcp.call('agent-coord', 'whoami').catch(() => null)
192 const me = call && parseJsonBlock<WhoamiView>(call.content, call.isError)
193
194 if (me) {
195 hasWhoami = true
196 bus = me.bound && me.agentId ? { agentId: me.agentId, rooms: me.rooms ?? [], unread: me.inboxUnread ?? null } : null
197 outcome = bus ? 'ok' : 'none'
198 } else if (call?.isError) {
199 hasWhoami = false
200 }
201 }
202
203 if (hasWhoami === false) {
204 if (!bus && !isBusChecked) {
205 isBusChecked = true
206 const joined = findJoin(await $.session.messages({ as: 'api' }))
207 bus = joined ? { agentId: joined.agentId, rooms: [], unread: null } : null
208 }
209
210 const seat = bus
211
212 if (!seat) {
213 outcome = 'none'
214 } else {
215 const [statusCall, roomsCall] = await Promise.all([
216 $.mcp.call('agent-coord', 'status', { agentId: seat.agentId }).catch(() => null),
217 $.mcp.call('agent-coord', 'list_rooms').catch(() => null),
218 ])
219 const status = statusCall && parseJsonBlock<{ registered?: boolean; inboxUnread?: number }>(statusCall.content, statusCall.isError)
220 const listing = roomsCall && parseJsonBlock<{ rooms?: { room: string; members?: string[] }[] }>(roomsCall.content, roomsCall.isError)
221
222 if (status?.registered === false) {
223 bus = null
224 outcome = 'none'
225 } else if (status || listing) {
226 bus = {
227 ...seat,
228 unread: status?.inboxUnread ?? seat.unread,
229 rooms: listing?.rooms?.filter(r => r.members?.includes(seat.agentId)).map(r => r.room) ?? seat.rooms,
230 }
231 outcome = 'ok'
232 }
233 }
234 }
235
236 // No bus on this machine backs off instead of asking every 15 seconds forever; a `join` resets it.
237 busDelayMs = outcome === 'ok' ? BUS_MS : outcome === 'none' ? BUS_IDLE_MS : backoff(busDelayMs, BUS_IDLE_MS, BACKOFF_MAX_MS)
238 busDueAt = now + busDelayMs
239 isChanged ||= JSON.stringify(bus) !== seen
240 }
241
242 if (showUsage && now >= usageDueAt) {
243 usageDueAt = now + USAGE_MS
244 const usage = await $.session.usage().catch(() => null)
245
246 if (usage) {
247 const seen = JSON.stringify([todayUsd, limits])
248 const day = localDay(now)
249 const keyPrefix = `${STORE_COST_PREFIX}${day}:`
250 const sessionUsd = usage.cost?.usd
251 limits = usage.rateLimits
252
253 if (sessionUsd === undefined) {
254 todayUsd = null
255 } else {
256 const ownKey = `${keyPrefix}${await $.session.id()}`
257 const delta = lastSessionUsd === null ? 0 : costDelta(lastSessionUsd, sessionUsd)
258 lastSessionUsd = sessionUsd
259 ownUsd = ownDay === day ? ownUsd + delta : delta
260 ownDay = day
261
262 if (delta > 0) {
263 await $.store.set(ownKey, ownUsd)
264 }
265
266 // The other sessions' spend changes slowly, so it is re-read every couple of minutes, not every poll.
267 if (othersDay !== day || now >= othersDueAt) {
268 othersDay = day
269 othersDueAt = now + OTHER_SESSIONS_MS
270 const keys = await $.store.keys()
271
272 if (!isUsagePruned) {
273 isUsagePruned = true
274 const cutoff = localDay(now - COST_KEEP_DAYS * 24 * 60 * 60_000)
275 const dateAt = STORE_COST_PREFIX.length
276
277 await Promise.all(
278 keys
279 .filter(key => key.startsWith(STORE_COST_PREFIX) && key.slice(dateAt, dateAt + 10) < cutoff)
280 .map(key => $.store.delete(key)),
281 )
282 }
283
284 const amounts = await Promise.all(
285 keys.filter(key => key.startsWith(keyPrefix) && key !== ownKey).map(key => $.store.get(key)),
286 )
287 othersUsd = amounts.reduce<number>((sum, value) => sum + (typeof value === 'number' ? value : 0), 0)
288 }
289
290 todayUsd = othersUsd + ownUsd
291 }
292
293 isChanged ||= seen !== JSON.stringify([todayUsd, limits])
294 }
295 }
296
297 if (showPrs && now >= prsDueAt) {
298 const repo = await $.session.repo()
299
300 if (!repo?.remote) {
301 isChanged ||= prs !== null
302 prs = null
303 prsDelayMs = PR_REFRESH_MS
304 } else {
305 const ran = await $.process
306 .run(['gh', 'pr', 'list', '--state', 'open', '--limit', '100', '--json', 'number,isDraft'], {
307 cwd: repo.root,
308 timeoutMs: 15_000,
309 })
310 .catch(() => null)
311 const counted = ran?.exitCode === 0 ? parsePrs(ran.stdout) : null
312
313 prsDelayMs = counted ? PR_REFRESH_MS : backoff(prsDelayMs, PR_REFRESH_MS, BACKOFF_MAX_MS)
314 isChanged ||= counted !== null && (counted.open !== prs?.open || counted.drafts !== prs?.drafts)
315 prs = counted ?? prs
316 }
317
318 prsDueAt = now + prsDelayMs
319 }
320
321 if (showRuns && now >= runsDueAt) {
322 const repo = await $.session.repo()
323
324 if (!repo?.remote) {
325 isChanged ||= runs !== null
326 runs = null
327 runsDelayMs = RUNS_REFRESH_MS
328 } else {
329 const ran = await $.process
330 .run(['gh', 'run', 'list', '--limit', '100', '--json', 'status'], {
331 cwd: repo.root,
332 timeoutMs: 15_000,
333 })
334 .catch(() => null)
335 const counted = ran?.exitCode === 0 ? parseRuns(ran.stdout) : null
336
337 runsDelayMs = counted ? RUNS_REFRESH_MS : backoff(runsDelayMs, RUNS_REFRESH_MS, BACKOFF_MAX_MS)
338 isChanged ||= counted !== null && (counted.queued !== runs?.queued || counted.running !== runs?.running)
339 runs = counted ?? runs
340 }
341
342 runsDueAt = now + runsDelayMs
343 }
344
345 if (isChanged) {
346 $.ui.invalidate('ui.render')
347 }
348 }
349
350 poll ??= $.clock.every(POLL_MS, runPoll)
351
352 if (!hasPolledOnce) {
353 hasPolledOnce = true
354 $.clock.after(500, runPoll)
355 }
356 } catch {
357 // see above
358 }
359
360 if (!isDetectedLoaded) {
361 isDetectedLoaded = true
362 const stored = await $.store.get(STORE_TTL_KEY).catch(() => undefined)
363 detected ??= isTtl(stored) ? stored : null
364 }
365
366 const { Box, Text } = $.ui.resolve(e)
367 const ttl = configured ?? detected ?? '5m'
368 const remainingMs = lastResponseAt === null ? 0 : TTL_MS[ttl] - ((await $.clock.now()) - lastResponseAt)
369 const cacheState: CacheState =
370 lastResponseAt === null
371 ? { kind: 'waiting' }
372 : e.props.isWorking
373 ? { kind: 'working' }
374 : remainingMs <= 0
375 ? { kind: 'expired' }
376 : { kind: 'ticking', remainingMs, ttl, source: configured ? 'set' : detected ? 'detected' : 'assumed', lastCheck }
377 isTicking = cacheState.kind === 'ticking'
378
379 const usage = showUsage ? usageSegment(todayUsd, limits) : null
380 const width = Math.max(20, (e.props.bodyColumns || e.viewport?.columns || 100) - 2)
381 const rows = layoutRows(width, [
382 cacheSegment(cacheState),
383 ...(usage ? [usage] : []),
384 ...(showPrs && prs ? [prSegment(prs)] : []),
385 ...(showRuns && runs ? [runSegment(runs)] : []),
386 ...(showBus && bus ? [busSegment(bus)] : []),
387 ])
388
389 return (
390 <Box flexDirection="column">
391 {rows.map(row => (
392 <Box>
393 {row.map(piece => (
394 <Text color={piece.color} dimColor={piece.dim} bold={piece.bold}>
395 {piece.text}
396 </Text>
397 ))}
398 </Box>
399 ))}
400 </Box>
401 )
402 })
403}
404hooks/bus.ts 78 lines1import type { Segment } from './pieces'
2
3export type Bus = {
4 agentId: string
5 rooms: readonly string[]
6 unread: number | null
7}
8
9export type WhoamiView = { bound?: boolean; agentId?: string; rooms?: string[]; inboxUnread?: number }
10
11export type McpBlock = { type: string; text?: string }
12
13export const parseJsonBlock = <T,>(content: readonly McpBlock[], isError: boolean) => {
14 const block = content[0]
15
16 return isError || block?.type !== 'text' || !block.text ? null : (JSON.parse(block.text) as T)
17}
18
19const roleLabel = (role: unknown) => {
20 if (typeof role === 'string') {
21 return role
22 }
23
24 if (role && typeof role === 'object') {
25 const { displayName, roleId } = role as { displayName?: unknown; roleId?: unknown }
26
27 return typeof displayName === 'string' ? displayName : typeof roleId === 'string' ? roleId : undefined
28 }
29
30 return undefined
31}
32
33type JoinCall = { agentId: string; role?: string }
34
35/** The seat this transcript last joined the bus as, or null if it never did or has since unregistered. */
36export const findJoin = (messages: readonly { content?: unknown }[]): JoinCall | null => {
37 let seat: JoinCall | null = null
38
39 for (const message of messages) {
40 if (!Array.isArray(message.content)) {
41 continue
42 }
43
44 for (const block of message.content as { type?: string; name?: string; input?: Record<string, unknown> }[]) {
45 if (block?.type !== 'tool_use') {
46 continue
47 }
48
49 if (block.name === 'mcp__agent-coord__join' && typeof block.input?.agentId === 'string') {
50 seat = { agentId: block.input.agentId, role: roleLabel(block.input.role) }
51 } else if (block.name === 'mcp__agent-coord__unregister') {
52 seat = null
53 }
54 }
55 }
56
57 return seat
58}
59
60export const busLine = (bus: Bus) =>
61 [
62 bus.agentId,
63 bus.rooms.map(room => `#${room}`).join(' ') || 'no room',
64 bus.unread === null ? null : bus.unread === 0 ? 'inbox clear' : `${bus.unread} unread`,
65 ]
66 .filter(Boolean)
67 .join(' · ')
68
69export const busSegment = (bus: Bus): Segment => {
70 const rooms = bus.rooms.map(room => `#${room}`).join(' ')
71 const unread = bus.unread ? ` ✉${bus.unread}` : ''
72
73 return {
74 long: [{ text: '●', color: 'success' }, { text: ` bus: ${busLine(bus)}`, dim: true }],
75 short: [{ text: '●', color: 'success' }, { text: ` ${bus.agentId}${rooms ? ` ${rooms}` : ''}${unread}`, dim: true }],
76 }
77}
78hooks/cache.ts 104 lines1import type { Piece, Segment } from './pieces'
2
3export const BAR_CELLS = 20
4export const SHORT_BAR_CELLS = 10
5export const TTL_MS = { '5m': 5 * 60_000, '1h': 60 * 60_000 } as const
6const MARGIN_MS = 30_000
7
8export type Ttl = keyof typeof TTL_MS
9
10export type RequestUsage = {
11 input_tokens: number
12 cache_read_input_tokens: number
13 cache_creation_input_tokens: number
14}
15
16export const isTtl = (value: unknown): value is Ttl => value === '5m' || value === '1h'
17
18export const formatRemaining = (ms: number) => {
19 const total = Math.max(0, Math.ceil(ms / 1000))
20 const minutes = Math.floor(total / 60)
21 const seconds = total % 60
22
23 return `${minutes}:${String(seconds).padStart(2, '0')}`
24}
25
26export const barColor = (fraction: number) => (fraction > 0.5 ? 'success' : fraction > 0.2 ? 'warning' : 'error')
27
28/**
29 * Reads the TTL off the first request after an idle gap. If the previous context was still served from
30 * cache after more than 5 minutes the cache lives an hour; if a good part of it was written afresh within
31 * the hour it lives 5 minutes (a shared system-prompt prefix can stay cached either way, so the rebuilt
32 * share is what counts, not the cached one). Anything else (short gap, nothing to compare, an hour or
33 * more, a mixed result) says nothing.
34 */
35export const judgeTtl = (gapMs: number, previousTokens: number, usage: RequestUsage): Ttl | null => {
36 if (previousTokens <= 0 || gapMs <= TTL_MS['5m'] + MARGIN_MS) {
37 return null
38 }
39
40 if (usage.cache_read_input_tokens / previousTokens >= 0.8) {
41 return '1h'
42 }
43
44 const isRebuilt = usage.cache_creation_input_tokens / previousTokens >= 0.3
45
46 return isRebuilt && gapMs < TTL_MS['1h'] - MARGIN_MS ? '5m' : null
47}
48
49export const describeCheck = (gapMs: number, previousTokens: number, usage: RequestUsage) => {
50 const percent = (tokens: number) => (previousTokens > 0 ? Math.round((tokens / previousTokens) * 100) : 0)
51
52 return `last check: idle ${formatRemaining(gapMs)}, ${percent(usage.cache_read_input_tokens)}% read, ${percent(usage.cache_creation_input_tokens)}% written`
53}
54
55const barPieces = (fraction: number, cells: number, color: string): Piece[] => {
56 const filled = Math.max(1, Math.ceil(fraction * cells))
57
58 return [{ text: '█'.repeat(filled), color }, { text: '░'.repeat(cells - filled), dim: true }]
59}
60
61export type CacheState =
62 | { kind: 'waiting' }
63 | { kind: 'working' }
64 | { kind: 'expired' }
65 | { kind: 'ticking'; remainingMs: number; ttl: Ttl; source: string; lastCheck: string | null }
66
67export const cacheSegment = (state: CacheState): Segment => {
68 switch (state.kind) {
69 case 'waiting':
70 return {
71 long: [{ text: 'Cache timer: starts after the next response', dim: true }],
72 short: [{ text: 'cache: waiting', dim: true }],
73 }
74 case 'working':
75 return {
76 long: [{ text: 'Cache: refreshing while the model works', dim: true }],
77 short: [{ text: 'cache: refreshing', dim: true }],
78 }
79 case 'expired':
80 return {
81 long: [
82 { text: '░'.repeat(BAR_CELLS), color: 'error' },
83 { text: ' Cache expired: next prompt re-caches the context at a higher cost', color: 'error', bold: true },
84 ],
85 short: [{ text: 'Cache expired: next prompt costs more', color: 'error', bold: true }],
86 }
87 case 'ticking': {
88 const fraction = state.remainingMs / TTL_MS[state.ttl]
89 const color = barColor(fraction)
90 const time: Piece = { text: ` ${formatRemaining(state.remainingMs)}`, color }
91 const check = state.lastCheck && state.source === 'assumed' ? `; ${state.lastCheck}` : ''
92
93 return {
94 long: [
95 ...barPieces(fraction, BAR_CELLS, color),
96 time,
97 { text: ` until prompt cache expires (${state.ttl} ${state.source}${check})`, dim: true },
98 ],
99 short: [...barPieces(fraction, SHORT_BAR_CELLS, color), time, { text: ' cache', dim: true }],
100 }
101 }
102 }
103}
104hooks/pieces.ts 47 lines1export type Piece = { text: string; color?: string; dim?: boolean; bold?: boolean }
2
3/** One status item in a long and a short form; the layout picks the form that fits. */
4export type Segment = { long: readonly Piece[]; short: readonly Piece[] }
5
6type Form = keyof Segment
7
8const SEPARATOR: Piece = { text: ' │ ', dim: true }
9
10export const widthOf = (pieces: readonly Piece[]) => pieces.reduce((total, piece) => total + [...piece.text].length, 0)
11
12const joinRow = (pieces: readonly (readonly Piece[])[]) =>
13 pieces.flatMap((row, index) => (index === 0 ? [...row] : [SEPARATOR, ...row]))
14
15/**
16 * Fits the segments (cache first, then the optional ones) into as few rows as the width allows,
17 * shortening the extras before the cache. Falls back to one row each, shortened only if it must.
18 */
19export const layoutRows = (width: number, segments: readonly Segment[]): Piece[][] => {
20 const fits = (rows: readonly (readonly Piece[])[]) => rows.every(row => widthOf(row) <= width)
21 const oneRow = (forms: readonly Form[]) => [joinRow(segments.map((segment, i) => segment[forms[i] ?? 'short']))]
22 const [cache, ...extras] = segments
23 const all = (form: Form) => segments.map(() => form)
24 const plans: (() => Piece[][])[] = [
25 () => oneRow(all('long')),
26 () => oneRow(segments.map((_, i) => (i === 0 ? 'long' : 'short'))),
27 () => oneRow(all('short')),
28 ]
29
30 if (cache && extras.length > 0) {
31 plans.push(
32 () => [[...cache.long], joinRow(extras.map(segment => segment.long))],
33 () => [[...cache.long], joinRow(extras.map(segment => segment.short))],
34 )
35 }
36
37 for (const plan of plans) {
38 const rows = plan()
39
40 if (fits(rows)) {
41 return rows
42 }
43 }
44
45 return segments.map(segment => (widthOf(segment.long) <= width ? [...segment.long] : [...segment.short]))
46}
47hooks/prs.ts 28 lines1import type { Segment } from './pieces'
2
3export type PrCount = { open: number; drafts: number }
4
5export const parsePrs = (text: string): PrCount | null => {
6 try {
7 const prs: unknown = JSON.parse(text)
8
9 return Array.isArray(prs)
10 ? { open: prs.length, drafts: prs.filter(pr => pr?.isDraft === true).length }
11 : null
12 } catch {
13 return null
14 }
15}
16
17export const prLine = ({ open, drafts }: PrCount) =>
18 `${open} open PR${open === 1 ? '' : 's'}${drafts > 0 ? ` (${drafts} draft)` : ''}`
19
20export const prSegment = (prs: PrCount): Segment => {
21 const color = prs.open > 0 ? 'warning' : 'success'
22
23 return {
24 long: [{ text: '⎇', color }, { text: ` ${prLine(prs)}`, dim: true }],
25 short: [{ text: '⎇', color }, { text: ` ${prs.open} PR${prs.open === 1 ? '' : 's'}`, dim: true }],
26 }
27}
28hooks/runs.ts 37 lines1import type { Segment } from './pieces'
2
3export type RunCount = { queued: number; running: number }
4
5const QUEUED = new Set(['queued', 'waiting', 'pending', 'requested'])
6
7export const parseRuns = (text: string): RunCount | null => {
8 try {
9 const runs: unknown = JSON.parse(text)
10
11 if (!Array.isArray(runs)) {
12 return null
13 }
14
15 const statuses = runs.map(run => run?.status)
16
17 return {
18 queued: statuses.filter(status => QUEUED.has(status)).length,
19 running: statuses.filter(status => status === 'in_progress').length,
20 }
21 } catch {
22 return null
23 }
24}
25
26export const runLine = ({ queued, running }: RunCount) =>
27 `${queued} queued${running > 0 ? ` · ${running} running` : ''}`
28
29export const runSegment = (runs: RunCount): Segment => {
30 const color = runs.queued > 0 ? 'warning' : 'success'
31
32 return {
33 long: [{ text: '▶', color }, { text: ` ${runLine(runs)}`, dim: true }],
34 short: [{ text: '▶', color }, { text: ` ${runs.queued} queued`, dim: true }],
35 }
36}
37hooks/schedule.ts 4 lines1/** The next wait after a failure: double the last one, never below `baseMs` and never above `maxMs`. */
2export const backoff = (previousMs: number, baseMs: number, maxMs: number) =>
3 Math.min(maxMs, Math.max(baseMs, previousMs * 2))
4hooks/usage.ts 60 lines1import type { Piece, Segment } from './pieces'
2
3export type PlanLimit = { kind: string; percentUsed: number }
4
5/** What a session spent since the last reading; a counter that went backwards (a clear) restarts from zero. */
6export const costDelta = (previousUsd: number, currentUsd: number) =>
7 currentUsd >= previousUsd ? currentUsd - previousUsd : currentUsd
8
9export const localDay = (ms: number) => {
10 const date = new Date(ms)
11
12 return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
13}
14
15export const formatUsd = (usd: number) => (usd >= 100 ? `$${Math.round(usd)}` : `$${usd.toFixed(2)}`)
16
17const LIMIT_LABELS: Readonly<Record<string, string>> = { five_hour: '5h', seven_day: '7d', spend_limit: 'spend' }
18
19export const limitLabel = (kind: string) => LIMIT_LABELS[kind] ?? kind
20
21export const limitColor = (percentUsed: number) =>
22 percentUsed < 60 ? 'success' : percentUsed < 85 ? 'warning' : 'error'
23
24const percentText = (percentUsed: number) => `${Math.round(percentUsed)}%`
25
26const gap = (pieces: readonly Piece[]): Piece[] => (pieces.length > 0 ? [{ text: ' · ', dim: true }] : [])
27
28export const usageSegment = (todayUsd: number | null, limits: readonly PlanLimit[]): Segment | null => {
29 if (todayUsd === null && limits.length === 0) {
30 return null
31 }
32
33 const cost: Piece[] = todayUsd === null ? [] : [{ text: formatUsd(todayUsd) }, { text: ' today', dim: true }]
34 const busiest = limits.reduce<PlanLimit | null>(
35 (worst, limit) => (!worst || limit.percentUsed > worst.percentUsed ? limit : worst),
36 null,
37 )
38
39 return {
40 long: [
41 ...cost,
42 ...limits.flatMap((limit, index) => [
43 ...(index === 0 ? gap(cost) : [{ text: ' ', dim: true }]),
44 { text: `${limitLabel(limit.kind)} `, dim: true },
45 { text: percentText(limit.percentUsed), color: limitColor(limit.percentUsed) },
46 ]),
47 ],
48 short: [
49 ...(todayUsd === null ? [] : [{ text: formatUsd(todayUsd) }]),
50 ...(busiest
51 ? [
52 ...gap(todayUsd === null ? [] : cost),
53 { text: `${limitLabel(busiest.kind)} `, dim: true },
54 { text: percentText(busiest.percentUsed), color: limitColor(busiest.percentUsed) },
55 ]
56 : []),
57 ],
58 }
59}
60