SLOPSHOPPER

session-radar

A live sidebar for long sessions: usage limits, context, agents, background shells and progress at a glance

paneguardcommandtoastpromptprocess
★ 3v0.3.1MITupdated 2026-10-25ibrahimkobeissy/claude-mods/mods/session-radar
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · session-radar
│ ┃ session-radar ✕ › fix the failing auth test and add an audit log call │ ┃ RADAR · Opus 5.5 │ ┃ ■ main ■ agents ■ mcp ■ skills ■ s ⏺ Read(src/auth.ts) │ ┃ ⎿ Read 6 lines │ ┃ ╭─────────────────────────────────────────── ⏺ Update(src/auth.ts) │ ┃ │ ▾ Opus 5.5 · main ⎿ Added 2 lines, removed 1 line │ ┃ │ effort — session 30m ⏺ Bash(bun test) │ ┃ │ ctx ▬▬▬▬▬▬▱▱▱▱▱▱ 49% 97k/200k ⎿ 3 pass, 1 fail │ ┃ │ 5h ▬▬▱▱▱▱▱▱ 31% │ ┃ │ dir /work/app ● Done. refresh now rejects expired claims and logs an audit event. │ ┃ ╰─────────────────────────────────────────── │ ┃ ╭─────────────────────────────────────────── ✻ Worked for 42s · done 4:20 PM │ ┃ │ ▾ AGENTS │ ┃ │ none yet › /radar │ ┃ ╰─────────────────────────────────────────── ⎿ session-radar: Radar closed. │ ┃ ╭─────────────────────────────────────────── │ ┃ │ ▾ MCP │ ┃ │ no MCP servers connected │ ┃ ╰─────────────────────────────────────────── │ ┃ ╭─────────────────────────────────────────── │ ┃ │ ▾ SKILLS │ ┃ │ none in use │ ┃ ╰─────────────────────────────────────────── │ ┃ ╭─────────────────────────────────────────── │ ┃ │ ▾ BACKGROUND │ ┃ │ nothing in the background ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Pane · session-radar
RADAR · Opus 5.5 ■ main ■ agents ■ mcp ■ skills ■ shells ╭──────────────────────────────────────────────────────╮ │ ▾ Opus 5.5 · main │ │ effort — session 30m │ │ ctx ▬▬▬▬▬▬▱▱▱▱▱▱ 49% 97k/200k │ │ 5h ▬▬▱▱▱▱▱▱ 31% │ │ dir /work/app │ ╰──────────────────────────────────────────────────────╯ ╭──────────────────────────────────────────────────────╮ │ ▾ AGENTS │ │ none yet │ ╰──────────────────────────────────────────────────────╯ ╭──────────────────────────────────────────────────────╮ │ ▾ MCP │ │ no MCP servers connected │ ╰──────────────────────────────────────────────────────╯ ╭──────────────────────────────────────────────────────╮ │ ▾ SKILLS │ │ none in use │ ╰──────────────────────────────────────────────────────╯ ╭──────────────────────────────────────────────────────╮ │ ▾ BACKGROUND │ │ nothing in the background │ ╰──────────────────────────────────────────────────────╯ ctrl+x tab to use · /radar to close
README

📡 session-radar

A live sidebar for long Claude Code sessions. Usage limits, context, agents, MCP servers, skills, background shells and progress, all in one small pane next to your transcript. It changes none of Claude Code's own behaviour.

<img src="assets/overview.png" alt="session-radar docked beside a real Claude Code session with four agents and two background shells" width="100%">

Install

/plugin marketplace add ibrahimkobeissy/claude-mods
/plugin install session-radar@claude-mods

It opens by itself when a session starts, wherever it fits as a sidebar. /radar opens or closes it at any time.

What it shows

Each part of the session gets its own colour-coded box:

BoxWhat's in it
⚠ Needs you (yellow)Shown while a permission prompt, a question or a plan approval is waiting, with who it's from and for how long
Main (orange)Model, effort, context gauge (turns yellow, then red with "compaction soon"), 5-hour and 7-day limits with reset times, when the 5h window fills at your current pace, the folder the session runs in, and your git branch or worktree
Agents (lavender)Up to four cards, one per subagent: task, type, context, tool calls, errors, branch or worktree, running time, and the MCP server or skill it is using right now. Select a card to see its last message
MCP (sky)Every connected MCP server with its tool count, in two rows (+ N more shows the rest). A server lights up while one of its tools is being called, with the tool and who called it
Skills (pink)The skills in use right now, by main or by agent. A skill counts as in use from when it is invoked until that agent's turn ends, so when Claude is idle nothing is lit. + N available lists every skill, the ones in use highlighted
Background (green)The background shells and monitors the footer counts (1 shell · 4 monitors), running ones first, each with its process ID (teal), including those subagents started, plus scheduled cron jobs and /loop wakeups. Select one to open its live output, exit code and test result
Progress (purple)The task list and the approved plan, shown only when there is one

You also get a toast when a background shell or agent finishes or fails.

A background shell, opened

<img src="assets/shell.png" alt="A background shell's live output in the radar pane" width="100%">

You get the last lines of output, refreshed every 2 seconds. Copy puts them on your clipboard. Stop calls TaskStop, which asks for permission like any other tool call.

Keys

The radar never takes over your keyboard. While you type at the prompt, every Claude Code shortcut works as it always does.

