Live coding-orchestrator cockpit: relay context zone, a plain-language timeline of what the main loop and subagents are doing, Hunch calls and the Jev decision…

A Claude Code mod (a plugin of function hooks) that shows the orchestrator's state inside Claude Code.
Band above the prompt
● AMBER 162k/250k ██████░░░░ Jev ✔ 🧠 hunch 5 ⚠1 now: run: Run unit tests (12s) agents: critic 2m [ orch ] [ 🗂 9 ] [ hide ]
now: what the main loop is doing this moment, in plain words (read parse.ts, run: <the command's description>, waiting on critic, thinking, idle, waiting for you), and which subagents run and for how long.relay/config.json soft_tokens / hard_tokens.NoApiKey).⚠N counts the ones that warned or failed.agents: the subagents running now, by role, with how long each has run.🗂 N: how many Claude Code sessions are registered on this machine; it opens the /sessions pane./orch pane
By default the pane is short:
you, main, or the role), ✔ / ✖ / ■ / ▶, a few plain words, and how long it took. Every tool call is a line (read parse.ts, edit register.tsx, run: Run unit tests, Hunch: check rules for lib/a.dart, start critic (fable): Review diff), as are your prompts, each subagent finishing and each turn ending. A line with more behind it (the full shell command, an agent's brief, an edit's old and new text, a long prompt) has a ▸ button that opens it as a drawer below the line; ▾ closes it.details opens the full sections below:
htask_ id, calls per tool, and the last eight calls (mcp__hunch__* or plugin-provided mcp__plugin_hunch_hunch__* tools and the hunch CLI run through Bash, task verify included) with caller, duration, target and outcome: constraint counts, merge verdict, escalations, verify exit code.relay/jev-log.jsonl./sessions pane
One row per registered Claude Code session, from the registry Claude Code keeps in ~/.claude/sessions/<pid>.json: name, repo, idle or busy, and how long since it last changed; this session is marked. A VS Code session has a switch button that runs bin/session-focus.py (with python, else python3, else py), which asks the handoff bridge (0.6.0 or later) in the window that owns the session to bring its tab forward; a terminal session has no button. The helper refuses a registry file whose process is gone or whose PID now belongs to another process, so a stale entry does not send the switch to a window that would resume a duplicate of the session. A crashed session's file can linger until its row's switch reports it gone. Switching needs session-focus.py and rollover-open.py in ~/.claude/bin and the bridge installed in every VS Code window.
Toasts when the zone changes, a role report comes back weak (a missing field, confidence below high, or UNVERIFIED items), the Jev risk gate denies an action, Jev flags a weak report, Jev goes offline, a Hunch invariant of warning severity or above first applies (once per session), a Hunch merge verdict is BLOCK, Hunch escalations need your decision, a task verify check fails, a Hunch call errors, or a task is finished without a hunch_context brief.
/orch band hides or shows the band; while it is hidden, a one-line summary sits in the status line.
Copy this folder to ~/.claude/mods/mission-control, then name it in the env block of ~/.claude/settings.json so every session in every repo loads it:
"env": {
"CLAUDE_CODE_PLUGIN_DIRS": "C:\\Users\\<you>\\.claude\\mods\\mission-control"
}
Several plugin folders are separated by the platform's path-list separator (; on Windows, : elsewhere). Open sessions pick it up after a restart; an interactive session then reloads the mod whenever a file in the folder is saved.
claude plugin validate mods/mission-control
claude plugin test mods/mission-control
The engine writes the API types into .claude-plugin/types/ and a tsconfig.json beside them when it loads the mod; both are generated and ignored here.
hooks/register.tsx 1023 lines1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, Register, ToolCallResult } from 'claude-code'
3
4import type {
5 ActivityEntry,
6 AgentRun,
7 Gauge,
8 HunchCall,
9 HunchConstraint,
10 HunchLevel,
11 HunchLog,
12 JevStatus,
13 ReportCard,
14 SessionRow,
15 Zone,
16} from '../types'
17import {
18 ago,
19 bar,
20 capDetail,
21 clip,
22 clockSeconds,
23 clockTime,
24 describeTool,
25 hunchCli,
26 hunchInvocation,
27 hunchName,
28 hunchOutcome,
29 isRole,
30 isToastSeverity,
31 jevStatus,
32 kTokens,
33 localDay,
34 maxLevel,
35 parseCard,
36 parseLines,
37 reapStale,
38 repoName,
39 roleOf,
40 seconds,
41 sessionRow,
42 sessionRows,
43 shortModel,
44 STALE_MS,
45 toolDetail,
46 wasInterrupted,
47 zoneOf,
48} from './parse'
49
50const PANE = 'mission-control'
51const SESSIONS_PANE = 'mission-control-sessions'
52const POLL_MS = 5000
53
54const agents = atom({ plugin: 'mission-control', key: 'agents' } as const, [])
55const reports = atom({ plugin: 'mission-control', key: 'reports' } as const, [])
56const gauge = atom({ plugin: 'mission-control', key: 'gauge' } as const, null)
57const jev = atom({ plugin: 'mission-control', key: 'jev' } as const, null)
58const hunch = atom({ plugin: 'mission-control', key: 'hunch' } as const, { calls: [], total: 0, seenConstraints: [] })
59const isBandHidden = atom({ plugin: 'mission-control', key: 'isBandHidden' } as const, false)
60const tick = atom({ plugin: 'mission-control', key: 'tick' } as const, 0)
61const sessions = atom({ plugin: 'mission-control', key: 'sessions' } as const, [])
62const sessionsCheckedAt = atom({ plugin: 'mission-control', key: 'sessionsCheckedAt' } as const, 0)
63const activity = atom({ plugin: 'mission-control', key: 'activity' } as const, [])
64const showDetails = atom({ plugin: 'mission-control', key: 'showDetails' } as const, false)
65const openEntries = atom({ plugin: 'mission-control', key: 'openEntries' } as const, [])
66// Set by a prompt, cleared when the main loop's turn ends: the timeline's prompt line can scroll out mid-turn.
67const turnOpen = atom({ plugin: 'mission-control', key: 'turnOpen' } as const, false)
68
69const DRAWER_LINES = 20
70
71const HUNCH_KEEP = 40
72const ACTIVITY_KEEP = 80
73const TIMELINE_ROWS = 15
74
75const ACTIVITY_MARK: Record<ActivityEntry['status'], string> = { running: '▶', ok: '✔', error: '✖', stopped: '■', note: '·' }
76
77const ACTIVITY_COLOR: Record<ActivityEntry['status'], string | undefined> = {
78 running: 'yellow',
79 ok: 'green',
80 error: 'red',
81 stopped: 'gray',
82 note: undefined,
83}
84
85const ZONE_PLAIN: Record<Zone, string> = {
86 green: 'keep going',
87 amber: 'getting full, hand off soon',
88 red: 'full, hand off now',
89 unknown: 'not measured yet',
90}
91
92const HUNCH_COLOR: Record<HunchLevel, string | undefined> = { info: undefined, warn: 'yellow', alert: 'red' }
93
94const HUNCH_MARK: Record<HunchCall['status'], string> = { running: '…', ok: '✔', error: '✖', denied: '⛔' }
95
96const ZONE_COLOR: Record<Zone, string> = { green: 'green', amber: 'yellow', red: 'red', unknown: 'gray' }
97
98const ZONE_HINT: Record<Zone, string> = {
99 green: 'continue',
100 amber: 'delegate reads, hand off at the next boundary',
101 red: 'write a relay handoff before new work',
102 unknown: '',
103}
104
105const CONFIDENCE_COLOR: Record<ReportCard['confidence'], string> = {
106 high: 'green',
107 medium: 'yellow',
108 low: 'red',
109 missing: 'red',
110}
111
112// A hot reload evaluates this module afresh, so these start over; everything drawn lives in $.state.
113let homeDir = ''
114let relayDir = ''
115let soft = 150_000
116let hard = 250_000
117let isJevEnabled = true
118let logSize = -1
119let alertCursor = -1
120
121async function loadRelay($: EngineInterface) {
122 // An empty variable counts as unset.
123 const home = (await $.env.get('USERPROFILE')) || (await $.env.get('HOME')) || ''
124 homeDir = home.replace(/\\/g, '/')
125 relayDir = `${homeDir}/.claude/relay`
126
127 try {
128 const config = JSON.parse(await $.fs.read(`${relayDir}/config.json`)) as {
129 soft_tokens?: number
130 hard_tokens?: number
131 jev?: { enabled?: boolean }
132 }
133 soft = config.soft_tokens ?? soft
134 hard = config.hard_tokens ?? hard
135 isJevEnabled = config.jev?.enabled !== false
136 } catch {
137 // no relay installed: default thresholds, the gauge still draws
138 }
139}
140
141async function measure($: EngineInterface, tokens: number | undefined, window: number, percent?: number, usd?: number) {
142 const zone = zoneOf(tokens, soft, hard)
143 const before = await read($, gauge)
144 const next: Gauge = { tokens, window, percent, zone, soft, hard, usd }
145 await update($, gauge, () => next)
146
147 if (before !== null && before.zone !== zone && zone !== 'unknown' && before.zone !== 'unknown') {
148 $.ui.toast(`Relay ${zone.toUpperCase()} at ${kTokens(tokens)}: ${ZONE_HINT[zone]}`, { timeoutMs: 8000 })
149 }
150 await refreshStatus($)
151}
152
153async function pollJev($: EngineInterface) {
154 const path = `${relayDir}/jev-log.jsonl`
155 const stat = await $.fs.stat(path).catch(() => undefined)
156
157 // Rotated away or truncated: the next file's lines are all new, so alert on them from its start.
158 if (stat === undefined || stat.size < logSize) {
159 logSize = -1
160 if (alertCursor >= 0) alertCursor = 0
161 }
162 if (stat === undefined) {
163 await update($, jev, () => ({ isOnline: null, spendToday: 0, deniesToday: 0, weakToday: 0, recent: [], note: 'no jev-log.jsonl' }))
164 return
165 }
166 if (stat.size === logSize) return
167 logSize = stat.size
168
169 let raw: string
170 try {
171 raw = await $.fs.read(path)
172 } catch {
173 await update($, jev, current => ({
174 ...(current ?? { isOnline: null, spendToday: 0, deniesToday: 0, weakToday: 0, recent: [] }),
175 note: 'jev-log.jsonl unreadable (over 4 MiB?)',
176 }))
177 return
178 }
179
180 const lines = parseLines(raw)
181 const before = await read($, jev)
182 const status: JevStatus = jevStatus(lines, localDay(await $.clock.now()), isJevEnabled)
183 await update($, jev, () => status)
184
185 // Alert only on lines written after this load first read the log.
186 if (alertCursor >= 0) {
187 for (const line of lines.slice(alertCursor)) {
188 if (line.feature === 'risk_gate' && line.decision === 'deny') {
189 const why = line.fail_closed === true ? `fail-closed, Jev ${String(line.error ?? 'unavailable')}` : 'risky'
190 $.ui.toast(`⛔ Jev risk gate denied ${String(line.op ?? 'the action')} (${why})`, { timeoutMs: 10000 })
191 } else if (line.feature === 'report_check' && (line.decision === 'deny' || line.decision === 'weak')) {
192 $.ui.toast(`⚠ Jev: ${String(line.subagent_type ?? 'subagent')} report ${String(line.decision)}`, { timeoutMs: 8000 })
193 }
194 }
195 }
196 alertCursor = lines.length
197
198 if (before !== null && before.isOnline === true && status.isOnline === false) {
199 $.ui.toast(`Jev went offline: ${status.lastError ?? 'unavailable'}; risk gate now fails closed`, { timeoutMs: 10000 })
200 }
201 await refreshStatus($)
202}
203
204/** The calls that belong to the current task, or every call while no task id has been seen. */
205function taskCalls(log: HunchLog): HunchCall[] {
206 return log.taskId === undefined ? log.calls : log.calls.filter(call => call.taskId === undefined || call.taskId === log.taskId)
207}
208
209function loudest(calls: HunchCall[]): HunchLevel {
210 return calls.reduce<HunchLevel>((level, call) => maxLevel(level, call.level), 'info')
211}
212
213function resultText(result: ToolCallResult): string {
214 if (result.deny !== undefined) return result.deny
215 if (result.text !== undefined) return result.text
216 if (typeof result.result === 'string') return result.result
217
218 return result.result === undefined ? '' : JSON.stringify(result.result)
219}
220
221async function startHunchCall(
222 $: EngineInterface,
223 id: string,
224 agentId: string | undefined,
225 invocation: { name: string; target: string; taskId?: string },
226) {
227 const caller = agentId === undefined ? undefined : (await read($, agents)).find(agent => agent.id === agentId)
228 const call: HunchCall = {
229 id,
230 name: invocation.name,
231 target: invocation.target,
232 taskId: invocation.taskId,
233 role: agentId === undefined ? 'main' : roleOf(caller?.type ?? 'subagent'),
234 startedAt: await $.clock.now(),
235 status: 'running',
236 summary: '',
237 level: 'info',
238 }
239 await update($, hunch, log => ({
240 ...log,
241 taskId: agentId === undefined ? (invocation.taskId ?? log.taskId) : log.taskId,
242 total: log.total + 1,
243 calls: [...reapStale(log.calls, call.startedAt).filter(one => one.id !== id), call].slice(-HUNCH_KEEP),
244 }))
245 await refreshStatus($)
246}
247
248async function finishHunchCall($: EngineInterface, id: string, result: ToolCallResult) {
249 const log = await read($, hunch)
250 const call = log.calls.find(one => one.id === id)
251 if (call === undefined) return
252
253 const now = await $.clock.now()
254 const isDenied = result.deny !== undefined
255
256 // The person stopped it: no verdict on Hunch, so no failure toast and no finish check.
257 if (!isDenied && wasInterrupted(result.result, resultText(result))) {
258 const stopped: HunchCall = { ...call, status: 'error', durationMs: now - call.startedAt, summary: 'interrupted', level: 'info' }
259 await update($, hunch, current => ({ ...current, calls: current.calls.map(one => (one.id === id ? stopped : one)) }))
260 await refreshStatus($)
261
262 return
263 }
264
265 const isError = isDenied || result.isError === true
266 const outcome = hunchOutcome(call.name, resultText(result), isError)
267 const taskId = call.taskId ?? outcome.taskId
268 let { level, summary } = outcome
269
270 // A task closed through the tool without the brief Hunch says to read first.
271 const isFinish = call.name === 'task' && call.target.startsWith('finish')
272 const hadContext = log.calls.some(
273 one => one.name === 'context' && (taskId === undefined || one.taskId === undefined || one.taskId === taskId),
274 )
275 if (isFinish && !isError && !hadContext) {
276 level = maxLevel(level, 'warn')
277 summary = `no hunch_context this task · ${summary}`
278 }
279
280 let fresh: HunchConstraint[] = []
281 const done: HunchCall = {
282 ...call,
283 taskId,
284 status: isDenied ? 'denied' : isError ? 'error' : 'ok',
285 durationMs: now - call.startedAt,
286 summary,
287 level,
288 }
289 // Read seenConstraints inside the write, so parallel checks of one invariant toast it once.
290 // 5: a task id in an output only moves the current task when the main loop started it.
291 const isMainStart = call.role === 'main' && call.name === 'task' && call.target.startsWith('start')
292 await update($, hunch, current => {
293 fresh = outcome.constraints.filter(one => isToastSeverity(one.severity) && !current.seenConstraints.includes(one.id))
294
295 return {
296 ...current,
297 taskId: isMainStart ? (outcome.taskId ?? current.taskId) : current.taskId,
298 seenConstraints: [...current.seenConstraints, ...fresh.map(one => one.id)].slice(-200),
299 calls: current.calls.map(one => (one.id === id ? done : one)),
300 }
301 })
302
303 const where = call.target === '' ? '' : ` (${call.target})`
304 const first = fresh[0]
305 if (first !== undefined) {
306 const more = fresh.length > 1 ? ` +${fresh.length - 1} more` : ''
307 $.ui.toast(`🧠 Hunch invariant [${first.severity}]${where}: ${first.statement}${more}`, { timeoutMs: 10000 })
308 }
309 if (outcome.verdict === 'BLOCK') {
310 $.ui.toast(`⛔ Hunch merge verdict BLOCK${where}: fix the cited invariant before merging`, { timeoutMs: 12000 })
311 }
312 if (call.name === 'escalations' && level === 'alert' && !isError) {
313 $.ui.toast(`🧠 Hunch escalations: ${summary}; ask the user, silence is never approval`, { timeoutMs: 10000 })
314 }
315 if (call.name === 'verify' && level === 'alert') {
316 $.ui.toast(`✖ Hunch verify ${summary}${where}`, { timeoutMs: 10000 })
317 }
318 if (isError && call.name !== 'verify') {
319 $.ui.toast(`✖ Hunch ${call.name} ${isDenied ? 'denied' : 'failed'}: ${summary}`, { timeoutMs: 8000 })
320 }
321 if (isFinish && !hadContext && !isError) {
322 $.ui.toast('⚠ Hunch task finished without a hunch_context brief', { timeoutMs: 8000 })
323 }
324 await refreshStatus($)
325}
326
327/** Closes a call that got no result: `interrupted` (the dispatch was abandoned) is quiet, `lost` alerts. */
328async function settleHunchCall($: EngineInterface, id: string, why: 'interrupted' | 'lost') {
329 const now = await $.clock.now()
330 const [level, summary] = why === 'interrupted' ? (['info', 'interrupted'] as const) : (['alert', 'aborted or not recorded'] as const)
331 await update($, hunch, log => ({
332 ...log,
333 calls: log.calls.map(one =>
334 one.id === id && one.status === 'running' ? { ...one, status: 'error' as const, level, durationMs: now - one.startedAt, summary } : one,
335 ),
336 }))
337 await refreshStatus($)
338}
339
340async function whoOf($: EngineInterface, agentId: string | undefined): Promise<string> {
341 if (agentId === undefined) return 'main'
342 const run = (await read($, agents)).find(agent => agent.id === agentId)
343
344 return roleOf(run?.type ?? 'agent')
345}
346
347/** Adds or replaces one timeline line; running lines older than STALE_MS are closed as stopped. */
348async function logActivity($: EngineInterface, entry: ActivityEntry) {
349 await update($, activity, list =>
350 [
351 ...list
352 .filter(one => one.id !== entry.id)
353 .map(one => (one.status === 'running' && entry.at - one.at > STALE_MS ? { ...one, status: 'stopped' as const } : one)),
354 entry,
355 ].slice(-ACTIVITY_KEEP),
356 )
357}
358
359/** Closes one line; a line already closed as stale (stopped, no duration) still takes its real outcome. */
360async function endActivity($: EngineInterface, id: string, status: ActivityEntry['status']) {
361 const now = await $.clock.now()
362 const isOpen = (one: ActivityEntry) => one.status === 'running' || (one.status === 'stopped' && one.durationMs === undefined)
363 await update($, activity, list => list.map(one => (one.id === id && isOpen(one) ? { ...one, status, durationMs: now - one.at } : one)))
364}
365
366/** Closes running lines older than STALE_MS as stopped; writes only when one changed, so idle polls draw nothing. */
367async function reapActivity($: EngineInterface, now: number) {
368 const isStale = (one: ActivityEntry) => one.status === 'running' && now - one.at > STALE_MS
369 if (!(await read($, activity)).some(isStale)) return
370 await update($, activity, list => list.map(one => (isStale(one) ? { ...one, status: 'stopped' as const } : one)))
371}
372
373/** The time a drawing measures ages against, from state alone: the poll's tick advances it while work runs. */
374function drawnNow(tick: number, list: readonly ActivityEntry[], runs: readonly AgentRun[]): number {
375 return Math.max(tick, ...list.map(one => one.at), ...runs.map(run => run.startedAt))
376}
377
378/** What the session is doing right now, in a few words. */
379function nowText(list: readonly ActivityEntry[], running: readonly AgentRun[], now: number, isTurnOpen: boolean): string {
380 const main = list.filter(one => one.who === 'main' && one.status === 'running').at(-1)
381 if (main !== undefined) return `${main.text} (${seconds(now - main.at)})`
382 if (running.length > 0) return `waiting on ${running.map(agent => roleOf(agent.type)).join(', ')}`
383
384 return isTurnOpen ? 'thinking' : 'idle, waiting for you'
385}
386
387/** The status line text last set by this copy of the module; a repeat of it is not sent again. */
388let shownStatus: string | undefined | null = null
389
390function setStatus($: EngineInterface, text: string | undefined) {
391 if (text === shownStatus) return
392 shownStatus = text
393 $.ui.status(text)
394}
395
396async function refreshStatus($: EngineInterface) {
397 if (!(await read($, isBandHidden))) {
398 setStatus($, undefined)
399 return
400 }
401 const g = await read($, gauge)
402 const list = await read($, agents)
403 const running = list.filter(agent => agent.status === 'running')
404 const zone = g === null ? '?' : g.zone.toUpperCase()
405 const lines = await read($, activity)
406 const doing = nowText(lines, running, drawnNow(await read($, tick), lines, running), await read($, turnOpen))
407 setStatus($, clip(`${zone} ${kTokens(g?.tokens)} · now: ${doing} · ${running.length} agents`, 100))
408}
409
410function openPane($: EngineInterface) {
411return $.ui.open({ id: PANE, title: 'Mission Control' })
412}
413
414/** Rereads the session registry; writes the atom only when a row changed, so idle polls draw nothing. */
415async function pollSessions($: EngineInterface) {
416 if (homeDir === '') await loadRelay($)
417 const dir = `${homeDir}/.claude/sessions`
418 const entries = await $.fs.list(dir).catch(() => [])
419 const files = entries.filter(entry => entry.kind === 'file' && entry.name.endsWith('.json'))
420 const raws = await Promise.all(files.map(entry => $.fs.read(`${dir}/${entry.name}`).catch(() => '')))
421 const rows = sessionRows(raws.flatMap(raw => sessionRow(typeof raw === 'string' ? raw : '') ?? []))
422
423 if (JSON.stringify(rows) !== JSON.stringify(await read($, sessions))) await update($, sessions, () => rows)
424
425 // Ages are drawn from the clock: bump this at most every 30 s so the pane redraws without a row change.
426 const checkedAt = Math.floor((await $.clock.now()) / 30_000) * 30_000
427 if (checkedAt !== (await read($, sessionsCheckedAt))) await update($, sessionsCheckedAt, () => checkedAt)
428}
429
430// `python` first, then `python3` where only that is installed, then `py`, the Windows launcher.
431const PYTHONS = ['python', 'python3', 'py']
432
433/** Runs a Python script with the first interpreter that starts; 9009 is Windows' "not found" (the Store alias). */
434async function runPython($: EngineInterface, args: string[], timeoutMs: number) {
435 let failure: unknown
436 let notFound: Awaited<ReturnType<EngineInterface['process']['run']>> | undefined
437 for (const python of PYTHONS) {
438 try {
439 const run = await $.process.run([python, ...args], { timeoutMs })
440 if (run.exitCode !== 9009) return run
441 notFound ??= run
442 } catch (error) {
443 // Only a missing interpreter moves on: a timeout or abort means the script itself ran.
444 if (!/failed to start|ENOENT/i.test(error instanceof Error ? error.message : String(error))) throw error
445 failure ??= error
446 }
447 }
448 if (notFound !== undefined) return notFound
449 throw failure
450}
451
452/** Asks the handoff bridge in the session's own VS Code window to bring its tab forward. */
453async function focusSession($: EngineInterface, row: SessionRow) {
454 $.ui.toast(`Switching to ${row.name}…`, { timeoutMs: 3000 })
455 let message: string
456 try {
457 const helper = `${homeDir}/.claude/bin/session-focus.py`
458 const { exitCode, stdout, stderr } = await runPython($, [helper, '--session', row.sessionId], 20_000)
459 const last = (text: string) => text.trim().split(/\r?\n/).at(-1) ?? ''
460 const line = last(stdout) || last(stderr) || `session-focus exited ${exitCode}`
461 message = exitCode === 0 ? `🗂 ${line}` : `✖ ${line}`
462 } catch (error) {
463 message = `✖ session-focus could not run: ${error instanceof Error ? error.message : String(error)}`
464 }
465 $.ui.toast(message, { timeoutMs: 8000 })
466}
467
468async function openSessions($: EngineInterface) {
469 await pollSessions($)
470
471 return $.ui.open({ id: SESSIONS_PANE, title: 'Sessions' })
472}
473
474async function setBandHidden($: EngineInterface, isHidden: boolean) {
475 await update($, isBandHidden, () => isHidden)
476 await refreshStatus($)
477}
478
479export const register: Register = on => {
480 on('session.start', async ($, e, next) => {
481 await loadRelay($)
482 await $.command.register({
483 name: 'orch',
484 description: 'Mission Control: open the orchestrator pane (`/orch band` toggles the band)',
485 })
486 await $.command.register({
487 name: 'sessions',
488 description: 'Mission Control: list open Claude Code sessions and switch VS Code to one',
489 })
490
491 const usage = await $.session.usage()
492 await measure($, usage.context.tokens, usage.context.window, usage.context.percent, usage.cost?.usd)
493 await pollJev($)
494 await pollSessions($)
495
496 $.clock.every(POLL_MS, () => {
497 void (async () => {
498 await pollJev($)
499 await pollSessions($)
500 const list = await read($, agents)
501 await reapActivity($, await $.clock.now())
502 const isBusy = (await read($, activity)).some(one => one.status === 'running')
503 if (isBusy || list.some(agent => agent.status === 'running')) {
504 const now = await $.clock.now()
505 await update($, tick, () => now)
506 }
507 })()
508 })
509
510 return next(e)
511 })
512
513 on('command.run', { command: 'orch' }, async ($, e) => {
514 if (e.args.trim() === 'band') {
515 const isHidden = !(await read($, isBandHidden))
516 await setBandHidden($, isHidden)
517
518 return { text: isHidden ? 'Mission Control band hidden (summary moved to the status line).' : 'Mission Control band shown.' }
519 }
520 await openPane($)
521
522 return { text: 'Mission Control opened.' }
523 })
524
525 on('command.run', { command: 'sessions' }, async ($) => {
526 await openSessions($)
527 const count = (await read($, sessions)).length
528
529 return { text: `Sessions opened: ${count} registered.` }
530 })
531
532 on('prompt.submit', async ($, e, next) => {
533 try {
534 const at = await $.clock.now()
535 const detail = e.text.length > 70 ? capDetail(e.text) : undefined
536 await update($, turnOpen, () => true)
537 await logActivity($, { id: `prompt-${at}`, at, who: 'you', text: `asked: "${clip(e.text, 70)}"`, status: 'note', detail })
538 } catch {
539 // the timeline is a view; a prompt never waits on it
540 }
541
542 return next(e)
543 }).catch(($, e, next) => next(e))
544
545 // Every tool call, from the main loop or a subagent, becomes one plain timeline line.
546 on('tool.call', async ($, e, next) => {
547 const id = e.tool_use_id
548 // Logged alongside the call, not before it: the tool never waits on the timeline.
549 const logged = (async () => {
550 const at = await $.clock.now()
551 const args = e as unknown as Record<string, unknown>
552 const text = describeTool(e.tool, args)
553 const detail = toolDetail(e.tool, args) || undefined
554 await logActivity($, { id, at, who: await whoOf($, e.agentId), text, status: 'running', detail })
555 await refreshStatus($)
556 })().catch(() => undefined)
557
558 let status: ActivityEntry['status'] = 'stopped'
559 try {
560 const result = await next(e)
561 if (!next.signal.aborted) {
562 const isStopped = result.deny === undefined && wasInterrupted(result.result, resultText(result))
563 status = isStopped ? 'stopped' : result.deny !== undefined || result.isError === true ? 'error' : 'ok'
564 }
565
566 return result
567 } finally {
568 // A fast call can settle before its line is written; close the line only once it exists.
569 await logged
570 await endActivity($, id, status).catch(() => undefined)
571 await refreshStatus($).catch(() => undefined)
572 }
573 // An observer: whatever went wrong here, the call itself goes on (or replays what it settled to).
574 }).catch(($, e, next) => next(e))
575
576 on('session.measure', async ($, e, next) => {
577 await measure($, e.context.tokens, e.context.window, e.context.percent, e.cost?.usd)
578
579 return next(e)
580 })
581
582 on('agent.spawn', async ($, e, next) => {
583 const spawned = await next(e)
584 const agentId = 'agentId' in spawned ? spawned.agentId : undefined
585 const model = 'model' in spawned ? spawned.model : undefined
586
587 if (agentId !== undefined && model !== undefined) {
588 const run: AgentRun = {
589 id: agentId,
590 type: e.subagentType,
591 model: shortModel(model),
592 description: e.description,
593 isBackground: e.background,
594 startedAt: await $.clock.now(),
595 status: 'running',
596 }
597 await update($, agents, list => [...list.filter(one => one.id !== agentId), run].slice(-30))
598 await refreshStatus($)
599 }
600
601 return spawned
602 }).catch(($, e, next) => next(e))
603
604 on('turn.complete', async ($, e, next) => {
605 const agentId = e.agentId
606 if (agentId === undefined) {
607 const at = await $.clock.now()
608 const how = e.reason === 'answer' ? 'answered' : e.reason === 'aborted' ? 'stopped' : 'ended with an error'
609 await logActivity($, {
610 id: `turn-${at}`,
611 at,
612 who: 'main',
613 text: `${how} (turn took ${seconds(e.durationMs)})`,
614 status: e.reason === 'answer' ? 'note' : e.reason === 'aborted' ? 'stopped' : 'error',
615 }).catch(() => undefined)
616 await update($, turnOpen, () => false).catch(() => undefined)
617 await refreshStatus($).catch(() => undefined)
618
619 return next(e)
620 }
621
622 const now = await $.clock.now()
623 const status: AgentRun['status'] = e.reason === 'answer' ? 'done' : e.reason === 'aborted' ? 'aborted' : 'error'
624 const run = (await read($, agents)).find(one => one.id === agentId)
625 await update($, agents, list => list.map(one => (one.id === agentId ? { ...one, status, endedAt: now } : one)))
626
627 const type = run?.type ?? 'subagent'
628 const card = parseCard(e.answer)
629
630 // Only role agents owe a card; an Explore or general-purpose answer is not graded.
631 if (status === 'done' && (isRole(type) || card.hasAnyField)) {
632 const report: ReportCard = {
633 agentId,
634 type,
635 model: run?.model ?? shortModel(e.usage?.model ?? ''),
636 at: now,
637 durationMs: e.durationMs,
638 confidence: card.confidence,
639 missing: card.missing,
640 unverified: card.unverified,
641 exitCodes: card.exitCodes,
642 isWeak: card.isWeak,
643 result: card.result,
644 }
645 await update($, reports, list => [...list, report].slice(-20))
646
647 if (card.isWeak) {
648 const why = [
649 card.missing.length > 0 ? `missing ${card.missing.join('/')}` : '',
650 card.confidence !== 'high' && card.confidence !== 'missing' ? `confidence ${card.confidence}` : '',
651 card.unverified > 0 ? `${card.unverified} unverified` : '',
652 ]
653 .filter(Boolean)
654 .join(', ')
655 $.ui.toast(`⚠ ${roleOf(type)} report weak: ${why}; verify before relying on it`, { timeoutMs: 8000 })
656 }
657 }
658 const verdict = card.result === '' ? '' : `: ${card.result}`
659 const graded = card.hasAnyField ? ` (${card.confidence} confidence)` : ''
660 await logActivity($, {
661 id: `agent-end-${agentId}`,
662 at: now,
663 who: roleOf(type),
664 text: clip(status === 'done' ? `finished${graded}${verdict}` : `${status}`, 90),
665 status: status === 'done' ? 'ok' : status === 'aborted' ? 'stopped' : 'error',
666 durationMs: run === undefined ? undefined : now - run.startedAt,
667 }).catch(() => undefined)
668 await refreshStatus($)
669
670 return next(e)
671 })
672
673 on('tool.call', { tool: /^mcp__(?:plugin_hunch_)?hunch__/ }, async ($, e, next) => {
674 const name = hunchName(e.tool)
675 if (name === undefined) return next(e)
676
677 await startHunchCall($, e.tool_use_id, e.agentId, hunchInvocation(name, e as unknown as Record<string, unknown>))
678 const onAbort = () => void settleHunchCall($, e.tool_use_id, 'interrupted').catch(() => undefined)
679 next.signal.addEventListener('abort', onAbort, { once: true })
680 if (next.signal.aborted) onAbort()
681 const result = await next(e)
682 next.signal.removeEventListener('abort', onAbort)
683 // Abandoned, then resolved late (e.g. backgrounded by a turn abort): keep it interrupted.
684 if (next.signal.aborted) return result
685 await finishHunchCall($, e.tool_use_id, result)
686
687 return result
688 }).catch(async ($, e, next) => {
689 try {
690 return await next(e)
691 } finally {
692 await settleHunchCall($, e.tool_use_id, next.signal.aborted ? 'interrupted' : 'lost').catch(() => undefined)
693 }
694 })
695
696 on('tool.call', { tool: 'Bash' }, async ($, e, next) => {
697 const invocation = e.tool === 'Bash' ? hunchCli(e.command) : undefined
698 if (invocation === undefined) return next(e)
699
700 await startHunchCall($, e.tool_use_id, e.agentId, invocation)
701 const onAbort = () => void settleHunchCall($, e.tool_use_id, 'interrupted').catch(() => undefined)
702 next.signal.addEventListener('abort', onAbort, { once: true })
703 if (next.signal.aborted) onAbort()
704 const result = await next(e)
705 next.signal.removeEventListener('abort', onAbort)
706 // Abandoned, then resolved late (e.g. backgrounded by a turn abort): keep it interrupted.
707 if (next.signal.aborted) return result
708 await finishHunchCall($, e.tool_use_id, result)
709
710 return result
711 }).catch(async ($, e, next) => {
712 try {
713 return await next(e)
714 } finally {
715 await settleHunchCall($, e.tool_use_id, next.signal.aborted ? 'interrupted' : 'lost').catch(() => undefined)
716 }
717 })
718
719 on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
720 if (e.props.hasSurvey || (await read($, isBandHidden))) return next(e)
721
722 const { Box, Text, Button } = $.ui.resolve(e)
723 const g = await read($, gauge)
724 const j = await read($, jev)
725 const running = (await read($, agents)).filter(agent => agent.status === 'running')
726 const hunchNow = taskCalls(await read($, hunch))
727 const hunchLevel = loudest(hunchNow)
728 const sessionCount = (await read($, sessions)).length
729 const isWide = e.props.bodyColumns >= 100
730 const list = await read($, activity)
731 const now = drawnNow(await read($, tick), list, running)
732
733 const zone: Zone = g?.zone ?? 'unknown'
734 const fill = g?.tokens === undefined ? 0 : g.tokens / g.hard
735 const jevColor = j?.isOnline === true ? 'green' : j?.isOnline === false ? 'red' : 'gray'
736 const jevText = j?.isOnline === true ? 'Jev ✔' : j?.isOnline === false ? `Jev ✖ ${j.lastError ?? ''}`.trim() : 'Jev ?'
737 const doing = nowText(list, running, now, await read($, turnOpen))
738 const crew = running.map(agent => `${roleOf(agent.type)} ${seconds(now - agent.startedAt)}`).join(', ')
739
740 return (
741 <Box flexDirection="row" flexWrap="wrap" columnGap={2}>
742 <Text color={ZONE_COLOR[zone]} bold>
743 {'●'} {zone.toUpperCase()} {kTokens(g?.tokens)}/{kTokens(g?.hard)}
744 </Text>
745 {isWide && <Text color={ZONE_COLOR[zone]}>{bar(fill, 10)}</Text>}
746 <Text color={jevColor}>{jevText}</Text>
747 <Text color={HUNCH_COLOR[hunchLevel] ?? (hunchNow.length === 0 ? 'gray' : 'cyan')}>
748 {'🧠'} hunch {hunchNow.length}
749 {hunchNow.some(call => call.status === 'running') ? '…' : ''}
750 {hunchLevel !== 'info' ? ` ⚠${hunchNow.filter(call => call.level !== 'info').length}` : ''}
751 </Text>
752 <Text wrap="truncate" color={doing.startsWith('idle') ? 'gray' : 'yellow'}>
753 now: {doing}
754 </Text>
755 {crew !== '' && <Text wrap="truncate">agents: {crew}</Text>}
756 <Button key="open" label="orch" onPress={() => openPane($)} />
757 <Button key="sessions" label={`🗂 ${sessionCount}`} onPress={() => openSessions($)} />
758 <Button key="hide" label="hide" onPress={() => setBandHidden($, true)} />
759 </Box>
760 )
761 })
762
763 on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
764 const { Box, Text, Button } = $.ui.resolve(e)
765 const g = await read($, gauge)
766 const j = await read($, jev)
767 const list = await read($, agents)
768 const cards = await read($, reports)
769 const hunchLog = await read($, hunch)
770 const hunchNow = taskCalls(hunchLog)
771 const counts = new Map<string, number>()
772 for (const call of hunchNow) counts.set(call.name, (counts.get(call.name) ?? 0) + 1)
773 const now = drawnNow(await read($, tick), await read($, activity), list)
774 const width = Math.max(20, e.props.bodyColumns)
775 const zone: Zone = g?.zone ?? 'unknown'
776 const running = list.filter(agent => agent.status === 'running')
777 const lines = await read($, activity)
778 const isDetailed = await read($, showDetails)
779 const opened = await read($, openEntries)
780 const mainNow = lines.filter(one => one.who === 'main' && one.status === 'running').at(-1)
781 const isThinking = await read($, turnOpen)
782 const lastCard = cards.at(-1)
783 const hunchWarnings = hunchNow.filter(call => call.level !== 'info').length
784
785 return (
786 <Box flexDirection="column" width={width}>
787 <Text bold>Now</Text>
788 <Text wrap="truncate" color={mainNow === undefined && running.length === 0 ? 'gray' : 'yellow'}>
789 {' '}main {mainNow === undefined ? (isThinking ? 'thinking' : 'idle, waiting for you') : `${mainNow.text} · ${seconds(now - mainNow.at)}`}
790 </Text>
791 {running.map(agent => (
792 <Text wrap="truncate" color="yellow">
793 {' '}
794 {roleOf(agent.type)} ({agent.model}) {agent.description} · {seconds(now - agent.startedAt)}
795 {agent.isBackground ? ' · background' : ''}
796 </Text>
797 ))}
798
799 <Text bold>Timeline</Text>
800 {lines.length === 0 && <Text dimColor>{' '}Nothing yet.</Text>}
801 {lines
802 .slice(-TIMELINE_ROWS)
803 .reverse()
804 .map(one => {
805 const isOpen = one.detail !== undefined && opened.includes(one.id)
806 const drawer = isOpen ? (one.detail ?? '').split(/\r?\n/) : []
807
808 return (
809 <Box key={`line-${one.id}`} flexDirection="column">
810 <Box flexDirection="row" columnGap={1}>
811 {one.detail !== undefined ? (
812 <Button
813 key={`drawer-${one.id}`}
814 label={isOpen ? '▾' : '▸'}
815 onPress={() => update($, openEntries, ids => (ids.includes(one.id) ? ids.filter(id => id !== one.id) : [...ids, one.id].slice(-20)))}
816 />
817 ) : (
818 <Text> </Text>
819 )}
820 <Text wrap="truncate" color={one.status === 'note' ? undefined : ACTIVITY_COLOR[one.status]} dimColor={one.status === 'note'}>
821 {clockSeconds(one.at)} {clip(one.who, 8).padEnd(8)} {ACTIVITY_MARK[one.status]} {one.text}
822 {one.status === 'running'
823 ? ` · ${seconds(now - one.at)}`
824 : one.durationMs !== undefined && one.durationMs >= 1000
825 ? ` · ${seconds(one.durationMs)}`
826 : ''}
827 </Text>
828 </Box>
829 {drawer.slice(0, DRAWER_LINES).map(line => (
830 <Text dimColor wrap="truncate">
831 {' │ '}
832 {line}
833 </Text>
834 ))}
835 {drawer.length > DRAWER_LINES && <Text dimColor>{` │ … ${drawer.length - DRAWER_LINES} more lines`}</Text>}
836 </Box>
837 )
838 })}
839
840 <Text bold>Summary</Text>
841 <Text wrap="truncate" color={ZONE_COLOR[zone]}>
842 {' '}context {kTokens(g?.tokens)} of {kTokens(g?.hard)} · {zone.toUpperCase()} · {ZONE_PLAIN[zone]}
843 {g?.usd !== undefined ? ` · $${g.usd.toFixed(2)}` : ''}
844 </Text>
845 <Text wrap="truncate">
846 {' '}agents {running.length} running
847 {lastCard !== undefined
848 ? ` · last report: ${roleOf(lastCard.type)} ${lastCard.confidence}${lastCard.unverified > 0 ? `, ${lastCard.unverified} unverified` : ''}`
849 : ''}
850 </Text>
851 <Text wrap="truncate" color={HUNCH_COLOR[loudest(hunchNow)]}>
852 {' '}hunch {hunchNow.length} call{hunchNow.length === 1 ? '' : 's'} · {hunchWarnings === 0 ? 'no warnings' : `${hunchWarnings} warning${hunchWarnings === 1 ? '' : 's'}`}
853 </Text>
854 <Text wrap="truncate" color={j?.isOnline === false ? 'red' : undefined}>
855 {' '}jev {j?.isOnline === true ? 'online' : j?.isOnline === false ? `offline (${j.lastError ?? 'unavailable'})` : 'unknown'}
856 </Text>
857
858 <Box flexDirection="row" columnGap={1}>
859 <Button key="details" label={isDetailed ? 'hide details' : 'details'} onPress={() => update($, showDetails, shown => !shown)} />
860 <Button
861 key="band"
862 label="toggle band"
863 onPress={async () => setBandHidden($, !(await read($, isBandHidden)))}
864 />
865 <Button
866 key="clear"
867 label="clear done"
868 onPress={async () => {
869 await update($, agents, all => all.filter(agent => agent.status === 'running'))
870 await update($, activity, all => all.filter(one => one.status === 'running'))
871 const now = await $.clock.now()
872 await update($, hunch, log => ({ ...log, calls: reapStale(log.calls, now).filter(call => call.status === 'running') }))
873 }}
874 />
875 </Box>
876
877 {isDetailed && (
878 <Box flexDirection="column">
879 <Text bold>Relay</Text>
880 <Text color={ZONE_COLOR[zone]}>
881 {zone.toUpperCase()} {bar(g?.tokens === undefined ? 0 : g.tokens / g.hard, Math.min(24, width - 22))}{' '}
882 {kTokens(g?.tokens)}/{kTokens(g?.hard)}
883 </Text>
884 <Text dimColor wrap="truncate">
885 amber {kTokens(g?.soft)} · red {kTokens(g?.hard)}
886 {g?.usd !== undefined ? ` · session $${g.usd.toFixed(2)}` : ''}
887 {ZONE_HINT[zone] !== '' ? ` · ${ZONE_HINT[zone]}` : ''}
888 </Text>
889
890 <Text bold>In flight ({running.length})</Text>
891 {running.length === 0 && <Text dimColor>No subagents running.</Text>}
892 {running.map(agent => (
893 <Text wrap="truncate">
894 {roleOf(agent.type).padEnd(8)} {agent.model.padEnd(7)} {seconds(now - agent.startedAt).padStart(4)}{' '}
895 {agent.isBackground ? 'bg ' : ''}
896 {agent.description}
897 </Text>
898 ))}
899
900 <Text bold>Report cards</Text>
901 {cards.length === 0 && <Text dimColor>No role reports yet.</Text>}
902 {cards
903 .slice(-6)
904 .reverse()
905 .map(card => (
906 <Box flexDirection="column">
907 <Text wrap="truncate">
908 <Text color={CONFIDENCE_COLOR[card.confidence]}>{card.confidence.toUpperCase().padEnd(7)}</Text>{' '}
909 {roleOf(card.type).padEnd(8)} {seconds(card.durationMs).padStart(4)}
910 {card.exitCodes.length > 0 ? ` exit ${card.exitCodes.join(',')}` : ''}
911 {card.unverified > 0 ? ` ⚠ ${card.unverified} unverified` : ''}
912 {card.missing.length > 0 ? ` missing ${card.missing.join('/')}` : ''}
913 </Text>
914 {card.result !== '' && (
915 <Text dimColor wrap="truncate">
916 {' '}
917 {card.result}
918 </Text>
919 )}
920 </Box>
921 ))}
922
923 <Text bold>
924 Hunch{' '}
925 <Text color={HUNCH_COLOR[loudest(hunchNow)]}>
926 {hunchLog.taskId ?? 'no task id yet'} · {hunchNow.length} call{hunchNow.length === 1 ? '' : 's'}
927 </Text>
928 </Text>
929 {hunchNow.length === 0 && <Text dimColor>No Hunch calls yet this task.</Text>}
930 {counts.size > 0 && (
931 <Text dimColor wrap="truncate">
932 {[...counts].map(([name, count]) => `${name} ${count}`).join(' · ')}
933 </Text>
934 )}
935 {hunchNow
936 .slice(-8)
937 .reverse()
938 .map(call => (
939 <Box flexDirection="column">
940 <Text wrap="truncate" color={HUNCH_COLOR[call.level]}>
941 {clockTime(call.startedAt)} {HUNCH_MARK[call.status]} {call.role.padEnd(7)} {call.name.padEnd(17)}{' '}
942 {call.durationMs === undefined ? '' : `${seconds(call.durationMs).padStart(4)} `}
943 {call.target}
944 </Text>
945 {call.summary !== '' && (
946 <Text dimColor wrap="truncate">
947 {' '}
948 {call.summary}
949 </Text>
950 )}
951 </Box>
952 ))}
953
954 <Text bold>
955 Jev{' '}
956 <Text color={j?.isOnline === true ? 'green' : j?.isOnline === false ? 'red' : 'gray'}>
957 {j?.isOnline === true ? 'online' : j?.isOnline === false ? `offline (${j.lastError ?? 'unavailable'})` : 'unknown'}
958 </Text>
959 </Text>
960 {j !== null && (
961 <Text dimColor>
962 today ${j.spendToday.toFixed(4)} · {j.deniesToday} gate denies · {j.weakToday} weak reports
963 </Text>
964 )}
965 {j?.note !== undefined && <Text color="yellow">{j.note}</Text>}
966 {(j?.recent ?? []).map(entry => (
967 <Text wrap="truncate" color={entry.isAlert ? 'red' : undefined}>
968 {entry.ts.slice(11, 16)} {entry.feature.padEnd(13)} {entry.summary}
969 </Text>
970 ))}
971 </Box>
972 )}
973 </Box>
974 )
975 })
976
977 on('ui.render', { component: 'Pane', requestId: SESSIONS_PANE }, async ($, e) => {
978 const { Box, Text, Button } = $.ui.resolve(e)
979 const rows = await read($, sessions)
980 await read($, sessionsCheckedAt) // read so the pane redraws as ages advance
981 const self = await $.session.id()
982 const now = await $.clock.now()
983 const width = Math.max(20, e.props.bodyColumns)
984 const nameWidth = Math.min(22, Math.max(8, ...rows.map(row => row.name.length)))
985
986 return (
987 <Box flexDirection="column" width={width}>
988 <Text bold>Open sessions ({rows.length})</Text>
989 {rows.length === 0 && <Text dimColor>No Claude Code sessions registered.</Text>}
990 {rows.map(row => {
991 const isSelf = row.sessionId === self
992 const isEditor = row.entrypoint === 'claude-vscode'
993
994 return (
995 <Box key={`row-${row.sessionId}`} flexDirection="row" columnGap={1}>
996 <Text wrap="truncate" color={isSelf ? 'cyan' : undefined}>
997 <Text color={row.status === 'busy' ? 'yellow' : row.status === 'idle' ? 'green' : 'gray'}>
998 {row.status === 'busy' ? '◐' : '●'}
999 </Text>{' '}
1000 {row.name.slice(0, nameWidth).padEnd(nameWidth)} {repoName(row.cwd).slice(0, 18).padEnd(18)}{' '}
1001 {row.status.padEnd(4)} {ago(now - row.updatedAt).padStart(4)}
1002 </Text>
1003 {isSelf ? (
1004 <Text dimColor>this session</Text>
1005 ) : isEditor ? (
1006 <Button key={`focus-${row.sessionId}`} label="switch" onPress={() => focusSession($, row)} />
1007 ) : (
1008 <Text dimColor>terminal</Text>
1009 )}
1010 </Box>
1011 )
1012 })}
1013 <Text dimColor wrap="truncate">
1014 switch asks the handoff bridge in the session's VS Code window to show its tab
1015 </Text>
1016 <Box flexDirection="row" columnGap={1}>
1017 <Button key="refresh" label="refresh" onPress={() => pollSessions($)} />
1018 </Box>
1019 </Box>
1020 )
1021 })
1022}
1023hooks/parse.ts 675 lines1import type { Confidence, HunchCall, HunchConstraint, HunchLevel, JevEntry, JevStatus, SessionRow, Zone } from '../types'
2
3// Pure helpers: no `$`, so the tests exercise them directly.
4
5export const ROLES = ['scout', 'runner', 'builder', 'critic'] as const
6
7const FIELDS = ['RESULT', 'EVIDENCE', 'CONFIDENCE', 'UNVERIFIED'] as const
8
9// Uppercase and a colon, so prose like "Result was fine" is not taken for a header.
10const HEADER = /^[ \t>#*_\-]*(RESULT|EVIDENCE|CONFIDENCE|UNVERIFIED)[ \t*_]*:[ \t]*(.*)$/
11
12const LEVELS = ['high', 'medium', 'med', 'low']
13
14const NOTHING = /^(none|n\/?a|nothing|-+|—|\(none\)|no(ne)? unverified.*)\.?$/i
15
16const BULLET = /^\s*(?:[-*•]|\d+[.)])\s+/
17
18export type ParsedCard = {
19 hasAnyField: boolean
20 confidence: Confidence
21 missing: string[]
22 unverified: number
23 exitCodes: number[]
24 isWeak: boolean
25 result: string
26}
27
28/** The role an agent type names: `scout` for `scout` or `some-plugin:scout`. */
29export function roleOf(type: string): string {
30 return type.slice(type.lastIndexOf(':') + 1)
31}
32
33export function isRole(type: string): boolean {
34 return (ROLES as readonly string[]).includes(roleOf(type).toLowerCase())
35}
36
37/** `claude-sonnet-5-5` -> `sonnet`; anything else as given. */
38export function shortModel(model: string): string {
39 const family = /(opus|sonnet|haiku|fable)/i.exec(model)
40 return (family?.[1] ?? model).toLowerCase()
41}
42
43/** Reads the orchestrator's report card out of a subagent's final answer. */
44export function parseCard(answer: string): ParsedCard {
45 const sections = new Map<string, string[]>()
46 let current: string | undefined
47
48 for (const raw of answer.split(/\r?\n/)) {
49 const line = raw.replace(/\*\*/g, '')
50 const header = HEADER.exec(line)
51
52 if (header !== null) {
53 const [, name = '', rest = ''] = header
54 current = name
55 sections.set(current, rest.trim() === '' ? [] : [rest.trim()])
56 } else if (current !== undefined) {
57 sections.get(current)?.push(line)
58 }
59 }
60
61 const missing = FIELDS.filter(field => !sections.has(field))
62 const confidenceText = (sections.get('CONFIDENCE') ?? []).join(' ').toLowerCase()
63 // The first word only: "not high" is no claim of high.
64 const word = /^[^a-z]*([a-z]+)/.exec(confidenceText)?.[1] ?? ''
65 const level = LEVELS.includes(word) ? word : undefined
66 const confidence: Confidence =
67 level === undefined ? 'missing' : level === 'med' ? 'medium' : (level as Confidence)
68
69 const unverifiedLines = (sections.get('UNVERIFIED') ?? [])
70 .map(line => line.trim())
71 .filter(line => line !== '')
72 const realItems = unverifiedLines.filter(line => !NOTHING.test(line.replace(BULLET, '').trim()))
73 const bullets = realItems.filter(line => BULLET.test(line)).length
74 const unverified = realItems.length === 0 ? 0 : Math.max(1, bullets)
75
76 // `exit 0`, `exit code: 1`, and JSON's `"exit_code": 2`.
77 const exitCodes = [...answer.matchAll(/\bexit(?:[\s_]+code)?"?\s*[:=]?\s*(-?\d+)\b/gi)].map(match =>
78 Number(match[1]),
79 )
80
81 const result = (sections.get('RESULT') ?? [])
82 .map(line => line.replace(BULLET, '').trim())
83 .find(line => line !== '') ?? ''
84
85 return {
86 hasAnyField: missing.length < FIELDS.length,
87 confidence,
88 missing,
89 unverified,
90 exitCodes,
91 isWeak: missing.length > 0 || confidence !== 'high' || unverified > 0,
92 result: result.slice(0, 120),
93 }
94}
95
96export function zoneOf(tokens: number | undefined, soft: number, hard: number): Zone {
97 if (tokens === undefined) return 'unknown'
98 if (tokens >= hard) return 'red'
99 if (tokens >= soft) return 'amber'
100
101 return 'green'
102}
103
104type JevLine = Record<string, unknown>
105
106const text = (value: unknown): string => (typeof value === 'string' ? value : '')
107
108/** One display line for a Jev decision, or undefined for noise (usage rows, routine shifts). */
109export function summarize(line: JevLine): JevEntry | undefined {
110 if (line.kind === 'usage') return undefined
111
112 const ts = text(line.ts)
113 const feature = text(line.feature)
114 const decision = text(line.decision)
115 const offline = text(line.error) !== '' ? ' (offline)' : ''
116
117 switch (feature) {
118 case 'risk_gate': {
119 const fail = line.fail_closed === true ? ' fail-closed' : ''
120 const risk = typeof line.risk === 'number' || typeof line.risk === 'string' ? ` risk ${line.risk}` : ''
121
122 return {
123 ts,
124 feature,
125 summary: `${text(line.op)} ${decision.toUpperCase()}${fail}${risk}`,
126 isAlert: decision === 'deny',
127 }
128 }
129 case 'report_check': {
130 if (decision === '' || decision.startsWith('skipped')) return undefined
131 const reasons = Array.isArray(line.reasons) ? line.reasons.map(text).filter(Boolean) : []
132
133 return {
134 ts,
135 feature,
136 summary: `${text(line.subagent_type)} ${decision}${reasons.length > 0 ? `: ${reasons[0]}` : ''}${offline}`,
137 isAlert: decision === 'deny' || decision === 'weak',
138 }
139 }
140 case 'route': {
141 const choice = text(line.choice) || text(line.current)
142 const applied = line.applied === true ? '' : ' (kept)'
143
144 return { ts, feature, summary: `${text(line.subagent_type)} -> ${choice}${applied}${offline}`, isAlert: false }
145 }
146 case 'shift':
147 if (decision === '' || decision === 'continue' || decision === 'unsure') return undefined
148
149 return { ts, feature, summary: `${text(line.zone)} ${decision}`, isAlert: false }
150 case 'handoff_grade': {
151 const score = typeof line.score === 'number' ? line.score.toFixed(2) : '?'
152
153 return { ts, feature, summary: `score ${score}${line.weak === true ? ' WEAK' : ''}`, isAlert: line.weak === true }
154 }
155 default:
156 return feature === '' ? undefined : { ts, feature, summary: decision || '-', isAlert: false }
157 }
158}
159
160export function parseLines(raw: string): JevLine[] {
161 const lines: JevLine[] = []
162
163 for (const one of raw.split(/\r?\n/)) {
164 if (one.trim() === '') continue
165 try {
166 const value: unknown = JSON.parse(one)
167 if (value !== null && typeof value === 'object' && !Array.isArray(value)) lines.push(value as JevLine)
168 } catch {
169 // a torn last line while Jev writes: skipped, read again next poll
170 }
171 }
172
173 return lines
174}
175
176/** Jev's health and today's figures from its log, newest line last. */
177export function jevStatus(lines: JevLine[], today: string, isEnabled: boolean): JevStatus {
178 let isOnline: boolean | null = null
179 let lastError: string | undefined
180
181 const newestFirst = [...lines].reverse()
182
183 for (const line of newestFirst.slice(0, 400)) {
184 if (isOnline !== null) break
185 if (line.kind === 'usage') {
186 isOnline = true
187 } else if (text(line.error) !== '') {
188 isOnline = false
189 lastError = text(line.error)
190 }
191 }
192
193 let spendToday = 0
194 let deniesToday = 0
195 let weakToday = 0
196
197 for (const line of newestFirst) {
198 const ts = text(line.ts)
199 // A line without a stamp says nothing about the day: skip it, stop at the first older one.
200 if (ts === '') continue
201 if (!ts.startsWith(today)) break
202 if (line.kind === 'usage' && typeof line.usd === 'number') spendToday += line.usd
203 if (line.feature === 'risk_gate' && line.decision === 'deny') deniesToday += 1
204 if (line.feature === 'report_check' && (line.decision === 'deny' || line.decision === 'weak')) weakToday += 1
205 }
206
207 const recent: JevEntry[] = []
208 for (const line of newestFirst) {
209 if (recent.length >= 8) break
210 const entry = summarize(line)
211 if (entry !== undefined) recent.push(entry)
212 }
213
214 return {
215 isOnline: isEnabled ? isOnline : false,
216 lastError: isEnabled ? lastError : 'disabled',
217 spendToday,
218 deniesToday,
219 weakToday,
220 recent,
221 }
222}
223
224/** `2026-10-06` for a clock reading, in local time as Jev stamps it. */
225export function localDay(ms: number): string {
226 const date = new Date(ms)
227 const pad = (n: number) => String(n).padStart(2, '0')
228
229 return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}`
230}
231
232export function kTokens(n: number | undefined): string {
233 if (n === undefined) return '?'
234
235 return n >= 1000 ? `${Math.round(n / 1000)}k` : String(n)
236}
237
238export function bar(fraction: number, cells: number): string {
239 // A narrow pane can ask for no cells or fewer: draw nothing rather than throw.
240 const width = Math.max(0, cells)
241 const filled = Math.max(0, Math.min(width, Math.round(fraction * width)))
242
243 return '█'.repeat(filled) + '░'.repeat(width - filled)
244}
245
246export function seconds(ms: number): string {
247 const s = Math.max(0, Math.round(ms / 1000))
248
249 return s < 90 ? `${s}s` : `${Math.round(s / 60)}m`
250}
251
252/** `14:05` for a clock reading, local time. */
253export function clockTime(ms: number): string {
254 const date = new Date(ms)
255 const pad = (n: number) => String(n).padStart(2, '0')
256
257 return `${pad(date.getHours())}:${pad(date.getMinutes())}`
258}
259
260// Hunch: calls through its MCP server (`mcp__hunch__hunch_context`, or `mcp__plugin_hunch_hunch__hunch_context`
261// when the Hunch plugin provides it) or its CLI through Bash.
262
263const HUNCH_MCP = /^mcp__(?:plugin_hunch_)?hunch__(?:hunch_)?(.+)$/
264
265const TASK_ID = /\bhtask_[a-f0-9]{24}\b/
266
267const TARGET_KEYS = ['target', 'scope', 'topic', 'symbol', 'symptom_or_symbol', 'query', 'id', 'title'] as const
268
269// The CLI as the prompt hook prints it (`node .../@davesheffer/hunch/dist/cli/index.js task verify ...`),
270// or `hunch <sub>` / `npx @davesheffer/hunch <sub>` starting a command (matched with quoted text blanked
271// and heredoc bodies dropped, so `git commit -m "hunch update"` is not a call).
272
273// A heredoc opener (`<<EOF`, `<<-'EOF'`; not `<<<` or `1 << 2`), the rest of its line, then its body
274// up to the terminator line, or to the end when none follows.
275const HEREDOC = /(?<!<)<<-?[ \t]*(['"]?)([A-Za-z_]\w*)\1([^\n]*)(?:\n[\s\S]*?(?:\n[ \t]*\2[ \t]*(?=\r?\n|$)|$)|$)/g
276const HUNCH_LAUNCHER = /@davesheffer[\\/]+hunch[\\/]+dist[\\/]+cli[\\/]+index\.js['"]?\s+([a-z][\w-]*)(?:\s+([a-z][\w-]*))?/i
277
278const HUNCH_BARE = /(?:^|[;&|\n]|\$\()\s*(?:\(\s*)?(?:npx\s+(?:-y\s+)?)?(?:@davesheffer\/)?hunch\s+([a-z][\w-]*)(?:\s+([a-z][\w-]*))?/i
279
280const LEVEL_RANK: Record<HunchLevel, number> = { info: 0, warn: 1, alert: 2 }
281
282const BLOCKING = /^(blocking|block|error|critical|must)$/i
283
284export type HunchInvocation = {
285 name: string
286 target: string
287 taskId?: string
288}
289
290export type HunchOutcome = {
291 summary: string
292 level: HunchLevel
293 constraints: HunchConstraint[]
294 verdict?: 'BLOCK' | 'WARN' | 'PASS'
295 exitCode?: number
296 taskId?: string
297}
298
299/** An invariant severity worth a toast: `warning` or a blocking one; advisory and info stay in the pane. */
300export function isToastSeverity(severity: string): boolean {
301 return /^warn(ing)?$/i.test(severity) || BLOCKING.test(severity)
302}
303
304export function maxLevel(a: HunchLevel, b: HunchLevel): HunchLevel {
305 return LEVEL_RANK[a] >= LEVEL_RANK[b] ? a : b
306}
307
308/** `context` for `mcp__hunch__hunch_context`; undefined for any other tool. */
309export function hunchName(tool: string): string | undefined {
310 return HUNCH_MCP.exec(tool)?.[1]
311}
312
313/** What an MCP Hunch call is about, read from its arguments. */
314export function hunchInvocation(name: string, args: Record<string, unknown>): HunchInvocation {
315 const taskId = text(args.task_id) || undefined
316 let target: string
317
318 if (name === 'task') {
319 target = [text(args.action), text(args.title)].filter(Boolean).join(' ')
320 } else if (name === 'merge_verdict' || name === 'pr_impact') {
321 target = text(args.base) || text(args.commit) || (args.working === true ? 'working tree' : 'staged')
322 } else if (name === 'compare' && Array.isArray(args.candidates)) {
323 target = args.candidates.map(text).filter(Boolean).join(' vs ')
324 } else {
325 target = TARGET_KEYS.map(key => text(args[key])).find(Boolean) ?? ''
326 }
327
328 return { name, target: oneLine(target), taskId }
329}
330
331/** The hunch CLI call a Bash command makes, or undefined when it makes none. */
332export function hunchCli(command: string): HunchInvocation | undefined {
333 const lines = command.replace(HEREDOC, (_all, _quote: string, tag: string, rest: string) => `<<${tag}${rest}`)
334 const match = HUNCH_LAUNCHER.exec(lines) ?? HUNCH_BARE.exec(lines.replace(/"[^"]*"|'[^']*'/g, '""'))
335 if (match === null) return undefined
336
337 const [, sub = '', action = ''] = match
338 const taskId = TASK_ID.exec(command)?.[0]
339
340 if (sub === 'task' && action === 'verify') {
341 const separator = command.indexOf(' -- ')
342 const checked = separator >= 0 ? command.slice(separator + 4) : ''
343
344 return { name: 'verify', target: oneLine(checked.replace(/\s*2>&1.*$/, '')), taskId }
345 }
346
347 return { name: `cli ${sub}`, target: action, taskId }
348}
349
350/** Grades what a Hunch call returned: a summary line, how loud, and what to toast about. */
351export function hunchOutcome(name: string, output: string, isError: boolean): HunchOutcome {
352 const taskId = TASK_ID.exec(output)?.[0]
353
354 if (name === 'verify') return verifyOutcome(output, isError)
355 if (isError) {
356 return { summary: firstLine(output) || 'failed', level: 'alert', constraints: [], taskId }
357 }
358
359 switch (name) {
360 case 'check_constraints': {
361 const constraints = [...output.matchAll(/^\s*[•*-]\s*(con_\w+)\s*\[([\w-]+)[^\]]*\]\s*(.*)$/gm)].map(match => ({
362 id: match[1] ?? '',
363 severity: (match[2] ?? '').toLowerCase(),
364 statement: oneLine(match[3] ?? ''),
365 }))
366 const blocking = constraints.filter(one => BLOCKING.test(one.severity)).length
367 const warnings = constraints.filter(one => one.severity === 'warning').length
368 const parts = [blocking > 0 ? `${blocking} blocking` : '', warnings > 0 ? `${warnings} warning` : ''].filter(Boolean)
369
370 return {
371 summary:
372 constraints.length === 0
373 ? 'no constraints in scope'
374 : `${constraints.length} constraint${constraints.length === 1 ? '' : 's'}${parts.length > 0 ? ` (${parts.join(', ')})` : ''}`,
375 level: blocking > 0 ? 'alert' : warnings > 0 ? 'warn' : 'info',
376 constraints,
377 taskId,
378 }
379 }
380 case 'merge_verdict': {
381 const verdict = /VERDICT:\W*(BLOCK|WARN|PASS)/i.exec(output)?.[1]?.toUpperCase() as HunchOutcome['verdict']
382 const scope = /\(scope:\s*(.+?)\)\s*$/m.exec(output)?.[1]
383
384 return {
385 summary: `verdict ${verdict ?? '?'}${scope !== undefined ? ` · ${scope}` : ''}`,
386 level: verdict === 'BLOCK' ? 'alert' : verdict === 'WARN' ? 'warn' : 'info',
387 constraints: [],
388 verdict,
389 taskId,
390 }
391 }
392 case 'escalations': {
393 if (/nothing needs/i.test(output) || output.trim() === '') {
394 return { summary: 'none', level: 'info', constraints: [], taskId }
395 }
396 const headline = /(\d+)\s+decisions?\s+needs?\b/i.exec(output)?.[1]
397 const items = output.split(/\r?\n/).filter(line => /^\s*(?:[-*•⚖·]|\d+[.)])\s+/.test(line)).length
398 const count = headline !== undefined ? Number(headline) : Math.max(1, items)
399
400 return { summary: `${count} need your decision`, level: 'alert', constraints: [], taskId }
401 }
402 default:
403 return { summary: firstLine(output), level: 'info', constraints: [], taskId }
404 }
405}
406
407/**
408 * `task verify` streams the checked command's output, then its result JSON last: the last
409 * `"exit_code"` is the launcher's. Piped through `tail` or cut by the Bash output cap the JSON
410 * can be gone; then the Bash call's own exit (`Exit code N`, isError) is the evidence.
411 */
412function verifyOutcome(output: string, isError: boolean): HunchOutcome {
413 const taskId = TASK_ID.exec(output)?.[0]
414 const codes = [...output.matchAll(/"exit_code"\s*:\s*(-?\d+)/g)]
415 const jsonCode = codes.at(-1)?.[1]
416 const bashCode = /^Exit code (-?\d+)/m.exec(output)?.[1]
417 // On an errored call core's `Exit code N` beats a 0 that may be the checked command's own JSON
418 // (the launcher's cut off); otherwise an `Exit code` line is the command's stdout, not evidence.
419 const code = isError && bashCode !== undefined && bashCode !== '0' ? bashCode : (jsonCode ?? bashCode)
420 const isTimedOut = /"timed_out"\s*:\s*true/.test(output)
421
422 if (code === undefined) {
423 if (isTimedOut && isError) return { summary: 'timed out', level: 'alert', constraints: [], taskId }
424
425 return isError
426 ? { summary: `failed: ${firstLine(output) || 'no exit code'}`, level: 'alert', constraints: [], taskId }
427 : { summary: 'exit code not in output (piped or truncated?)', level: 'warn', constraints: [], taskId }
428 }
429 const exitCode = Number(code)
430
431 return {
432 summary: `exit ${exitCode}${isTimedOut ? ' (timed out)' : ''}`,
433 level: exitCode === 0 && !isTimedOut && !isError ? 'info' : 'alert',
434 constraints: [],
435 exitCode,
436 taskId,
437 }
438}
439
440/** A call still running this long never got its result recorded (a lost abort, a reload); past Bash's 10 min cap. */
441export const STALE_MS = 15 * 60_000
442
443/** Marks running calls older than STALE_MS as errored, so the pane and band stop waiting on them. */
444export function reapStale(calls: readonly HunchCall[], now: number): HunchCall[] {
445 return calls.map(call =>
446 call.status === 'running' && now - call.startedAt > STALE_MS
447 ? { ...call, status: 'error', level: 'warn', durationMs: now - call.startedAt, summary: 'no result recorded' }
448 : call,
449 )
450}
451
452/** Whether an abort ended the call: Bash's own `interrupted`, or the marker text core gives the model. */
453export function wasInterrupted(result: unknown, text: string): boolean {
454 if (typeof result === 'object' && result !== null && (result as { interrupted?: unknown }).interrupted === true) return true
455
456 return /^\[?Request interrupted by user|^Interrupted by user/i.test(text.trim())
457}
458
459function oneLine(value: string): string {
460 return value.replace(/\s+/g, ' ').trim().slice(0, 120)
461}
462
463/** The first line that says something: no rule, bare heading mark or footer. */
464function firstLine(output: string): string {
465 for (const raw of output.split(/\r?\n/)) {
466 const line = raw
467 .replace(/<[^>]+>/g, '')
468 .replace(/^[\s#>*_`•-]+/, '')
469 .replace(/\*\*/g, '')
470 .trim()
471 if (line !== '' && !/^[-=_─]{3,}$/.test(line) && line !== '{') return oneLine(line)
472 }
473
474 return ''
475}
476
477// Sessions: the registry Claude Code keeps at `~/.claude/sessions/<pid>.json`, one file per live process.
478
479const SESSION_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i
480
481/** The last path segment of a Windows or POSIX path. */
482export function repoName(cwd: string): string {
483 return cwd.replace(/[\\/]+$/, '').split(/[\\/]/).at(-1) ?? ''
484}
485
486/** One registry file as a row; undefined for anything that is not a session entry. */
487export function sessionRow(raw: string): SessionRow | undefined {
488 let entry: unknown
489 try {
490 entry = JSON.parse(raw)
491 } catch {
492 return undefined
493 }
494 if (typeof entry !== 'object' || entry === null) return undefined
495
496 const { pid, sessionId, cwd, name, entrypoint, status, updatedAt, startedAt } = entry as Record<string, unknown>
497 if (typeof pid !== 'number' || typeof sessionId !== 'string' || !SESSION_ID.test(sessionId)) return undefined
498
499 const folder = typeof cwd === 'string' ? cwd : ''
500 const id = sessionId.toLowerCase()
501
502 return {
503 pid,
504 sessionId: id,
505 name: typeof name === 'string' && name.trim() !== '' ? oneLine(name) : repoName(folder) || id.slice(0, 8),
506 cwd: folder,
507 entrypoint: typeof entrypoint === 'string' ? entrypoint : 'unknown',
508 status: status === 'idle' || status === 'busy' ? status : 'unknown',
509 updatedAt: typeof updatedAt === 'number' ? updatedAt : typeof startedAt === 'number' ? startedAt : 0,
510 }
511}
512
513/** Newest first, one row per session: a crashed process can leave an older file for the same id. */
514export function sessionRows(rows: readonly SessionRow[]): SessionRow[] {
515 const newest = new Map<string, SessionRow>()
516 for (const row of rows) {
517 const seen = newest.get(row.sessionId)
518 if (seen === undefined || row.updatedAt > seen.updatedAt) newest.set(row.sessionId, row)
519 }
520
521 return [...newest.values()].sort((a, b) => b.updatedAt - a.updatedAt || a.name.localeCompare(b.name))
522}
523
524/** `45s`, `12m`, `3h`, `2d`: how long ago, coarsely. */
525export function ago(ms: number): string {
526 const s = Math.max(0, Math.round(ms / 1000))
527 if (s < 90) return `${s}s`
528 if (s < 90 * 60) return `${Math.round(s / 60)}m`
529 if (s < 36 * 3600) return `${Math.round(s / 3600)}h`
530
531 return `${Math.round(s / 86400)}d`
532}
533
534// Activity: one short plain-language line per thing the session does.
535
536const HUNCH_VERB: Record<string, string> = {
537 context: 'brief on',
538 check_constraints: 'check rules for',
539 why: 'why',
540 bug_lineage: 'past bugs for',
541 blast_radius: 'blast radius of',
542 get_dependents: 'dependents of',
543 current_decision: 'current decision on',
544 record_decision: 'record decision',
545 record_correction: 'record correction',
546 record_finding: 'record finding',
547 capture_decision: 'capture decision',
548 merge_verdict: 'merge verdict for',
549 pr_impact: 'PR impact of',
550 conformance: 'conformance check',
551 escalations: 'open escalations',
552 structure: 'repo map',
553 query: 'search',
554 verify: 'check',
555}
556
557/** The last segment of a path, for a short label. */
558export function fileName(path: string): string {
559 return path.split(/[\\/]+/).filter(Boolean).at(-1) ?? path
560}
561
562export function clip(value: string, max: number): string {
563 const line = value.replace(/\s+/g, ' ').trim()
564
565 return line.length > max ? `${line.slice(0, max - 1)}…` : line
566}
567
568/** `hh:mm:ss`, local time. */
569export function clockSeconds(ms: number): string {
570 const date = new Date(ms)
571
572 return `${clockTime(ms)}:${String(date.getSeconds()).padStart(2, '0')}`
573}
574
575const DETAIL_MAX = 4000
576
577/** The full text behind a timeline line (a command, a prompt, an edit), for its drawer; '' when the line says it all. */
578export function toolDetail(tool: string, args: Record<string, unknown>): string {
579 let detail: string
580 switch (tool) {
581 case 'Bash':
582 case 'PowerShell':
583 detail = text(args.command)
584 break
585 case 'Agent':
586 detail = text(args.prompt)
587 break
588 case 'Edit':
589 detail = `${text(args.file_path)}\n--- old\n${text(args.old_string)}\n+++ new\n${text(args.new_string)}`
590 break
591 case 'Write':
592 detail = `${text(args.file_path)}\n${text(args.content)}`
593 break
594 case 'Read':
595 case 'Glob':
596 case 'Grep':
597 case 'ToolSearch':
598 case 'Skill':
599 detail = ''
600 break
601 default: {
602 const reserved = ['tool', 'tool_use_id', 'agentId', 'consent']
603 const rest = Object.fromEntries(Object.entries(args).filter(([key]) => !reserved.includes(key)))
604 detail = tool.startsWith('mcp__') && Object.keys(rest).length > 0 ? JSON.stringify(rest, null, 2) : ''
605 }
606 }
607
608 return capDetail(detail)
609}
610
611/** Cuts drawer text to DETAIL_MAX characters, saying how much was left out. */
612export function capDetail(detail: string): string {
613 return detail.length > DETAIL_MAX ? `${detail.slice(0, DETAIL_MAX)}\n… (${detail.length - DETAIL_MAX} more characters)` : detail
614}
615
616/** What a tool call does, in a few plain words: `read parse.ts`, `start critic (fable): Review diff`. */
617export function describeTool(tool: string, args: Record<string, unknown>): string {
618 const file = fileName(text(args.file_path) || text(args.notebook_path) || text(args.path))
619 const hunch = hunchName(tool)
620 if (hunch !== undefined) {
621 const { target } = hunchInvocation(hunch, args)
622 const verb = HUNCH_VERB[hunch] ?? hunch.replace(/_/g, ' ')
623
624 return clip(`Hunch: ${verb}${target === '' ? '' : ` ${target}`}`, 80)
625 }
626
627 switch (tool) {
628 case 'Bash':
629 case 'PowerShell': {
630 const command = text(args.command)
631 const cli = hunchCli(command)
632 const what = text(args.description) || command
633 if (cli?.name === 'verify') return clip(`check: ${what}`, 80)
634
635 return clip(`run: ${what}`, 80)
636 }
637 case 'Read':
638 return `read ${file}`
639 case 'Edit':
640 case 'NotebookEdit':
641 return `edit ${file}`
642 case 'Write':
643 return `write ${file}`
644 case 'Grep':
645 return clip(`search for "${text(args.pattern)}"${file === '' ? '' : ` in ${file}`}`, 80)
646 case 'Glob':
647 return clip(`find files ${text(args.pattern)}`, 80)
648 case 'Agent': {
649 const role = roleOf(text(args.subagent_type) || 'general-purpose')
650 const model = text(args.model)
651
652 return clip(`start ${role}${model === '' ? '' : ` (${model})`}: ${text(args.description)}`, 80)
653 }
654 case 'SendMessage':
655 return 'message an agent'
656 case 'Skill':
657 return `load skill ${text(args.skill)}`
658 case 'ToolSearch':
659 return 'load tool definitions'
660 case 'WebSearch':
661 return clip(`web search "${text(args.query)}"`, 80)
662 case 'WebFetch':
663 return clip(`fetch ${text(args.url).replace(/^https?:\/\//, '').split('/')[0] ?? ''}`, 80)
664 case 'AskUserQuestion':
665 return 'ask you a question'
666 case 'Artifact':
667 return `artifact ${text(args.action) || 'publish'}`
668 }
669
670 const mcp = /^mcp__(.+?)__(.+)$/.exec(tool)
671 if (mcp !== null) return clip(`${mcp[1]?.replace(/^claude_ai_/, '')}: ${mcp[2]?.replace(/_/g, ' ')}`, 80)
672
673 return tool
674}
675types/index.d.ts 153 lines1export type AgentStatusMark = 'running' | 'done' | 'aborted' | 'error'
2
3/** One subagent the session spawned, from `agent.spawn` to its `turn.complete`. */
4export type AgentRun = {
5 id: string
6 type: string
7 model: string
8 description: string
9 isBackground: boolean
10 startedAt: number
11 endedAt?: number
12 status: AgentStatusMark
13}
14
15export type Confidence = 'high' | 'medium' | 'low' | 'missing'
16
17/** The RESULT / EVIDENCE / CONFIDENCE / UNVERIFIED card a role agent hands back. */
18export type ReportCard = {
19 agentId: string
20 type: string
21 model: string
22 at: number
23 durationMs: number
24 confidence: Confidence
25 missing: string[]
26 unverified: number
27 exitCodes: number[]
28 isWeak: boolean
29 result: string
30}
31
32export type Zone = 'green' | 'amber' | 'red' | 'unknown'
33
34/** The relay gauge: live context tokens against relay/config.json thresholds. */
35export type Gauge = {
36 tokens?: number
37 window: number
38 percent?: number
39 zone: Zone
40 soft: number
41 hard: number
42 usd?: number
43}
44
45/** One Jev decision line, summarized for display. */
46export type JevEntry = {
47 ts: string
48 feature: string
49 summary: string
50 isAlert: boolean
51}
52
53export type JevStatus = {
54 /** null while no recent line says either way. */
55 isOnline: boolean | null
56 lastError?: string
57 spendToday: number
58 deniesToday: number
59 weakToday: number
60 recent: JevEntry[]
61 note?: string
62}
63
64export type HunchLevel = 'info' | 'warn' | 'alert'
65
66export type HunchCallStatus = 'running' | 'ok' | 'error' | 'denied'
67
68/** One Hunch call: an `mcp__hunch__*` tool, or the hunch CLI run through Bash (`task verify`). */
69export type HunchCall = {
70 /** The tool_use_id. */
71 id: string
72 /** `context`, `check_constraints`, `verify`, `cli update`, ... */
73 name: string
74 target: string
75 taskId?: string
76 /** `main`, or the subagent role that made the call. */
77 role: string
78 startedAt: number
79 durationMs?: number
80 status: HunchCallStatus
81 summary: string
82 level: HunchLevel
83}
84
85/** Constraint lines `hunch_check_constraints` returned. */
86export type HunchConstraint = {
87 id: string
88 severity: string
89 statement: string
90}
91
92export type HunchLog = {
93 /** The newest htask_ id seen in a call's arguments or result. */
94 taskId?: string
95 calls: HunchCall[]
96 total: number
97 /** Constraint ids already toasted this session, so a `**` invariant toasts once. */
98 seenConstraints: string[]
99}
100
101/** One open Claude Code session, from its `~/.claude/sessions/<pid>.json` registry file. */
102export type SessionRow = {
103 pid: number
104 sessionId: string
105 name: string
106 cwd: string
107 /** `claude-vscode` (a VS Code tab the bridge can switch to) or `cli` (a terminal). */
108 entrypoint: string
109 /** `idle` or `busy`, as the session last wrote it; anything else is `unknown`. */
110 status: 'idle' | 'busy' | 'unknown'
111 updatedAt: number
112}
113
114/** One line of the activity timeline: a prompt, a tool call, an agent finishing, a turn ending. */
115export type ActivityEntry = {
116 /** The tool_use_id for a tool call; a made-up id otherwise. */
117 id: string
118 at: number
119 /** `you`, `main`, or the subagent role. */
120 who: string
121 /** A few plain words: `read parse.ts`, `run: Run unit tests`. */
122 text: string
123 status: 'running' | 'ok' | 'error' | 'stopped' | 'note'
124 durationMs?: number
125 /** The full command, prompt or edit, shown in the line's drawer when opened. */
126 detail?: string
127}
128
129declare module 'claude-code' {
130 interface PluginState {
131 'mission-control': {
132 agents: AgentRun[]
133 reports: ReportCard[]
134 gauge: Gauge | null
135 jev: JevStatus | null
136 hunch: HunchLog
137 isBandHidden: boolean
138 tick: number
139 sessions: SessionRow[]
140 /** When the session registry was last polled, rounded down to 30 s so the pane's ages redraw. */
141 sessionsCheckedAt: number
142 /** The newest activity lines, oldest first. */
143 activity: ActivityEntry[]
144 /** Whether the /orch pane shows its full report cards, Hunch calls and Jev log. */
145 showDetails: boolean
146 /** Timeline lines whose drawer is open, by entry id. */
147 openEntries: string[]
148 /** Whether the main loop is mid-turn: set by a prompt, cleared by the main loop's turn end. */
149 turnOpen: boolean
150 }
151 }
152}
153