Shows the main model and its effort, the live agents by model and effort, named agent crews, and the working directory, and warns about agent crowds and huge…

Shows the main thread's model and effort, the agents running now, by model and effort, and the session's working directory. Agents include the main thread, subagents and teammates that run inside the session. It warns when too many run at once, or when one sends a huge context with every request.
model: Opus · effort: high · agents: Opus (12 medium, 1 high), Sonnet (2 low) · ⚠ 15 live · ⚠ ctx 910K · cwd: ~/src/app
The line is dim. Only the warnings marked ⚠ are drawn in the warning color. The directory comes last, with your home folder shown as ~. When the band is too narrow, the path loses its start, so the folders nearest you stay readable: cwd: …/plugins/session-models. The line sits in the band above the prompt, alongside any other plugin's line there; collapse the band with its [-] or ctrl+x ctrl+a. In the VS Code extension and on a phone, which have no band, the line falls back to the plugin status line. That status shows everywhere, in its usual yellow, while such a surface is attached.
A crew is a named top-level agent (one with a name, spawned by the main thread) that has at least one live descendant. Its size is the lead plus every live descendant, grandchildren included, and the segment breaks that size down by model:
crews: export 4 (sonnet 3, opus 1) · staffing 3 (sonnet 2, opus 1)
Crews run largest first, then by name, and models within a crew by count. A foundry lead and its crew show up here this way. Past three, the rest collapse to +N more. With no crew, the segment is left out. Crew members still count in agents: and in the live total as before. An unnamed lead, a named agent with no live helpers, and finished helpers are not counted. A member whose model is not known yet adds to the size but not to the breakdown.
| Setting | Default | What it does |
|---|---|---|
liveAgentsWarn | 6 | Warns when this many agents run at once, counting the main thread. |
contextWarnK | 300 | Warns when a running agent sends this many thousand tokens of context per request. |
The main README covers installing, reading the line, and what it can't see.
hooks/register.tsx 368 lines1import { atom, read, update } from 'claude-code'
2import type { AgentStatus, EngineInterface, Register } from 'claude-code'
3
4import type { AgentsSeen } from '../types'
5
6const agentsSeen = atom({ plugin: 'session-models', key: 'agents' } as const, {} as AgentsSeen)
7
8export type Thresholds = { liveAgents: number; context: number }
9
10// the crowd toast re-arms only once the count drops this far below the threshold,
11// and never fires twice within the quiet period
12const CROWD_HYSTERESIS = 2
13const CROWD_QUIET_MS = 10 * 60_000
14// a busy session steps many times a second across its agents: redraw at most this often
15const REFRESH_MIN_MS = 2_000
16// the surfaces that raise the AbovePrompt band; any other gets the line as a status
17const BAND_SURFACES: readonly string[] = ['terminal', 'desktop']
18
19// claude-opus-5-5 -> Opus; an id outside the known families is shown as-is
20export function family(model: string): string {
21 const m = /(opus|sonnet|haiku|fable)/i.exec(model)
22 if (m === null) return model.replace(/^claude-/, '')
23 const name = m[1]!.toLowerCase()
24 return name[0]!.toUpperCase() + name.slice(1)
25}
26
27// 955492 -> 955K, 1200000 -> 1.2M
28export function tokens(n: number): string {
29 return n >= 1_000_000 ? `${(n / 1_000_000).toFixed(1)}M` : `${Math.round(n / 1000)}K`
30}
31
32// an agent at work: taking a turn, or held on background work it owns (a long shell,
33// an Agent call it waits on); an idle teammate waits for a message and is not
34export function isLive(status: AgentStatus): boolean {
35 return status === 'running' || status === 'waiting'
36}
37
38// the agents running now: the main thread always, plus every live subagent or teammate
39export function liveAgents(agents: AgentsSeen, running: ReadonlySet<string>): string[] {
40 return Object.keys(agents).filter(id => id === 'main' || running.has(id))
41}
42
43// where an agent sits in the spawn tree: its parent, and the name it was given
44export type AgentNode = { parentId?: string; name?: string }
45export type Crew = { name: string; size: number; models: Map<string, number> }
46const CREWS_SHOWN = 3
47
48// a crew is a named top-level agent with at least one live descendant; its size is the
49// lead plus those descendants, grandchildren included. Largest first, then by name
50export function crews(tree: ReadonlyMap<string, AgentNode>, agents: AgentsSeen, running: ReadonlySet<string>): Crew[] {
51 const byLead = new Map<string, string[]>()
52 for (const id of running) {
53 // climb to the top-level ancestor; the hop limit guards against a cycle
54 let top = id
55 for (let hops = 0; hops <= tree.size; hops++) {
56 const parent = tree.get(top)?.parentId
57 if (parent === undefined || parent === 'main' || !tree.has(parent)) break
58 top = parent
59 }
60 if (top === id || tree.get(top)?.name === undefined || tree.get(top)?.name === '') continue
61 byLead.set(top, [...(byLead.get(top) ?? []), id])
62 }
63 const out: Crew[] = []
64 for (const [lead, members] of byLead) {
65 const models = new Map<string, number>()
66 for (const id of [lead, ...members]) {
67 const model = agents[id]?.model
68 if (model !== undefined) models.set(family(model).toLowerCase(), (models.get(family(model).toLowerCase()) ?? 0) + 1)
69 }
70 out.push({ name: tree.get(lead)!.name!, size: members.length + 1, models })
71 }
72 return out.sort((a, b) => b.size - a.size || a.name.localeCompare(b.name))
73}
74
75// export 4 (opus 1, sonnet 3) · staffing 3 (opus 1, sonnet 2) · +2 more
76export function crewsPart(list: readonly Crew[]): string | undefined {
77 if (list.length === 0) return undefined
78 const shown = list.slice(0, CREWS_SHOWN).map(c => {
79 const models = [...c.models].sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0])).map(([m, n]) => `${m} ${n}`)
80 return models.length > 0 ? `${c.name} ${c.size} (${models.join(', ')})` : `${c.name} ${c.size}`
81 })
82 if (list.length > CREWS_SHOWN) shown.push(`+${list.length - CREWS_SHOWN} more`)
83 return `crews: ${shown.join(' · ')}`
84}
85
86// the live agent carrying the most context, when any carries at least `threshold`
87export function biggestContext(agents: AgentsSeen, live: readonly string[], threshold: number) {
88 let top: { id: string; context: number } | undefined
89 for (const id of live) {
90 const context = agents[id]?.context ?? 0
91 if (context >= threshold && (top === undefined || context > top.context)) top = { id, context }
92 }
93 return top
94}
95
96// a level as named, an integer budget as a token count: high, 32K
97export function effortLabel(effort: string | number): string {
98 return typeof effort === 'number' ? tokens(effort) : effort
99}
100
101// /home/me/src/app -> ~/src/app; a path outside home, or no home known, as-is
102export function shortPath(path: string, home: string | undefined): string {
103 if (home === undefined || home === '') return path
104 const h = home.replace(/[\\/]+$/, '')
105 // a Windows path matches without case
106 const isUnder = /^[a-z]:/i.test(h) ? path.toLowerCase().startsWith(h.toLowerCase()) : path.startsWith(h)
107 if (!isUnder) return path
108 const rest = path.slice(h.length)
109 if (rest === '') return '~'
110 // /home/meg is not under /home/me
111 return /^[\\/]/.test(rest) ? `~${rest}` : path
112}
113
114// "model: Opus · effort: high · agents: Opus (12 medium, 1 high), Sonnet (2 low) · crews: export 4 (opus 1, sonnet 3) · ⚠ 15 live · ⚠ ctx 955K · cwd: ~/src/app"
115// the agents part counts the live ones, main included, by the model and effort of each
116// one's latest request; it appears while anything beyond the main thread is running.
117// The directory goes last, so a long path is cut (from its head, by fitLine) rather
118// than pushing the warnings out of sight
119export function formatModels(
120 current: string,
121 agents: AgentsSeen,
122 running: ReadonlySet<string>,
123 limits: Thresholds,
124 cwd?: string,
125 tree?: ReadonlyMap<string, AgentNode>,
126): string {
127 return modelParts(current, agents, running, limits, cwd, tree).join(' · ')
128}
129
130// the line's parts, as formatModels joins them
131export function modelParts(
132 current: string,
133 agents: AgentsSeen,
134 running: ReadonlySet<string>,
135 limits: Thresholds,
136 cwd?: string,
137 tree?: ReadonlyMap<string, AgentNode>,
138): string[] {
139 const parts = [`model: ${family(current)}`]
140 // the main thread's latest request; unknown until it has made one
141 const effort = agents.main?.effort
142 if (effort !== undefined) parts.push(`effort: ${effortLabel(effort)}`)
143 const live = new Set(liveAgents(agents, running))
144 if (live.size > 1) {
145 // family -> effort -> count; '' for a model that takes no effort
146 const counts = new Map<string, Map<string, number>>()
147 for (const id of live) {
148 const seen = agents[id]
149 // state written before agents kept their latest model
150 if (seen?.model === undefined) continue
151 const f = family(seen.model)
152 const efforts = counts.get(f) ?? new Map<string, number>()
153 const e = seen.effort === undefined ? '' : effortLabel(seen.effort)
154 efforts.set(e, (efforts.get(e) ?? 0) + 1)
155 counts.set(f, efforts)
156 }
157 const total = (efforts: Map<string, number>) => [...efforts.values()].reduce((a, b) => a + b, 0)
158 const list = [...counts]
159 .sort((a, b) => total(b[1]) - total(a[1]))
160 .map(([f, efforts]) => {
161 const byEffort = [...efforts]
162 .sort((a, b) => b[1] - a[1])
163 .map(([e, n]) => (e !== '' ? `${n} ${e}` : efforts.size > 1 ? `${n} no effort` : `${n}`))
164 return `${f} (${byEffort.join(', ')})`
165 })
166 .join(', ')
167 parts.push(`agents: ${list}`)
168 // named leads with live helpers, by the same live agents counted above
169 const crewsText = tree === undefined ? undefined : crewsPart(crews(tree, agents, running))
170 if (crewsText !== undefined) parts.push(crewsText)
171 }
172 if (live.size >= limits.liveAgents) parts.push(`⚠ ${live.size} live`)
173 const top = biggestContext(agents, [...live], limits.context)
174 if (top !== undefined) parts.push(`⚠ ctx ${tokens(top.context)}`)
175 if (cwd !== undefined) parts.push(`cwd: ${cwd}`)
176 return parts
177}
178
179// the line within `columns`: a directory too long loses its head, cut back to a path
180// separator where one falls in the kept tail, so the folders nearest it stay readable
181export function fitLine(parts: readonly string[], columns: number): string[] {
182 const last = parts[parts.length - 1]
183 if (last === undefined || !last.startsWith('cwd: ')) return [...parts]
184 const width = (s: string) => Array.from(s).length
185 const path = Array.from(last.slice('cwd: '.length))
186 const over = width(parts.join(' · ')) - columns
187 if (over <= 0) return [...parts]
188 const room = path.length - over - 1
189 let tail = room > 0 ? path.slice(path.length - room).join('') : ''
190 const cut = tail.search(/[\\/]/)
191 if (cut > 0) tail = tail.slice(cut)
192 return [...parts.slice(0, -1), `cwd: …${tail}`]
193}
194
195// the line as runs of text: each part marked ⚠ a warning run of its own, the other
196// parts and the separators merged into dim runs
197export type Run = { text: string; isWarning: boolean }
198export function runs(parts: readonly string[]): Run[] {
199 const out: Run[] = []
200 parts.forEach((part, i) => {
201 const pieces: Run[] = i > 0 ? [{ text: ' · ', isWarning: false }] : []
202 pieces.push({ text: part, isWarning: part.startsWith('⚠') })
203 for (const piece of pieces) {
204 const last = out[out.length - 1]
205 if (last !== undefined && !last.isWarning && !piece.isWarning) last.text += piece.text
206 else out.push({ ...piece })
207 }
208 })
209 return out
210}
211
212// whether no surface the session draws on raises a band (or nothing draws at all, as
213// under -p or an SDK host), so the line goes out as a status instead; a phone or IDE
214// attached beside a terminal goes without, so the terminal keeps its quiet band alone
215export function needsStatus(surfaces: readonly string[]): boolean {
216 return !surfaces.some(s => BAND_SURFACES.includes(s))
217}
218
219export type Crowd = { isArmed: boolean; lastToastAt: number }
220
221// whether this live count earns a crowd toast, and the alarm's next state
222export function crowdAlarm(crowd: Crowd, live: number, now: number, threshold: number) {
223 if (live < threshold - CROWD_HYSTERESIS) return { toast: false, crowd: { ...crowd, isArmed: true } }
224 if (live >= threshold && crowd.isArmed && now - crowd.lastToastAt >= CROWD_QUIET_MS) {
225 return { toast: true, crowd: { isArmed: false, lastToastAt: now } }
226 }
227 return { toast: false, crowd }
228}
229
230// an agent by the task it was given, falling back to its id when it has none
231export function agentLabel(id: string, description: string | undefined): string {
232 if (id === 'main') return 'The main thread'
233 return description !== undefined && description !== '' ? description : `Agent ${id.slice(0, 8)}`
234}
235
236// a configured number, or the default when unset or not a number, held within bounds
237export function setting(value: unknown, fallback: number, min: number, max: number): number {
238 const n = Number(value ?? fallback)
239 return Number.isFinite(n) ? Math.min(max, Math.max(min, n)) : fallback
240}
241
242// module state: a reload starts these over, so a toast may repeat once after one
243let crowd: Crowd = { isArmed: true, lastToastAt: -Infinity }
244const flaggedContext = new Set<string>()
245let lastRefreshAt = -Infinity
246// the line the band draws
247let line: string[] | undefined
248
249// the band draws the line where it is raised; the status carries it where it is not
250async function show($: EngineInterface, parts: string[]) {
251 if (line === undefined || line.join(' · ') !== parts.join(' · ')) {
252 line = parts
253 $.ui.invalidate('ui.render')
254 }
255 $.ui.status(needsStatus(await $.session.surfaces()) ? parts.join(' · ') : undefined)
256}
257
258async function refresh($: EngineInterface, limits: Thresholds) {
259 const now = await $.clock.now()
260 lastRefreshAt = now
261 const agents = await read($, agentsSeen)
262 const listed = await $.agent.list()
263 const running = new Set(listed.filter(a => isLive(a.status)).map(a => a.id))
264 const descriptions = new Map(listed.map(a => [a.id, a.description]))
265 const tree = new Map<string, AgentNode>(listed.map(a => [a.id, { parentId: a.parentId, name: a.name }]))
266 const home = (await $.env.get('HOME')) ?? (await $.env.get('USERPROFILE'))
267 const cwd = shortPath(await $.session.cwd(), home)
268 await show($, modelParts(await $.session.model(), agents, running, limits, cwd, tree))
269
270 const live = liveAgents(agents, running)
271 const alarm = crowdAlarm(crowd, live.length, now, limits.liveAgents)
272 crowd = alarm.crowd
273 if (alarm.toast) $.ui.toast(`${live.length} agents are running at once in this session`)
274 for (const id of live) {
275 const context = agents[id]?.context ?? 0
276 if (context >= limits.context && !flaggedContext.has(id)) {
277 flaggedContext.add(id)
278 $.ui.toast(`${agentLabel(id, descriptions.get(id))} is re-reading ${tokens(context)} of context on every request`)
279 }
280 }
281}
282
283export const register: Register = (on, options) => {
284 const limits: Thresholds = {
285 liveAgents: setting(options.liveAgentsWarn, 6, 2, 100),
286 context: setting(options.contextWarnK, 300, 10, 10_000) * 1000,
287 }
288
289 on('session.start', async ($, e, next) => {
290 const result = await next(e)
291 await refresh($, limits)
292 // agents finish between steps: keep the live counts honest
293 $.clock.every(15_000, () => refresh($, limits).catch(() => undefined))
294 return result
295 })
296
297 on('session.end', { reason: 'clear' }, async ($, e, next) => {
298 await update($, agentsSeen, () => ({}))
299 flaggedContext.clear()
300 crowd = { isArmed: true, lastToastAt: -Infinity }
301 const result = await next(e)
302 await refresh($, limits)
303 return result
304 })
305
306 // every model request of the main loop, a subagent or an in-process teammate
307 on('turn.step', async function* ($, e, next) {
308 const result = yield* next(e)
309 const usage = result.usage
310 // a request that got no response used no model
311 if (usage === null) return result
312 // the model that actually answered (a fallback may differ from the one asked)
313 const model = usage.model
314 const id = e.agentId ?? 'main'
315 const context = usage.input_tokens + usage.cache_read_input_tokens + usage.cache_creation_input_tokens
316 // absent for a model that takes no effort
317 const effort = e.effort
318 // a new agent, model or effort redraws at once; otherwise the throttle decides
319 const before = (await read($, agentsSeen))[id]
320 const isNew = before?.model !== model || before.effort !== effort
321 await update($, agentsSeen, agents => ({ ...agents, [id]: { model, context, effort } }))
322 if (isNew || (await $.clock.now()) - lastRefreshAt >= REFRESH_MIN_MS) await refresh($, limits)
323 return result
324 })
325
326 // these two gate the engine: a failed redraw must not fail the switch or the move
327 on('classic.PostModelSwitch', async ($, e, next) => {
328 const result = await next(e)
329 await refresh($, limits).catch(() => undefined)
330 return result
331 })
332
333 // a shell `cd`, `/cd` or a worktree move
334 on('classic.CwdChanged', async ($, e, next) => {
335 const result = await next(e)
336 await refresh($, limits).catch(() => undefined)
337 return result
338 })
339
340 // a phone or an IDE joining or leaving changes whether the status is needed
341 on('session.attach', async ($, e, next) => {
342 const result = await next(e)
343 if (line !== undefined) await show($, line)
344 return result
345 })
346 on('session.detach', async ($, e, next) => {
347 const result = await next(e)
348 if (line !== undefined) await show($, line)
349 return result
350 })
351
352 // one dim line in the band above the prompt, under what the plugins beneath drew;
353 // only the parts marked ⚠ take the warning color
354 on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
355 const below = await next(e)
356 if (e.props.hasSurvey || line === undefined) return below
357 const { Box, Text } = $.ui.resolve(e)
358 return (
359 <Box flexDirection="column">
360 {below}
361 <Text wrap="truncate-end">
362 {runs(fitLine(line, e.props.bodyColumns)).map(r => (r.isWarning ? <Text color="warning">{r.text}</Text> : <Text dimColor>{r.text}</Text>))}
363 </Text>
364 </Box>
365 )
366 })
367}
368types/index.d.ts 19 lines1// what the mod has seen of one agent ('main', or a subagent or teammate id)
2export type AgentSeen = {
3 // the model id its latest request called; absent in state from before 0.5.0
4 model?: string
5 // tokens its latest request carried: input plus cache reads and writes
6 context: number
7 // the effort its latest request asked for: a level or an integer budget; absent
8 // for a model that takes none
9 effort?: string | number
10}
11
12export type AgentsSeen = Record<string, AgentSeen>
13
14declare module 'claude-code' {
15 interface PluginState {
16 'session-models': { agents: AgentsSeen }
17 }
18}
19