Orange HUD for Claude Code: a side pane with session, workspace and agent status, turn work folded into one line, and restyled prompts and replies

Terminal mods for Claude Code, packaged as a plugin marketplace.
An orange heads-up display for the Claude Code terminal.
.claude/agents, .claude/skills) and your own (~/.claude), and every subagent with its status, tools and timing. Click an agent of the toolkit to leave Use the <name> agent to in the prompt box for Claude to launch it; click a skill to run it, after a dialog for its arguments. Click a subagent to read its conversation in the pane; ← HUD goes back. The agent whose transcript Claude Code has in view is marked ▶./thoughts to expand or fold every turn.At the prompt of a Claude Code terminal session:
/plugin install orange-hud --marketplace diegopc99/claude-cli
Answer y to add the marketplace, then pick the user scope. The mod is active right away.
| Command | What it does |
|---|---|
/hud | Opens the side pane when it is not showing |
/thoughts | Expands or folds the work of every turn |
axScreenReader or CLAUDE_AX_SCREEN_READER; plugins cannot see the --ax-screen-reader flag), replies and prompts keep Claude Code's own drawing, and the HUD leaves out Clawd, meter lines and the glyphs of the band above the prompt. With prefersReducedMotion, the agent spinner holds still.statusLine; that keeps drawing under the prompt./effort and /model show at once. Rate-limit figures come from the session's last API response, so a window whose reset has passed shows reset until the next response.git --no-optional-locks -c core.fsmonitor=false status --porcelain=v2 --ignore-submodules=dirty and kubectl config view --minify in the session's directory; git rev-parse runs once per directory and git log -1 --no-show-signature only when HEAD moves. Both tools are optional: without git or kubectl those rows are simply not shown. The toolkit is re-read every minute and when a turn ends.git status runs: an fsmonitor hook, and clean filters for the files .gitattributes maps to them. The HUD turns fsmonitor off and empties every filter the repo's local or worktree config names (it lists them first with git config --get-regexp); if a filter name cannot be overridden on the command line, it leaves the git rows out. Your global filters, such as Git LFS, still run. Changes inside a submodule's working tree are not counted./plugin uninstall orange-hud@claude-cli
/plugin marketplace remove claude-cli
claude plugin validate orange-hud
claude plugin test orange-hudhooks/register.tsx 2220 lines1import { atom, memberOf, read, update } from 'claude-code'
2import type {
3 AgentStatus,
4 Color,
5 EngineInterface,
6 Register,
7 RenderElement,
8 RenderInput,
9 ResolveInput,
10 SessionMessage,
11 Timer,
12} from 'claude-code'
13
14import type {
15 AccessMode,
16 AgentLogEntry,
17 AgentLogView,
18 AgentRow,
19 AgentStatusLabel,
20 AgentToolOutcome,
21 GitCommit,
22 GitOperation,
23 GitState,
24 HudInfo,
25 KubeState,
26 RateLimitGauge,
27 ToolDefinition,
28 ToolkitGroup,
29 TurnGroupView,
30} from '../types'
31
32type SiteInput = RenderInput<'Pane'> | RenderInput<'AbovePrompt'>
33type ClassicSessionFields = { effort?: { level: string }; agent_id?: string }
34type TranscriptInput =
35 | RenderInput<'AssistantMessage'>
36 | RenderInput<'ToolUse'>
37 | RenderInput<'ToolResult'>
38 | RenderInput<'ToolGroup'>
39 | RenderInput<'ToolProgress'>
40
41// Neutrals are keys of the person's theme, so a light, ANSI, daltonized or
42// custom theme keeps them readable; the section accents are the HUD's own.
43const ORANGE = 'claude'
44const MASCOT_BODY = 'clawd_body'
45const MASCOT_EYES = 'clawd_background'
46const KUBE_BLUE = '#326CE5'
47const WORKSPACE_GREEN = '#7FB77E'
48const AGENTS_BLUE = '#7AA2F7'
49const TOOLKIT_PURPLE = '#BB9AF7'
50const TOOLKIT_MS = 60_000
51const NO_ARGS = 'No arguments'
52const CANCEL = 'Cancel'
53// Secondary text that carries something to read: faint text falls under a
54// readable contrast on most terminals, the theme's inactive grey does not.
55const QUIET = 'inactive'
56const TRACK = 'subtle'
57const METER = '─'
58// What a card's border and padding take of its width.
59const CARD_CHROME = 4
60const PROMPT_CARD = 'userMessageBackground'
61const CODE_CARD = 'composerSidebarBackground'
62const PANE_GUTTER = 2
63const PANE = 'hud'
64const PANE_COLUMNS = 46
65const VIEWER_COLUMNS = 96
66const MAX_AGENTS = 50
67const MAX_LOG_ENTRIES = 300
68const LIVE_MS = 1_000
69const WORKSPACE_MS = 5_000
70const POLL_MS = 1_000
71// A finished subagent leaves $.agent.list() a little after it ends; one that is
72// gone before a poll ever saw it is taken as done once this has passed.
73const GRACE_MS = 5_000
74const CAVEMAN_MODES = new Set([
75 'off', 'lite', 'full', 'ultra', 'wenyan-lite', 'wenyan', 'wenyan-full', 'wenyan-ultra',
76 'commit', 'review', 'compress',
77])
78const SPINNER = ['◐', '◓', '◑', '◒']
79const LIMIT_LABELS: Record<string, string> = { five_hour: '5h', seven_day: '7d' }
80
81// Clawd as the session header draws it (default pose): body glyphs, with the
82// eye spans painted over a dark background so the quadrant gaps read as eyes.
83const MASCOT: ReadonlyArray<ReadonlyArray<{ glyphs: string; isEye?: true }>> = [
84 [{ glyphs: ' ▐' }, { glyphs: '▛███▛█', isEye: true }, { glyphs: ' ' }],
85 [{ glyphs: '▝▜' }, { glyphs: '█████', isEye: true }, { glyphs: '█▀' }],
86 [{ glyphs: ' ▝▝ ▝▝ ' }],
87]
88
89const info = atom({ plugin: 'orange-hud', key: 'info' } as const, null)
90const hint = atom({ plugin: 'orange-hud', key: 'hint' } as const, '')
91const agents = atom({ plugin: 'orange-hud', key: 'agents' } as const, [])
92const now = atom({ plugin: 'orange-hud', key: 'now' } as const, 0)
93const effort = atom({ plugin: 'orange-hud', key: 'effort' } as const, null)
94const groupOf = atom({ plugin: 'orange-hud', key: 'groupOf' } as const, null)
95const turnGroup = atom({ plugin: 'orange-hud', key: 'turnGroup' } as const, null)
96const groupOpen = atom({ plugin: 'orange-hud', key: 'groupOpen' } as const, false)
97const showThoughts = atom({ plugin: 'orange-hud', key: 'showThoughts' } as const, false)
98const working = atom({ plugin: 'orange-hud', key: 'isWorking' } as const, false)
99const toolkit = atom({ plugin: 'orange-hud', key: 'toolkit' } as const, [])
100const collapsed = atom({ plugin: 'orange-hud', key: 'collapsed' } as const, [])
101const viewing = atom({ plugin: 'orange-hud', key: 'viewing' } as const, null)
102const agentLog = atom({ plugin: 'orange-hud', key: 'agentLog' } as const, null)
103const access = atom({ plugin: 'orange-hud', key: 'access' } as const, { isScreenReader: false, isReducedMotion: false })
104
105let poller: Timer | undefined
106let isLogLoading = false
107let isLogStale = false
108let paneHinted = false
109let isAutoOpened = false
110let isRefreshQueued = false
111let isFullscreen: boolean | undefined
112const ASKING_TOOLS = new Set(['AskUserQuestion', 'ExitPlanMode'])
113// The main conversation's open turn: prose not yet known to be intermediate,
114// and the group its work folds into.
115const tracker: GroupTracker = { pending: [], group: null }
116let lastHint: string | undefined
117let lastWorking: boolean | undefined
118
119const isLiveLabel = (status: AgentStatusLabel) => status === 'running' || status === 'idle'
120const isLive = (row: AgentRow) => isLiveLabel(row.status)
121
122function statusLabel(status: AgentStatus): AgentStatusLabel {
123 switch (status) {
124 case 'idle':
125 case 'completed':
126 case 'failed':
127 case 'killed':
128 return status
129 default:
130 return 'running'
131 }
132}
133
134export function modelLabel(model: string): string {
135 const match = /^claude-([a-z]+)-(\d+)-(\d+)(?:-\d{8})?(\[1m\])?$/i.exec(model)
136 if (match === null) return model
137 const family = match[1] ?? ''
138 const size = match[4] === undefined ? '' : ' · 1M'
139 return `${family.charAt(0).toUpperCase()}${family.slice(1)} ${match[2]}.${match[3]}${size}`
140}
141
142export function tokens(count: number): string {
143 if (count >= 1_000_000) return `${Number((count / 1_000_000).toFixed(1))}M`
144 if (count >= 1_000) return `${Math.round(count / 1_000)}k`
145 return String(count)
146}
147
148export function elapsed(ms: number): string {
149 const seconds = Math.max(0, Math.round(ms / 1_000))
150 return seconds < 60 ? `${seconds}s` : `${Math.floor(seconds / 60)}m ${seconds % 60}s`
151}
152
153export function span(ms: number): string {
154 const minutes = Math.max(0, Math.floor(ms / 60_000))
155 if (minutes < 60) return `${minutes}m`
156 const hours = Math.floor(minutes / 60)
157 if (hours < 24) return `${hours}h ${String(minutes % 60).padStart(2, '0')}m`
158 return `${Math.floor(hours / 24)}d ${hours % 24}h`
159}
160
161export function ago(ms: number): string {
162 const minutes = Math.max(0, Math.floor(ms / 60_000))
163 if (minutes < 1) return 'now'
164 if (minutes < 60) return `${minutes}m`
165 const hours = Math.floor(minutes / 60)
166 return hours < 24 ? `${hours}h` : `${Math.floor(hours / 24)}d`
167}
168
169export type GitStatus = Pick<
170 GitState,
171 'branch' | 'isDetached' | 'oid' | 'upstream' | 'ahead' | 'behind' | 'staged' | 'modified' | 'untracked' | 'conflicts' | 'stashes'
172>
173
174// Reads `git status --porcelain=v2 --branch --show-stash`: headers, then one
175// line per path whose XY pair is the index's state and the work tree's.
176export function parseGitStatus(stdout: string): GitStatus {
177 const status: GitStatus = {
178 branch: '',
179 isDetached: false,
180 oid: null,
181 upstream: null,
182 ahead: null,
183 behind: null,
184 staged: 0,
185 modified: 0,
186 untracked: 0,
187 conflicts: 0,
188 stashes: 0,
189 }
190 for (const line of stdout.split('\n')) {
191 const [kind = '', field = '', ...rest] = line.split(' ')
192 if (kind === '#') {
193 const value = printable(rest.join(' '))
194 if (field === 'branch.oid') status.oid = value === '(initial)' ? null : value
195 if (field === 'branch.head') {
196 status.isDetached = value === '(detached)'
197 status.branch = status.isDetached ? 'detached' : value
198 }
199 if (field === 'branch.upstream') status.upstream = value
200 if (field === 'branch.ab') {
201 status.ahead = Math.abs(Number(rest[0] ?? 0))
202 status.behind = Math.abs(Number(rest[1] ?? 0))
203 }
204 if (field === 'stash') status.stashes = Number(rest[0] ?? 0)
205 } else if (kind === '1' || kind === '2') {
206 if (field[0] !== '.') status.staged++
207 if (field[1] !== '.') status.modified++
208 } else if (kind === 'u') {
209 status.conflicts++
210 } else if (kind === '?') {
211 status.untracked++
212 }
213 }
214 return status
215}
216
217const OPERATION_MARKERS: ReadonlyArray<[string, GitOperation]> = [
218 ['rebase-merge', 'rebase'],
219 ['rebase-apply', 'rebase'],
220 ['MERGE_HEAD', 'merge'],
221 ['CHERRY_PICK_HEAD', 'cherry-pick'],
222 ['REVERT_HEAD', 'revert'],
223 ['BISECT_LOG', 'bisect'],
224]
225
226export function gitOperation(names: readonly string[]): GitOperation | null {
227 const present = new Set(names)
228 return OPERATION_MARKERS.find(([marker]) => present.has(marker))?.[1] ?? null
229}
230
231export function parseKube(stdout: string): KubeState | null {
232 const [context = '', namespace = ''] = stdout.trim().split('\t')
233 const name = printable(context)
234 return name === '' ? null : { context: name, namespace: printable(namespace) || null }
235}
236
237function levelColor(percent: number): Color {
238 if (percent >= 85) return 'error'
239 if (percent >= 60) return 'warning'
240 return ORANGE
241}
242
243function statusColor(status: AgentStatusLabel): Color {
244 switch (status) {
245 case 'completed':
246 return 'success'
247 case 'failed':
248 return 'error'
249 case 'killed':
250 return 'inactive'
251 case 'idle':
252 return 'warning'
253 default:
254 return AGENTS_BLUE
255 }
256}
257
258function statusIcon(row: AgentRow, at: number, isStill: boolean): string {
259 switch (row.status) {
260 case 'completed':
261 return '✓'
262 case 'failed':
263 return '✗'
264 case 'killed':
265 return '■'
266 case 'idle':
267 return '◌'
268 default:
269 return isStill ? '●' : (SPINNER[Math.floor(at / 1_000) % SPINNER.length] ?? '●')
270 }
271}
272
273export type ListItem = { marker: string; text: string; depth: number }
274
275export type ReplyBlock =
276 | { kind: 'heading'; level: number; text: string }
277 | { kind: 'list'; isOrdered: boolean; items: ListItem[] }
278 | { kind: 'code'; language: string; source: string }
279 | { kind: 'quote'; lines: string[] }
280 | { kind: 'rule' }
281 | { kind: 'markdown'; text: string }
282
283const FENCE = /^\s*(`{3,}|~{3,})\s*([\w+#.-]*)/
284// The closing #s are cut by hand: a lazy capture before `\s*#*\s*$` backtracks
285// for seconds on one long line of spaces.
286const HEADING = /^(#{1,6})\s+([^]*)$/
287const RULE = /^\s*([-*_])(\s*\1){2,}\s*$/
288const LIST_ITEM = /^(\s*)([-*+]|\d+[.)])\s+(.*)$/
289const QUOTE = /^\s*>\s?(.*)$/
290
291function headingText(raw: string): string {
292 let end = raw.trimEnd().length
293 while (end > 0 && raw[end - 1] === '#') end--
294 return raw.slice(0, end).trimEnd()
295}
296
297// Splits a reply into the blocks the HUD styles itself; paragraphs and tables
298// stay markdown so the engine's renderer keeps inline formatting and tables.
299export function parseReply(text: string): ReplyBlock[] {
300 const lines = text.replace(/\r\n/g, '\n').split('\n')
301 const blocks: ReplyBlock[] = []
302 let prose: string[] = []
303 const flush = () => {
304 if (prose.some(line => line.trim() !== '')) blocks.push({ kind: 'markdown', text: prose.join('\n').trim() })
305 prose = []
306 }
307
308 for (let i = 0; i < lines.length; i++) {
309 const line = lines[i] ?? ''
310 const fence = FENCE.exec(line)
311 if (fence !== null) {
312 flush()
313 const mark = fence[1] ?? '```'
314 const body: string[] = []
315 i++
316 while (i < lines.length && !(lines[i] ?? '').trim().startsWith(mark)) body.push(lines[i++] ?? '')
317 blocks.push({ kind: 'code', language: fence[2] ?? '', source: body.join('\n') })
318 continue
319 }
320 const heading = HEADING.exec(line)
321 if (heading !== null) {
322 flush()
323 blocks.push({ kind: 'heading', level: (heading[1] ?? '#').length, text: headingText(heading[2] ?? '') })
324 continue
325 }
326 if (RULE.test(line)) {
327 flush()
328 blocks.push({ kind: 'rule' })
329 continue
330 }
331 const item = LIST_ITEM.exec(line)
332 if (item !== null) {
333 flush()
334 const isOrdered = /\d/.test(item[2] ?? '')
335 const items: ListItem[] = []
336 while (i < lines.length) {
337 const current = lines[i] ?? ''
338 const match = LIST_ITEM.exec(current)
339 if (match !== null && /\d/.test(match[2] ?? '') === isOrdered) {
340 items.push({ marker: match[2] ?? '-', text: match[3] ?? '', depth: Math.floor((match[1] ?? '').length / 2) })
341 } else if (current.trim() !== '' && /^\s+/.test(current) && items.length > 0) {
342 const last = items[items.length - 1]
343 if (last !== undefined) last.text = `${last.text}\n${current.trim()}`
344 } else if (current.trim() === '' && LIST_ITEM.test(lines[i + 1] ?? '')) {
345 // a blank line between items keeps the list going
346 } else {
347 break
348 }
349 i++
350 }
351 i--
352 blocks.push({ kind: 'list', isOrdered, items })
353 continue
354 }
355 const quote = QUOTE.exec(line)
356 if (quote !== null) {
357 flush()
358 const quoted: string[] = []
359 while (i < lines.length && QUOTE.test(lines[i] ?? '')) quoted.push(QUOTE.exec(lines[i++] ?? '')?.[1] ?? '')
360 i--
361 blocks.push({ kind: 'quote', lines: quoted })
362 continue
363 }
364 if (line.trim() === '') {
365 flush()
366 continue
367 }
368 prose.push(line)
369 }
370 flush()
371
372 return blocks
373}
374
375export type GroupRow = {
376 uuid: string
377 isPrompt: boolean
378 isAssistant: boolean
379 blocks: ReadonlyArray<{ type: string; id?: unknown; name?: unknown }>
380}
381
382export type GroupTracker = {
383 pending: Array<{ key: string; isText: boolean }>
384 group: TurnGroupView | null
385}
386
387export type GroupChange = { members: string[]; view: TurnGroupView }
388
389// Folds a turn's work into one group: prose a tool call follows, and the calls.
390// Prose no call follows (the final answer) stays out, and so does everything up
391// to a call that asks the person something, which also closes the group.
392export function noteGroupRow(tracker: GroupTracker, row: GroupRow): GroupChange | null {
393 if (row.isPrompt) {
394 tracker.pending = []
395 tracker.group = null
396 return null
397 }
398 if (!row.isAssistant) return null
399
400 const calls = row.blocks.filter(block => block.type === 'tool_use' && typeof block.id === 'string')
401 const isText = row.blocks.some(block => block.type === 'text')
402 const isProse = isText || row.blocks.some(block => block.type === 'thinking' || block.type === 'redacted_thinking')
403 if (calls.length === 0) {
404 if (isProse) tracker.pending.push({ key: row.uuid, isText })
405 return null
406 }
407 if (calls.some(call => ASKING_TOOLS.has(String(call.name)))) {
408 tracker.pending = []
409 tracker.group = null
410 return null
411 }
412
413 const prose = isProse ? [...tracker.pending, { key: row.uuid, isText }] : tracker.pending
414 const members = [...prose.map(part => part.key), ...calls.map(call => String(call.id))]
415 // The head draws the group's summary line, so it must be a row the transcript
416 // draws: thinking rows are hidden there, so a text row or the first call.
417 const head = prose.find(part => part.isText)?.key ?? String(calls[0]?.id ?? row.uuid)
418 const current = tracker.group ?? { head, texts: 0, tools: {}, last: null, isActive: true }
419 const tools = { ...current.tools }
420 for (const call of calls) {
421 const name = printable(String(call.name)).replace(/^mcp__[^_]+__/, '')
422 tools[name] = (tools[name] ?? 0) + 1
423 }
424 const view: TurnGroupView = {
425 head: current.head,
426 texts: current.texts + prose.filter(part => part.isText).length,
427 tools,
428 last: printable(String(calls.at(-1)?.name ?? '')).replace(/^mcp__[^_]+__/, '') || null,
429 isActive: true,
430 }
431 tracker.pending = []
432 tracker.group = view
433
434 return { members, view }
435}
436
437export function groupSummary(view: TurnGroupView): string {
438 const tools = Object.entries(view.tools).sort((a, b) => b[1] - a[1])
439 const calls = tools.reduce((total, [, count]) => total + count, 0)
440 const counts = [
441 view.texts > 0 ? `${view.texts} text${view.texts === 1 ? '' : 's'}` : null,
442 `${calls} tool${calls === 1 ? '' : 's'}`,
443 ].filter(part => part !== null)
444 const detail = tools.slice(0, 4).map(([name, count]) => `${name} ${count}`).join(' · ')
445 const lead = view.isActive ? `working${view.last !== null ? ` (${view.last})` : ''} · ` : ''
446
447 return `${lead}${counts.join(' · ')}${detail === '' ? '' : ` — ${detail}`}`
448}
449
450export type GroupDrawing = 'engine' | 'hidden' | 'summary' | 'expanded-head'
451
452// A call's result and progress rows carry its id but never head the group: the
453// call's own row does, and a screen reader's drawing shows the result apart.
454export function groupDrawing(
455 head: string | null,
456 keys: readonly string[],
457 isOpen: boolean,
458 isShowingAll: boolean,
459 canHead = true,
460): GroupDrawing {
461 if (isShowingAll || head === null) return 'engine'
462 const isHead = canHead && keys.includes(head)
463 if (isOpen) return isHead ? 'expanded-head' : 'engine'
464 return isHead ? 'summary' : 'hidden'
465}
466
467// Text from outside the session (a kubeconfig, git, the model) is drawn as is,
468// so control characters that could carry terminal escape sequences are dropped.
469export function printable(text: string): string {
470 return text.replace(/[\u0000-\u001f\u007f-\u009f]/g, '')
471}
472
473function printableLines(text: string): string {
474 return text.replace(/[\u0000-\u0008\u000b-\u001f\u007f-\u009f]/g, '')
475}
476
477export function clip(text: string, width: number): string {
478 if (text.length <= width) return text
479 return width <= 1 ? text.slice(0, Math.max(0, width)) : `${text.slice(0, width - 1)}…`
480}
481
482const SUMMARY_KEYS = ['file_path', 'path', 'pattern', 'command', 'url', 'query', 'skill', 'description', 'prompt']
483
484export function toolSummary(input: Record<string, unknown>): string {
485 for (const key of SUMMARY_KEYS) {
486 const value = input[key]
487 if (typeof value === 'string' && value.trim() !== '') return clip(printable(value.replace(/\s+/g, ' ').trim()), 200)
488 }
489 return ''
490}
491
492// An agent's conversation as the viewer draws it: tool results are read off the
493// calls they answer, and injected reminders are not the agent's prompt.
494export function agentLogEntries(messages: readonly SessionMessage[]): AgentLogEntry[] {
495 const entries: AgentLogEntry[] = []
496 for (const message of messages) {
497 if (message.role === 'user') {
498 if ((message.toolResults?.length ?? 0) > 0) continue
499 const text = printableLines(message.text.replace(/<system-reminder>[\s\S]*?<\/system-reminder>/g, '')).trim()
500 if (text !== '') entries.push({ kind: 'prompt', text })
501 continue
502 }
503 const text = printableLines(message.text).trim()
504 if (text !== '') entries.push({ kind: 'reply', text })
505 for (const use of message.toolUses) {
506 const outcome: AgentToolOutcome =
507 use.isError === true ? 'error' : use.text === undefined && use.result === undefined ? 'pending' : 'ok'
508 entries.push({
509 kind: 'tool',
510 name: printable(use.tool).replace(/^mcp__[^_]+__/, ''),
511 summary: toolSummary(use.input),
512 outcome,
513 })
514 }
515 }
516 return entries.slice(-MAX_LOG_ENTRIES)
517}
518
519function cwdLabel(hud: HudInfo): string {
520 if (hud.home !== null && hud.cwd === hud.home) return '~'
521 return printable(hud.cwd.split('/').filter(part => part !== '').at(-1) ?? hud.cwd)
522}
523
524async function attempt<T>(work: () => Promise<T>, fallback: T): Promise<T> {
525 try {
526 return await work()
527 } catch {
528 return fallback
529 }
530}
531
532async function storeEffort($: EngineInterface, value: string): Promise<void> {
533 if ((await read($, effort)) === value) return
534 await update($, effort, () => value)
535}
536
537// No optional locks: a background poll must not take the index lock from the
538// person's own git commands. No fsmonitor: its hook is a command a config names.
539const GIT = ['git', '--no-optional-locks', '-c', 'core.fsmonitor=false'] as const
540
541// A filter the repo's own config names runs on `git status`, so each one is
542// emptied for the HUD's call; a name `-c` cannot spell leaves git out instead.
543export function filterOverrides(listing: string): string[] | null {
544 const fields = listing.split('\0')
545 const names = new Set<string>()
546 for (let i = 0; i + 1 < fields.length; i += 2) {
547 if (fields[i] !== 'local' && fields[i] !== 'worktree') continue
548 const name = /^filter\.([^]*)\.[^.]*$/.exec(fields[i + 1] ?? '')?.[1]
549 if (name === undefined) continue
550 if (/[=\n]/.test(name)) return null
551 names.add(name)
552 }
553 return [...names].flatMap(name => ['-c', `filter.${name}.clean=`, '-c', `filter.${name}.process=`])
554}
555
556let repoCache: { cwd: string; root: string; gitDir: string; isWorktree: boolean } | undefined
557let commitCache: { oid: string; commit: GitCommit | null } | undefined
558
559async function gitRepo($: EngineInterface, cwd: string): Promise<typeof repoCache> {
560 if (repoCache?.cwd === cwd) return repoCache
561 const run = await $.process.run(
562 [...GIT, 'rev-parse', '--path-format=absolute', '--show-toplevel', '--git-dir', '--git-common-dir'],
563 { timeoutMs: 2_000 },
564 )
565 if (run.exitCode !== 0) return undefined
566 const [root = '', gitDir = '', commonDir = ''] = run.stdout.split('\n')
567 repoCache = { cwd, root, gitDir, isWorktree: gitDir !== commonDir }
568 return repoCache
569}
570
571async function lastCommit($: EngineInterface, oid: string | null): Promise<GitCommit | null> {
572 if (oid === null) return null
573 if (commitCache?.oid === oid) return commitCache.commit
574 const run = await $.process.run([...GIT, 'log', '-1', '--no-show-signature', '--format=%h%x1f%ct%x1f%s'], { timeoutMs: 2_000 })
575 const [hash = '', at = '', subject = ''] = run.exitCode === 0 ? run.stdout.trim().split('\x1f') : []
576 const commit = hash === '' ? null : { hash: printable(hash), subject: printable(subject), at: Number(at) * 1_000 }
577 commitCache = { oid, commit }
578 return commit
579}
580
581// A rebase, merge or pick in progress leaves its marker in the git dir, so a
582// listing tells without a process; a rebase's step is two numbers beside it.
583async function gitProgress($: EngineInterface, gitDir: string): Promise<Pick<GitState, 'operation' | 'step'>> {
584 const names = (await attempt(() => $.fs.list(gitDir), [])).map(entry => entry.name)
585 const operation = gitOperation(names)
586 if (operation !== 'rebase') return { operation, step: null }
587 const isMerge = names.includes('rebase-merge')
588 const dir = `${gitDir}/${isMerge ? 'rebase-merge' : 'rebase-apply'}`
589 const read = (name: string) => attempt(async () => (await $.fs.read(`${dir}/${name}`)).trim(), '')
590 const [done, total] = await Promise.all([read(isMerge ? 'msgnum' : 'next'), read(isMerge ? 'end' : 'last')])
591 return { operation, step: /^\d+$/.test(done) && /^\d+$/.test(total) ? `${done}/${total}` : null }
592}
593
594async function gitState($: EngineInterface): Promise<GitState | null> {
595 const filters = await $.process.run([...GIT, 'config', '--show-scope', '-z', '--name-only', '--get-regexp', '^filter\\.'], {
596 timeoutMs: 2_000,
597 })
598 const overrides =
599 filters.exitCode === 1 ? [] : filters.exitCode === 0 && !filters.isStdoutTruncated ? filterOverrides(filters.stdout) : null
600 if (overrides === null) return null
601 // A submodule's own status would run its filters, which are not emptied here.
602 const run = await $.process.run(
603 [...GIT, ...overrides, 'status', '--porcelain=v2', '--branch', '--show-stash', '--ignore-submodules=dirty'],
604 { timeoutMs: 2_000 },
605 )
606 if (run.exitCode !== 0) return null
607 const status = parseGitStatus(run.stdout)
608 const cwd = await $.session.cwd()
609 const repo = await gitRepo($, cwd)
610 const [progress, commit] = await Promise.all([
611 repo === undefined ? { operation: null, step: null } : gitProgress($, repo.gitDir),
612 lastCommit($, status.oid),
613 ])
614 const root = repo?.root ?? cwd
615 return {
616 ...status,
617 ...progress,
618 lastCommit: commit,
619 repo: printable(root.split('/').filter(part => part !== '').at(-1) ?? root),
620 subdir: repo !== undefined && cwd.startsWith(`${root}/`) ? printable(cwd.slice(root.length + 1)) : null,
621 isWorktree: repo?.isWorktree ?? false,
622 }
623}
624
625async function kubeState($: EngineInterface): Promise<KubeState | null> {
626 const run = await $.process.run(
627 ['kubectl', 'config', 'view', '--minify', '-o', 'jsonpath={.current-context}{"\\t"}{..namespace}'],
628 { timeoutMs: 2_000 },
629 )
630 return run.exitCode === 0 ? parseKube(run.stdout) : null
631}
632
633// Only a line that is a title record: the same key inside a tool's output is not.
634const TITLE_PATTERN = '^\\{"type":"(custom-title","customTitle|ai-title","aiTitle)":"([^"\\\\]|\\\\.)*"'
635let transcript: { id: string; path: string } | undefined
636// The title last read, keyed by the transcript's size and mtime: re-read only once the file changed.
637let titleCache: { id: string; stamp: string; title: string | null } | undefined
638
639// The title a /rename set wins over the one Claude Code generated; both are the
640// latest of their kind in the transcript lines `grep` hands back.
641export function pickSessionTitle(lines: readonly string[]): string | null {
642 let custom: string | null = null
643 let generated: string | null = null
644 for (const line of lines) {
645 try {
646 const entry = JSON.parse(`${line}}`) as { customTitle?: unknown; aiTitle?: unknown }
647 if (typeof entry.customTitle === 'string') custom = entry.customTitle
648 if (typeof entry.aiTitle === 'string') generated = entry.aiTitle
649 } catch {
650 // a line grep cut mid-escape is skipped
651 }
652 }
653 const title = printable(custom ?? generated ?? '').trim()
654 return title === '' ? null : title
655}
656
657export function isTitleFresh(
658 cache: { id: string; stamp: string } | undefined,
659 id: string,
660 stamp: string,
661): boolean {
662 return cache !== undefined && cache.id === id && cache.stamp === stamp
663}
664
665// No API carries the session's name, so it is read off the transcript. The file
666// outgrows $.fs.read's limit, so grep returns only the title entries.
667async function sessionTitle($: EngineInterface, configDir: string): Promise<string | null> {
668 const id = await $.session.id()
669 if (!/^[0-9a-f-]{36}$/i.test(id)) return null
670 if (transcript?.id !== id) {
671 const found = await $.process.run(
672 ['find', `${configDir}/projects`, '-maxdepth', '2', '-name', `${id}.jsonl`, '-print', '-quit'],
673 { timeoutMs: 3_000 },
674 )
675 const path = found.exitCode === 0 ? found.stdout.trim() : ''
676 if (path === '') return null
677 transcript = { id, path }
678 }
679 const stat = await $.fs.stat(transcript.path)
680 const stamp = `${stat.size}:${stat.mtimeMs}`
681 if (titleCache !== undefined && isTitleFresh(titleCache, id, stamp)) return titleCache.title
682 const run = await $.process.run(['grep', '-a', '-o', '-E', TITLE_PATTERN, transcript.path], { timeoutMs: 3_000 })
683 const title = run.exitCode === 0 ? pickSessionTitle(run.stdout.split('\n').filter(line => line !== '')) : null
684 titleCache = { id, stamp, title }
685 return title
686}
687
688// Mirrors ~/.claude/hooks/caveman-statusline.sh, which the HUD replaces; the
689// flag text is reduced to [a-z0-9-] so nothing from the file reaches the terminal raw.
690async function cavemanBadge($: EngineInterface, configDir: string): Promise<string | null> {
691 const raw = await $.fs.read(`${configDir}/.caveman-active`)
692 const mode = raw.slice(0, 64).toLowerCase().replace(/[^a-z0-9-]/g, '')
693 if (!CAVEMAN_MODES.has(mode)) return null
694 const badge = mode === 'full' ? '[CAVEMAN]' : `[CAVEMAN:${mode.toUpperCase()}]`
695 const savings = await attempt(
696 async () => (await $.fs.read(`${configDir}/.caveman-statusline-suffix`)).slice(0, 64).replace(/[\u0000-\u001f\u007f]/g, '').trim(),
697 '',
698 )
699 return savings === '' ? badge : `${badge} ${savings}`
700}
701
702async function configDirOf($: EngineInterface, home: string | undefined): Promise<string | undefined> {
703 const explicit = await attempt(() => $.env.get('CLAUDE_CONFIG_DIR'), undefined)
704 return explicit ?? (home === undefined ? undefined : `${home}/.claude`)
705}
706
707// /effort saves the level under the model it was set for, and the plain
708// effortLevel is what a model with no entry of its own runs at.
709export function settingsEffort(settings: Readonly<Record<string, unknown>>, model: string): string | null {
710 const field = (value: unknown, key: string): unknown =>
711 typeof value === 'object' && value !== null ? (value as Record<string, unknown>)[key] : undefined
712 const base = model.replace(/\[1m\]$/i, '').replace(/-\d{8}$/, '')
713 const level = field(field(settings['modelSettings'], base), 'effortLevel') ?? settings['effortLevel']
714 return typeof level === 'string' && level !== '' ? printable(level) : null
715}
716
717const EFFORT_LEVELS = new Set(['low', 'medium', 'high', 'xhigh', 'max'])
718
719// /effort's output, kept as a command row whether typed or picked, names the
720// level it set: the only trace of one set for this session alone, which the
721// settings never see.
722export function effortSet(text: string): string | null {
723 const level = /<local-command-stdout>Set effort level to ([a-z]+)\b/.exec(text)?.[1]
724 return level !== undefined && EFFORT_LEVELS.has(level) ? level : null
725}
726
727const ON_WORDS = ['1', 'true', 'yes', 'on']
728const OFF_WORDS = ['0', 'false', 'no', 'off']
729
730// Claude Code's own switches, in its order: --ax-screen-reader, which no plugin
731// can read, then CLAUDE_AX_SCREEN_READER, then the axScreenReader setting.
732export function accessMode(settings: Readonly<Record<string, unknown>>, screenReaderEnv: string | undefined): AccessMode {
733 const word = screenReaderEnv?.trim().toLowerCase() ?? ''
734 return {
735 isScreenReader: ON_WORDS.includes(word) || (!OFF_WORDS.includes(word) && settings['axScreenReader'] === true),
736 isReducedMotion: settings['prefersReducedMotion'] === true,
737 }
738}
739
740type LiveInfo = Omit<HudInfo, 'git' | 'kube' | 'sessionTitle' | 'fetchedAt'>
741type WorkspaceInfo = Pick<HudInfo, 'git' | 'kube' | 'sessionTitle'>
742
743const NO_INFO: HudInfo = {
744 version: '',
745 model: '',
746 cwd: '',
747 home: null,
748 git: null,
749 kube: null,
750 contextPercent: null,
751 contextTokens: null,
752 contextWindow: 0,
753 rateLimits: [],
754 costUsd: null,
755 prompts: null,
756 sessionStartedAt: null,
757 fetchedAt: 0,
758 effortSetting: null,
759 caveman: null,
760 sessionTitle: null,
761}
762
763// What the session reports in process, no child spawned: cheap enough to poll each second.
764async function collectLive($: EngineInterface): Promise<LiveInfo & { access: AccessMode }> {
765 const home = await attempt(() => $.env.get('HOME'), undefined)
766 const configDir = await configDirOf($, home)
767 const [version, model, cwd, usage, prompts, settings, caveman, screenReader] = await Promise.all([
768 attempt(async () => (await $.session.version()).version, ''),
769 attempt(() => $.session.model(), ''),
770 attempt(() => $.session.cwd(), ''),
771 attempt(() => $.session.usage(), undefined),
772 attempt(() => $.session.turns(), null),
773 attempt(() => $.settings.read(), {}),
774 configDir === undefined ? Promise.resolve(null) : attempt(() => cavemanBadge($, configDir), null),
775 attempt(() => $.env.get('CLAUDE_AX_SCREEN_READER'), undefined),
776 ])
777 const rateLimits: RateLimitGauge[] = (usage?.rateLimits ?? []).map(limit => {
778 const resetsAt = limit.resetsAt === undefined ? NaN : Date.parse(limit.resetsAt)
779 return {
780 label: LIMIT_LABELS[limit.kind] ?? limit.kind,
781 percent: limit.percentUsed,
782 resetsAt: Number.isNaN(resetsAt) ? null : resetsAt,
783 }
784 })
785
786 return {
787 version,
788 model,
789 cwd,
790 home: home ?? null,
791 contextPercent: usage?.context.percent ?? null,
792 contextTokens: usage?.context.tokens ?? null,
793 contextWindow: usage?.context.window ?? 0,
794 rateLimits,
795 costUsd: usage?.cost?.usd ?? null,
796 prompts,
797 sessionStartedAt: usage?.startedAt ?? null,
798 effortSetting: settingsEffort(settings, model),
799 caveman,
800 access: accessMode(settings, screenReader),
801 }
802}
803
804async function collectWorkspace($: EngineInterface): Promise<WorkspaceInfo> {
805 const configDir = await configDirOf($, await attempt(() => $.env.get('HOME'), undefined))
806 const [git, kube, title] = await Promise.all([
807 attempt(() => gitState($), null),
808 attempt(() => kubeState($), null),
809 configDir === undefined ? Promise.resolve(null) : attempt(() => sessionTitle($, configDir), null),
810 ])
811 return { git, kube, sessionTitle: title }
812}
813
814type Refresh = 'live' | 'access' | 'workspace' | 'toolkit'
815
816let passes = 0
817const landed: Record<Refresh, number> = { live: 0, access: 0, workspace: 0, toolkit: 0 }
818
819// Refreshes overlap (the timers, a turn's end, a command), so a pass lands only
820// if no later one has: a slow pass never writes an older snapshot over a newer
821// one, and a pass that never settles holds nothing up. Called inside update's
822// function, so a write retried after a newer one landed is dropped too.
823function lands(refresh: Refresh, pass: number): boolean {
824 if (pass < landed[refresh]) return false
825 landed[refresh] = pass
826 return true
827}
828
829// Durations are drawn against fetchedAt, so it moves on each minute and as a
830// limit's reset passes, and not on every poll.
831function clockMark(at: number, limits: readonly RateLimitGauge[]): string {
832 return `${Math.floor(at / 60_000)}:${limits.filter(limit => limit.resetsAt !== null && limit.resetsAt <= at).length}`
833}
834
835async function refreshLive($: EngineInterface): Promise<void> {
836 const pass = ++passes
837 const { access: mode, ...fresh } = await collectLive($)
838 const at = await $.clock.now()
839 const current = await read($, info)
840 if (pass < landed.live) return
841 const isSame =
842 current !== null &&
843 JSON.stringify({ ...current, ...fresh }) === JSON.stringify(current) &&
844 clockMark(current.fetchedAt, current.rateLimits) === clockMark(at, fresh.rateLimits)
845 if (!isSame) await update($, info, value => (lands('live', pass) ? { ...(value ?? NO_INFO), ...fresh, fetchedAt: at } : value))
846 // A level the settings take on (an /effort, a /model) is newer than the one
847 // the last turn reported, so it replaces it until the next turn reports again.
848 if (pass === landed.live && current !== null && fresh.effortSetting !== null && fresh.effortSetting !== current.effortSetting) {
849 await storeEffort($, fresh.effortSetting)
850 }
851 if (pass >= landed.access && JSON.stringify(await read($, access)) !== JSON.stringify(mode)) {
852 await update($, access, value => (lands('access', pass) ? mode : value))
853 }
854}
855
856async function refreshWorkspace($: EngineInterface): Promise<void> {
857 const pass = ++passes
858 const fresh = await collectWorkspace($)
859 const at = await $.clock.now()
860 const current = await read($, info)
861 if (pass < landed.workspace) return
862 if (current !== null && JSON.stringify({ ...current, ...fresh }) === JSON.stringify(current)) return
863 await update($, info, value =>
864 lands('workspace', pass) ? { ...(value ?? { ...NO_INFO, fetchedAt: at }), ...fresh } : value,
865 )
866}
867
868// Re-reads the session title alone, for the moment a /rename has just written it.
869async function refreshTitle($: EngineInterface): Promise<void> {
870 const configDir = await configDirOf($, await attempt(() => $.env.get('HOME'), undefined))
871 if (configDir === undefined) return
872 const title = await attempt(() => sessionTitle($, configDir), null)
873 const current = await read($, info)
874 if (current === null || current.sessionTitle === title) return
875 await update($, info, value => (value === null ? value : { ...value, sessionTitle: title }))
876}
877
878// Reads `name` and `description` off a definition's front matter: plain,
879// quoted or block (`>`, `|`) values, which is all agent and skill files use.
880export function parseFrontmatter(text: string): ToolDefinition | null {
881 const lines = text.replace(/\r\n/g, '\n').split('\n')
882 if (lines[0]?.trim() !== '---') return null
883 const fields: Record<string, string> = {}
884 for (let i = 1; i < lines.length; i++) {
885 const line = lines[i] ?? ''
886 if (line.trim() === '---') break
887 const match = /^([A-Za-z_][\w-]*):\s*(.*)$/.exec(line)
888 if (match === null) continue
889 let value = (match[2] ?? '').trim()
890 if (/^[>|][+-]?$/.test(value)) {
891 const block: string[] = []
892 while (i + 1 < lines.length && /^\s+\S/.test(lines[i + 1] ?? '')) block.push((lines[++i] ?? '').trim())
893 value = block.join(' ')
894 }
895 fields[match[1] ?? ''] = value.replace(/^(['"])(.*)\1$/, '$2')
896 }
897 const name = printable(fields['name'] ?? '').trim()
898 return name === '' ? null : { name, description: printable(fields['description'] ?? '').trim() }
899}
900
901// Claude Code's own rule for agent and skill names; anything else in a repo's
902// definition is not offered, so the prompt box and /name carry no surprises.
903const DEFINITION_NAME = /^[a-z0-9][a-z0-9-]{0,63}$/
904const MAX_DEFINITIONS = 100
905const MAX_DEFINITION_BYTES = 64 * 1024
906
907// A repo's definitions may be links: only a regular file of a definition's size
908// is read, never a device or a pipe one points to.
909async function readDefinition($: EngineInterface, path: string): Promise<ToolDefinition | null> {
910 const stat = await $.fs.stat(path)
911 if (stat.kind !== 'file' || stat.size > MAX_DEFINITION_BYTES) return null
912 const definition = parseFrontmatter(await $.fs.read(path))
913 return definition !== null && DEFINITION_NAME.test(definition.name) ? definition : null
914}
915
916async function readDefinitions($: EngineInterface, dir: string, kind: 'agents' | 'skills'): Promise<ToolDefinition[]> {
917 const entries = await attempt(() => $.fs.list(dir), [])
918 const paths =
919 kind === 'agents'
920 ? entries.filter(entry => entry.kind === 'file' && entry.name.endsWith('.md')).map(entry => `${dir}/${entry.name}`)
921 : entries.filter(entry => entry.kind !== 'file' && !entry.name.startsWith('.')).map(entry => `${dir}/${entry.name}/SKILL.md`)
922 const found = await Promise.all(paths.slice(0, MAX_DEFINITIONS).map(path => attempt(() => readDefinition($, path), null)))
923 return found.filter(definition => definition !== null).sort((a, b) => a.name.localeCompare(b.name))
924}
925
926// The repo's own definitions first; the person's own follow, less any the repo
927// redefines under the same name.
928async function collectToolkit($: EngineInterface): Promise<ToolkitGroup[]> {
929 const configDir = await configDirOf($, await attempt(() => $.env.get('HOME'), undefined))
930 const root = await attempt(() => $.session.root(), '')
931 // A skill named like a built-in or a plugin's command would run that command
932 // under the skill's description, so it is not offered.
933 const taken = new Set((await attempt(() => $.command.list(), [])).filter(one => one.source !== 'user').map(one => one.name))
934 const readSkills = async (dir: string) => (await readDefinitions($, dir, 'skills')).filter(one => !taken.has(one.name))
935 const groups: ToolkitGroup[] = []
936 if (root !== '' && `${root}/.claude` !== configDir) {
937 const [agentDefs, skillDefs] = await Promise.all([
938 readDefinitions($, `${root}/.claude/agents`, 'agents'),
939 readSkills(`${root}/.claude/skills`),
940 ])
941 const label = printable(root.split('/').filter(part => part !== '').at(-1) ?? root)
942 if (agentDefs.length + skillDefs.length > 0) groups.push({ origin: 'repo', label, agents: agentDefs, skills: skillDefs })
943 }
944 if (configDir !== undefined) {
945 const repo = groups[0]
946 const [agentDefs, skillDefs] = await Promise.all([
947 readDefinitions($, `${configDir}/agents`, 'agents'),
948 readSkills(`${configDir}/skills`),
949 ])
950 const agentsLeft = agentDefs.filter(one => !repo?.agents.some(other => other.name === one.name))
951 const skillsLeft = skillDefs.filter(one => !repo?.skills.some(other => other.name === one.name))
952 if (agentsLeft.length + skillsLeft.length > 0) groups.push({ origin: 'user', label: 'you', agents: agentsLeft, skills: skillsLeft })
953 }
954 return groups
955}
956
957async function refreshToolkit($: EngineInterface): Promise<void> {
958 const pass = ++passes
959 const fresh = await collectToolkit($)
960 if (pass < landed.toolkit || JSON.stringify(await read($, toolkit)) === JSON.stringify(fresh)) return
961 await update($, toolkit, value => (lands('toolkit', pass) ? fresh : value))
962}
963
964// Claude launches the agent: the request is left in the prompt box for the
965// person to finish with the task, under anything already typed there.
966async function askForAgent($: EngineInterface, name: string): Promise<void> {
967 const request = `Use the ${name} agent to `
968 const box = await $.prompt.read()
969 await $.prompt.fill(box.text.trim() === '' ? { text: request } : { text: `\n${request}`, mode: 'append' })
970}
971
972export function skillArgs(answer: string): string | null {
973 if (answer === CANCEL) return null
974 return answer === NO_ARGS ? '' : answer.trim()
975}
976
977async function runSkill($: EngineInterface, name: string): Promise<void> {
978 const answer = await attempt(
979 () => $.ui.ask(`Arguments for /${name}?`, { options: [NO_ARGS, CANCEL], header: 'Skill' }),
980 CANCEL,
981 )
982 const args = skillArgs(answer)
983 if (args === null) return
984 try {
985 await $.command.run({ command: name, args })
986 } catch {
987 $.ui.toast(`/${name} could not be run`)
988 }
989}
990
991// A drawing that finds no figures yet asks for them from outside the draw.
992function queueRefresh($: EngineInterface): void {
993 if (isRefreshQueued) return
994 isRefreshQueued = true
995 $.clock.after(1, () => {
996 void refreshLive($)
997 void refreshWorkspace($)
998 void refreshToolkit($)
999 })
1000}
1001
1002function noteSession($: EngineInterface, e: ClassicSessionFields): void {
1003 if (e.agent_id !== undefined) return
1004 if (e.effort?.level) void storeEffort($, e.effort.level)
1005}
1006
1007async function openPane($: EngineInterface, isAsked: boolean): Promise<void> {
1008 const columns = (await read($, viewing)) === null ? PANE_COLUMNS : VIEWER_COLUMNS
1009 const opened = await $.ui.open({ id: PANE, title: 'HUD', columns })
1010 $.ui.invalidate('ui.render')
1011 if (!opened.isPlaced && !isAsked && !paneHinted) {
1012 paneHinted = true
1013 $.ui.toast('HUD: widen the terminal or run /hud to dock it on the right')
1014 }
1015}
1016
1017async function loadAgentLog($: EngineInterface): Promise<void> {
1018 const agentId = await read($, viewing)
1019 if (agentId === null) return
1020 const found = await attempt(() => $.session.messages({ agentId }), { deny: 'unreadable' })
1021 if ((await read($, viewing)) !== agentId) return
1022 const current = await read($, agentLog)
1023 if (!Array.isArray(found) && current?.agentId === agentId && current.entries.length > 0) return
1024 const fresh: AgentLogView = Array.isArray(found)
1025 ? { agentId, entries: agentLogEntries(found), isDenied: false }
1026 : { agentId, entries: [], isDenied: true }
1027 if (JSON.stringify(current) === JSON.stringify(fresh)) return
1028 await update($, agentLog, () => fresh)
1029}
1030
1031// A refresh asked for while one runs is folded into one more pass after it, so
1032// an agent's last turn is never dropped behind a poll that read it a moment early.
1033async function refreshAgentLog($: EngineInterface): Promise<void> {
1034 if (isLogLoading) {
1035 isLogStale = true
1036 return
1037 }
1038 isLogLoading = true
1039 try {
1040 do {
1041 isLogStale = false
1042 await loadAgentLog($)
1043 } while (isLogStale)
1044 } finally {
1045 isLogLoading = false
1046 }
1047}
1048
1049async function showAgent($: EngineInterface, agentId: string | null): Promise<void> {
1050 await update($, viewing, () => agentId)
1051 await update($, agentLog, () => null)
1052 await openPane($, true)
1053 if (agentId === null) return
1054 await refreshAgentLog($)
1055 await attempt(() => $.ui.scroll({ to: 'end', in: PANE }), undefined)
1056}
1057
1058async function isHudInPane($: EngineInterface): Promise<boolean> {
1059 const panes = await attempt(() => $.ui.panes(), [])
1060 return panes.some(pane => pane.id === PANE && pane.isPlaced && pane.isShown)
1061}
1062
1063async function finish(
1064 $: EngineInterface,
1065 matches: (row: AgentRow) => boolean,
1066 status: AgentStatusLabel,
1067 totals?: { tools?: number; tokens?: number },
1068): Promise<void> {
1069 const at = await $.clock.now()
1070 await update($, agents, list =>
1071 list.map(row =>
1072 matches(row) && isLive(row)
1073 ? { ...row, status, endedAt: at, tools: totals?.tools ?? row.tools, tokens: totals?.tokens ?? row.tokens }
1074 : row,
1075 ),
1076 )
1077}
1078
1079async function countTool($: EngineInterface, agentId: string, tool: string): Promise<void> {
1080 const list = await read($, agents)
1081 if (!list.some(row => row.id === agentId && isLive(row))) return
1082 await update($, agents, rows =>
1083 rows.map(row => (row.id === agentId ? { ...row, tools: row.tools + 1, lastTool: printable(tool) } : row)),
1084 )
1085}
1086
1087async function pollAgents($: EngineInterface): Promise<void> {
1088 const at = await $.clock.now()
1089 const rows = await read($, agents)
1090 if (!rows.some(isLive)) {
1091 poller?.cancel()
1092 poller = undefined
1093 return
1094 }
1095 await update($, now, () => at)
1096 const listed = new Map((await $.agent.list()).map(agent => [agent.id, agent.status]))
1097 await update($, agents, list =>
1098 list.map((row): AgentRow => {
1099 if (!isLive(row)) return row
1100 const status = listed.get(row.id)
1101 if (status === undefined) {
1102 return at - row.startedAt > GRACE_MS ? { ...row, status: 'completed', endedAt: at } : row
1103 }
1104 const label = statusLabel(status)
1105 if (label === row.status) return row
1106 return isLiveLabel(label) ? { ...row, status: label } : { ...row, status: label, endedAt: at }
1107 }),
1108 )
1109 const shown = await read($, viewing)
1110 if (shown !== null && rows.some(row => row.id === shown && isLive(row))) void refreshAgentLog($)
1111}
1112
1113function ensurePoller($: EngineInterface): void {
1114 if (poller !== undefined) return
1115 poller = $.clock.every(POLL_MS, () => void pollAgents($))
1116}
1117
1118// A secondary control, drawn from a Text child so it rests in a theme colour:
1119// the Button's own dimColor is faint text. Its hover needs a keyed Box above it.
1120function quietButton(
1121 $: EngineInterface,
1122 e: ResolveInput,
1123 key: string,
1124 text: string,
1125 onPress: () => unknown,
1126 color: Color = QUIET,
1127): RenderElement {
1128 const { Button, Text } = $.ui.resolve(e)
1129
1130 return (
1131 <Button key={key} label={text} plain hover={{ inverse: false }} onPress={() => void onPress()}>
1132 <Text color={color} hover={{ color: 'text', bold: true }}>{text}</Text>
1133 </Button>
1134 )
1135}
1136
1137async function drawGrouped(
1138 $: EngineInterface,
1139 e: TranscriptInput,
1140 keys: readonly string[],
1141 draw: () => Promise<RenderElement>,
1142 canHead = true,
1143): Promise<RenderElement> {
1144 let found: string | null = null
1145 for (const key of keys) {
1146 found = await read($, memberOf(groupOf, { requestId: key }))
1147 if (found !== null) break
1148 }
1149 const head = found
1150 const [view, isOpen, isShowingAll] = await Promise.all([
1151 head === null ? Promise.resolve(null) : read($, memberOf(turnGroup, { requestId: head })),
1152 head === null ? Promise.resolve(false) : read($, memberOf(groupOpen, { requestId: head })),
1153 read($, showThoughts),
1154 ])
1155 const drawing = groupDrawing(view === null ? null : head, keys, isOpen, isShowingAll, canHead)
1156 if (drawing === 'engine' || head === null || view === null) return draw()
1157
1158 const { Box } = $.ui.resolve(e)
1159 if (drawing === 'hidden') return <Box />
1160 if (drawing === 'expanded-head') {
1161 const drawn = await draw()
1162 return (
1163 <Box flexDirection="column">
1164 <Box key="group-row">
1165 {quietButton($, e, 'group', `▾ hide · ${groupSummary(view)}`, () => update($, memberOf(groupOpen, { requestId: head }), () => false))}
1166 </Box>
1167 {drawn}
1168 </Box>
1169 )
1170 }
1171
1172 return (
1173 <Box key="group-row" paddingLeft={2}>
1174 {quietButton($, e, 'group', `▸ ${groupSummary(view)}`, () => update($, memberOf(groupOpen, { requestId: head }), () => true))}
1175 </Box>
1176 )
1177}
1178
1179// Plain, for a screen reader: no glyph that is only decoration, and no rule,
1180// which it reads out character by character.
1181function replyBlock($: EngineInterface, e: ResolveInput, block: ReplyBlock, columns: number, isPlain: boolean): RenderElement {
1182 const { Box, Code, Markdown, Text } = $.ui.resolve(e)
1183 const plain = (text: string) => text.replace(/\*\*|__|`/g, '')
1184 const rule = '─'.repeat(Math.max(1, columns))
1185
1186 switch (block.kind) {
1187 case 'heading':
1188 return block.level <= 2 && !isPlain ? (
1189 <Box flexDirection="column">
1190 <Text color={ORANGE} bold>{`◆ ${plain(block.text)}`}</Text>
1191 <Text color={ORANGE} dimColor wrap="truncate-end">{rule}</Text>
1192 </Box>
1193 ) : (
1194 <Text color={block.level <= 3 ? ORANGE : 'text'} bold>{plain(block.text)}</Text>
1195 )
1196 case 'list': {
1197 let ordinal = 0
1198 return (
1199 <Box flexDirection="column">
1200 {block.items.map(item => {types/index.d.ts 136 lines1export type GitOperation = 'rebase' | 'merge' | 'cherry-pick' | 'revert' | 'bisect'
2
3export type GitCommit = {
4 hash: string
5 subject: string
6 at: number
7}
8
9export type GitState = {
10 branch: string
11 isDetached: boolean
12 oid: string | null
13 upstream: string | null
14 ahead: number | null
15 behind: number | null
16 staged: number
17 modified: number
18 untracked: number
19 conflicts: number
20 stashes: number
21 operation: GitOperation | null
22 step: string | null
23 lastCommit: GitCommit | null
24 repo: string
25 subdir: string | null
26 isWorktree: boolean
27}
28
29export type KubeState = {
30 context: string
31 namespace: string | null
32}
33
34export type RateLimitGauge = {
35 label: string
36 percent: number
37 resetsAt: number | null
38}
39
40export type HudInfo = {
41 version: string
42 model: string
43 cwd: string
44 home: string | null
45 git: GitState | null
46 kube: KubeState | null
47 contextPercent: number | null
48 contextTokens: number | null
49 contextWindow: number
50 rateLimits: RateLimitGauge[]
51 costUsd: number | null
52 prompts: number | null
53 sessionStartedAt: number | null
54 fetchedAt: number
55 effortSetting: string | null
56 caveman: string | null
57 sessionTitle: string | null
58}
59
60export type AgentStatusLabel = 'running' | 'idle' | 'completed' | 'failed' | 'killed'
61
62export type AgentRow = {
63 id: string
64 toolUseId: string
65 description: string
66 type: string
67 model: string
68 isBackground: boolean
69 status: AgentStatusLabel
70 startedAt: number
71 endedAt: number | null
72 tools: number
73 lastTool: string | null
74 tokens: number | null
75}
76
77export type AgentToolOutcome = 'pending' | 'ok' | 'error'
78
79export type AgentLogEntry =
80 | { kind: 'prompt'; text: string }
81 | { kind: 'reply'; text: string }
82 | { kind: 'tool'; name: string; summary: string; outcome: AgentToolOutcome }
83
84export type AgentLogView = {
85 agentId: string
86 entries: AgentLogEntry[]
87 isDenied: boolean
88}
89
90export type ToolDefinition = {
91 name: string
92 description: string
93}
94
95export type ToolkitGroup = {
96 origin: 'repo' | 'user'
97 label: string
98 agents: ToolDefinition[]
99 skills: ToolDefinition[]
100}
101
102export type AccessMode = {
103 isScreenReader: boolean
104 isReducedMotion: boolean
105}
106
107export type TurnGroupView = {
108 head: string
109 texts: number
110 tools: Record<string, number>
111 last: string | null
112 isActive: boolean
113}
114
115declare module 'claude-code' {
116 interface PluginState {
117 'orange-hud': {
118 info: HudInfo | null
119 hint: string
120 agents: AgentRow[]
121 now: number
122 effort: string | null
123 groupOf: StateFamily<string | null>
124 turnGroup: StateFamily<TurnGroupView | null>
125 groupOpen: StateFamily<boolean>
126 showThoughts: boolean
127 isWorking: boolean
128 toolkit: ToolkitGroup[]
129 collapsed: string[]
130 viewing: string | null
131 agentLog: AgentLogView | null
132 access: AccessMode
133 }
134 }
135}
136