KeyWhereDoes
ctrl+x tabpromptMoves the keyboard into the pane (press it again if another plugin's band is showing)
tab / shift+tabpaneNext / previous row
enterpaneOpen a shell, show an agent's last message, fold or unfold a box
↑ ↓paneScroll
b / c / sshell viewBack / copy / stop
escpaneBack to the prompt

You can also click rows.

Options

OptionDefault
autoOpentrueOpen the radar when a session starts. When opened this way it only appears where it fits as a sidebar (144+ columns); in a narrower terminal, type /radar

Set it from /plugin → session-radar → configure.

Good to know

  • The pane docks as a sidebar in the fullscreen layout. In a narrow terminal it opens above the prompt instead and scrolls.
  • Limits appear once the first API response reports them, and only on a Claude subscription. The 5h forecast appears after about 5 minutes of usage data.
  • An agent's context is shown in tokens (from its last model request), since agents can run on different models.
  • It tracks what happens while it's loaded. Shells and agents started before you installed it won't show up.

Permissions and privacy

It reads your session's own events and runs git rev-parse locally to find branches. While a background shell runs it reads the last line of its output file (where Claude Code writes [exited with code N]) and runs ps to find its process ID. No network access, and nothing is written to disk.

Develop

claude --plugin-dir mods/session-radar       # try it live; saves hot-reload
scripts/validate.sh mods/session-radar       # validate + run tests/
Source 3 files
hooks/register.tsx 1106 lines
1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, Register, Timer } from 'claude-code'
3
4import type { AgentRow, AgentStatusName, Catalog, Cron, InUse, Main, ProgressItem, ShellRow, Usage, View } from '../types'
5import {
6  addSamples, clip, clock, duration, effortMeter, exitTrailer, findPid, isKilledTrailer, gauge, modelName, shortPath, stopwatch, exitCodeOf, forecast,
7  lastLine, limitLabel, mcpParts, outputPathOf, pack, parentDir, parsePs, parseTails, parseTaskNotice, resetLabel, tail, testSummary, tokens,
8} from './lib'
9import type { TaskNotice } from './lib'
10
11const PANE = 'session-radar'
12const WAKEUP = 'wakeup'
13const TICK_MS = 5000
14const OUTPUT_MS = 2000
15// A monitor's expiry notice gets this long to arrive before its deadline alone ends it.
16const EXPIRY_GRACE_MS = 30_000
17// Branches are read with git, so not on every tick.
18const BRANCH_EVERY_TICKS = 6
19const MAX_OUTPUT_LINES = 200
20const MAX_CARDS = 4
21// The MCP and skill lists show this many rows until unrolled.
22const LIST_ROWS = 2
23const ACTIVE_ROWS = 3
24const C = {
25  main: '#d97757', agents: '#a5b4fc', shells: '#4ade80', progress: '#c084fc',
26  warn: '#facc15', bad: '#f87171', branch: '#7ab7ff', mcp: '#38bdf8', skills: '#f472b6', pid: '#5eead4',
27} as const
28const FINISHED_SHELLS_SHOWN = 3
29// Beyond this the newest live tasks show and the rest are counted.
30const LIVE_SHELLS_SHOWN = 8
31const ENDED: ReadonlySet<AgentStatusName> = new Set(['completed', 'failed', 'killed'])
32const WAITING_NOTIFICATIONS = new Set(['permission_prompt', 'elicitation_dialog'])
33
34const usage = atom({ plugin: 'session-radar', key: 'usage' } as const, null)
35const samples = atom({ plugin: 'session-radar', key: 'samples' } as const, [])
36const main = atom({ plugin: 'session-radar', key: 'main' } as const, { isWorktree: false })
37const agents = atom({ plugin: 'session-radar', key: 'agents' } as const, {})
38const shells = atom({ plugin: 'session-radar', key: 'shells' } as const, {})
39const crons = atom({ plugin: 'session-radar', key: 'crons' } as const, [])
40const progress = atom({ plugin: 'session-radar', key: 'progress' } as const, { todos: [], tasks: [] })
41const needs = atom({ plugin: 'session-radar', key: 'needs' } as const, null)
42const view = atom({ plugin: 'session-radar', key: 'view' } as const, { screen: 'overview', folded: [] })
43const output = atom({ plugin: 'session-radar', key: 'output' } as const, null)
44const tick = atom({ plugin: 'session-radar', key: 'tick' } as const, 0)
45const catalog = atom({ plugin: 'session-radar', key: 'catalog' } as const, { servers: [], toolServer: {}, skills: [] })
46const inUse = atom({ plugin: 'session-radar', key: 'inUse' } as const, {})
47
48let ticker: Timer | undefined
49let outputTimer: Timer | undefined
50let ticks = 0
51// The radar's own version, from its plugin.json; '' when it cannot be read.
52let version: string | undefined
53// The engine's own process, the parent of the shells it starts; null when it cannot be read.
54let enginePid: number | null | undefined
55// Tasks whose process was missing on the last check.
56const goneOnce = new Set<string>()
57// Agent tool calls that asked for a worktree, until agent.spawn names the agent.
58const worktreeCalls = new Set<string>()
59const branchOf = new Map<string, { branch?: string; isWorktree: boolean }>()
60// Skill tool calls in flight, by skill name: their skill.prompt is already counted.
61const skillCalls = new Map<string, number>()
62
63// ── reading the world ────────────────────────────────────────────────────────
64
65async function readBranch($: EngineInterface, cwd: string) {
66  // Absolute paths: from a subfolder git prints the git dir absolute and the
67  // common dir relative, which would read as a worktree. Git before 2.31 lacks
68  // the flag, so the branch alone is asked for then.
69  const git = (args: string[]) => $.process.run(['git', '-C', cwd, ...args], { timeoutMs: 3000 }).catch(() => undefined)
70  const ran = await git(['rev-parse', '--abbrev-ref', 'HEAD', '--path-format=absolute', '--git-dir', '--git-common-dir'])
71  const out = ran?.exitCode === 0 ? ran : await git(['rev-parse', '--abbrev-ref', 'HEAD'])
72  if (!out || out.exitCode !== 0) return { isWorktree: false }
73  const [head, gitDir, commonDir] = out.stdout.trim().split('\n')
74  const found = { branch: head === 'HEAD' ? 'detached' : head, isWorktree: Boolean(gitDir && commonDir && gitDir !== commonDir) }
75  branchOf.set(cwd, found)
76  return found
77}
78
79async function refreshBranches($: EngineInterface) {
80  const cwd = await $.session.cwd()
81  const found = await readBranch($, cwd)
82  await update($, main, (m): Main => ({ ...m, cwd, ...found }))
83  const list = Object.values(await read($, agents)).filter(a => a.cwd && !ENDED.has(a.status))
84  for (const a of list) {
85    const b = await readBranch($, a.cwd!)
86    await update($, agents, all => (all[a.id] ? { ...all, [a.id]: { ...all[a.id]!, ...b } } : all))
87  }
88}
89
90async function saveUsage($: EngineInterface, u: Omit<Usage, 'startedAt'>) {
91  const now = await $.clock.now()
92  await update($, usage, (old): Usage => ({ startedAt: old?.startedAt ?? now, ...u }))
93  await update($, samples, s => addSamples(s, u.rateLimits, now))
94}
95
96// The servers and skills the context lists, estimated locally (no API call).
97async function refreshCatalog($: EngineInterface) {
98  const b = (await $.session.usage({ breakdown: 'summary' }).catch(() => undefined))?.context.breakdown
99  if (!b) return
100  const count = new Map<string, number>()
101  const toolServer: Record<string, string> = {}
102  for (const t of b.mcpTools) {
103    count.set(t.serverName, (count.get(t.serverName) ?? 0) + 1)
104    toolServer[t.name] = t.serverName
105  }
106  const servers = [...count].map(([name, tools]) => ({ name, tools })).sort((x, y) => x.name.localeCompare(y.name))
107  const skills = (b.skills?.skillFrontmatter ?? []).map(s => s.name).sort()
108  await update($, catalog, (): Catalog => ({ servers, toolServer, skills }))
109}
110
111async function startUse($: EngineInterface, use: Omit<InUse, 'startedAt'>) {
112  const startedAt = await $.clock.now()
113  await update($, inUse, all => ({ ...all, [use.id]: { ...use, startedAt } }))
114}
115
116function endUse($: EngineInterface, keep: (x: InUse) => boolean) {
117  return update($, inUse, all => {
118    const gone = Object.values(all).filter(x => !keep(x))
119    if (gone.length === 0) return all
120    const next = { ...all }
121    for (const x of gone) delete next[x.id]
122    return next
123  })
124}
125
126// A loop's turn is over: what it used is no longer in use.
127function endTurn($: EngineInterface, agentId: string | undefined) {
128  return endUse($, x => x.agentId !== agentId)
129}
130
131async function pollAgents($: EngineInterface) {
132  const list = await $.agent.list().catch(() => [])
133  const now = await $.clock.now()
134  const before = await read($, agents)
135  await update($, agents, all => {
136    let next = all
137    for (const info of list) {
138      const row = next[info.id]
139      const status = info.status as AgentStatusName
140      if (!row) {
141        next = {
142          ...next,
143          [info.id]: {
144            id: info.id, type: info.type, description: info.description, status, startedAt: now,
145            tools: 0, errors: 0, isWorktree: false, endedAt: ENDED.has(status) ? now : undefined,
146          },
147        }
148      } else if (row.status !== status) {
149        next = { ...next, [info.id]: { ...row, status, endedAt: ENDED.has(status) ? (row.endedAt ?? now) : undefined } }
150      }
151    }
152    return next
153  })
154  for (const info of list) {
155    const was = before[info.id]
156    if (was && !ENDED.has(was.status) && ENDED.has(info.status as AgentStatusName)) {
157      await announceAgentEnd($, was, info.status as AgentStatusName, now)
158    }
159  }
160}
161
162async function announceAgentEnd($: EngineInterface, agent: AgentRow, status: AgentStatusName, now: number) {
163  const word = status === 'completed' ? 'completed' : status
164  $.ui.toast(`${status === 'completed' ? '✓' : '✗'} agent ${word}: ${clip(agent.description, 40)}`)
165  await endTurn($, agent.id)
166  // The engine stops a foreground subagent's background shells with it.
167  await update($, shells, all => {
168    let next = all
169    for (const x of Object.values(all)) {
170      if (x.agentId === agent.id && x.endsWithAgent && x.status === 'running') {
171        next = { ...next, [x.id]: { ...x, status: 'completed', endedAt: now, summary: 'ended with its agent' } }
172      }
173    }
174    return next
175  })
176}
177
178// A Stop names every task still in flight, the list the footer counts from: a
179// row it leaves out ended without a notice reaching us (a monitor's timeout, a
180// task stopped with its agent), so it is marked done.
181async function reconcileShells($: EngineInterface, inFlight: readonly { id: string }[] | undefined) {
182  if (!inFlight) return
183  const live = new Set(inFlight.map(t => t.id))
184  const now = await $.clock.now()
185  await update($, shells, all => {
186    let next = all
187    for (const x of Object.values(all)) {
188      if (x.status === 'running' && !live.has(x.id)) next = { ...next, [x.id]: { ...x, status: 'completed', endedAt: now, summary: x.summary ?? 'ended' } }
189    }
190    return next
191  })
192}
193
194// A background task ended, however we heard: the row is marked once, with one toast.
195// An end we only inferred, not one the engine reported, is marked without a toast.
196async function finishShell($: EngineInterface, id: string, end: { status: ShellRow['status']; summary: string; exitCode?: number; endedAt: number; outputPath?: string }, { quiet = false } = {}) {
197  const shell = (await read($, shells))[id]
198  if (!shell || shell.status !== 'running') return
199  goneOnce.delete(id)
200  await patchShell($, id, s => ({ ...s, ...end, outputPath: s.outputPath ?? end.outputPath }))
201  if (quiet) return
202  const code = end.exitCode ?? exitCodeOf(end.summary)
203  $.ui.toast(`${end.status === 'completed' ? '✓' : '✗'} ${shell.kind} ${end.status}: ${clip(shell.command, 40)}${code !== undefined ? ` (exit ${code})` : ''}`)
204}
205
206async function readEnginePid($: EngineInterface) {
207  const ran = await $.process.run(['sh', '-c', 'echo $PPID'], { timeoutMs: 3000 }).catch(() => undefined)
208  const pid = Number(ran?.stdout.trim())
209  return ran?.exitCode === 0 && pid > 1 ? pid : null
210}
211
212// The engine's word on a live task, read from the task itself rather than
213// waited for: its output file's last line once it exits, and its process id.
214async function checkShells($: EngineInterface, only?: string) {
215  const running = async () => Object.values(await read($, shells)).filter(s => s.status === 'running' && (only === undefined || s.id === only))
216  let live = await running()
217  // A monitor's result names no output file; it sits beside the others.
218  const dir = tasksDir(Object.values(await read($, shells)))
219  if (dir && live.some(s => !s.outputPath)) {
220    for (const s of live) if (!s.outputPath) await patchShell($, s.id, x => ({ ...x, outputPath: `${dir}/${x.id}.output` }))
221    live = await running()
222  }
223  const files = live.flatMap(s => (s.outputPath ? [s.outputPath] : []))
224  if (files.length) {
225    const ran = await $.process.run(['tail', '-n', '1', '--', ...files], { timeoutMs: 3000 }).catch(() => undefined)
226    const last = parseTails(ran?.stdout ?? '', files)
227    for (const s of live) {
228      const line = s.outputPath ? last.get(s.outputPath) : undefined
229      const code = exitTrailer(line)
230      const killed = isKilledTrailer(line)
231      if (code === undefined && !killed) continue
232      const endedAt = (await $.fs.stat(s.outputPath!).catch(() => undefined))?.mtimeMs || (await $.clock.now())
233      if (killed) await finishShell($, s.id, { status: 'killed', summary: 'killed', endedAt })
234      else await finishShell($, s.id, { status: code === 0 ? 'completed' : 'failed', summary: `exit code ${code}`, exitCode: code, endedAt })
235    }
236  }
237  // A task can end with no notice reaching us (a subagent's, once that agent is
238  // gone): a monitor past its deadline, or a process that is gone, has ended.
239  const now = await $.clock.now()
240  for (const s of live) {
241    if (s.expiresAt !== undefined && now > s.expiresAt + EXPIRY_GRACE_MS) await finishShell($, s.id, { status: 'completed', summary: 'expired', endedAt: s.expiresAt }, { quiet: true })
242  }
243  live = await running()
244  const unknown = live.filter(s => s.pid === undefined && s.command)
245  const known = live.filter(s => s.pid !== undefined)
246  if (unknown.length === 0 && known.length === 0) return
247  enginePid ??= await readEnginePid($)
248  const ps = await $.process.run(['ps', '-A', '-ww', '-o', 'pid=,ppid=,args='], { timeoutMs: 3000 }).catch(() => undefined)
249  if (!ps || ps.exitCode !== 0) return
250  const procs = parsePs(ps.stdout)
251  const alive = new Set(procs.map(p => p.pid))
252  // Gone on two checks in a row, so the exit line written as it ends is read first.
253  for (const s of known) {
254    if (alive.has(s.pid!)) goneOnce.delete(s.id)
255    else if (goneOnce.has(s.id)) await finishShell($, s.id, { status: 'completed', summary: 'ended', endedAt: now }, { quiet: true })
256    else goneOnce.add(s.id)
257  }
258  const taken = new Set(Object.values(await read($, shells)).flatMap(s => (s.pid ? [s.pid] : [])))
259  for (const s of unknown) {
260    const pid = findPid(procs, s.command, enginePid ?? undefined, taken)
261    if (pid === undefined) continue
262    taken.add(pid)
263    await patchShell($, s.id, x => ({ ...x, pid }))
264  }
265}
266
267// The folder the engine writes this session's task output to, from any task that named it.
268function tasksDir(rows: readonly ShellRow[]) {
269  const known = rows.find(s => s.outputPath)?.outputPath
270  return known ? parentDir(known) : undefined
271}
272
273// "1 shell · 4 monitors", the way the footer counts what runs in the background.
274function backgroundCount(live: readonly ShellRow[]) {
275  const shells = live.filter(x => x.kind === 'shell').length
276  const others = live.length - shells
277  const parts = [shells ? `${shells} shell${shells === 1 ? '' : 's'}` : '', others ? `${others} monitor${others === 1 ? '' : 's'}` : '']
278  return parts.filter(Boolean).join(' · ')
279}
280
281async function onTick($: EngineInterface) {
282  ticks += 1
283  await update($, tick, () => ticks)
284  await pollAgents($)
285  await checkShells($)
286  if (ticks % BRANCH_EVERY_TICKS === 0) {
287    await refreshBranches($)
288    await refreshCatalog($)
289  }
290}
291
292async function readOutput($: EngineInterface, shell: ShellRow, count: number) {
293  if (!shell.outputPath) return { lines: [], error: 'No output file for this task.' }
294  try {
295    const stat = await $.fs.stat(shell.outputPath)
296    if (stat.size > 2 * 1024 * 1024) {
297      const ran = await $.process.run(['tail', '-n', String(count), shell.outputPath], { timeoutMs: 3000 })
298      return { lines: tail(ran.stdout, count) }
299    }
300    return { lines: tail(await $.fs.read(shell.outputPath), count) }
301  } catch {
302    return { lines: [], error: 'The output file is gone.' }
303  }
304}
305
306async function refreshOutput($: EngineInterface) {
307  const v = await read($, view)
308  const shell = v.shellId ? (await read($, shells))[v.shellId] : undefined
309  if (v.screen !== 'shell' || !shell) return
310  if (shell.status === 'running') await checkShells($, shell.id)
311  const got = await readOutput($, shell, MAX_OUTPUT_LINES)
312  const at = await $.clock.now()
313  await update($, output, () => ({ shellId: shell.id, at, ...got }))
314}
315
316async function openShell($: EngineInterface, id: string) {
317  await update($, output, () => null)
318  await update($, view, (v): View => ({ ...v, screen: 'shell', shellId: id }))
319  outputTimer?.cancel()
320  outputTimer = $.clock.every(OUTPUT_MS, () => void refreshOutput($))
321  await refreshOutput($)
322}
323
324async function back($: EngineInterface) {
325  outputTimer?.cancel()
326  outputTimer = undefined
327  await update($, view, (v): View => ({ ...v, screen: 'overview', shellId: undefined }))
328}
329
330async function setNeeds($: EngineInterface, agentId: string | undefined, what: string) {
331  const who = agentId ? ((await read($, agents))[agentId]?.type ?? 'agent') : 'main'
332  const since = await $.clock.now()
333  await update($, needs, () => ({ who, agentId, what, since }))
334}
335
336async function clearNeeds($: EngineInterface, agentId?: string | null) {
337  await update($, needs, n => (n && (agentId === null || n.agentId === agentId) ? null : n))
338}
339
340function patchAgent($: EngineInterface, id: string | undefined, fn: (a: AgentRow) => AgentRow) {
341  if (!id) return Promise.resolve()
342  return update($, agents, all => (all[id] ? { ...all, [id]: fn(all[id]!) } : all))
343}
344
345function patchShell($: EngineInterface, id: string, fn: (s: ShellRow) => ShellRow) {
346  return update($, shells, all => (all[id] ? { ...all, [id]: fn(all[id]!) } : all))
347}
348
349async function togglePane($: EngineInterface) {
350  const isOpen = (await $.ui.panes()).some(p => p.id === PANE)
351  if (isOpen) {
352    await $.ui.close({ id: PANE })
353    return 'Radar closed.'
354  }
355  await $.ui.open({ id: PANE, title: 'Radar' })
356  return 'Radar opened. ctrl+x tab moves the keyboard into it; Esc hands it back.'
357}
358
359async function applyNotices($: EngineInterface, text: string) {
360  for (const part of text.split('</task-notification>')) {
361    const notice = parseTaskNotice(part)
362    if (notice) await applyNotice($, notice)
363  }
364}
365
366async function applyNotice($: EngineInterface, notice: TaskNotice) {
367  const now = await $.clock.now()
368  const shell = (await read($, shells))[notice.id]
369  const agent = (await read($, agents))[notice.id]
370  if (shell && shell.status === 'running') {
371    const code = exitCodeOf(notice.summary)
372    await finishShell($, notice.id, {
373      status: notice.status, summary: notice.summary, endedAt: now, outputPath: notice.outputPath, exitCode: code === undefined ? undefined : Number(code),
374    })
375  } else if (agent && !ENDED.has(agent.status)) {
376    const status: AgentStatusName = notice.status
377    await patchAgent($, notice.id, a => ({ ...a, status, endedAt: now }))
378    await announceAgentEnd($, agent, status, now)
379  }
380}
381
382async function readVersion($: EngineInterface) {
383  const text = await $.fs.read(`${$.plugin.root}/.claude-plugin/plugin.json`).catch(() => '')
384  try {
385    const v = (JSON.parse(text) as { version?: unknown }).version
386    return typeof v === 'string' ? v : ''
387  } catch {
388    return ''
389  }
390}
391
392// ── hooks ────────────────────────────────────────────────────────────────────
393
394export const register: Register = (on, options) => {
395  on('session.start', async ($, e, next) => {
396    const result = await next(e)
397    await $.command.register({ name: 'radar', description: 'Toggle the session radar sidebar' })
398    const u = await $.session.usage().catch(() => undefined)
399    if (u) {
400      await update($, usage, (): Usage => ({
401        startedAt: u.startedAt, contextTokens: u.context.tokens, contextWindow: u.context.window,
402        contextPercent: u.context.percent, rateLimits: u.rateLimits,
403      }))
404    }
405    const model = await $.session.model().catch(() => undefined)
406    await update($, main, (m): Main => ({ ...m, model: m.model ?? model }))
407    ticker?.cancel()
408    ticker = $.clock.every(TICK_MS, () => void onTick($))
409    const cwd = await $.session.cwd().catch(() => undefined)
410    await update($, main, (m): Main => ({ ...m, cwd: m.cwd ?? cwd }))
411    await refreshBranches($)
412    await refreshCatalog($)
413    if (options.autoOpen === true) void $.ui.open({ id: PANE, title: 'Radar' })
414    return result
415  })
416
417  on('command.run', { command: 'radar' }, async $ => ({ text: await togglePane($) }))
418
419  on('ui.close', async ($, e, next) => {
420    if (e.id === PANE) await back($)
421    return next(e)
422  })
423
424  on('session.measure', async ($, e, next) => {
425    const result = await next(e)
426    await saveUsage($, {
427      contextTokens: e.context.tokens, contextWindow: e.context.window, contextPercent: e.context.percent,
428      rateLimits: e.rateLimits,
429    })
430    return result
431  })
432
433  // Each model request: the main loop's model and effort, an agent's context and words.
434  on('turn.step', async function* ($, e, next) {
435    const result = yield* next(e)
436    if (e.agentId === undefined) {
437      const effort = e.effort === undefined ? undefined : String(e.effort)
438      await update($, main, (m): Main => ({ ...m, model: e.model, effort }))
439    } else {
440      const u = result.usage
441      const said = lastLine(result.answer)
442      await patchAgent($, e.agentId, a => ({
443        ...a,
444        model: a.model ?? e.model,
445        contextTokens: u ? u.input_tokens + u.cache_read_input_tokens + u.cache_creation_input_tokens : a.contextTokens,
446        lastMessage: said || a.lastMessage,
447      }))
448    }
449    return result
450  })
451
452  on('tool.call', { tool: 'Agent' }, async ($, e, next) => {
453    if (e.isolation === 'worktree') worktreeCalls.add(e.tool_use_id)
454    return next(e)
455  })
456
457  on('agent.spawn', async ($, e, next) => {
458    const result = await next(e)
459    if (result.agentId) {
460      const id = result.agentId
461      const startedAt = await $.clock.now()
462      const isWorktree = worktreeCalls.delete(e.tool_use_id)
463      await update($, agents, (all): Record<string, AgentRow> => ({
464        ...all,
465        [id]: {
466          id, type: e.subagentType, description: e.description, status: 'running', model: result.model,
467          startedAt, tools: all[id]?.tools ?? 0, errors: 0, isWorktree, cwd: e.cwd,
468        },
469      }))
470    }
471    return result
472  })
473
474  // Every tool call: counts per agent, a question or a dialog answered, and an
475  // MCP call in use from its start until it returns.
476  on('tool.call', async ($, e, next) => {
477    if (e.agentId) await patchAgent($, e.agentId, a => ({ ...a, tools: a.tools + 1 }))
478    if (e.tool === 'AskUserQuestion') await setNeeds($, e.agentId, 'a question for you')
479    if (e.tool === 'ExitPlanMode') await setNeeds($, e.agentId, 'plan approval')
480    const mcp = mcpParts(e.tool)
481    if (mcp) {
482      const known = (await read($, catalog)).toolServer[e.tool]
483      await startUse($, { id: e.tool_use_id, kind: 'mcp', name: known ?? mcp.server, tool: mcp.tool, agentId: e.agentId })
484    }
485    let ran: Awaited<ReturnType<typeof next>>
486    try {
487      ran = await next(e)
488    } finally {
489      if (mcp) await endUse($, x => x.id !== e.tool_use_id)
490    }
491    if (e.agentId && ran.isError === true) await patchAgent($, e.agentId, a => ({ ...a, errors: a.errors + 1 }))
492    await clearNeeds($, e.agentId)
493    return ran
494  })
495
496  // A skill is in use from its call until the turn of the loop that called it ends.
497  on('tool.call', { tool: 'Skill' }, async ($, e, next) => {
498    skillCalls.set(e.skill, (skillCalls.get(e.skill) ?? 0) + 1)
499    try {
500      const ran = await next(e)
501      if (ran.deny === undefined && ran.isError !== true) await startUse($, { id: e.tool_use_id, kind: 'skill', name: e.skill, agentId: e.agentId })
502      return ran
503    } finally {
504      const left = (skillCalls.get(e.skill) ?? 1) - 1
505      if (left > 0) skillCalls.set(e.skill, left)
506      else skillCalls.delete(e.skill)
507    }
508  })
509
510  // A skill typed as /name expands with no Skill tool call: it runs in the main loop.
511  on('skill.prompt', async ($, e, next) => {
512    const result = await next(e)
513    if (!skillCalls.has(e.skill)) await startUse($, { id: `typed-${e.skill}`, kind: 'skill', name: e.skill })
514    return result
515  })
516
517  // A background shell: Bash with run_in_background, or one the person backgrounded.
518  on('tool.call', { tool: 'Bash' }, async ($, e, next) => {
519    const ran = await next(e)
520    const result = ran.deny === undefined && ran.isError !== true ? ran.result : undefined
521    const id = result?.backgroundTaskId
522    if (id) {
523      const dir = tasksDir(Object.values(await read($, shells)))
524      const outputPath = outputPathOf(ran.text) ?? (dir ? `${dir}/${id}.output` : undefined)
525      const startedAt = await $.clock.now()
526      const endsWithAgent = result.backgroundEndsWithFinalResponse === true
527      await update($, shells, (all): Record<string, ShellRow> => ({
528        ...all,
529        [id]: { id, kind: 'shell', command: e.command, description: e.description, startedAt, status: 'running', outputPath, agentId: e.agentId, endsWithAgent },
530      }))
531    }
532    return ran
533  })
534
535  // A monitor: a background watch the footer counts beside the shells.
536  on('tool.call', { tool: 'Monitor' }, async ($, e, next) => {
537    const ran = await next(e)
538    const result = ran.deny === undefined && ran.isError !== true ? ran.result : undefined
539    const id = result?.taskId
540    if (id) {
541      const startedAt = await $.clock.now()
542      const command = e.command ?? e.ws?.url ?? e.description
543      const dir = tasksDir(Object.values(await read($, shells)))
544      const outputPath = outputPathOf(ran.text) ?? (dir ? `${dir}/${id}.output` : undefined)
545      // 0 is a persistent watch, with no deadline.
546      const expiresAt = result.timeoutMs > 0 && !result.persistent ? startedAt + result.timeoutMs : undefined
547      await update($, shells, (all): Record<string, ShellRow> => ({
548        ...all,
549        [id]: { id, kind: 'monitor', command, description: e.description, startedAt, status: 'running', outputPath, agentId: e.agentId, expiresAt },
550      }))
551    }
552    return ran
553  })
554
555  on('tool.call', { tool: 'TodoWrite' }, async ($, e, next) => {
556    const ran = await next(e)
557    if (e.agentId === undefined && ran.deny === undefined && ran.isError !== true) {
558      const todos = e.todos.map((t, i): ProgressItem => ({
559        id: String(i), text: t.status === 'in_progress' ? t.activeForm || t.content : t.content, status: t.status,
560      }))
561      await update($, progress, p => ({ ...p, todos }))
562    }
563    return ran
564  })
565
566  on('tool.call', { tool: 'TaskCreate' }, async ($, e, next) => {
567    const ran = await next(e)
568    const task = ran.deny === undefined && ran.isError !== true ? ran.result?.task : undefined
569    if (e.agentId === undefined && task) {
570      const item: ProgressItem = { id: task.id, text: task.subject, status: 'pending' }
571      await update($, progress, p => ({ ...p, tasks: [...p.tasks, item] }))
572    }
573    return ran
574  })
575
576  on('tool.call', { tool: 'TaskUpdate' }, async ($, e, next) => {
577    const ran = await next(e)
578    if (e.agentId === undefined && ran.deny === undefined && ran.isError !== true) {
579      const status = e.status
580      await update($, progress, p => ({
581        ...p,
582        tasks: status === 'deleted'
583          ? p.tasks.filter(t => t.id !== e.taskId)
584          : p.tasks.map((t): ProgressItem => (t.id === e.taskId ? { ...t, text: e.subject ?? t.text, status: status ?? t.status } : t)),
585      }))
586    }
587    return ran
588  })
589
590  on('tool.call', { tool: 'ExitPlanMode' }, async ($, e, next) => {
591    const ran = await next(e)
592    const plan = ran.deny === undefined && ran.isError !== true ? ran.result?.plan : undefined
593    if (e.agentId === undefined && plan) {
594      const title = plan.split('\n').map(l => l.replace(/^#+\s*/, '').trim()).find(Boolean)
595      await update($, progress, p => ({ ...p, plan: title }))
596    }
597    return ran
598  })
599
600  // An agent working in a directory of its own (a worktree): its tool calls say where.
601  on('classic.PostToolUse', async ($, e, next) => {
602    const id = e.agent_id
603    if (id) {
604      const row = (await read($, agents))[id]
605      if (row && row.cwd !== e.cwd) {
606        const b = branchOf.get(e.cwd) ?? (await readBranch($, e.cwd))
607        await patchAgent($, id, a => ({ ...a, cwd: e.cwd, ...b, isWorktree: a.isWorktree || b.isWorktree }))
608      }
609    }
610    return next(e)
611  })
612
613  on('classic.Notification', async ($, e, next) => {
614    if (WAITING_NOTIFICATIONS.has(e.notification_type)) await setNeeds($, e.agent_id, e.message || 'permission needed')
615    return next(e)
616  })
617
618  on('prompt.submit', async ($, e, next) => {
619    if (e.origin.kind === 'task-notification') await applyNotices($, e.text)
620    else if (e.origin.kind === 'scheduled-trigger') await update($, crons, list => list.filter(c => c.recurring || (c.id !== WAKEUP && c.prompt.trim() !== e.text.trim())))
621    else {
622      await clearNeeds($, null)
623      // A new prompt: the last turn is over even if it was interrupted before its Stop.
624      await endTurn($, undefined)
625    }
626    return next(e)
627  })
628
629  on('classic.SubagentStop', async ($, e, next) => {
630    if (e.last_assistant_message) {
631      await patchAgent($, e.agent_id, a => ({ ...a, lastMessage: lastLine(e.last_assistant_message ?? '') }))
632    }
633    await reconcileShells($, e.background_tasks)
634    await endTurn($, e.agent_id)
635    return next(e)
636  })
637
638  on('classic.Stop', async ($, e, next) => {
639    await reconcileShells($, e.background_tasks)
640    await endTurn($, undefined)
641    return next(e)
642  })
643
644  // Scheduled work: cron jobs and /loop wakeups the model sets up.
645  on('tool.call', { tool: 'CronCreate' }, async ($, e, next) => {
646    const ran = await next(e)
647    const job = ran.deny === undefined && ran.isError !== true ? ran.result : undefined
648    if (job) {
649      const cron: Cron = { id: job.id, schedule: job.humanSchedule, recurring: job.recurring, prompt: e.prompt }
650      await update($, crons, list => [...list.filter(c => c.id !== job.id), cron])
651    }
652    return ran
653  })
654
655  on('tool.call', { tool: 'CronDelete' }, async ($, e, next) => {
656    const ran = await next(e)
657    if (ran.deny === undefined && ran.isError !== true) await update($, crons, list => list.filter(c => c.id !== e.id))
658    return ran
659  })
660
661  on('tool.call', { tool: 'ScheduleWakeup' }, async ($, e, next) => {
662    const ran = await next(e)
663    if (ran.deny === undefined && ran.isError !== true) {
664      const others = (list: readonly Cron[]) => list.filter(c => c.id !== WAKEUP)
665      if (e.stop || !e.delaySeconds) {
666        await update($, crons, list => others(list))
667      } else {
668        const at = (await $.clock.now()) + Math.min(3600, Math.max(60, e.delaySeconds)) * 1000
669        const cron: Cron = { id: WAKEUP, schedule: `at ${clock(at)}`, recurring: false, prompt: e.reason || e.prompt || 'wakeup', at }
670        await update($, crons, list => [...others(list), cron])
671      }
672    }
673    return ran
674  })
675
676  // A stopped task, by the model or the Stop button.
677  on('tool.call', { tool: 'TaskStop' }, async ($, e, next) => {
678    const ran = await next(e)
679    const id = ran.deny === undefined && ran.isError !== true ? (ran.result?.task_id ?? e.task_id ?? e.shell_id) : undefined
680    if (id) {
681      const now = await $.clock.now()
682      await patchShell($, id, s => (s.status === 'running' ? { ...s, status: 'killed', endedAt: now } : s))
683      await patchAgent($, id, a => (ENDED.has(a.status) ? a : { ...a, status: 'killed', endedAt: now }))
684    }
685    return ran
686  })
687
688  // A background task ended: its notice reaches the session one of three ways.
689  on('session.receive', async ($, e, next) => {
690    if (e.origin.kind === 'task-notification') await applyNotices($, e.text)
691    return next(e)
692  })
693
694  // Notices also arrive mid-turn as queued attachments, and a subagent's own
695  // shells report to that subagent: any row, in any conversation, can carry one.
696  // Only rows that are a notice: a file read or a reply may quote one.
697  on('session.append', async ($, e, next) => {
698    if (e.message.role === 'user' && e.door !== 'tool-result') {
699      const text = e.message.content.map(b => (b.type === 'text' ? b.text : '')).join('\n').trim()
700      if (text.startsWith('<task-notification>')) await applyNotices($, text)
701    }
702    return next(e)
703  })
704
705  // ── drawing ────────────────────────────────────────────────────────────────
706
707  on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
708    const { Box, Text, Button } = $.ui.resolve(e)
709    const W = Math.max(28, e.props.bodyColumns)
710    const IN = W - 4
711    const v = await read($, view)
712    await read($, tick)
713    const now = await $.clock.now()
714    version ??= await readVersion($)
715
716    const toggle = (section: string) => () =>
717      void update($, view, x => ({
718        ...x, folded: x.folded.includes(section) ? x.folded.filter(s => s !== section) : [...x.folded, section],
719      }))
720    const isFolded = (section: string) => v.folded.includes(section)
721
722    // A section: a rounded box in the section's color, its title on the first row.
723    const box = (section: string, color: string, title: string, right: JSX.Element | string | null, body: JSX.Element | null) => (
724      <Box key={`box-${section}`} flexDirection="column" borderStyle="round" borderColor={color} paddingX={1} width={W}>
725        <Box justifyContent="space-between" width={IN}>
726          <Box>
727            <Button key={`fold-${section}`} plain dimColor label={isFolded(section) ? '▸ ' : '▾ '} onPress={toggle(section)} />
728            <Text color={color} bold>{clip(title, IN - 14)}</Text>
729          </Box>
730          {typeof right === 'string' ? <Text dimColor>{right}</Text> : right}
731        </Box>
732        {isFolded(section) ? null : body}
733      </Box>
734    )
735    const hint = (focused: string) => (
736      <Box key="hint" marginTop={1}>
737        <Text dimColor>{clip(e.props.isFocused ? focused : 'ctrl+x tab to use · /radar to close', W)}</Text>
738      </Box>
739    )
740
741    // ── one background task, opened ──
742    if (v.screen === 'shell' && v.shellId) {
743      const shell = (await read($, shells))[v.shellId]
744      const out = await read($, output)
745      if (!shell) return <Box flexDirection="column"><Button key="back" autoFocus plain hotkey="b" label="back" onPress={() => void back($)} /></Box>
746      const room = Math.max(4, (e.viewport?.rows ?? 30) - 14)
747      const all = out?.shellId === shell.id ? out.lines : []
748      const lines = all.slice(-room)
749      // The output's own last line outranks the row: the view never says running under "[exited …]".
750      const trailer = exitTrailer(all.at(-1))
751      const wasKilled = isKilledTrailer(all.at(-1))
752      const isLive = shell.status === 'running' && trailer === undefined && !wasKilled
753      const code = shell.exitCode ?? trailer
754      const status = isLive ? 'running' : shell.status === 'running' ? (wasKilled ? 'killed' : trailer === 0 ? 'completed' : 'failed') : shell.status
755      const isGood = status === 'completed'
756      const statusColor = isLive ? C.shells : isGood ? C.shells : C.bad
757      const statusText = isLive ? '● running' : status === 'killed' ? '✗ killed' : `${isGood ? '✓' : '✗'} ${code !== undefined ? `exit ${code}` : status}`
758      const owner = shell.agentId ? ((await read($, agents))[shell.agentId]?.type ?? 'agent') : 'main'
759      const took = stopwatch((shell.endedAt ?? (isLive ? now : (out?.at ?? now))) - shell.startedAt)
760      const result = testSummary(all)
761      const meta = [shell.kind, `by ${owner}`, shell.id].join(' · ')
762      return (
763        <Box flexDirection="column" width={W}>
764          <Box flexDirection="column" borderStyle="round" borderColor={C.shells} paddingX={1} width={W}>
765            <Box justifyContent="space-between" width={IN}>
766              <Box>
767                <Button key="back" autoFocus plain hotkey="b" label="back" onPress={() => void back($)} />
768                <Text color={C.shells} bold>{`  ${clip(shell.description || shell.command, IN - 22)}`}</Text>
769              </Box>
770              <Text color={statusColor} bold={!isLive}>{statusText}</Text>
771            </Box>
772            {shell.description ? <Text wrap="truncate-end">{clip(`$ ${shell.command}`, IN)}</Text> : null}
773            <Text wrap="truncate-end">
774              {shell.pid ? <Text color={C.pid}>{`pid ${shell.pid}`}</Text> : null}
775              {shell.pid ? <Text dimColor>{' · '}</Text> : null}
776              <Text>{`${isLive ? 'running' : 'ran'} ${took}`}</Text>
777              <Text dimColor>{clip(` · ${meta}`, Math.max(0, IN - took.length - 8 - (shell.pid ? String(shell.pid).length + 7 : 0)))}</Text>
778            </Text>
779            {result ? <Text color={isLive ? undefined : statusColor} bold wrap="truncate-end">{clip(result, IN)}</Text> : null}
780            {!result && shell.summary && exitCodeOf(shell.summary) === undefined ? <Text dimColor>{clip(shell.summary, IN)}</Text> : null}
781          </Box>
782          <Box flexDirection="column" borderStyle="round" borderDimColor paddingX={1} width={W}>
783            <Box justifyContent="space-between" width={IN}>
784              <Text dimColor>{`output · last ${lines.length} lines`}</Text>
785              <Text color={isLive ? C.shells : undefined} dimColor={!isLive}>{isLive ? '● live' : 'ended'}</Text>
786            </Box>
787            {out?.error ? <Text dimColor>{out.error}</Text> : null}
788            {!out ? <Text dimColor>reading…</Text> : null}
789            {out && !out.error && lines.length === 0 ? <Text dimColor>no output yet</Text> : null}
790            {lines.map((line, i) => <Text key={`l${i}`} wrap="truncate-end">{line || ' '}</Text>)}
791          </Box>
792          <Box marginTop={1} gap={2}>
793            <Button key="copy" hotkey="c" label="Copy" onPress={press => void $.ui.copy({ text: lines.join('\n'), surface: press.surface })} />
794            {isLive ? <Button key="stop" hotkey="s" label="Stop" onPress={() => void $.tool.call({ tool: 'TaskStop', task_id: shell.id }).catch(() => undefined)} /> : null}
795          </Box>
796          {isLive ? <Text dimColor>{clip('Stop asks for permission like any tool call.', W)}</Text> : null}
797          {hint('tab next · b back · c copy · esc prompt')}
798        </Box>
799      )
800    }
801
802    // ── overview ──
803    const u = await read($, usage)
804    const m = await read($, main)
805    const n = await read($, needs)
806    const hist = await read($, samples)
807    const agentRows = Object.values(await read($, agents))
808    const shellRows = Object.values(await read($, shells))
809    const cronRows = await read($, crons)
810    const prog = await read($, progress)
811    const cat = await read($, catalog)
812    const using = Object.values(await read($, inUse)).sort((a, b) => a.startedAt - b.startedAt)
813
814    const model = m.model ? modelName(m.model) : 'claude'
815    const home = await $.env.get('HOME').catch(() => undefined)
816    const G = Math.max(6, Math.min(12, IN - 26))
817
818    // Main
819    const effort = effortMeter(m.effort)
820    const ctxPct = u?.contextPercent ?? (u?.contextTokens && u.contextWindow ? (u.contextTokens / u.contextWindow) * 100 : undefined)
821    const ctxColor = ctxPct === undefined ? undefined : ctxPct >= 85 ? C.bad : ctxPct >= 65 ? C.warn : C.main
822    const ctx = gauge(ctxPct ?? 0, G)
823    const five = u?.rateLimits.find(l => l.kind === 'five_hour')
824    const fc = five ? forecast(hist, five, now) : undefined
825    const limitLine = (l: { kind: string; percentUsed: number; resetsAt?: string }) => {
826      const g = gauge(l.percentUsed, Math.max(4, G - 4))
827      const color = l.percentUsed >= 90 ? C.bad : l.percentUsed >= 70 ? C.warn : C.main
828      return (
829        <Text key={`lim-${l.kind}`} wrap="truncate-end">
830          <Text dimColor>{`${limitLabel(l.kind).padEnd(3)}`}</Text>
831          <Text color={color}>{g.full}</Text>
832          <Text dimColor>{g.empty}</Text>
833          <Text bold>{` ${String(Math.round(l.percentUsed)).padStart(3)}%`}</Text>
834          <Text dimColor>{` ${resetLabel(l.resetsAt, now)}`}</Text>
835        </Text>
836      )
837    }
838    const mainBody = (
839      <Box flexDirection="column">
840        <Text wrap="truncate-end">
841          <Text dimColor>{'effort '}</Text>
842          {effort ? <Text color={C.main}>{effort.full}</Text> : null}
843          {effort ? <Text dimColor>{effort.empty}</Text> : null}
844          <Text bold>{` ${m.effort ?? '—'}`}</Text>
845          <Text dimColor>{u ? `  session ${duration(now - u.startedAt)}` : ''}</Text>
846        </Text>
847        <Text wrap="truncate-end">
848          <Text dimColor>{'ctx    '}</Text>
849          <Text color={ctxColor}>{ctx.full}</Text>
850          <Text dimColor>{ctx.empty}</Text>
851          <Text bold color={ctxColor}>{ctxPct !== undefined ? ` ${Math.round(ctxPct)}%` : ' —'}</Text>
852          <Text dimColor>{u?.contextTokens !== undefined ? ` ${tokens(u.contextTokens)}/${tokens(u.contextWindow)}` : ''}</Text>
853          {ctxPct !== undefined && ctxPct >= 85 ? <Text color={C.bad}>{' compaction soon'}</Text> : null}
854        </Text>
855        {(u?.rateLimits ?? []).map(limitLine)}
856        {fc?.kind === 'full' ? <Text color={C.warn} wrap="truncate-end">{`5h full ≈ ${clock(fc.at)} at this pace`}</Text> : null}
857        {fc?.kind === 'ok' ? <Text color={C.shells} wrap="truncate-end">{'5h lasts until reset at this pace'}</Text> : null}
858        {m.cwd ? (
859          <Text wrap="truncate-end">
860            <Text dimColor>{'dir    '}</Text>
861            <Text>{shortPath(m.cwd, home, IN - 7)}</Text>
862          </Text>
863        ) : null}
864        {m.branch ? <Text color={C.branch} wrap="truncate-end">{`⎇ ${m.branch}${m.isWorktree ? ' (worktree)' : ''}`}</Text> : null}
865      </Box>
866    )
867
868    // Agents, as cards
869    const running = agentRows.filter(a => !ENDED.has(a.status)).sort((a, b) => a.startedAt - b.startedAt)
870    const done = agentRows.filter(a => ENDED.has(a.status)).sort((a, b) => (b.endedAt ?? 0) - (a.endedAt ?? 0))
871    const shown = [...running.slice(-MAX_CARDS), ...done.slice(0, Math.max(0, MAX_CARDS - running.length))]
872    const moreRunning = running.length - Math.min(running.length, MAX_CARDS)
873    const moreDone = done.length - (shown.length - (running.length - moreRunning))
874    // Cards sit inside the agents box, so they share its inner width; four make a 2×2 grid.
875    const cols = IN >= 40 ? 2 : 1
876    const cardW = Math.floor((IN - (cols - 1)) / cols)
877    const cardIn = cardW - 4
878    const card = (a: AgentRow, index: number) => {
879      const isEnded = ENDED.has(a.status)
880      const isBad = a.status === 'failed' || a.status === 'killed'
881      const isOpen = v.expanded === a.id
882      const glyph = isBad ? '✗' : isEnded ? '✓' : a.status === 'waiting' ? '◐' : '◐'
883      const glyphColor = isBad ? C.bad : isEnded ? C.shells : a.status === 'waiting' ? C.warn : C.agents
884      const uses = isEnded ? [] : using.filter(x => x.agentId === a.id)
885      const facts = [a.contextTokens !== undefined ? `ctx ${tokens(a.contextTokens)}` : '', `${a.tools} tools`].filter(Boolean).join(' · ')
886      return (
887        <Box key={`card-${a.id}`} flexDirection="column" borderStyle="round" borderColor={C.agents} borderDimColor={isEnded} paddingX={1} width={cardW}>
888          <Button key={`agent-${a.id}`} plain label={clip(`${index + 1}: ${a.description.trim()}`, cardIn)} onPress={() => void update($, view, x => ({ ...x, expanded: x.expanded === a.id ? undefined : a.id }))} />
889          <Text dimColor wrap="truncate-end">{clip(a.type, cardIn)}</Text>
890          <Text dimColor wrap="truncate-end">
891            {clip(facts, cardIn)}
892            {a.errors > 0 ? <Text color={C.bad}>{` · ${a.errors} err`}</Text> : null}
893          </Text>
894          {uses.length ? (
895            <Text wrap="truncate-end">
896              {uses.map((x, i) => (
897                <Text key={`use-${a.id}-${x.id}`} color={x.kind === 'mcp' ? C.mcp : C.skills}>{`${i ? ' ' : ''}${x.kind === 'mcp' ? '●' : '⚡'} ${x.name}`}</Text>
898              ))}
899            </Text>
900          ) : null}
901          {a.branch || a.isWorktree ? <Text color={C.branch} wrap="truncate-end">{clip(`⎇ ${a.branch ?? 'worktree'}`, cardIn)}</Text> : null}
902          <Text wrap="truncate-end">
903            <Text color={glyphColor}>{`${glyph} `}</Text>
904            <Text dimColor={isEnded}>{stopwatch((a.endedAt ?? now) - a.startedAt)}</Text>
905            {isBad ? <Text color={C.bad}>{` ${a.status}`}</Text> : null}
906          </Text>
907          {isOpen && a.lastMessage ? <Text dimColor wrap="wrap">{clip(`"${a.lastMessage}"`, cardIn * 3)}</Text> : null}
908          {isOpen && a.model ? <Text dimColor wrap="truncate-end">{clip(modelName(a.model), cardIn)}</Text> : null}
909        </Box>
910      )
911    }
912
913    // MCP and skills: who is using one, and the list of what there is.
914    const cardNo = new Map(shown.map((a, i) => [a.id, i + 1]))
915    const owner = (x: InUse) => {
916      if (!x.agentId) return 'main'
917      const no = cardNo.get(x.agentId)
918      return no ? `agent ${no}` : ((agentRows.find(a => a.id === x.agentId)?.type) ?? 'agent')
919    }
920    const isUnrolled = (list: string) => (v.unrolled ?? []).includes(list)
921    const unroll = (list: string) => () =>
922      void update($, view, x => {
923        const open = x.unrolled ?? []
924        return { ...x, unrolled: open.includes(list) ? open.filter(l => l !== list) : [...open, list] }
925      })
926    // Names laid side by side; the ones in use first and bright, the rest dim.
927    const chips = (list: string, color: string, names: readonly { name: string; label: string }[], active: ReadonlySet<string>, limit: number | undefined) => {
928      const ordered = [...names.filter(n => active.has(n.name)), ...names.filter(n => !active.has(n.name))]
929      const words = ordered.map(n => `${active.has(n.name) ? '● ' : ''}${clip(n.label, IN)}`)
930      const rows = pack(words, IN, 3)
931      const seen = limit === undefined ? rows : rows.slice(0, limit)
932      const hidden = rows.slice(seen.length).reduce((sum, r) => sum + r.length, 0)
933      return {
934        hidden,
935        rows: seen.map((row, r) => (
936          <Text key={`${list}-row-${r}`} wrap="truncate-end">
937            {row.map((i, k) => (
938              <Text key={`${list}-${i}`}>
939                {k ? <Text dimColor>{' · '}</Text> : null}
940                {active.has(ordered[i]!.name) ? <Text color={color} bold>{words[i]}</Text> : <Text dimColor>{words[i]}</Text>}
941              </Text>
942            ))}
943          </Text>
944        )),
945      }
946    }
947    const useRow = (x: InUse, color: string) => {
948      const time = stopwatch(now - x.startedAt)
949      const who = owner(x)
950      const what = x.kind === 'mcp' ? `● ${x.name}${x.tool ? ` · ${x.tool}` : ''}` : `⚡ ${x.name}`
951      return (
952        <Box key={`use-${x.id}`} justifyContent="space-between" width={IN}>
953          <Text color={color} wrap="truncate-end">{clip(what, IN - who.length - time.length - 3)}</Text>
954          <Text dimColor>{`${who} ${time}`}</Text>
955        </Box>
956      )
957    }
958
959    const mcpUses = using.filter(x => x.kind === 'mcp')
960    const mcpActive = new Set(mcpUses.map(x => x.name))
961    const mcpNames = cat.servers.map(sv => ({ name: sv.name, label: `${sv.name} (${sv.tools})` }))
962    // A server the catalog has not caught up with yet still shows while in use.
963    for (const name of mcpActive) if (!cat.servers.some(sv => sv.name === name)) mcpNames.push({ name, label: name })
964    const mcpList = chips('mcp', C.mcp, mcpNames, mcpActive, isUnrolled('mcp') ? undefined : LIST_ROWS)
965    const mcpBody = (
966      <Box flexDirection="column">
967        {mcpNames.length === 0 ? <Text dimColor>no MCP servers connected</Text> : null}
968        {mcpList.rows}
969        {mcpList.hidden > 0 || isUnrolled('mcp') ? (
970          <Button key="more-mcp" plain dimColor label={isUnrolled('mcp') ? '− show less' : `+ ${mcpList.hidden} more`} onPress={unroll('mcp')} />
971        ) : null}
972        {mcpUses.slice(-ACTIVE_ROWS).map(x => useRow(x, C.mcp))}
973        {mcpUses.length > ACTIVE_ROWS ? <Text dimColor>{`+ ${mcpUses.length - ACTIVE_ROWS} more calls`}</Text> : null}
974      </Box>
975    )
976
977    const skillUses = using.filter(x => x.kind === 'skill')
978    const skillActive = new Set(skillUses.map(x => x.name))
979    const skillNames = [...new Set([...cat.skills, ...skillActive])].map(name => ({ name, label: name }))
980    const skillList = chips('skills', C.skills, skillNames, skillActive, undefined)
981    const skillsBody = (
982      <Box flexDirection="column">
983        {skillUses.length === 0 ? <Text dimColor>none in use</Text> : null}
984        {skillUses.slice(-ACTIVE_ROWS).map(x => useRow(x, C.skills))}
985        {skillUses.length > ACTIVE_ROWS ? <Text dimColor>{`+ ${skillUses.length - ACTIVE_ROWS} more`}</Text> : null}
986        {skillNames.length ? (
987          <Button key="more-skills" plain dimColor label={isUnrolled('skills') ? '− hide skills' : `+ ${skillNames.length} available`} onPress={unroll('skills')} />
988        ) : null}
989        {isUnrolled('skills') ? skillList.rows : null}
990      </Box>
991    )
992
993    // Background
994    const liveShells = shellRows.filter(x => x.status === 'running').sort((a, b) => a.startedAt - b.startedAt)
995    const endedShells = shellRows.filter(x => x.status !== 'running').sort((a, b) => (b.endedAt ?? 0) - (a.endedAt ?? 0))
996    const shellRow = (x: ShellRow) => {
997      const time = stopwatch((x.endedAt ?? now) - x.startedAt)
998      const isLive = x.status === 'running'
999      const glyph = isLive ? '●' : x.status === 'completed' ? '✓' : '✗'
1000      const color = isLive ? C.shells : x.status === 'completed' ? undefined : C.bad
1001      const pid = x.pid ? `${x.pid} ` : ''
1002      return (
1003        <Box key={`s-${x.id}`} justifyContent="space-between" width={IN}>
1004          <Box>
1005            <Text color={color} dimColor={!isLive}>{`${glyph} `}</Text>
1006            {pid ? <Text color={C.pid} dimColor={!isLive}>{pid}</Text> : null}
1007            <Button key={`shell-${x.id}`} plain dimColor={!isLive || undefined} label={clip(x.description || x.command, IN - time.length - pid.length - 4)} onPress={() => void openShell($, x.id)} />
1008          </Box>
1009          <Text dimColor>{time}</Text>
1010        </Box>
1011      )
1012    }
1013    const bgBody = (
1014      <Box flexDirection="column">
1015        {shellRows.length === 0 && cronRows.length === 0 ? <Text dimColor>nothing in the background</Text> : null}
1016        {liveShells.slice(-LIVE_SHELLS_SHOWN).map(shellRow)}
1017        {liveShells.length > LIVE_SHELLS_SHOWN ? <Text dimColor>{`+ ${liveShells.length - LIVE_SHELLS_SHOWN} more running`}</Text> : null}
1018        {endedShells.slice(0, FINISHED_SHELLS_SHOWN).map(shellRow)}
1019        {cronRows.map(c => (
1020          <Text key={`c-${c.id}`} dimColor wrap="truncate-end">{`↻ ${clip(c.prompt, IN - c.schedule.length - 5)} · ${c.schedule}`}</Text>
1021        ))}
1022      </Box>
1023    )
1024
1025    // Progress
1026    const items = prog.todos.length > 0 ? prog.todos : prog.tasks
1027    const finished = items.filter(i => i.status === 'completed').length
1028    const doneShown = items.length > 8 ? items.filter(i => i.status === 'completed').slice(-2) : items.filter(i => i.status === 'completed')
1029    const rest = items.filter(i => i.status !== 'completed')
1030    const hidden = finished - doneShown.length
1031    const pg = gauge(items.length ? (finished / items.length) * 100 : 0, IN)
1032    const progBody = (
1033      <Box flexDirection="column">
1034        {prog.plan ? <Text color={C.progress} wrap="truncate-end">{clip(`plan · ${prog.plan}`, IN)}</Text> : null}
1035        {items.length > 0 ? (
1036          <Text>
1037            <Text color={C.progress}>{pg.full}</Text>
1038            <Text dimColor>{pg.empty}</Text>
1039          </Text>
1040        ) : null}
1041        {hidden > 0 ? <Text dimColor>{`✓ ${hidden} earlier done`}</Text> : null}
1042        {[...doneShown, ...rest].map(i => (
1043          <Text key={`p-${i.id}`} wrap="truncate-end">
1044            <Text color={i.status === 'completed' ? C.shells : i.status === 'in_progress' ? C.progress : undefined} dimColor={i.status === 'pending'}>
1045              {i.status === 'completed' ? '✓ ' : i.status === 'in_progress' ? '◆ ' : '◇ '}
1046            </Text>
1047            <Text dimColor={i.status === 'completed'} bold={i.status === 'in_progress'}>{clip(i.text, IN - 2)}</Text>
1048          </Text>
1049        ))}
1050      </Box>
1051    )
1052
1053    return (
1054      <Box flexDirection="column" width={W}>
1055        <Box justifyContent="center" width={W}>
1056          <Text bold>{'RADAR · '}</Text>
1057          <Text color={C.main} bold>{model}</Text>
1058          {version ? <Text dimColor>{` · v${version}`}</Text> : null}
1059        </Box>
1060        <Box justifyContent="center" flexWrap="wrap" columnGap={2} width={W}>
1061          <Text><Text color={C.main}>■</Text><Text dimColor> main</Text></Text>
1062          <Text><Text color={C.agents}>■</Text><Text dimColor> agents</Text></Text>
1063          <Text><Text color={C.mcp}>■</Text><Text dimColor> mcp</Text></Text>
1064          <Text><Text color={C.skills}>■</Text><Text dimColor> skills</Text></Text>
1065          <Text><Text color={C.shells}>■</Text><Text dimColor> shells</Text></Text>
1066          {items.length || prog.plan ? <Text><Text color={C.progress}>■</Text><Text dimColor> progress</Text></Text> : null}
1067        </Box>
1068
1069        {n ? (
1070          <Box key="needs" flexDirection="column" borderStyle="round" borderColor={C.warn} paddingX={1} width={W} marginTop={1}>
1071            <Box justifyContent="space-between" width={IN}>
1072              <Text color={C.warn} bold>{`⚠ NEEDS YOU · ${clip(n.who, IN - 26)}`}</Text>
1073              <Text color={C.warn}>{stopwatch(now - n.since)}</Text>
1074            </Box>
1075            <Text wrap="truncate-end">{clip(n.what.trim(), IN)}</Text>
1076          </Box>
1077        ) : null}
1078
1079        <Box marginTop={n ? 0 : 1} />
1080        {box('main', C.main, `${model} · main`, '', mainBody)}
1081
1082        {box('agents', C.agents, 'AGENTS', agentRows.length ? `${running.length} running · ${agentRows.length} total` : '', (
1083          <Box flexDirection="column">
1084            {shown.length === 0 ? <Text dimColor>none yet</Text> : null}
1085            {shown.length ? (
1086              <Box flexDirection="row" flexWrap="wrap" columnGap={1} width={IN}>
1087                {shown.map(card)}
1088              </Box>
1089            ) : null}
1090            {agentRows.length > shown.length ? <Text dimColor>{`+ ${[moreRunning ? `${moreRunning} more running` : '', moreDone ? `${moreDone} more done` : ''].filter(Boolean).join(' · ')}`}</Text> : null}
1091          </Box>
1092        ))}
1093
1094        {box('mcp', C.mcp, 'MCP', cat.servers.length ? `${mcpActive.size} in use · ${cat.servers.length} servers` : '', mcpBody)}
1095
1096        {box('skills', C.skills, 'SKILLS', skillUses.length ? `${skillActive.size} in use` : '', skillsBody)}
1097
1098        {box('background', C.shells, 'BACKGROUND', backgroundCount(liveShells), bgBody)}
1099        {items.length || prog.plan ? box('progress', C.progress, 'PROGRESS', items.length ? `${finished}/${items.length}` : '', progBody) : null}
1100
1101        {hint('tab next · ⏎ open · ↑↓ scroll · esc prompt')}
1102      </Box>
1103    )
1104  })
1105}
1106
hooks/lib.ts 251 lines
1import type { LimitSample, RateLimit, ShellStatus } from '../types'
2
3const MIN = 60_000
4// A forecast needs this much history in the current window before it means anything.
5const FORECAST_MIN_SPAN = 5 * MIN
6// And looks back no further than this, so it follows the current pace.
7const FORECAST_LOOKBACK = 60 * MIN
8
9export function duration(ms: number) {
10  const s = Math.max(0, Math.floor(ms / 1000))
11  if (s < 60) return `${s}s`
12  const m = Math.floor(s / 60)
13  if (m < 60) return `${m}m`
14  const h = Math.floor(m / 60)
15  return `${h}h${String(m % 60).padStart(2, '0')}`
16}
17
18export function tokens(n: number) {
19  if (n < 1000) return String(n)
20  if (n < 1_000_000) return `${Math.round(n / 1000)}k`
21  return `${(n / 1_000_000).toFixed(1)}M`
22}
23
24export function clock(ms: number) {
25  const d = new Date(ms)
26  return `${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}`
27}
28
29// "resets 16:00" today, "resets Sat 00:00" on another day.
30export function resetLabel(iso: string | undefined, now: number) {
31  if (!iso) return ''
32  const at = Date.parse(iso)
33  if (Number.isNaN(at)) return ''
34  const isToday = new Date(at).toDateString() === new Date(now).toDateString()
35  if (isToday) return `resets ${clock(at)}`
36  return `resets ${new Date(at).toLocaleDateString('en-US', { weekday: 'short' })} ${clock(at)}`
37}
38
39// "claude-opus-5-5" → "Opus 5.5", "claude-haiku-4-5-20251001" → "Haiku 4.5".
40export function modelName(model: string) {
41  const [family, ...rest] = model.replace(/^claude-/, '').replace(/\[.*\]$/, '').split('-')
42  if (!family) return model
43  const version = rest.filter(p => /^\d{1,2}$/.test(p)).join('.')
44  return `${family[0]!.toUpperCase()}${family.slice(1)}${version ? ` ${version}` : ''}`
45}
46
47export function clip(text: string, width: number) {
48  const flat = text.replace(/\s+/g, ' ')
49  if (width <= 1) return flat.slice(0, Math.max(0, width))
50  return flat.length > width ? `${flat.slice(0, width - 1)}…` : flat
51}
52
53export function bar(percent: number, width: number) {
54  const full = Math.max(0, Math.min(width, Math.round((percent / 100) * width)))
55  return { full: '█'.repeat(full), empty: '░'.repeat(width - full) }
56}
57
58export const LIMIT_LABEL: Record<string, string> = { five_hour: '5h', seven_day: '7d' }
59
60export function limitLabel(kind: string) {
61  return LIMIT_LABEL[kind] ?? kind.replace(/_/g, ' ')
62}
63
64// Keeps a short history per window, restarted whenever the window resets.
65export function addSamples(samples: readonly LimitSample[], limits: readonly RateLimit[], at: number) {
66  let next = samples.filter(s => at - s.at <= FORECAST_LOOKBACK)
67  for (const l of limits) {
68    next = next.filter(s => s.kind !== l.kind || s.resetsAt === l.resetsAt)
69    const last = next.filter(s => s.kind === l.kind).at(-1)
70    if (last && last.percentUsed === l.percentUsed && at - last.at < MIN) continue
71    next.push({ kind: l.kind, at, percentUsed: l.percentUsed, resetsAt: l.resetsAt })
72  }
73  return next
74}
75
76export type Forecast = { kind: 'full'; at: number } | { kind: 'ok' } | undefined
77
78// When the window fills at the pace of the samples, or 'ok' when it resets first.
79export function forecast(samples: readonly LimitSample[], limit: RateLimit, now: number): Forecast {
80  const mine = samples.filter(s => s.kind === limit.kind && s.resetsAt === limit.resetsAt)
81  const first = mine[0]
82  if (!first || now - first.at < FORECAST_MIN_SPAN) return undefined
83  const rate = (limit.percentUsed - first.percentUsed) / (now - first.at)
84  if (rate <= 0) return { kind: 'ok' }
85  const at = now + (100 - limit.percentUsed) / rate
86  const resets = limit.resetsAt ? Date.parse(limit.resetsAt) : NaN
87  if (!Number.isNaN(resets) && at >= resets) return { kind: 'ok' }
88  return { kind: 'full', at }
89}
90
91export type TaskNotice = { id: string; status: ShellStatus; summary: string; outputPath?: string }
92
93const tag = (text: string, name: string) => text.match(new RegExp(`<${name}>([\\s\\S]*?)</${name}>`))?.[1]?.trim()
94
95// The <task-notification> the engine delivers when a background task ends.
96export function parseTaskNotice(text: string): TaskNotice | undefined {
97  const id = tag(text, 'task-id')
98  if (!id) return undefined
99  // A monitor's events come as notices too, with no status: only an end has one.
100  const raw = tag(text, 'status')
101  if (!raw) return undefined
102  const status: ShellStatus = raw === 'failed' || raw === 'killed' ? raw : 'completed'
103  return { id, status, summary: tag(text, 'summary') ?? '', outputPath: tag(text, 'output-file') }
104}
105
106// Bash's result names where a backgrounded command writes its output.
107export function outputPathOf(text: string | undefined) {
108  return text?.match(/written to:\s*(\S+?\.output)\b/)?.[1]
109}
110
111export function exitCodeOf(summary: string) {
112  return summary.match(/exit code (-?\d+)/)?.[1]
113}
114
115const ANSI = /\x1b\[[0-?]*[ -/]*[@-~]|\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)/g
116
117// The last `count` lines as a terminal would show them: colors dropped, a
118// carriage return keeping only what came after it.
119export function tail(text: string, count: number) {
120  const lines = text.replace(ANSI, '').split('\n')
121  if (lines.at(-1) === '') lines.pop()
122  return lines.slice(-count).map(line => line.slice(line.lastIndexOf('\r') + 1).replace(/\t/g, '  '))
123}
124
125export function lastLine(text: string) {
126  return text.split('\n').map(l => l.trim()).filter(Boolean).at(-1) ?? ''
127}
128
129export function parentDir(path: string) {
130  return path.slice(0, Math.max(0, path.lastIndexOf('/')))
131}
132
133// "0:42", "12:05", "1:02:09": a running time as a stopwatch reads it.
134export function stopwatch(ms: number) {
135  const s = Math.max(0, Math.floor(ms / 1000))
136  const h = Math.floor(s / 3600)
137  const m = Math.floor((s % 3600) / 60)
138  const ss = String(s % 60).padStart(2, '0')
139  return h > 0 ? `${h}:${String(m).padStart(2, '0')}:${ss}` : `${m}:${ss}`
140}
141
142const EFFORTS = ['low', 'medium', 'high', 'xhigh', 'max']
143
144// Five cells, filled up to the effort level: ▮▮▯▯▯ for medium.
145export function effortMeter(effort: string | undefined) {
146  const level = effort === undefined ? -1 : EFFORTS.indexOf(effort)
147  if (level < 0) return undefined
148  return { full: '▮'.repeat(level + 1), empty: '▯'.repeat(EFFORTS.length - level - 1) }
149}
150
151// A thin gauge: ▬▬▬▬▱▱▱▱.
152export function gauge(percent: number, width: number) {
153  const full = Math.max(0, Math.min(width, Math.round((percent / 100) * width)))
154  return { full: '▬'.repeat(full), empty: '▱'.repeat(width - full) }
155}
156
157// "/home/me/projects/app" → "~/projects/app"; too long, it keeps the end: "…/deep/app".
158export function shortPath(path: string, home: string | undefined, width: number) {
159  const tilde = home && (path === home || path.startsWith(`${home}/`)) ? `~${path.slice(home.length)}` : path
160  return tilde.length > width ? `…${tilde.slice(tilde.length - width + 1)}` : tilde
161}
162
163// "mcp__claude_ai_Gmail__create_draft" → { server: "claude_ai_Gmail", tool: "create_draft" }.
164export function mcpParts(name: string) {
165  if (!name.startsWith('mcp__')) return undefined
166  const rest = name.slice(5)
167  const cut = rest.indexOf('__')
168  return cut < 0 ? { server: rest, tool: '' } : { server: rest.slice(0, cut), tool: rest.slice(cut + 2) }
169}
170
171// Lays words into rows of `width`, `gap` apart; a word too wide gets a row of its own.
172export function pack(words: readonly string[], width: number, gap: number) {
173  const rows: number[][] = []
174  let used = 0
175  words.forEach((w, i) => {
176    const row = rows.at(-1)
177    if (row && used + gap + w.length <= width) {
178      row.push(i)
179      used += gap + w.length
180    } else {
181      rows.push([i])
182      used = w.length
183    }
184  })
185  return rows
186}
187
188// The engine ends a background shell's output file with "[exited with code N]".
189export function exitTrailer(line: string | undefined) {
190  const code = line?.trim().match(/^\[exited with code (-?\d+)\]$/)?.[1]
191  return code === undefined ? undefined : Number(code)
192}
193
194// The line the engine writes last when a background task is stopped.
195export function isKilledTrailer(line: string | undefined) {
196  return line?.trim() === '[killed]'
197}
198
199// What `tail -n 1 a b c` prints: a "==> a <==" header before each file's lines
200// once there is more than one file.
201export function parseTails(stdout: string, paths: readonly string[]) {
202  const last = new Map<string, string>()
203  if (paths.length === 1) {
204    last.set(paths[0]!, lastLine(stdout))
205    return last
206  }
207  for (const part of stdout.split(/^==> /m).slice(1)) {
208    const cut = part.indexOf(' <==')
209    if (cut >= 0) last.set(part.slice(0, cut), lastLine(part.slice(cut + 4)))
210  }
211  return last
212}
213
214export type Proc = { pid: number; ppid: number; args: string }
215
216// `ps -A -ww -o pid=,ppid=,args=`, one process per line.
217export function parsePs(stdout: string): Proc[] {
218  return stdout.split('\n').flatMap(line => {
219    const m = line.match(/^\s*(\d+)\s+(\d+)\s+(.*)$/)
220    return m ? [{ pid: Number(m[1]), ppid: Number(m[2]), args: m[3]! }] : []
221  })
222}
223
224// The shell the engine started for `command`: it runs it as `eval '<command>'`,
225// single quotes escaped. One the engine itself started comes first.
226export function findPid(procs: readonly Proc[], command: string, enginePid: number | undefined, taken: ReadonlySet<number>) {
227  const quoted = `eval '${command.replace(/'/g, `'\\''`)}'`
228  const hits = procs.filter(p => !taken.has(p.pid) && p.args.includes(quoted))
229  return (hits.find(p => p.ppid === enginePid) ?? hits[0])?.pid
230}
231
232// One line on how a test run ended, when the output has a runner's summary:
233// vitest, jest, node --test or pytest.
234export function testSummary(lines: readonly string[]) {
235  const text = lines.join('\n')
236  // The last run's summary, when the output holds several.
237  const vitest = [...text.matchAll(/^\s*Tests\s+(.+?)\s*$/gm)].at(-1)
238  if (vitest && /\d+ (passed|failed)/.test(vitest[1]!)) {
239    const files = text.match(/^\s*Test Files\s+.*?(\d+) passed/m)?.[1]
240    return `${vitest[1]!.replace(/\s*\(\d+\)$/, '').replace(/\s*\|\s*/g, ' · ')}${files ? ` · ${files} files` : ''}`
241  }
242  const jest = text.match(/^Tests:\s+(.+?)\s*$/m)
243  if (jest) return jest[1]!.replace(/, \d+ total$/, '').replace(/, /g, ' · ')
244  const pass = text.match(/^ℹ pass (\d+)$/m)?.[1]
245  const fail = text.match(/^ℹ fail (\d+)$/m)?.[1]
246  if (pass !== undefined) return `${pass} passed${fail && fail !== '0' ? ` · ${fail} failed` : ''}`
247  const pytest = text.match(/^=+ (.*\b(?:passed|failed)\b.*?) in [\d.]+s.* =+$/m)
248  if (pytest) return pytest[1]!.replace(/, /g, ' · ')
249  return undefined
250}
251
types/index.d.ts 96 lines
1export type RateLimit = { kind: string; percentUsed: number; resetsAt?: string }
2
3export type Usage = {
4  startedAt: number
5  contextTokens?: number
6  contextWindow: number
7  contextPercent?: number
8  rateLimits: RateLimit[]
9}
10
11export type LimitSample = { kind: string; at: number; percentUsed: number; resetsAt?: string }
12
13export type Main = { model?: string; effort?: string; cwd?: string; branch?: string; isWorktree: boolean }
14
15export type AgentStatusName = 'pending' | 'running' | 'waiting' | 'idle' | 'completed' | 'failed' | 'killed'
16
17export type AgentRow = {
18  id: string
19  type: string
20  description: string
21  status: AgentStatusName
22  model?: string
23  startedAt: number
24  endedAt?: number
25  tools: number
26  errors: number
27  contextTokens?: number
28  lastMessage?: string
29  cwd?: string
30  branch?: string
31  isWorktree: boolean
32}
33
34export type ShellStatus = 'running' | 'completed' | 'failed' | 'killed'
35
36export type ShellRow = {
37  id: string
38  kind: string
39  command: string
40  description?: string
41  startedAt: number
42  status: ShellStatus
43  endedAt?: number
44  summary?: string
45  outputPath?: string
46  // The process the engine started for it, found by its command line.
47  pid?: number
48  exitCode?: number
49  agentId?: string
50  // Started by a foreground subagent: the engine stops it when that agent ends.
51  endsWithAgent?: boolean
52  // A monitor's deadline: past it the engine has ended the watch.
53  expiresAt?: number
54}
55
56export type Cron = { id: string; schedule: string; recurring: boolean; prompt: string; at?: number }
57
58export type ProgressItem = { id: string; text: string; status: 'pending' | 'in_progress' | 'completed' }
59
60export type Progress = { todos: ProgressItem[]; tasks: ProgressItem[]; plan?: string }
61
62export type Needs = { who: string; agentId?: string; what: string; since: number }
63
64// A list shown whole ('mcp', 'skills') rather than cut to its first lines.
65export type View = { screen: 'overview' | 'shell'; shellId?: string; expanded?: string; folded: string[]; unrolled?: string[] }
66
67export type McpServer = { name: string; tools: number }
68
69// What the session has: its MCP servers (each tool's wire name → its server) and its skills.
70export type Catalog = { servers: McpServer[]; toolServer: Record<string, string>; skills: string[] }
71
72// Something in use right now: an MCP call until it returns, a skill until its agent's turn ends.
73export type InUse = { id: string; kind: 'mcp' | 'skill'; name: string; tool?: string; agentId?: string; startedAt: number }
74
75export type Output = { shellId: string; lines: string[]; at: number; error?: string }
76
77declare module 'claude-code' {
78  interface PluginState {
79    'session-radar': {
80      usage: Usage | null
81      samples: LimitSample[]
82      main: Main
83      agents: Record<string, AgentRow>
84      shells: Record<string, ShellRow>
85      crons: Cron[]
86      progress: Progress
87      needs: Needs | null
88      view: View
89      output: Output | null
90      catalog: Catalog
91      inUse: Record<string, InUse>
92      tick: number
93    }
94  }
95}
96