Flightdeck: a live agent dashboard for Claude Code. Main model vitals, an on-call architect, every permission check, subagent cards and swimlanes, a turn…

A Claude Code mod that puts a live agent dashboard in your terminal: context and cost, an advisor timeline, every permission check, and your subagents as cards or swimlanes. Every number comes from a real session event, and nothing leaves your machine.
<img src="docs/media/demo.gif" alt="Flightdeck during a live session: five audit subagents fan out as cards, switch to swimlanes and finish, while the permission gate fills with checks" width="520">
<a href="#install">Install</a> · <a href="#what-you-see">What you see</a> · <a href="#what-it-can-reach">What it can reach</a> · <a href="#configure">Configure</a> · <a href="#troubleshooting">Troubleshooting</a>
Inside Claude Code (2.1.287 or later):
/plugin marketplace add scasella/claude-flightdeck
/plugin install flightdeck@claude-flightdeck
/reload-plugins
/flightdeck
claude plugin marketplace add scasella/claude-flightdeck
claude plugin install flightdeck@claude-flightdeck
Or load it straight from a clone, for one session:
git clone https://github.com/scasella/claude-flightdeck
claude --plugin-dir ./claude-flightdeck
The installer may say config options aren't set; the defaults are fine, and /config changes them.
Mods are an early-access Claude Code feature and their API can change between releases. If something breaks, see Troubleshooting.
https://github.com/user-attachments/assets/9ad0fcc3-c81c-427a-a743-f7b6c49f5885
<img src="docs/media/docked-session.png" alt="Claude Code in fullscreen with the Flightdeck pane docked beside the transcript" width="820">
| Docked beside the transcript | Inline above the prompt |
|---|---|
| <img src="docs/media/docked-pane.png" alt="The docked pane: main model vitals, architect timeline, permission gate, five agents as swimlanes, last-turn receipt and session log" width="380"> | <img src="docs/media/inline-mini.png" alt="The inline mini layout: the model, context gauge, session cost and architect consults; the permission gate strip and totals; the last turn's duration, agents, edits, errors and cost" width="420"><br><br>On the main screen, without fullscreen, the pane is a summary of at most 8 rows; up to 3 agents join it when the session has subagents. |
| Panel | Shows | From |
|---|---|---|
| main | model, effort, permission mode, request count; a context gauge with compactions (⟲); cost and the first two rate-limit windows when your plan reports them | turn.step, session.measure, session.compact, $.session.usage() |
| architect | consults on a timeline, whether one is running, how long the last took; optionally the moment of each consult; the first line of a subagent architect's advice | a spawn of a matching agent type, or a matching server tool in the assistant's rows |
| gate | one cell per permission check: green allowed without asking, blue decided by the auto-mode classifier or you and then run, amber pending, red ✗ denied, dim if made inside a subagent. Totals, and a drill-down per tool family with credentials masked | tool.check, settled by the tool.call around it |
| agents | cards side by side while they fit: the task, type, live context and output tokens, steps, a running clock, max_tokens in red. Beyond that, swimlanes on one time axis | agent.spawn, turn.step, tool.call, turn.complete |
| loops | model loops that match no card: workflow agents, compactions, memory forks | turn.step ids no card claims |
| receipt | the running turn, or the last one: duration, agents, edits, errors, cost added | turn.start, turn.complete |
| board | the Pinboard (this copy's addition, from sirkitree/pinboard): open todos with the one in progress marked ▶, finished ones folded into "✓ n done", decisions waiting on you, and links Claude created (PRs, issues, published pages). It sits just above the log | the mcp__flightdeck__pinboard tool, and gh … create / git push / creating MCP calls for links |
| log | prompts, spawns, completions, consults, edits, errors and denials; filtered to one agent while you view its transcript | all of the above |
Connectors animate only while work flows: a turn is running, an agent is running, or a consult is open. Panels with nothing to show take no room, so a session without subagents shows just the main box and the log.
| Command | Does | |||
|---|---|---|---|---|
/flightdeck | open the pane | |||
/flightdeck close | close it | |||
/flightdeck reset | clear agents, checks, consults, log and the turn (cost, rate limits and compactions stay) | |||
| `/flightdeck layout auto\ | compact\ | wide\ | mini` | override the layout for this session |
Focus the pane with ctrl+x tab, then:
| Key | Does |
|---|---|
1, 2, … | expand an agent card or lane: its full task, last 3 tool calls, start of its answer |
f s o | open the gate's file / shell / other drill-down: the last 5 checks and their verdicts |
l | clear the Pinboard's links |
/clear resets the pane, Pinboard included, along with the conversation.
The Pinboard's guide and the current board ride at the end of the system prompt, so Claude keeps its task list there instead of in replies. A reply that ends on a question with no open decision sends Claude back once to pin it.
With openOnStart, the pane opens by itself when a session starts, in terminals at least 144 columns wide; below that, /flightdeck opens it. Colours come from your Claude Code theme, so light, dark and colour-blind themes all read.
Flightdeck only watches. Every hook passes its event on unchanged: it never denies, rewrites or delays a tool call, a prompt or a subagent.
| It sees | Through |
|---|---|
| every tool call's name and input, and whether it failed | tool.call |
| every permission verdict | tool.check |
| subagent spawns, their model requests and token usage, and their final answers | agent.spawn, turn.step, turn.complete |
| your prompts' first 70 characters, for the log | turn.start |
| context, cost and rate-limit readings | session.measure, $.session.usage() |
| advisor tool calls in the assistant's responses (their content is encrypted) | session.append |
What it keeps: short summaries (a tool name plus a path or command, with credentials masked) in session state, which ends with the session. It makes no network requests, runs no processes, reads and writes no files, stores nothing across sessions, and calls no model. claude plugin validate . prints exactly what it hooks and calls.
(inferred); turn them off with moments: false.advisor, the pane counts and times the consult but cannot show what it said.ctx, not cost: the API has no per-agent cost.In /config, or under pluginConfigs["flightdeck"].options in settings.json:
| Option | Default | Meaning | |
|---|---|---|---|
architectPattern | `advisor\ | architect` | case-insensitive regex for agent types and server tools that count as the architect |
matchDescriptions | false | also match agent descriptions, not just type names | |
architectLabel | ARCHITECT | the architect's name in the pane | |
gateLabel | GATE | the permission panel's name | |
panels | main,architect,gate,agents,loops,receipt,board,log | which panels show, in order | |
layout | auto | mini, compact, wide, or auto (mini inline, wide from 110 columns docked) | |
maxCards | 3 | cards side by side before swimlanes (1–6); fewer if the pane is too narrow | |
motion | while-active | off keeps connectors still | |
moments | true | show the inferred consult moments | |
palette | theme | pastel uses fixed colours tuned for dark terminals | |
openOnStart | true | ask to open the pane when a session starts | |
statusLine | true | context, running agents, consults and denials in the status line |
The pane doesn't appear.
claude --version is 2.1.287 or later, then run /reload-plugins and /flightdeck./flightdeck opens it at any width.flightdeck:. It names the hook that failed or the reason the pane was refused. Please open an issue with it.Colours look wrong. Set palette to pastel in /config.
It's too much motion. Set motion to off.
Counters look stale after an update. Run /flightdeck reset.
| File | Holds |
|---|---|
hooks/register.tsx | the event hooks, state access, and one function per panel |
hooks/core.ts | every reducer, formatter and layout rule as pure functions, so behaviour is testable directly |
hooks/rail.tsx, hooks/elapsed.tsx | surface modules: animated connectors and live clocks that redraw only themselves, on the surface's own frame clock |
types/index.d.ts | the state contract |
tests/ | 24 tests: pure behaviour, plus drawings mounted on every surface at 40–120 columns |
State lives in $.state atoms. Every read is merged over defaults, so a missing or older field never breaks the pane; an update that changes the state's shape may still reset its counters once. New to mods? Start with Claude Code mods and Getting started with Claude Code mods.
Flightdeck works alongside these, and owes ideas to them:
claude --plugin-dir . # load it; edits hot-reload
claude plugin validate .
claude plugin test .
npx -p typescript tsc -p . # after the first load, which writes .claude-plugin/types/
See CONTRIBUTING.md. Changes are listed in CHANGELOG.md.
MIT. The Pinboard panel (hooks/pinboard.tsx) is ported from sirkitree/pinboard, MIT, © 2026 Jerad Bitner: LICENSE-pinboard.
hooks/register.tsx 1146 lines1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, Register } from 'claude-code'
3
4import type { AgentCard, Architect, Bucket, Check, Gate, Layout, LogLine, Loop, Main, Roster, Turn, Usage, View } from '../types'
5import {
6 DEFAULT_ARCHITECT,
7 DEFAULT_GATE,
8 DEFAULT_MAIN,
9 DEFAULT_ROSTER,
10 DEFAULT_TURN,
11 DEFAULT_USAGE,
12 DEFAULT_VIEW,
13 EDIT_TOOLS,
14 SCHEMA_VERSION,
15 afterCall,
16 applyStep,
17 bucketOf,
18 cardTitle,
19 titleLines,
20 consultTimeline,
21 describeInput,
22 endConsult,
23 fitLegend,
24 fmtClock,
25 fmtDuration,
26 fmtTimer,
27 fmtUsd,
28 plural,
29 gateSummary,
30 gauge,
31 isAdvising,
32 isLoopActive,
33 kTokens,
34 lanes,
35 limitLabel,
36 listOf,
37 logRows,
38 momentOf,
39 normalize,
40 normalizeCard,
41 normalizeGate,
42 normalizeLog,
43 noteTool,
44 PALETTES,
45 SVG_COLORS,
46 parseConfig,
47 prettyModel,
48 promptLine,
49 handbackOf,
50 adviceLine,
51 receiptOf,
52 recordCheck,
53 settleCheck,
54 shorten,
55 startConsult,
56 stepLoop,
57} from './core'
58import type { Config, Panel } from './core'
59import { boardLine, boardPanel, boardRows, captureLinks, clearBoard, isBoardEmpty, readBoard, registerPinboard, startPinboard } from './pinboard'
60
61const PANE = 'flightdeck'
62const TITLE = 'Flightdeck'
63const PANE_COLUMNS = 66
64
65
66// ---------------------------------------------------------------- state
67
68const meta = atom({ plugin: 'flightdeck', key: 'meta' } as const, { schemaVersion: SCHEMA_VERSION })
69const main = atom({ plugin: 'flightdeck', key: 'main' } as const, DEFAULT_MAIN)
70const usage = atom({ plugin: 'flightdeck', key: 'usage' } as const, DEFAULT_USAGE)
71const architect = atom({ plugin: 'flightdeck', key: 'architect' } as const, DEFAULT_ARCHITECT)
72const gate = atom({ plugin: 'flightdeck', key: 'gate' } as const, DEFAULT_GATE)
73const agents = atom({ plugin: 'flightdeck', key: 'agents' } as const, [])
74const loops = atom({ plugin: 'flightdeck', key: 'loops' } as const, [])
75const log = atom({ plugin: 'flightdeck', key: 'log' } as const, [])
76const turn = atom({ plugin: 'flightdeck', key: 'turn' } as const, DEFAULT_TURN)
77const receipt = atom({ plugin: 'flightdeck', key: 'receipt' } as const, null)
78const view = atom({ plugin: 'flightdeck', key: 'view' } as const, DEFAULT_VIEW)
79const roster = atom({ plugin: 'flightdeck', key: 'roster' } as const, DEFAULT_ROSTER)
80const paneOpen = atom({ plugin: 'flightdeck', key: 'paneOpen' } as const, false)
81
82type ServerBlock = { type: string; id?: string; name?: string; tool_use_id?: string }
83
84// Every read goes through these, so a value saved under an older shape still reads.
85async function getMain($: EngineInterface): Promise<Main> {
86 return normalize(DEFAULT_MAIN, await read($, main))
87}
88async function getUsage($: EngineInterface): Promise<Usage> {
89 return normalize(DEFAULT_USAGE, await read($, usage))
90}
91async function getArchitect($: EngineInterface): Promise<Architect> {
92 const a = normalize(DEFAULT_ARCHITECT, await read($, architect))
93 return { ...a, consults: listOf(a.consults), ids: listOf(a.ids), seen: listOf(a.seen) }
94}
95async function getGate($: EngineInterface): Promise<Gate> {
96 return normalizeGate(await read($, gate))
97}
98async function getCards($: EngineInterface): Promise<AgentCard[]> {
99 return listOf<unknown>(await read($, agents)).map(normalizeCard)
100}
101async function getLoops($: EngineInterface): Promise<Loop[]> {
102 return listOf<Loop>(await read($, loops))
103}
104async function getLog($: EngineInterface): Promise<LogLine[]> {
105 return normalizeLog(await read($, log))
106}
107async function getTurn($: EngineInterface): Promise<Turn> {
108 return normalize(DEFAULT_TURN, await read($, turn))
109}
110async function getView($: EngineInterface): Promise<View> {
111 return normalize(DEFAULT_VIEW, await read($, view))
112}
113async function getRoster($: EngineInterface): Promise<Roster> {
114 const r = normalize(DEFAULT_ROSTER, await read($, roster))
115 return { architectTypes: listOf(r.architectTypes) }
116}
117
118/** A stored shape older than this build's: drop what cannot be read, keep the rest. */
119async function migrate($: EngineInterface) {
120 const m = await read($, meta)
121 if ((m?.schemaVersion ?? 0) >= SCHEMA_VERSION) return
122 await update($, log, list => normalizeLog(list))
123 await update($, agents, list => listOf<unknown>(list).map(normalizeCard))
124 await update($, gate, g => normalizeGate(g))
125 await update($, meta, () => ({ schemaVersion: SCHEMA_VERSION }))
126}
127
128async function say($: EngineInterface, who: string, text: string, kind: LogLine['kind'] = 'info', agentId: string | null = null) {
129 const line: LogLine = { at: await $.clock.now(), who, text, kind, agentId }
130 await update($, log, list => [...normalizeLog(list), line].slice(-60))
131}
132
133async function refreshStatus($: EngineInterface, cfg: Config) {
134 if (!cfg.statusLine) return $.ui.status(undefined)
135 const [u, a, g, cards] = await Promise.all([getUsage($), getArchitect($), getGate($), getCards($)])
136 const running = cards.filter(c => c.status === 'running').length
137 const s = gateSummary(g)
138 const parts = [
139 u.pct !== null ? `ctx ${Math.round(u.pct)}%` : null,
140 cards.length > 0 ? `agents ${running}/${cards.length}` : null,
141 a.consults.length > 0 || a.ids.length > 0 ? `${cfg.architectLabel.toLowerCase()} ${isAdvising(a) ? 'advising' : a.consults.length}` : null,
142 s.deny > 0 ? `denied ${s.deny}` : null,
143 ]
144 // Only fields with something to say; with none, no status entry at all.
145 const shown = parts.filter(Boolean)
146 $.ui.status(shown.length > 0 ? shown.join(' · ') : undefined)
147}
148
149async function whoIs($: EngineInterface, agentId: string | undefined) {
150 if (!agentId) return 'main'
151 const card = (await getCards($)).find(c => c.id === agentId)
152 return card ? shorten(cardTitle(card), 14) : 'agent'
153}
154
155async function consultStarted($: EngineInterface, cfg: Config, id: string, via: string) {
156 const t = await getTurn($)
157 const moment = momentOf(t)
158 const at = await $.clock.now()
159 await update($, architect, a => startConsult(normalize(DEFAULT_ARCHITECT, a), { id, at, moment, via }))
160 if (moment === 'before done') await update($, turn, x => ({ ...normalize(DEFAULT_TURN, x), isReviewing: true }))
161 await say($, cfg.architectLabel.toLowerCase(), cfg.moments ? `${moment} · ${via}` : `consulted · ${via}`, 'consult')
162 await refreshStatus($, cfg)
163}
164
165async function consultEnded($: EngineInterface, cfg: Config, advice: string | null, id?: string) {
166 const at = await $.clock.now()
167 const first = advice?.split('\n').find(l => l.trim()) ?? null
168 const text = first ? shorten(first.replace(/^[#>*\s-]+/, ''), 160) : null
169 await update($, architect, a => endConsult(normalize(DEFAULT_ARCHITECT, a), at, text, id))
170 await update($, turn, t => ({ ...normalize(DEFAULT_TURN, t), isReviewing: false }))
171 await say($, cfg.architectLabel.toLowerCase(), text ? `advice: ${shorten(text, 60)}` : 'advice returned', 'consult')
172 await refreshStatus($, cfg)
173}
174
175async function noteAdvice($: EngineInterface, cfg: Config, advice: string) {
176 await update($, architect, x => ({ ...normalize(DEFAULT_ARCHITECT, x), lastAdvice: advice }))
177 await say($, cfg.architectLabel.toLowerCase(), `advice: ${shorten(advice, 60)}`, 'consult')
178}
179
180async function isArchitectType($: EngineInterface, cfg: Config, type: string) {
181 return cfg.architect.test(type) || (await getRoster($)).architectTypes.includes(type)
182}
183
184async function openPane($: EngineInterface) {
185 // columns apply when docked beside the transcript, rows when seated inline above the prompt.
186 return $.ui.open({ id: PANE, title: TITLE, columns: PANE_COLUMNS, rows: 8 })
187}
188
189async function resetAll($: EngineInterface) {
190 await update($, main, m => ({ ...DEFAULT_MAIN, model: normalize(DEFAULT_MAIN, m).model, mode: normalize(DEFAULT_MAIN, m).mode }))
191 await update($, architect, () => DEFAULT_ARCHITECT)
192 await update($, gate, () => DEFAULT_GATE)
193 await update($, agents, () => [])
194 await update($, loops, () => [])
195 await update($, log, () => [])
196 await update($, turn, () => DEFAULT_TURN)
197 await update($, receipt, () => null)
198 await update($, view, () => DEFAULT_VIEW)
199 // The context gauge waits for the next measurement rather than showing the pre-clear fill.
200 await update($, usage, x => ({ ...normalize(DEFAULT_USAGE, x), pct: null, tokens: null }))
201}
202
203/** The session's cost read fresh, not from the last measurement: the receipt subtracts two of these. */
204async function costNow($: EngineInterface): Promise<number | null> {
205 const u = await $.session.usage().catch(() => null)
206 return u?.cost?.usd ?? null
207}
208
209async function noteMode($: EngineInterface, mode: string | undefined) {
210 if (mode) await update($, main, m => (normalize(DEFAULT_MAIN, m).mode === mode ? normalize(DEFAULT_MAIN, m) : { ...normalize(DEFAULT_MAIN, m), mode }))
211}
212
213// ---------------------------------------------------------------- hooks
214
215export const register: Register = (on, options) => {
216 const cfg = parseConfig(options)
217 const C = PALETTES[cfg.palette]
218 // tool.check carries no loop id; the tool.call around it does, keyed by the call's id.
219 const callLoop = new Map<string, string | null>()
220 registerPinboard(on)
221
222 on('session.start', async ($, e, next) => {
223 await $.command.register({
224 name: 'flightdeck',
225 description: 'Flightdeck, the live agent dashboard: open, close, reset, or set the layout',
226 argumentHint: '[open|close|status|reset|layout auto|compact|wide|mini]',
227 })
228 await migrate($)
229 await startPinboard($)
230 // A reload keeps the pane up but starts the module over: re-read whether it is open
231 const isUp = (await $.ui.panes().catch(() => [])).some(p => p.id === PANE)
232 await update($, paneOpen, () => isUp)
233 // A host without usage (headless, an SDK host, a session not yet bound) just starts without it.
234 const u = await $.session.usage().catch(() => null)
235 if (u) {
236 await update($, usage, x => ({
237 ...normalize(DEFAULT_USAGE, x),
238 pct: u.context.percent ?? null,
239 tokens: u.context.tokens ?? null,
240 window: u.context.window,
241 costUsd: u.cost?.usd ?? null,
242 limits: u.rateLimits.map(r => ({ kind: r.kind, pct: r.percentUsed })),
243 }))
244 }
245 if (cfg.openOnStart) void openPane($).catch(() => undefined)
246 await refreshStatus($, cfg)
247 return next(e)
248 })
249
250 // Mod Tools' Show column reads paneOpen; the engine lists a plugin's panes only to that plugin
251 on('ui.open', { id: PANE }, async ($, e, next) => {
252 const opened = await next(e)
253 await update($, paneOpen, () => true)
254 return opened
255 }).catch(($, e, next) => next(e))
256
257 on('ui.close', { id: PANE }, async ($, e, next) => {
258 const closed = await next(e)
259 await update($, paneOpen, () => false)
260 return closed
261 }).catch(($, e, next) => next(e))
262
263 on('session.end', async ($, e, next) => {
264 if (e.reason === 'clear') {
265 await resetAll($)
266 await clearBoard($)
267 await refreshStatus($, cfg)
268 }
269 return next(e)
270 })
271
272 on('command.run', { command: 'flightdeck' }, async ($, e) => {
273 const [verb = 'open', arg = ''] = e.args.trim().split(/\s+/)
274 if (verb === 'close') {
275 await $.ui.close({ id: PANE })
276 return { text: 'Flightdeck closed.' }
277 }
278 if (verb === 'reset') {
279 await resetAll($)
280 await refreshStatus($, cfg)
281 return { text: 'Flightdeck reset.' }
282 }
283 // Where the pane stands: whether its tab is the one in front, and whether it holds the keys
284 if (verb === 'status') {
285 const pane = (await $.ui.panes().catch(() => [])).find(p => p.id === PANE)
286 if (!pane) return { text: 'Flightdeck is closed.' }
287 return { text: `Flightdeck: ${pane.isShown ? 'in front' : 'behind another tab'}, ${pane.isPlaced ? 'placed' : 'waiting to be placed'}, ${pane.isFocused ? 'holds the keyboard' : 'prompt has the keyboard'}.` }
288 }
289 if (verb === 'layout') {
290 const layout: Layout | null = arg === 'compact' || arg === 'wide' || arg === 'auto' || arg === 'mini' ? arg : null
291 if (!layout) return { text: 'Usage: /flightdeck layout auto|compact|wide|mini' }
292 await update($, view, v => ({ ...normalize(DEFAULT_VIEW, v), layout }))
293 const opened = await openPane($)
294 return { text: opened.isPlaced ? `Flightdeck layout: ${layout}.` : `Layout set to ${layout}; the pane is not shown yet: ${opened.reason}` }
295 }
296 const opened = await openPane($)
297 if (!opened.isPlaced) return { text: `Flightdeck is not shown yet: ${opened.reason}` }
298 return { text: 'Flightdeck opened. Focus it with ctrl+x tab; 1-6 expand cards, f/s/o open the gate rows, l clears the pinboard links.' }
299 })
300
301 on('classic.UserPromptSubmit', async ($, e, next) => {
302 await noteMode($, e.permission_mode)
303 return next(e)
304 })
305
306 on('agent.offer', async ($, e, next) => {
307 const offered = await next(e)
308 if (cfg.architect.test(e.agent) || (cfg.matchDescriptions && cfg.architect.test(e.description))) {
309 await update($, roster, r => {
310 const x = normalize(DEFAULT_ROSTER, r)
311 return x.architectTypes.includes(e.agent) ? x : { architectTypes: [...listOf<string>(x.architectTypes), e.agent].slice(-20) }
312 })
313 }
314 return offered
315 })
316
317 on('turn.start', async ($, e, next) => {
318 const [now, cost] = await Promise.all([$.clock.now(), costNow($)])
319 await update($, turn, () => ({ ...DEFAULT_TURN, startedAt: now, costAtStart: cost }))
320 await update($, main, m => ({ ...normalize(DEFAULT_MAIN, m), isRunning: true }))
321 // A background architect's report reaches the main loop as the text opening this turn. The
322 // SubagentHandback tool call (in tool.call) normally carries it first; this is the fallback.
323 const back = e.text ? handbackOf(e.text) : null
324 const a = back ? await getArchitect($) : null
325 if (back && a && a.ids.includes(back.from)) {
326 const advice = adviceLine(back.body)
327 if (advice && advice !== a.lastAdvice) await noteAdvice($, cfg, advice)
328 } else if (e.text) {
329 const p = promptLine(e.text)
330 await say($, p.who, p.text)
331 }
332 return next(e)
333 })
334
335 on('turn.step', async function* ($, e, next) {
336 // The main loop's model is known when its request starts; a long first request shouldn't read "—".
337 if (!e.agentId) {
338 await update($, main, m => {
339 const x = normalize(DEFAULT_MAIN, m)
340 return { ...x, model: e.model, effort: String(e.effort ?? x.effort), steps: x.steps + 1 }
341 })
342 return yield* next(e)
343 }
344 const result = yield* next(e)
345 const id = e.agentId
346 const [cards, a] = await Promise.all([getCards($), getArchitect($)])
347 if (cards.some(c => c.id === id)) {
348 const step = { model: e.model, usage: result.usage, stopReason: result.stopReason }
349 await update($, agents, list => listOf<unknown>(list).map(normalizeCard).map(c => (c.id === id ? applyStep(c, step) : c)))
350 if (result.stopReason === 'max_tokens') await say($, await whoIs($, id), 'hit max_tokens', 'error', id)
351 } else if (!a.ids.includes(id)) {
352 const now = await $.clock.now()
353 await update($, loops, l => stepLoop(listOf<Loop>(l), id, now))
354 }
355 return result
356 })
357
358 on('session.measure', async ($, e, next) => {
359 await update($, usage, x => ({
360 ...normalize(DEFAULT_USAGE, x),
361 pct: e.context.percent ?? null,
362 tokens: e.context.tokens ?? null,
363 window: e.context.window,
364 costUsd: e.cost?.usd ?? null,
365 limits: e.rateLimits.map(r => ({ kind: r.kind, pct: r.percentUsed })),
366 }))
367 if (e.changed.includes('context')) await refreshStatus($, cfg)
368 return next(e)
369 })
370
371 on('session.compact', async ($, e, next) => {
372 const done = await next(e)
373 if (!e.agentId && e.trigger !== 'precompute') {
374 const now = await $.clock.now()
375 await update($, usage, x => {
376 const u = normalize(DEFAULT_USAGE, x)
377 return { ...u, compactions: u.compactions + 1, lastCompactAt: now }
378 })
379 await say($, 'main', `context compacted (${e.trigger})`)
380 }
381 return done
382 })
383
384 on('tool.check', async ($, e, next) => {
385 const verdict = await next(e)
386 if (e.tool_use_id) {
387 const check: Check = {
388 id: e.tool_use_id,
389 tool: e.tool,
390 bucket: bucketOf(e.tool),
391 verdict: verdict.decision === 'allow' ? 'rule' : verdict.decision,
392 inSubagent: Boolean(callLoop.get(e.tool_use_id)),
393 detail: shorten(describeInput(e.tool, e.input), 90),
394 at: await $.clock.now(),
395 }
396 await update($, gate, g => recordCheck(normalizeGate(g), check))
397 // The status line updates when the call settles; only a refusal ends here.
398 if (verdict.decision === 'deny') {
399 await say($, 'gate', `denied by rule · ${check.detail}`, 'error')
400 await refreshStatus($, cfg)
401 }
402 }
403 return verdict
404 })
405
406 on('tool.call', async ($, e, next) => {
407 callLoop.set(e.tool_use_id, e.agentId ?? null)
408 const ran = await next(e).finally(() => callLoop.delete(e.tool_use_id))
409 await captureLinks($, e, ran)
410 const didRun = ran.deny === undefined
411 // Settle this call's pending ask, if it had one; skip the write (and the redraw) otherwise.
412 const g0 = await getGate($)
413 const isSettled = settleCheck(g0, e.tool_use_id, didRun) !== g0
414 if (isSettled) await update($, gate, g => settleCheck(normalizeGate(g), e.tool_use_id, didRun))
415 // A background agent hands its report back through this tool; an architect's report is its advice.
416 if (String(e.tool) === 'SubagentHandback') {
417 const message = (e as unknown as { message?: unknown }).message
418 const a = e.agentId ? await getArchitect($) : null
419 if (a && e.agentId && a.ids.includes(e.agentId) && typeof message === 'string') {
420 const advice = adviceLine(message)
421 if (advice && advice !== a.lastAdvice) await noteAdvice($, cfg, advice)
422 }
423 return ran
424 }
425 if (e.tool === 'Agent') {
426 if (isSettled) await refreshStatus($, cfg)
427 return ran
428 }
429 const hasFailed = didRun && ran.isError === true
430 const isEdit = !hasFailed && didRun && EDIT_TOOLS.has(e.tool)
431 const t0 = await getTurn($)
432 if (isEdit || hasFailed || (!e.agentId && t0.errorStreak > 0)) {
433 await update($, turn, t => afterCall(normalize(DEFAULT_TURN, t), { inSubagent: Boolean(e.agentId), hasFailed, isEdit }))
434 }
435 const text = shorten(describeInput(e.tool, e), 64)
436 if (e.agentId) {
437 const id = e.agentId
438 await update($, agents, list =>
439 listOf<unknown>(list)
440 .map(normalizeCard)
441 .map(c => (c.id === id ? noteTool(c, { tool: e.tool, text, isError: hasFailed || ran.deny !== undefined }) : c)),
442 )
443 }
444 // The log keeps what is worth a glance: refusals, errors and edits; the rest is on the cards.
445 if (ran.deny !== undefined) await say($, await whoIs($, e.agentId), `${text} denied`, 'error', e.agentId ?? null)
446 else if (hasFailed) await say($, await whoIs($, e.agentId), `${text} ✗`, 'error', e.agentId ?? null)
447 else if (isEdit) await say($, await whoIs($, e.agentId), text, 'info', e.agentId ?? null)
448 if (isSettled || !didRun) await refreshStatus($, cfg)
449 return ran
450 })
451
452 // A server-side review tool never reaches tool.call: it shows only in the assistant's rows.
453 on('session.append', async ($, e, next) => {
454 if (!e.agentId && e.message.type === 'assistant') {
455 const a = await getArchitect($)
456 // Consults this row opened: their result may be in the same row, after the stale read above.
457 const opened = new Set<string>()
458 for (const block of e.message.content as unknown as readonly ServerBlock[]) {
459 if (block.type === 'server_tool_use' && block.name && block.id && cfg.architect.test(block.name)) {
460 if (a.seen.includes(block.id)) continue
461 const id = block.id
462 await update($, architect, x => {
463 const y = normalize(DEFAULT_ARCHITECT, x)
464 return { ...y, seen: [...listOf<string>(y.seen), id].slice(-60) }
465 })
466 opened.add(id)
467 await consultStarted($, cfg, id, `${block.name} tool`)
468 } else if (block.type.endsWith('_tool_result') && block.tool_use_id) {
469 const id = block.tool_use_id
470 const isOpen = opened.has(id) || (await getArchitect($)).consults.some(c => c.id === id && c.endAt === null)
471 if (isOpen) await consultEnded($, cfg, null, id)
472 }
473 }
474 }
475 return next(e)
476 })
477
478 on('agent.spawn', async ($, e, next) => {
479 const started = await next(e)
480 if (!e.parentAgentId) await noteMode($, e.permissionMode)
481 if (started.deny !== undefined || !started.agentId) return started
482 const id = started.agentId
483 if (await isArchitectType($, cfg, e.subagentType)) {
484 await update($, architect, a => {
485 const x = normalize(DEFAULT_ARCHITECT, a)
486 return { ...x, ids: [...listOf<string>(x.ids), id].slice(-40) }
487 })
488 await update($, loops, l => listOf<Loop>(l).filter(x => x.id !== id))
489 await consultStarted($, cfg, id, e.subagentType.split(':').pop() ?? 'agent')
490 return started
491 }
492 const card: AgentCard = {
493 ...normalizeCard({}),
494 id,
495 type: e.name ?? e.subagentType,
496 model: started.model,
497 description: e.description,
498 spawnedAt: await $.clock.now(),
499 }
500 await update($, agents, list => [...listOf<unknown>(list).map(normalizeCard), card].slice(-24))
501 await update($, loops, l => listOf<Loop>(l).filter(x => x.id !== id))
502 await say($, shorten(cardTitle(card), 12), `spawned · ${card.type}`, 'info', id)
503 await refreshStatus($, cfg)
504 return started
505 })
506
507 on('turn.complete', async ($, e, next) => {
508 const done = await next(e)
509 const id = e.agentId
510 const now = await $.clock.now()
511 if (!id) {
512 const [t, cards, cost] = await Promise.all([getTurn($), getCards($), costNow($)])
513 const r = receiptOf(t, {
514 durationMs: e.durationMs,
515 agentsSince: cards.filter(c => c.spawnedAt >= t.startedAt).length,
516 costNow: cost,
517 reason: e.reason,
518 })
519 await update($, receipt, () => r)
520 await update($, main, m => ({ ...normalize(DEFAULT_MAIN, m), isRunning: false }))
521 await refreshStatus($, cfg)
522 return done
523 }
524 if ((await getArchitect($)).ids.includes(id)) {
525 await consultEnded($, cfg, e.answer, id)
526 return done
527 }
528 const cards = await getCards($)
529 if (cards.some(c => c.id === id)) {
530 const status = e.reason === 'answer' ? 'done' : e.reason === 'aborted' ? 'stopped' : 'failed'
531 await update($, agents, list =>
532 listOf<unknown>(list)
533 .map(normalizeCard)
534 .map(c => (c.id === id ? { ...c, status, endedAt: now, answer: shorten(e.answer, 400) } : c)),
535 )
536 const card = cards.find(c => c.id === id)
537 const took = card ? fmtDuration(now - card.spawnedAt) : ''
538 await say($, await whoIs($, id), status === 'done' ? `done · ${took}` : status, status === 'done' ? 'done' : 'error', id)
539 } else {
540 await update($, loops, l => listOf<Loop>(l).map(x => (x.id === id ? { ...x, isDone: true, lastAt: now } : x)))
541 }
542 await refreshStatus($, cfg)
543 return done
544 })
545
546 // ---------------------------------------------------------------- drawing
547
548 on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
549 const els = $.ui.resolve(e)
550 const { Box, Text, Button } = els
551 const hasClient = 'Client' in els
552 const [m, u, a, g, cards, lp, lines, t, r, v, now, pb] = await Promise.all([
553 getMain($),
554 getUsage($),
555 getArchitect($),
556 getGate($),
557 getCards($),
558 getLoops($),
559 getLog($),
560 getTurn($),
561 read($, receipt),
562 getView($),
563 $.clock.now(),
564 readBoard($),
565 ])
566 const W = Math.max(40, e.props.bodyColumns)
567 const layout = v.layout ?? cfg.layout
568 const isWide = layout === 'wide' || (layout === 'auto' && W >= 110)
569 const colW = isWide ? Math.floor((W - 2) / 2) : W
570 const modelName = prettyModel(m.model)
571 const viewed = e.props.view?.agentId ?? null
572 const advising = isAdvising(a)
573 const running = cards.filter(c => c.status === 'running')
574 const showArchitect = a.consults.length > 0 || a.ids.length > 0
575 const motion = cfg.motion && hasClient
576 // A panel with nothing to show yet takes no room: most sessions never spawn an agent.
577 const isEmpty: Record<Panel, boolean> = {
578 main: false,
579 architect: !showArchitect,
580 gate: g.recent.length === 0 && gateSummary(g).total === 0,
581 agents: cards.length === 0,
582 loops: lp.length === 0,
583 receipt: !m.isRunning && !r,
584 board: isBoardEmpty(pb),
585 log: false,
586 }
587 const panels = cfg.panels.filter(p => !isEmpty[p])
588 const decider = m.mode === 'auto' ? 'classifier' : 'you'
589
590 // A connector between panels: animated while its flow is live, a dim line otherwise.
591 const rail = (key: string, active: boolean, color: string, width: number, marks: number[] = [], isMerge = false) =>
592 motion ? (
593 <els.Client
594 key={key}
595 module="./rail.tsx"
596 width={width}
597 height={1}
598 props={{ active, width, color, dim: C.faint, marks, isMerge }}
599 />
600 ) : (
601 <Text color={C.faint}>{'─'.repeat(Math.max(1, width))}</Text>
602 )
603
604 // A start time of 0 is unknown (state saved before it was recorded): no clock, not decades.
605 const clock = (key: string, since: number, endAt: number | null, color: string) =>
606 since <= 0 ? (
607 <Text color={color}>—</Text>
608 ) : hasClient ? (
609 <els.Client key={key} module="./elapsed.tsx" props={{ since, now, endAt, color }} />
610 ) : (
611 <Text color={color}>{fmtTimer((endAt ?? now) - since)}</Text>
612 )
613
614 // ---- main
615 const effortN = { low: 1, medium: 2, high: 3, xhigh: 4, max: 4 }[m.effort] ?? 0
616 const ctxGauge = u.pct !== null ? gauge(u.pct, 10) : null
617 const mainPanel = (w: number) => (
618 <Box flexDirection="column" borderStyle="round" borderColor={C.main} paddingX={1} width={w}>
619 <Box justifyContent="space-between">
620 <Text color={C.main} bold>
621 {modelName} · main
622 </Text>
623 <Text color={m.isRunning ? C.main : C.dim}>{m.isRunning ? '● working' : '○ idle'}</Text>
624 </Box>
625 <Text wrap="truncate">
626 <Text dimColor>effort </Text>
627 <Text color={C.main}>{'▮'.repeat(effortN) + '▯'.repeat(4 - effortN)} </Text>
628 <Text color={C.main} bold>
629 {m.effort || '—'}
630 </Text>
631 {m.mode ? <Text dimColor>{` mode ${m.mode}`}</Text> : null}
632 <Text dimColor>{` ${m.steps} req`}</Text>
633 </Text>
634 {ctxGauge ? (
635 <Text wrap="truncate">
636 <Text dimColor>ctx </Text>
637 <Text color={u.pct !== null && u.pct >= 80 ? C.warn : C.main}>{ctxGauge.on}</Text>
638 <Text color={C.faint}>{ctxGauge.off}</Text>
639 <Text bold>{` ${Math.round(u.pct ?? 0)}%`}</Text>
640 {u.tokens !== null ? <Text dimColor>{` ${kTokens(u.tokens)}/${kTokens(u.window)}`}</Text> : null}
641 {u.compactions > 0 ? <Text color={C.amber}>{` ⟲${u.compactions}`}</Text> : null}
642 </Text>
643 ) : null}
644 {u.costUsd !== null || u.limits.length > 0 ? (
645 <Text wrap="truncate">
646 {u.costUsd !== null ? <Text color={C.text}>{`${fmtUsd(u.costUsd)} `}</Text> : null}
647 {u.limits.slice(0, 2).map(l => {
648 const lg = gauge(l.pct, 5)
649 return (
650 <Text wrap="truncate">
651 <Text dimColor>{`${limitLabel(l.kind)} `}</Text>
652 <Text color={l.pct >= 80 ? C.warn : C.main}>{lg.on}</Text>
653 <Text color={C.faint}>{lg.off}</Text>
654 <Text dimColor>{` ${Math.round(l.pct)}% `}</Text>
655 </Text>
656 )
657 })}
658 </Text>
659 ) : null}
660 </Box>
661 )
662
663 // ---- architect
664 const lastConsult = a.consults[a.consults.length - 1]
665 const architectPanel = (w: number) => {
666 const tl = consultTimeline(a, now, Math.max(8, w - 4))
667 return (
668 <Box flexDirection="column" borderStyle="round" borderColor={C.arch} paddingX={1} width={w}>
669 <Box justifyContent="space-between">
670 <Text color={C.arch} bold>
671 {cfg.architectLabel} · {advising ? 'advising' : 'on call'}
672 </Text>
673 <Text>
674 <Text dimColor>consults </Text>
675 <Text color={C.arch} bold>
676 {a.consults.length}
677 </Text>
678 </Text>
679 </Box>
680 <Text color={C.arch}>{tl}</Text>
681 {lastConsult ? (
682 <Text dimColor wrap="truncate">
683 {advising
684 ? `consulting since ${fmtClock(lastConsult.at)}`
685 : `last ${fmtDuration(now - (lastConsult.endAt ?? lastConsult.at))} ago · took ${fmtDuration((lastConsult.endAt ?? now) - lastConsult.at)}`}
686 </Text>
687 ) : (
688 <Text dimColor>not consulted yet</Text>
689 )}
690 {cfg.moments ? (
691 <Box flexWrap="wrap" columnGap={2}>
692 {(['before a plan', 'error repeats', 'before done'] as const).map(mo => {
693 const isOn = lastConsult?.moment === mo
694 return (
695 <Text color={isOn ? C.arch : C.dim} bold={isOn}>
696 {isOn ? '◆' : '◇'} {mo}
697 </Text>
698 )
699 })}
700 <Text color={C.faint}>(inferred)</Text>
701 </Box>
702 ) : null}
703 {a.lastAdvice ? (
704 <Text color={C.arch} wrap="truncate">
705 » {a.lastAdvice}
706 </Text>
707 ) : null}
708 </Box>
709 )
710 }
711
712 // ---- gate
713 const s = gateSummary(g)
714 const verdictColor = (c: Check) =>
715 c.verdict === 'rule' ? C.gate : c.verdict === 'cleared' ? C.cleared : c.verdict === 'ask' ? C.amber : C.warn
716 const gatePanel = (w: number) => {
717 const strip = g.recent.slice(-Math.max(8, w - 4))
718 const open = v.gateOpen
719 return (
720 <Box flexDirection="column" borderStyle="round" borderColor={C.gate} paddingX={1} width={w}>
721 <Box justifyContent="space-between">
722 <Text color={C.gate} bold>
723 {cfg.gateLabel} · permissions
724 </Text>
725 <Text dimColor>{`${s.total} checks`}</Text>
726 </Box>
727 <Box>
728 {strip.length === 0 ? <Text color={C.faint}>no checks yet</Text> : null}
729 {strip.map(c => (
730 <Text color={verdictColor(c)} dimColor={c.inSubagent}>
731 {c.verdict === 'deny' ? '✗' : '■'}
732 </Text>
733 ))}
734 </Box>
735 <Text wrap="truncate">
736 <Text color={C.gate}>■</Text>
737 <Text dimColor>{` ${s.rule} allowed `}</Text>
738 <Text color={C.cleared}>■</Text>
739 <Text dimColor>{` ${s.cleared} ${decider} `}</Text>
740 {s.ask > 0 ? <Text color={C.amber}>{`■ ${s.ask} pending `}</Text> : null}
741 <Text color={s.deny > 0 ? C.warn : C.dim}>{`✗ ${s.deny} denied`}</Text>
742 {w >= 80 && g.recent.some(c => c.inSubagent) ? <Text color={C.faint}>{' dim: in subagents'}</Text> : null}
743 </Text>
744 <Box columnGap={2}>
745 {(['file', 'shell', 'other'] as const).map((b: Bucket) => {
746 const tl = g.totals[b]
747 const n = tl.rule + tl.ask + tl.cleared + tl.deny
748 return (
749 <Button
750 key={`gate-${b}`}
751 plain
752 hotkey={b[0]}
753 label={`${b} ${n}${open === b ? ' ▾' : ''}`}
754 dimColor={n === 0}
755 onPress={() => update($, view, x => ({ ...normalize(DEFAULT_VIEW, x), gateOpen: normalize(DEFAULT_VIEW, x).gateOpen === b ? null : b }))}
756 />
757 )
758 })}
759 </Box>
760 {open
761 ? g.recent
762 .filter(c => c.bucket === open)
763 .slice(-5)
764 .map(c => (
765 <Text wrap="truncate">
766 <Text color={verdictColor(c)}>{c.verdict === 'deny' ? '✗ ' : '■ '}</Text>
767 <Text color={C.dim}>{`${(c.verdict === 'rule' ? 'allowed' : c.verdict === 'cleared' ? decider : c.verdict === 'ask' ? 'pending' : 'denied').padEnd(10)} `}</Text>
768 <Text dimColor={c.inSubagent}>{shorten(c.detail, Math.max(10, w - 18))}</Text>
769 </Text>
770 ))
771 : null}
772 </Box>
773 )
774 }
775
776 // ---- agents: cards up to the limit, swimlanes beyond it
777 const statusColor = (c: AgentCard) => (c.status === 'failed' ? C.warn : c.status === 'done' ? C.gate : C.agent)
778 const glyph = (c: AgentCard) => (c.status === 'running' ? '◐' : c.status === 'done' ? '✓' : c.status === 'failed' ? '✗' : '■')
779 const expandOnPress = (id: string) => () =>
780 update($, view, x => ({ ...normalize(DEFAULT_VIEW, x), expanded: normalize(DEFAULT_VIEW, x).expanded === id ? null : id }))
781
782 const agentsPanel = (w: number) => {
783 // Cards need 20 columns each; when the pane can't hold the limit, lanes take over.
784 const fit = Math.max(1, Math.min(cfg.maxCards, Math.floor((w + 1) / 21)))
785 const useLanes = cards.length > fit
786 const header = (
787 <Box justifyContent="space-between" width={w}>
788 <Text bold>{`agents · ${running.length} running · ${cards.length} total`}</Text>
789 {cards.length > 0 ? <Text color={C.faint}>1-{Math.min(cards.length, useLanes ? 6 : fit)} expand</Text> : null}
790 </Box>
791 )
792 if (cards.length === 0) {
793 return (
794 <Box flexDirection="column" width={w}>
795 {header}
796 <Text color={C.faint}>no subagents yet</Text>
797 </Box>
798 )
799 }
800 if (useLanes) {
801 const shown = cards.slice(-6)
802 const barW = Math.max(8, w - 28)
803 const geo = lanes(shown, now, barW)
804 return (
805 <Box flexDirection="column" width={w}>
806 {header}
807 {cards.length > shown.length ? <Text color={C.faint}>{`+${cards.length - shown.length} earlier`}</Text> : null}
808 {shown.map((c, i) => {
809 const gm = geo[i]
810 const isViewed = viewed === c.id
811 return (
812 <Box>
813 <Text color={statusColor(c)} bold={isViewed}>{`${isViewed ? '▶' : glyph(c)} `}</Text>
814 <Box width={17}>
815 <Button key={`card-${c.id}`} plain hotkey={String(i + 1)} label={shorten(cardTitle(c), 14)} onPress={expandOnPress(c.id)} />
816 </Box>
817 <Text color={C.faint}>{' ' + '·'.repeat(gm?.before ?? 0)}</Text>
818 <Text color={statusColor(c)}>{'━'.repeat(gm?.bar ?? 1)}</Text>
819 <Text color={C.faint}>{'·'.repeat(gm?.after ?? 0) + ' '}</Text>
820 {clock(`lane-clock-${c.id}`, c.spawnedAt, c.endedAt, C.dim)}
821 </Box>
822 )
823 })}
824 </Box>
825 )
826 }
827 const shown = cards.slice(-fit)
828 const cardW = Math.max(20, Math.floor((w - (shown.length - 1)) / shown.length))
829 const centers = shown.map((_, i) => i * (cardW + 1) + Math.floor(cardW / 2))
830 return (
831 <Box flexDirection="column" width={w}>
832 {header}
833 {rail('fan-out', running.length > 0, C.agent, w, centers)}
834 <Box columnGap={1}>
835 {shown.map((c, i) => {
836 const isViewed = viewed === c.id
837 const sameModel = !c.model || prettyModel(c.model) === modelName
838 return (
839 <Box
840 flexDirection="column"
841 borderStyle={isViewed ? 'double' : 'round'}
842 borderColor={c.lastStop === 'max_tokens' ? C.warn : C.agent}
843 borderDimColor={c.status !== 'running' && !isViewed}
844 width={cardW}
845 paddingX={1}
846 >
847 <Button key={`card-${c.id}`} plain hotkey={String(i + 1)} label={titleLines(cardTitle(c), cardW - 7, cardW - 4)[0]} onPress={expandOnPress(c.id)} />
848 <Text bold wrap="truncate">
849 {titleLines(cardTitle(c), cardW - 7, cardW - 4)[1]}
850 </Text>
851 <Text color={C.dim} wrap="truncate">
852 {sameModel ? c.type : `${c.type} · ${prettyModel(c.model)}`}
853 </Text>
854 <Text dimColor wrap="truncate">
855 {c.steps > 0 ? `ctx ${kTokens(c.ctx)} · out ${kTokens(c.out)} · ${c.steps} st` : 'starting…'}
856 </Text>
857 <Box>
858 <Text color={c.lastStop === 'max_tokens' ? C.warn : statusColor(c)}>
859 {cardW >= 26 ? `${glyph(c)} ${c.lastStop === 'max_tokens' ? 'max_tokens' : c.status} ` : `${glyph(c)} `}
860 </Text>
861 <Box flexShrink={0}>{clock(`card-clock-${c.id}`, c.spawnedAt, c.endedAt, C.dim)}</Box>
862 </Box>
863 </Box>
864 )
865 })}
866 </Box>
867 {rail('merge', running.length > 0, C.agent, w, centers, true)}
868 </Box>
869 )
870 }
871
872 const expandedCard = cards.find(c => c.id === v.expanded)
873 const expandedPanel = (w: number) =>
874 expandedCard ? (
875 <Box flexDirection="column" borderStyle="single" borderColor={C.agent} paddingX={1} width={w}>
876 <Text bold wrap="wrap">
877 {expandedCard.description || expandedCard.type}
878 </Text>
879 <Text dimColor wrap="truncate">{`${expandedCard.type} · ${prettyModel(expandedCard.model)} · ${expandedCard.status} · ${expandedCard.steps} steps`}</Text>
880 {expandedCard.tools.length === 0 ? <Text color={C.faint}>no tool calls yet</Text> : null}
881 {expandedCard.tools.map(n => (
882 <Text color={n.isError ? C.warn : C.text} wrap="truncate">
883 {`${n.isError ? '✗' : '·'} ${n.text}`}
884 </Text>
885 ))}
886 {expandedCard.answer ? (
887 <Text dimColor wrap="wrap">
888 {`» ${shorten(expandedCard.answer, 240)}`}
889 </Text>
890 ) : null}
891 </Box>
892 ) : null
893
894 // ---- other loops (workflow agents, forks): ids that match no card
895 const loopsPanel = (w: number) => {
896 if (lp.length === 0) return null
897 const active = lp.filter(l => isLoopActive(l, now)).length
898 const dots = lp.slice(-Math.max(4, w - 38))
899 return (
900 <Box width={w}>
901 <Text bold>other loops </Text>
902 <Text dimColor>{`${lp.length} seen · ${active} active `}</Text>
903 {dots.map(l => (
904 <Text color={isLoopActive(l, now) ? C.agent : l.isDone ? C.dim : C.faint}>{isLoopActive(l, now) ? '●' : l.isDone ? '✓' : '○'}</Text>
905 ))}
906 </Box>
907 )
908 }
909
910 // ---- receipt: the turn now, or the last one
911 const receiptPanel = (w: number) => {
912 const isReview = t.isReviewing
913 return (
914 <Box flexDirection="column" borderStyle="round" borderColor={C.main} borderDimColor={!m.isRunning && !isReview} paddingX={1} width={w}>
915 {m.isRunning ? (
916 <Box>
917 <Text color={C.main} wrap="truncate">{`◐ back to ${modelName.toLowerCase()} · turn `}</Text>
918 <Box flexShrink={0}>{clock('turn-clock', t.startedAt, null, C.main)}</Box>
919 {w >= 60 ? <Text dimColor wrap="truncate">{` · ${plural(t.edits, 'edit')} · ${plural(t.errors, 'error')}`}</Text> : null}
920 </Box>
921 ) : r ? (
922 <Text wrap="truncate">
923 <Text color={r.reason === 'answer' ? C.gate : C.warn}>{r.reason === 'answer' ? '✓ ' : '✗ '}</Text>
924 <Text>{`last turn ${fmtDuration(r.durationMs)} · ${plural(r.agents, 'agent')} · ${plural(r.edits, 'edit')} · ${plural(r.errors, 'error')}`}</Text>
925 {r.costDelta !== null ? <Text color={C.main}>{` · +${fmtUsd(r.costDelta)}`}</Text> : null}
926 </Text>
927 ) : (
928 <Text color={C.faint}>no turn finished yet</Text>
929 )}
930 {isReview ? <Text color={C.arch}>{`${cfg.architectLabel.toLowerCase()} reviewing before done (inferred)`}</Text> : null}
931 </Box>
932 )
933 }
934
935 // ---- log: whatever rows the other panels leave, 4 to 8
936 const used = 2 + 5 + (showArchitect ? 6 : 0) + 6 + (v.gateOpen ? 5 : 0) + (cards.length > cfg.maxCards ? 3 + Math.min(6, cards.length) : 8) + (expandedCard ? 8 : 0) + (lp.length ? 1 : 0) + 3 + (panels.includes('board') ? boardRows(pb) : 0)
937 const bodyRows = e.props.scroll?.bodyRows ?? e.viewport?.rows ?? 40
938 const nLog = logRows(bodyRows, used)
939 const shownLines = (viewed ? lines.filter(l => l.agentId === viewed) : lines).slice(-nLog)
940 const colorOf = (l: LogLine) =>
941 l.kind === 'error' ? C.warn : l.kind === 'consult' ? C.arch : l.who === 'main' ? C.main : l.who === 'gate' ? C.gate : l.who === 'you' ? C.text : C.agent
942 const logPanel = (w: number) => (
943 <Box flexDirection="column" borderStyle="round" borderColor={C.faint} paddingX={1} width={w}>
944 <Text dimColor>{viewed ? 'session log · this agent' : 'session log'}</Text>
945 {shownLines.length === 0 ? <Text color={C.faint}>nothing yet</Text> : null}
946 {shownLines.map(l => (
947 <Box>
948 <Box width={9} flexShrink={0}>
949 <Text color={C.faint}>{fmtClock(l.at)}</Text>
950 </Box>
951 <Box width={13} flexShrink={0}>
952 <Text color={colorOf(l)} bold wrap="truncate">
953 {l.who}
954 </Text>
955 </Box>
956 <Text color={l.kind === 'error' ? C.warn : C.text} wrap="truncate">
957 {l.text}
958 </Text>
959 </Box>
960 ))}
961 </Box>
962 )
963
964 const draw = (p: Panel, w: number) =>
965 p === 'main'
966 ? mainPanel(w)
967 : p === 'architect'
968 ? architectPanel(w)
969 : p === 'gate'
970 ? gatePanel(w)
971 : p === 'agents'
972 ? agentsPanel(w)
973 : p === 'loops'
974 ? loopsPanel(w)
975 : p === 'receipt'
976 ? receiptPanel(w)
977 : p === 'board'
978 ? boardPanel($, els, C, pb, w)
979 : logPanel(w)
980
981 // Panels with the flow between them; the agents panel draws its own rails.
982 const column = (ps: Panel[], w: number) => (
983 <Box flexDirection="column" width={w}>
984 {ps.map((p, i) => {
985 const prev = ps[i - 1]
986 const link =
987 i === 0 || p === 'agents' || prev === 'agents' || p === 'board' || p === 'log' || p === 'loops' || prev === 'loops'
988 ? null
989 : rail(`link-${p}`, p === 'architect' ? advising : m.isRunning, p === 'architect' ? C.arch : C.main, w)
990 return (
991 <Box flexDirection="column">
992 {link}
993 {draw(p, w)}
994 {p === 'agents' ? expandedPanel(w) : null}
995 </Box>
996 )
997 })}
998 </Box>
999 )
1000
1001 // Desktop draws the agents' time axis as SVG under the panels.
1002 const svgLanes =
1003 e.surface !== 'terminal' && cards.length > 0
1004 ? (() => {
1005 const { Svg } = $.ui.resolve(e)
1006 const rowH = 18
1007 const pxW = 520
1008 const geo = lanes(cards.slice(-10), now, 100)
1009 const rects = cards
1010 .slice(-10)
1011 .map((c, i) => {
1012 const gm = geo[i]
1013 const x = 150 + ((gm?.before ?? 0) / 100) * (pxW - 160)
1014 const wpx = Math.max(3, ((gm?.bar ?? 1) / 100) * (pxW - 160))
1015 const fill = c.status === 'running' ? SVG_COLORS.running : c.status === 'done' ? SVG_COLORS.done : c.status === 'failed' ? SVG_COLORS.failed : SVG_COLORS.other
1016 const label = shorten(cardTitle(c), 22).replace(/[<&>]/g, '')
1017 return `<text x="4" y="${i * rowH + 13}" font-size="11" fill="${SVG_COLORS.label}">${label}</text><rect x="${x}" y="${i * rowH + 4}" width="${wpx}" height="10" rx="3" fill="${fill}"/>`
1018 })
1019 .join('')
1020 const svgH = Math.min(10, cards.length) * rowH + 4
1021 return (
1022 <Svg
1023 source={`<svg xmlns="http://www.w3.org/2000/svg" width="${pxW}" height="${svgH}" viewBox="0 0 ${pxW} ${svgH}">${rects}</svg>`}
1024 alt={`${cards.length} agents on a time axis`}
1025 width={pxW}
1026 height={svgH}
1027 />
1028 )
1029 })()
1030 : null
1031
1032 // Inline above the prompt (the terminal's main screen), the pane is a summary of at most 8 rows.
1033 const isMini = layout === 'mini' || (layout === 'auto' && e.props.placement === 'inline')
1034 if (isMini) {
1035 const live = [...cards.filter(c => c.status === 'running'), ...cards.filter(c => c.status !== 'running').reverse()].slice(0, 3)
1036 const counts = ` ${s.rule} allowed · ${s.cleared} ${decider}${s.ask > 0 ? ` · ${s.ask} pending` : ''} · ${s.deny} denied`
1037 const strip = g.recent.slice(-Math.max(4, W - cfg.gateLabel.length - 1 - counts.length))
1038 const mg = u.pct !== null ? gauge(u.pct, 6) : null
1039 return (
1040 <Box flexDirection="column" width={W}>
1041 <Text wrap="truncate">
1042 <Text color={C.main} bold>
1043 {modelName}
1044 </Text>
1045 <Text color={m.isRunning ? C.main : C.dim}>{m.isRunning ? ' ● working' : ' ○ idle'}</Text>
1046 {mg ? <Text dimColor> · ctx </Text> : null}
1047 {mg ? <Text color={(u.pct ?? 0) >= 80 ? C.warn : C.main}>{mg.on}</Text> : null}
1048 {mg ? <Text color={C.faint}>{mg.off}</Text> : null}
1049 {mg ? <Text>{` ${Math.round(u.pct ?? 0)}%`}</Text> : null}
1050 {u.compactions > 0 ? <Text color={C.amber}>{` ⟲${u.compactions}`}</Text> : null}
1051 {u.costUsd !== null ? <Text dimColor>{` · ${fmtUsd(u.costUsd)}`}</Text> : null}
1052 {showArchitect ? <Text color={C.arch}>{` · ${cfg.architectLabel.toLowerCase()} ${advising ? 'advising' : a.consults.length}`}</Text> : null}
1053 </Text>
1054 {strip.length > 0 ? (
1055 <Box>
1056 <Text dimColor>{`${cfg.gateLabel.toLowerCase()} `}</Text>
1057 {strip.map(c => (
1058 <Text color={verdictColor(c)} dimColor={c.inSubagent}>
1059 {c.verdict === 'deny' ? '✗' : '■'}
1060 </Text>
1061 ))}
1062 <Text color={s.deny > 0 ? C.warn : s.ask > 0 ? C.amber : C.dim} wrap="truncate">
1063 {counts}
1064 </Text>
1065 </Box>
1066 ) : null}
1067 {live.map(c => (
1068 <Box>
1069 <Text color={statusColor(c)}>{`${glyph(c)} `}</Text>
1070 <Box width={Math.max(10, W - 30)}>
1071 <Text wrap="truncate">{cardTitle(c)}</Text>
1072 </Box>
1073 <Text dimColor>{c.steps > 0 ? ` ctx ${kTokens(c.ctx)} ` : ' '}</Text>
1074 {clock(`mini-clock-${c.id}`, c.spawnedAt, c.endedAt, C.dim)}
1075 </Box>
1076 ))}
1077 {cards.length > live.length ? (
1078 <Text color={C.faint} wrap="truncate">{`+${cards.length - live.length} more agents · /flightdeck layout compact for all`}</Text>
1079 ) : null}
1080 {lp.length > 0 ? <Text dimColor>{`other loops ${lp.length} · ${lp.filter(l => isLoopActive(l, now)).length} active`}</Text> : null}
1081 {cfg.panels.includes('board') && !isBoardEmpty(pb) ? (
1082 <Text color={C.amber} wrap="truncate">
1083 {boardLine(pb)}
1084 </Text>
1085 ) : null}
1086 {!m.isRunning && r ? (
1087 <Text dimColor wrap="truncate">
1088 {`last turn ${fmtDuration(r.durationMs)} · ${plural(r.agents, 'agent')} · ${plural(r.edits, 'edit')} · ${plural(r.errors, 'error')}${r.costDelta !== null ? ` · +${fmtUsd(r.costDelta)}` : ''}`}
1089 </Text>
1090 ) : null}
1091 </Box>
1092 )
1093 }
1094
1095 const legend = fitLegend(
1096 [
1097 { label: 'main', color: C.main },
1098 { label: 'agents', color: C.agent },
1099 { label: cfg.gateLabel.toLowerCase(), color: C.gate },
1100 ...(showArchitect ? [{ label: cfg.architectLabel.toLowerCase(), color: C.arch }] : []),
1101 ...(panels.includes('board') ? [{ label: 'pinboard', color: C.amber }] : []),
1102 ],
1103 W,
1104 )
1105
1106 const body = isWide ? (
1107 <Box flexDirection="column">
1108 <Box columnGap={2}>
1109 {column(panels.filter(p => p === 'main' || p === 'architect' || p === 'gate'), colW)}
1110 {column(panels.filter(p => p === 'agents' || p === 'loops' || p === 'receipt'), colW)}
1111 </Box>
1112 {panels.includes('board') ? boardPanel($, els, C, pb, W) : null}
1113 {panels.includes('log') ? logPanel(W) : null}
1114 </Box>
1115 ) : (
1116 column(panels, W)
1117 )
1118
1119 return (
1120 <Box flexDirection="column" width={W}>
1121 <Box justifyContent="center">
1122 <Text bold wrap="truncate">
1123 <Text>FLIGHTDECK</Text>
1124 <Text color={C.dim}> · </Text>
1125 <Text color={C.main}>{modelName.toUpperCase()}</Text>
1126 <Text>{m.isRunning ? ' WORKS' : ' IDLE'}</Text>
1127 {showArchitect ? <Text color={C.dim}> · </Text> : null}
1128 {showArchitect ? <Text color={C.arch}>{cfg.architectLabel}</Text> : null}
1129 {showArchitect ? <Text>{advising ? ' ADVISING' : ' ON CALL'}</Text> : null}
1130 </Text>
1131 </Box>
1132 <Box justifyContent="center" columnGap={2}>
1133 {legend.map(l => (
1134 <Text>
1135 <Text color={l.color}>■</Text>
1136 <Text dimColor>{` ${l.label}`}</Text>
1137 </Text>
1138 ))}
1139 </Box>
1140 {body}
1141 {svgLanes}
1142 </Box>
1143 )
1144 })
1145}
1146hooks/core.ts 493 lines1// Pure data: defaults, reducers, formatting and layout math. Nothing here touches `$`, so every
2// behaviour is testable directly (the test kit cannot raise a subagent's tool call or a
3// permission check inside a call; these functions are what the hooks apply).
4import type {
5 AgentCard,
6 Architect,
7 Bucket,
8 Check,
9 Gate,
10 Layout,
11 LogLine,
12 Loop,
13 Main,
14 Moment,
15 Receipt,
16 Roster,
17 Tally,
18 ToolNote,
19 Turn,
20 Usage,
21 View,
22} from '../types'
23
24export const SCHEMA_VERSION = 2
25
26// ---------------------------------------------------------------- defaults
27
28export const DEFAULT_MAIN: Main = { model: '', effort: '', mode: '', steps: 0, isRunning: false }
29export const DEFAULT_USAGE: Usage = {
30 pct: null,
31 tokens: null,
32 window: 0,
33 costUsd: null,
34 limits: [],
35 compactions: 0,
36 lastCompactAt: null,
37}
38export const DEFAULT_ARCHITECT: Architect = { consults: [], ids: [], seen: [], lastAdvice: '' }
39const ZERO: Tally = { rule: 0, ask: 0, cleared: 0, deny: 0 }
40export const DEFAULT_GATE: Gate = { recent: [], totals: { file: ZERO, shell: ZERO, other: ZERO } }
41export const DEFAULT_TURN: Turn = { edits: 0, errorStreak: 0, errors: 0, isReviewing: false, startedAt: 0, costAtStart: null }
42export const DEFAULT_VIEW: View = { expanded: null, gateOpen: null, layout: null }
43export const DEFAULT_ROSTER: Roster = { architectTypes: [] }
44
45const isObject = (v: unknown): v is Record<string, unknown> => typeof v === 'object' && v !== null && !Array.isArray(v)
46
47/** A stored object merged over its defaults, so a value saved under an older shape still reads. */
48export const normalize = <T extends object>(def: T, stored: unknown): T =>
49 isObject(stored) ? ({ ...def, ...stored } as T) : def
50
51/** A stored list, or empty when what is stored is not a list. */
52export const listOf = <T>(stored: unknown): T[] => (Array.isArray(stored) ? (stored as T[]) : [])
53
54export const normalizeGate = (stored: unknown): Gate => {
55 const g = normalize(DEFAULT_GATE, stored)
56 const totals = normalize(DEFAULT_GATE.totals, g.totals)
57 return {
58 recent: listOf<Check>(g.recent),
59 totals: { file: normalize(ZERO, totals.file), shell: normalize(ZERO, totals.shell), other: normalize(ZERO, totals.other) },
60 }
61}
62
63export const normalizeCard = (stored: unknown): AgentCard =>
64 normalize<AgentCard>(
65 {
66 id: '',
67 type: 'agent',
68 model: '',
69 description: '',
70 status: 'running',
71 spawnedAt: 0,
72 endedAt: null,
73 ctx: 0,
74 out: 0,
75 steps: 0,
76 lastStop: null,
77 tools: [],
78 answer: '',
79 },
80 stored,
81 )
82
83export const normalizeLog = (stored: unknown): LogLine[] =>
84 listOf<Record<string, unknown>>(stored).map(l => ({
85 at: typeof l.at === 'number' ? l.at : 0,
86 who: String(l.who ?? ''),
87 text: String(l.text ?? ''),
88 agentId: typeof l.agentId === 'string' ? l.agentId : null,
89 kind: l.kind === 'error' || l.kind === 'consult' || l.kind === 'done' ? l.kind : 'info',
90 }))
91
92// ---------------------------------------------------------------- config
93
94export type Panel = 'main' | 'architect' | 'gate' | 'agents' | 'loops' | 'receipt' | 'board' | 'log'
95const PANELS: readonly Panel[] = ['main', 'architect', 'gate', 'agents', 'loops', 'receipt', 'board', 'log']
96
97export type Config = {
98 architect: RegExp
99 architectLabel: string
100 gateLabel: string
101 panels: Panel[]
102 motion: boolean
103 moments: boolean
104 matchDescriptions: boolean
105 maxCards: number
106 layout: Layout
107 palette: Palette
108 openOnStart: boolean
109 statusLine: boolean
110}
111
112const safeRegExp = (source: string, fallback: string) => {
113 try {
114 return new RegExp(source || fallback, 'i')
115 } catch {
116 return new RegExp(fallback, 'i')
117 }
118}
119
120/** The plugin's `/config` values, read leniently: anything malformed falls back to the default. */
121export const parseConfig = (o: Readonly<Record<string, unknown>>): Config => {
122 const str = (k: string, d: string) => (typeof o[k] === 'string' && o[k] !== '' ? (o[k] as string) : d)
123 const bool = (k: string, d: boolean) => (typeof o[k] === 'boolean' ? (o[k] as boolean) : d)
124 const panels = str('panels', PANELS.join(','))
125 .split(',')
126 .map(s => s.trim())
127 .filter((p): p is Panel => (PANELS as readonly string[]).includes(p))
128 const layout = str('layout', 'auto')
129 const max = typeof o.maxCards === 'number' ? Math.round(o.maxCards) : 3
130 return {
131 architect: safeRegExp(str('architectPattern', ''), 'advisor|architect'),
132 architectLabel: str('architectLabel', 'ARCHITECT'),
133 gateLabel: str('gateLabel', 'GATE'),
134 panels: panels.length > 0 ? [...new Set(panels)] : [...PANELS],
135 motion: str('motion', 'while-active') !== 'off',
136 moments: bool('moments', true),
137 matchDescriptions: bool('matchDescriptions', false),
138 maxCards: Math.min(6, Math.max(1, max)),
139 layout: layout === 'compact' || layout === 'wide' || layout === 'mini' ? layout : 'auto',
140 palette: str('palette', 'theme') === 'pastel' ? 'pastel' : 'theme',
141 openOnStart: bool('openOnStart', true),
142 statusLine: bool('statusLine', true),
143 }
144}
145
146// ---------------------------------------------------------------- palette
147
148export type Palette = 'theme' | 'pastel'
149export type Colors = Record<'main' | 'agent' | 'gate' | 'cleared' | 'arch' | 'amber' | 'warn' | 'dim' | 'faint' | 'text', string>
150
151/**
152 * `theme` names the person's own theme colours (they follow light, dark and colour-blind themes);
153 * `pastel` is fixed hex tuned for dark terminals.
154 */
155export const PALETTES: Record<Palette, Colors> = {
156 theme: {
157 main: 'claude',
158 agent: 'suggestion',
159 gate: 'success',
160 cleared: 'permission',
161 arch: 'merged',
162 amber: 'warning',
163 warn: 'error',
164 dim: 'inactive',
165 faint: 'subtle',
166 text: 'text',
167 },
168 pastel: {
169 main: '#7dd3fc',
170 agent: '#93c5fd',
171 gate: '#86efac',
172 cleared: '#5eead4',
173 arch: '#c4b5fd',
174 amber: '#fcd34d',
175 warn: '#fca5a5',
176 dim: '#6b7280',
177 faint: '#3f4654',
178 text: '#e5e7eb',
179 },
180}
181
182/** SVG cannot name theme keys: mid-tone colours that read on light and dark backgrounds. */
183export const SVG_COLORS = { running: '#3b82f6', done: '#16a34a', failed: '#dc2626', other: '#8b5cf6', label: '#6b7280' }
184
185// ---------------------------------------------------------------- formatting
186
187/** `claude-opus-5-5` → `Opus 5.5`; anything else is shown as given. */
188/**
189 * A model id as people say it, from any provider's spelling: `claude-opus-5-5[1m]` → `Opus 5.5 1M`,
190 * `us.anthropic.claude-sonnet-4-5-20250929-v1:0` → `Sonnet 4.5`, `claude-3-5-haiku-20241022` →
191 * `Haiku 3.5`. Anything else is shown as given, cut to 22 characters.
192 */
193export const prettyModel = (id: string) => {
194 if (!id) return '—'
195 const cap = (f: string) => f.charAt(0).toUpperCase() + f.slice(1)
196 const big = /\[1m\]|-1m\b/i.test(id) ? ' 1M' : ''
197 const now = /claude-([a-z]+)-(\d+)(?:-(\d{1,2}))?(?:-\d{8})?(?![\d])/i.exec(id)
198 if (now?.[1] && !/^\d/.test(now[1])) return `${cap(now[1].toLowerCase())} ${now[2]}${now[3] ? `.${now[3]}` : ''}${big}`
199 const old = /claude-(\d+)(?:-(\d))?-([a-z]+)/i.exec(id)
200 if (old?.[3]) return `${cap(old[3].toLowerCase())} ${old[1]}${old[2] ? `.${old[2]}` : ''}${big}`
201 return shorten(id, 22)
202}
203
204export const shorten = (s: string, n: number) => {
205 const one = s.replace(/\s+/g, ' ').trim()
206 return n <= 0 ? '' : one.length > n ? `${one.slice(0, Math.max(0, n - 1)).trimEnd()}…` : one
207}
208
209export const kTokens = (n: number) =>
210 n >= 1_000_000 ? `${(n / 1_000_000).toFixed(1)}M` : n >= 1000 ? `${Math.round(n / 1000)}k` : String(n)
211
212export const fmtDuration = (ms: number) => {
213 const s = Math.max(0, Math.round(ms / 1000))
214 if (s < 60) return `${s}s`
215 const m = Math.floor(s / 60)
216 return m < 60 ? `${m}m${String(s % 60).padStart(2, '0')}s` : `${Math.floor(m / 60)}h${String(m % 60).padStart(2, '0')}m`
217}
218
219/** A running clock as the live cards draw it: m:ss, or XhYY past an hour. */
220export const fmtTimer = (ms: number) => {
221 const s = Math.max(0, Math.floor(ms / 1000))
222 const m = Math.floor(s / 60)
223 return m < 60 ? `${m}:${String(s % 60).padStart(2, '0')}` : `${Math.floor(m / 60)}h${String(m % 60).padStart(2, '0')}`
224}
225
226export const fmtClock = (ms: number) => (ms > 0 ? new Date(ms).toTimeString().slice(0, 8) : '--:--:--')
227
228/** `1 error`, `2 errors`. */
229export const plural = (n: number, word: string) => `${n} ${word}${n === 1 ? '' : 's'}`
230
231export const fmtUsd = (n: number) => (n >= 100 ? `$${Math.round(n)}` : `$${n.toFixed(2)}`)
232
233/** A gauge of `width` cells: ▰ filled, ▱ empty. */
234export const gauge = (pct: number, width: number) => {
235 const full = Math.max(0, Math.min(width, Math.round((pct / 100) * width)))
236 return { on: '▰'.repeat(full), off: '▱'.repeat(width - full) }
237}
238
239/** A rate-limit window's short name: `five_hour` → `5h`, `seven_day_opus` → `7d opus`. */
240export const limitLabel = (kind: string) =>
241 kind
242 .replace(/five[_ -]?hours?/i, '5h')
243 .replace(/seven[_ -]?days?/i, '7d')
244 .replace(/[_-]+/g, ' ')
245 .trim()
246
247// ---------------------------------------------------------------- redaction
248
249const SECRETS: [RegExp, string][] = [
250 [/(authorization\s*[:=]\s*)(bearer\s+|basic\s+)?\S+/gi, '$1$2•••'],
251 [/\b(bearer)\s+[A-Za-z0-9._~+/-]{8,}=*/gi, '$1 •••'],
252 [/\b(sk|pk|rk|ghp|gho|ghs|github_pat|xox[abprs])[-_][A-Za-z0-9_-]{8,}/g, '•••'],
253 [/((?:api[_-]?key|access[_-]?token|token|secret|password|passwd|pwd)\s*[=:]\s*)("[^"]*"|'[^']*'|\S+)/gi, '$1•••'],
254 [/(--(?:token|password|api-key|secret)[= ])\S+/gi, '$1•••'],
255 [/(\b[A-Z][A-Z0-9_]*(?:KEY|TOKEN|SECRET|PASSWORD)=)\S+/g, '$1•••'],
256 [/(\b[a-z][a-z0-9+.-]*:\/\/[^\s/:@]+:)[^\s@]+@/gi, '$1•••@'],
257]
258
259/** What the gate drill-down may store: credentials masked before anything is written to state. */
260export const redact = (s: string) => SECRETS.reduce((t, [re, to]) => t.replace(re, to), s)
261
262// ---------------------------------------------------------------- tools and gate
263
264const FILE_TOOLS = new Set(['Read', 'Edit', 'Write', 'NotebookEdit', 'Glob', 'Grep'])
265const SHELL_TOOLS = new Set(['Bash', 'PowerShell'])
266export const EDIT_TOOLS = new Set(['Edit', 'Write', 'NotebookEdit'])
267
268export const bucketOf = (tool: string): Bucket =>
269 FILE_TOOLS.has(tool) ? 'file' : SHELL_TOOLS.has(tool) ? 'shell' : 'other'
270
271/** One line saying what a call was about: its command, path or pattern; redacted. */
272export const describeInput = (tool: string, input: unknown) => {
273 const i = isObject(input) ? input : {}
274 const path = typeof i.file_path === 'string' ? i.file_path.split(/[\\/]/).slice(-2).join('/') : ''
275 const what =
276 typeof i.command === 'string'
277 ? i.command
278 : path || (typeof i.pattern === 'string' ? i.pattern : typeof i.url === 'string' ? i.url : typeof i.description === 'string' ? i.description : '')
279 return redact(what ? `${tool} → ${what}` : tool)
280}
281
282/** Keeps the last `max` checks, but never drops a pending ask: its settle must still find it. */
283export const trimRecent = (list: Check[], max: number): Check[] => {
284 let extra = list.length - max
285 if (extra <= 0) return list
286 const out: Check[] = []
287 for (const c of list) {
288 if (extra > 0 && c.verdict !== 'ask') {
289 extra -= 1
290 continue
291 }
292 out.push(c)
293 }
294 return out.slice(-max * 2)
295}
296
297export const recordCheck = (g: Gate, c: Check): Gate => {
298 const t = g.totals[c.bucket]
299 return {
300 recent: trimRecent([...g.recent, c], 80),
301 totals: { ...g.totals, [c.bucket]: { ...t, [c.verdict]: t[c.verdict] + 1 } },
302 }
303}
304
305/** An `ask` settled by the call that followed it: it ran (cleared) or was refused (deny). */
306export const settleCheck = (g: Gate, id: string, didRun: boolean): Gate => {
307 const c = g.recent.find(r => r.id === id && r.verdict === 'ask')
308 if (!c) return g
309 const verdict = didRun ? 'cleared' : 'deny'
310 const t = g.totals[c.bucket]
311 return {
312 recent: g.recent.map(r => (r === c ? { ...r, verdict } : r)),
313 totals: { ...g.totals, [c.bucket]: { ...t, ask: Math.max(0, t.ask - 1), [verdict]: t[verdict] + 1 } },
314 }
315}
316
317export const gateSummary = (g: Gate) => {
318 const all = (['file', 'shell', 'other'] as const).reduce(
319 (s, k) => ({
320 rule: s.rule + g.totals[k].rule,
321 ask: s.ask + g.totals[k].ask,
322 cleared: s.cleared + g.totals[k].cleared,
323 deny: s.deny + g.totals[k].deny,
324 }),
325 { ...ZERO },
326 )
327 return { ...all, total: all.rule + all.ask + all.cleared + all.deny }
328}
329
330// ---------------------------------------------------------------- turn and architect
331
332/**
333 * The turn after one tool call. Errors count in the main loop only (a subagent's failure is its
334 * own); edits count from every loop, so delegated work still reaches "before done".
335 */
336export const afterCall = (t: Turn, c: { inSubagent: boolean; hasFailed: boolean; isEdit: boolean }): Turn => ({
337 ...t,
338 errorStreak: c.inSubagent ? t.errorStreak : c.hasFailed ? t.errorStreak + 1 : 0,
339 errors: t.errors + (!c.inSubagent && c.hasFailed ? 1 : 0),
340 edits: t.edits + (c.isEdit ? 1 : 0),
341})
342
343/** Which of the architect's three moments a consult falls at: an inference over this turn so far. */
344export const momentOf = (t: Pick<Turn, 'edits' | 'errorStreak'>): Moment =>
345 t.errorStreak >= 2 ? 'error repeats' : t.edits === 0 ? 'before a plan' : 'before done'
346
347export const startConsult = (a: Architect, c: { id: string; at: number; moment: Moment; via: string }): Architect =>
348 a.consults.some(x => x.id === c.id) ? a : { ...a, consults: [...a.consults, { ...c, endAt: null }].slice(-40) }
349
350/** Ends the open consult (the latest without an end), or the one named. */
351export const endConsult = (a: Architect, at: number, advice: string | null, id?: string): Architect => {
352 const open = [...a.consults].reverse().find(c => c.endAt === null && (id === undefined || c.id === id))
353 return {
354 ...a,
355 consults: a.consults.map(c => (c === open ? { ...c, endAt: at } : c)),
356 lastAdvice: advice ?? a.lastAdvice,
357 }
358}
359
360export const isAdvising = (a: Architect) => a.consults.some(c => c.endAt === null)
361
362/** A one-row timeline of consults across `width` cells: ◆ a consult, ━ while it ran. */
363export const consultTimeline = (a: Architect, now: number, width: number) => {
364 if (a.consults.length === 0 || width < 4) return '─'.repeat(Math.max(0, width))
365 const first = a.consults[0]?.at ?? now
366 const span = Math.max(1, now - first)
367 const cells = Array.from({ length: width }, () => '─')
368 for (const c of a.consults) {
369 const from = Math.min(width - 1, Math.floor(((c.at - first) / span) * (width - 1)))
370 const to = Math.min(width - 1, Math.floor((((c.endAt ?? now) - first) / span) * (width - 1)))
371 for (let i = from + 1; i <= to; i += 1) cells[i] = '━'
372 cells[from] = '◆'
373 }
374 return cells.join('')
375}
376
377export const receiptOf = (t: Turn, o: { durationMs: number; agentsSince: number; costNow: number | null; reason: string }): Receipt => ({
378 durationMs: o.durationMs,
379 agents: o.agentsSince,
380 edits: t.edits,
381 errors: t.errors,
382 costDelta: o.costNow !== null && t.costAtStart !== null && o.costNow - t.costAtStart >= 0.005 ? o.costNow - t.costAtStart : null,
383 reason: o.reason,
384})
385
386// ---------------------------------------------------------------- agents and loops
387
388type StepUsage = { input_tokens?: number; cache_read_input_tokens?: number; cache_creation_input_tokens?: number; output_tokens?: number } | null
389
390/** A card after one of its model requests: its context is the latest step's whole input; output adds up. */
391export const applyStep = (c: AgentCard, s: { model: string; usage: StepUsage; stopReason: string | null }): AgentCard => {
392 const u = s.usage ?? {}
393 const ctx = (u.input_tokens ?? 0) + (u.cache_read_input_tokens ?? 0) + (u.cache_creation_input_tokens ?? 0)
394 return {
395 ...c,
396 model: c.model || s.model,
397 steps: c.steps + 1,
398 ctx: ctx > 0 ? ctx : c.ctx,
399 out: c.out + (u.output_tokens ?? 0),
400 lastStop: s.stopReason,
401 }
402}
403
404export const noteTool = (c: AgentCard, n: ToolNote): AgentCard => ({ ...c, tools: [...c.tools, n].slice(-3) })
405
406export const stepLoop = (loops: Loop[], id: string, at: number): Loop[] => {
407 const found = loops.find(l => l.id === id)
408 const next = found
409 ? loops.map(l => (l === found ? { ...l, steps: l.steps + 1, lastAt: at } : l))
410 : [...loops, { id, steps: 1, firstAt: at, lastAt: at, isDone: false }]
411 return next.slice(-60)
412}
413
414export const LOOP_ACTIVE_MS = 15_000
415export const isLoopActive = (l: Loop, now: number) => !l.isDone && now - l.lastAt < LOOP_ACTIVE_MS
416
417/** Swimlane geometry: each agent's bar on one shared axis from the first spawn to now. */
418export const lanes = (cards: AgentCard[], now: number, width: number) => {
419 const start = Math.min(...cards.map(c => c.spawnedAt).filter(n => n > 0), now)
420 const span = Math.max(1, now - start)
421 return cards.map(c => {
422 const from = Math.floor(((Math.max(c.spawnedAt, start) - start) / span) * width)
423 const to = Math.max(from + 1, Math.ceil((((c.endedAt ?? now) - start) / span) * width))
424 return { id: c.id, before: Math.min(from, width), bar: Math.min(to, width) - Math.min(from, width), after: width - Math.min(to, width) }
425 })
426}
427
428// ---------------------------------------------------------------- layout
429
430/** How many log lines fit: what the other panels leave, never fewer than 4 nor more than 8. */
431export const logRows = (bodyRows: number, used: number) => Math.max(4, Math.min(8, bodyRows - used - 3))
432
433/** Legend items that fit on one row of `width` cells, in order; the rest are dropped. */
434export const fitLegend = <T extends { label: string }>(items: T[], width: number) => {
435 const out: T[] = []
436 let used = 0
437 for (const it of items) {
438 const w = it.label.length + 4
439 if (used + w > width) break
440 out.push(it)
441 used += w
442 }
443 return out
444}
445
446/** A card's title row: the task in the agent's own words, the type only when there is none. */
447export const cardTitle = (c: AgentCard) => c.description || c.type
448
449/** A title split over two rows at a word boundary: `first` cells on row one, `rest` on row two. */
450export const titleLines = (title: string, first: number, rest: number): [string, string] => {
451 const t = title.replace(/\s+/g, ' ').trim()
452 if (t.length <= first) return [t, '']
453 const cut = t.lastIndexOf(' ', first)
454 const at = cut > 0 ? cut : first
455 return [t.slice(0, at).trim(), shorten(t.slice(at), rest)]
456}
457
458/**
459 * What a turn's opening text was, for the log: the person's words, or for a turn the engine
460 * opened with a tagged message (a subagent's hand-back, a task notification), that message's kind.
461 */
462export const promptLine = (text: string): { who: string; text: string } => {
463 const tag = /^\s*<([a-z][\w-]*)/i.exec(text)?.[1]
464 if (!tag) return { who: 'you', text: shorten(text, 70) }
465 const from = /\bfrom="([^"]+)"/.exec(text)?.[1]
466 return { who: 'engine', text: shorten(`${tag.replace(/[-_]/g, ' ')}${from ? ` from ${from.slice(0, 8)}` : ''}`, 70) }
467}
468
469/**
470 * A subagent's hand-back message: who sent it and the first line of what it said. The report
471 * follows a framing header in the message; without one, the first line after the opening tag.
472 */
473export const handbackOf = (text: string): { from: string; body: string } | null => {
474 const from = /^\s*<agent-message\s+from="([^"]+)"/.exec(text)?.[1]
475 if (!from) return null
476 const afterHeader = text.split(/The report follows:\s*\n/)[1]
477 const rest = afterHeader ?? text.replace(/^\s*<agent-message[^>]*>/, '')
478 const body =
479 rest
480 .split('\n')
481 .map(l => l.trim())
482 .find(l => l && !l.startsWith('[') && !l.startsWith('<') && !l.startsWith('</')) ?? ''
483 return body ? { from, body } : null
484}
485
486/** The advice line a pane shows for a report: its first real line, markdown markers stripped, cut to 160. */
487export const adviceLine = (report: string) => {
488 const first = report.split('\n').map(l => l.trim()).find(l => l && !l.startsWith('[') && !l.startsWith('<')) ?? ''
489 return shorten(first.replace(/\*\*|__/g, '').replace(/^[#>*\s-]+/, ''), 160)
490}
491
492export const elapsedOf = (c: AgentCard, now: number) => (c.endedAt ?? now) - c.spawnedAt
493hooks/pinboard.tsx 295 lines1// Pinboard, folded into Flightdeck: the session's todos, open decisions and the links Claude made.
2// Ported from sirkitree/pinboard (MIT, see LICENSE-pinboard); its own pane is gone, and the board
3// is drawn as a Flightdeck panel above the session log.
4import { atom, read, update } from 'claude-code'
5import type { ElementTable, EngineInterface, On, RenderChildren } from 'claude-code'
6
7import type { Decision, Pin, Todo } from '../types'
8import { gauge } from './core'
9import type { Colors } from './core'
10
11/** The tool as the model sees it: the engine prefixes a plugin's tools with `mcp__<plugin>__`. */
12export const TOOL = 'mcp__flightdeck__pinboard'
13
14const decisions = atom({ plugin: 'flightdeck', key: 'decisions' } as const, [] as Decision[])
15const todos = atom({ plugin: 'flightdeck', key: 'todos' } as const, [] as Todo[])
16const links = atom({ plugin: 'flightdeck', key: 'links' } as const, [] as Pin[])
17
18export const DESCRIPTION = [
19 "Keep the session's task list and open decisions on the user's Pinboard, a panel in the Flightdeck sidebar that stays in view while the transcript scrolls.",
20 'Any question you end a reply on that needs the user to answer goes in open_decisions, however small the task, even a single yes/no.',
21 'Use it in place of writing task lists or decision lists in your reply, whenever the work takes 2+ distinct steps or the user gives new instructions.',
22 'add_todos: one action per item. start_todo: the todo id you are working on now; exactly one is in progress at a time. done_todos / remove_todos: todo ids.',
23 'Update in real time; do not batch completions. Mark a todo done only after the work is actually done, including any verification it needs, never based on intent.',
24 'If blocked or partly done, leave it in progress and add a follow-up todo describing the blocker.',
25 'open_decisions: questions that need the user to choose. decide: close a decision by id once the user has answered.',
26 'The current board, with ids, is at the end of your system prompt.',
27 "It is session-only: work that must outlive the session goes to a durable tracker (kindex task_add) instead.",
28].join(' ')
29
30// Pinboard is the person's task tracker; this rides in the system prompt beside the board
31export const GUIDE = [
32 "Pinboard is the user's task tracker (a panel in the Flightdeck pane beside the transcript); keep it current instead of listing tasks in replies.",
33 `For any job with 2+ steps, add the todos with ${TOOL} before starting work (load it with ToolSearch first if it is deferred).`,
34 'start_todo as each one begins; done_todos as each one finishes, after verifying it.',
35 'Put questions that need the user in open_decisions.',
36 "Pinboard holds only this session's steps and questions (/clear empties it). Kindex task_add is for work that must outlive the session (follow-ups, deferred items), never for the steps of the current job.",
37].join('\n')
38
39const strings = { type: 'array', items: { type: 'string' } }
40export const SCHEMA = {
41 type: 'object',
42 properties: {
43 add_todos: strings,
44 start_todo: { type: 'string' },
45 done_todos: strings,
46 remove_todos: strings,
47 open_decisions: strings,
48 decide: {
49 type: 'array',
50 items: { type: 'object', properties: { id: { type: 'string' }, answer: { type: 'string' } }, required: ['id', 'answer'] },
51 },
52 },
53}
54
55export type Update = {
56 add_todos?: string[]
57 start_todo?: string
58 done_todos?: string[]
59 remove_todos?: string[]
60 open_decisions?: string[]
61 decide?: { id: string; answer: string }[]
62}
63
64export type Board = { todos: Todo[]; decisions: Decision[] }
65
66// The next id for a prefix: one past the highest in use
67const nextId = (prefix: string, ids: string[]) =>
68 prefix + (Math.max(0, ...ids.map(id => Number(id.slice(prefix.length)) || 0)) + 1)
69
70export function applyUpdate(board: Board, change: Update): Board {
71 let { todos: t, decisions: d } = board
72 for (const text of change.add_todos ?? []) t = [...t, { id: nextId('t', t.map(x => x.id)), text, isDone: false }]
73 for (const text of change.open_decisions ?? []) d = [...d, { id: nextId('d', d.map(x => x.id)), text }]
74 const done = new Set(change.done_todos ?? [])
75 const removed = new Set(change.remove_todos ?? [])
76 const decided = new Set((change.decide ?? []).map(x => x.id))
77 t = t.filter(x => !removed.has(x.id)).map(x => (done.has(x.id) ? { ...x, isDone: true } : x))
78 // One todo in progress at a time; finishing it ends its turn too
79 if (change.start_todo) t = t.map(x => ({ ...x, isActive: x.id === change.start_todo }))
80 t = t.map(x => (x.isDone && x.isActive ? { ...x, isActive: false } : x))
81 d = d.filter(x => !decided.has(x.id))
82 return { todos: t, decisions: d }
83}
84
85export function describeBoard(board: Board): string {
86 if (board.todos.length + board.decisions.length === 0) return 'Pinboard is empty.'
87 return [
88 'Pinboard now:',
89 ...board.todos.map(t => `${t.id} [${t.isDone ? 'x' : t.isActive ? '>' : ' '}] ${t.text}`),
90 ...board.decisions.map(d => `${d.id} [?] ${d.text}`),
91 ].join('\n')
92}
93
94// A reply asks the user something when one of its last lines, outside code, ends in a question mark
95export function asksUser(reply: string): boolean {
96 const prose = reply.replace(/```[\s\S]*?```/g, '')
97 const lines = prose.split('\n').map(l => l.trim()).filter(Boolean).slice(-3)
98 return lines.some(l => /\?[*_`)"'\]]*$/.test(l))
99}
100
101const NUDGE =
102 'Your reply ends on a question for the user, but the Pinboard has no open decision. ' +
103 `Call ${TOOL} with open_decisions for it (close it with decide once answered), then end your turn. ` +
104 'If it was rhetorical, end your turn as is.'
105
106const MAKES_COMMAND = /\bgh\s+(?:(?:pr|issue|release|repo|gist)\s+create|(?:pr|issue)\s+comment)\b|\bgit\s+push\b/
107const MAKES_MCP = /^mcp__.*(?:create|draft|send|publish|share|canvas|upload)/i
108
109const URL = /https:\/\/[A-Za-z0-9.-]+(?::\d+)?(?:\/[A-Za-z0-9\-._~:/?#[\]!$&'()*+,;=%@]*)?/g
110
111export const urlPins = (text: string): Pin[] =>
112 [...new Set([...text.matchAll(URL)].map(m => m[0].replace(/[)\].,;:'!?*]+$/, '')))]
113 .filter(href => !href.includes('@') && href.length <= 2048)
114 .map(href => {
115 const gh = /github\.com\/[^/]+\/([^/]+)\/(pull|issues)\/(\d+)/.exec(href)
116 return { href, label: gh ? `${gh[1]} ${gh[2] === 'pull' ? 'PR' : 'issue'} #${gh[3]}` : href.slice(8) }
117 })
118
119// ---------------------------------------------------------------- the panel
120
121export type Pinned = Board & { links: Pin[] }
122
123export async function readBoard($: EngineInterface): Promise<Pinned> {
124 const [d, t, l] = await Promise.all([read($, decisions), read($, todos), read($, links)])
125 // Todos parsed from replies by older Pinboards have no id; drop anything malformed
126 return { todos: (t ?? []).filter(x => typeof x?.id === 'string'), decisions: d ?? [], links: l ?? [] }
127}
128
129export const isBoardEmpty = (b: Pinned) => b.todos.length + b.decisions.length + b.links.length === 0
130
131/** Rows the panel takes, about: its border and header, then one per item (wrapping ignored). */
132export function boardRows(b: Pinned): number {
133 if (isBoardEmpty(b)) return 0
134 const open = b.todos.filter(t => !t.isDone).length
135 const done = b.todos.length - open
136 return 3 + open + (done > 0 ? 1 : 0) + b.decisions.length + (b.links.length > 0 ? 1 + b.links.length : 0)
137}
138
139/** The one-line form for Flightdeck's mini layout. */
140export function boardLine(b: Pinned): string {
141 const open = b.todos.filter(t => !t.isDone)
142 const active = open.find(t => t.isActive)
143 return [
144 `pinboard ${open.length} todo`,
145 `${b.decisions.length} decision${b.decisions.length === 1 ? '' : 's'}`,
146 ...(active ? [`▶ ${active.text}`] : []),
147 ].join(' · ')
148}
149
150export function boardPanel($: EngineInterface, els: ElementTable, C: Colors, b: Pinned, w: number) {
151 const { Box, Text, Button, Link } = els
152 // The text area: the width less the border and one cell of padding each side
153 const inner = w - 4
154 const done = b.todos.filter(t => t.isDone).length
155 const open = b.todos.length - done
156 const g = gauge(b.todos.length ? (done / b.todos.length) * 100 : 0, 8)
157
158 // The glyph stays in its own column, so wrapped lines indent under the text
159 const item = (glyph: RenderChildren, text: string, props: { color?: string; bold?: boolean } = {}) => (
160 <Box flexDirection="row" width={inner}>
161 <Box width={2} flexShrink={0}>
162 {glyph}
163 </Box>
164 <Box flexShrink={1} flexGrow={1}>
165 <Text {...props} wrap="wrap">
166 {text}
167 </Text>
168 </Box>
169 </Box>
170 )
171
172 return (
173 <Box flexDirection="column" borderStyle="round" borderColor={C.amber} paddingX={1} width={w}>
174 <Box justifyContent="space-between" width={inner}>
175 <Text color={C.amber} bold wrap="truncate">
176 {`pinboard · ${open} todo · ${b.decisions.length} ${b.decisions.length === 1 ? 'decision' : 'decisions'}`}
177 </Text>
178 {b.todos.length > 0 ? (
179 <Text>
180 <Text color={C.main}>{g.on}</Text>
181 <Text color={C.faint}>{g.off}</Text>
182 <Text dimColor>{` ${done}/${b.todos.length}`}</Text>
183 </Text>
184 ) : null}
185 </Box>
186 {b.todos
187 .filter(t => !t.isDone)
188 .map(t =>
189 t.isActive
190 ? item(<Text color={C.main} bold>{'▶ '}</Text>, t.text, { color: C.main, bold: true })
191 : item(<Text dimColor>{'○ '}</Text>, t.text),
192 )}
193 {/* Finished todos fold into one line so open work stays on top */}
194 {done > 0 ? (
195 <Text>
196 <Text color={C.gate}>{'✓ '}</Text>
197 <Text dimColor>{`${done} done`}</Text>
198 </Text>
199 ) : null}
200 {b.decisions.map(d => item(<Text color={C.amber} bold>{'? '}</Text>, d.text))}
201 {b.links.length > 0 ? (
202 <Box columnGap={1}>
203 <Text dimColor>{`links ${b.links.length}`}</Text>
204 <Button key="clear-links" label="clear" hotkey="l" plain dimColor onPress={() => update($, links, () => [])} />
205 </Box>
206 ) : null}
207 {b.links.map(p => (
208 <Text wrap="truncate-middle">
209 <Link href={p.href} label={p.label} />
210 </Text>
211 ))}
212 </Box>
213 )
214}
215
216// ---------------------------------------------------------------- hooks
217
218// Flightdeck's own session.start, session.end and tool.call hooks call these: a module hooks an
219// event once without a matcher.
220
221export async function startPinboard($: EngineInterface) {
222 await $.tool.register({ name: 'pinboard', description: DESCRIPTION, inputSchema: SCHEMA })
223}
224
225/** /clear empties the board, as the guide promises. */
226export async function clearBoard($: EngineInterface) {
227 await update($, todos, () => [])
228 await update($, decisions, () => [])
229 await update($, links, () => [])
230}
231
232type CallInput = { tool: string; command?: unknown; agentId?: string }
233type CallResult = { deny?: string; isError?: boolean; text?: string }
234
235/** Links only from actions that make something; reads, fetches and test output just mention URLs. */
236export async function captureLinks($: EngineInterface, e: CallInput, ran: CallResult) {
237 const makes = e.tool === 'Bash' ? MAKES_COMMAND.test(String(e.command ?? '')) : MAKES_MCP.test(e.tool)
238 if (e.agentId || !makes || ran.deny !== undefined || ran.isError || typeof ran.text !== 'string') return
239 const found = urlPins(ran.text)
240 if (found.length > 0 && found.length <= 3) {
241 await update($, links, old => [...found, ...old.filter(p => !found.some(f => f.href === p.href))].slice(0, 12))
242 }
243}
244
245export function registerPinboard(on: On) {
246
247 // The board rides at the end of the system prompt, so it never has to be repeated in replies
248 on('prompt.compose', async ($, e, next) => {
249 const { sections } = await next(e)
250 const b = await readBoard($)
251 return {
252 sections: [
253 ...sections,
254 { id: 'flightdeck:pinboard-guide', text: GUIDE, scope: 'session' },
255 { id: 'flightdeck:pinboard-board', text: describeBoard(b), scope: 'session' },
256 ],
257 }
258 })
259
260 on('tool.call', { tool: TOOL }, async ($, e) => {
261 if (e.agentId) return { deny: 'Only the main conversation updates the Pinboard.' }
262 const b = applyUpdate(await readBoard($), e as Update)
263 await update($, todos, () => b.todos)
264 await update($, decisions, () => b.decisions)
265 return { result: describeBoard(b) }
266 })
267
268 // A question left only in the reply scrolls away; send Claude back once to pin it
269 on('classic.Stop', async ($, e, next) => {
270 const ran = await next(e)
271 if (ran.block || e.stop_hook_active || !asksUser(e.last_assistant_message ?? '')) return ran
272 if ((await read($, decisions)).length > 0) return ran
273 return { ...ran, block: NUDGE }
274 })
275
276 // An update is one dim line in the transcript; the board itself is in the pane
277 on('ui.render', { component: 'ToolUse', props: { tool: TOOL } }, async ($, e) => {
278 const { Text } = $.ui.resolve(e)
279 const change = (e.props.input ?? {}) as Update
280 const parts = [
281 change.add_todos?.length && `+${change.add_todos.length} todo`,
282 change.start_todo && `started ${change.start_todo}`,
283 change.done_todos?.length && `${change.done_todos.length} done`,
284 change.remove_todos?.length && `-${change.remove_todos.length} todo`,
285 change.open_decisions?.length && `+${change.open_decisions.length} decision`,
286 change.decide?.length && `${change.decide.length} decided`,
287 ].filter(Boolean)
288 return <Text dimColor>{'Pinboard: ' + (parts.join(', ') || 'no change')}</Text>
289 })
290
291 on('ui.render', { component: 'ToolResult', props: { tool: TOOL } }, async ($, e, next) =>
292 e.props.isErrored ? next(e) : $.ui.resolve(e).Text({ children: [''] }),
293 )
294}
295hooks/rail.tsx 75 lines1// A connector drawn on the surface's own frame clock: packets travel along it while `active`,
2// and it rests as a plain dim line otherwise. Only this region redraws; the pane does not.
3import type { ClientModule } from 'claude-code'
4
5type Props = {
6 active: boolean
7 width: number
8 color: string
9 dim: string
10 /** Cells where a branch drops (┬); the rest of the line is ─. */
11 marks: number[]
12 /** Draw ┴ instead of ┬ at the marks: a merge into what is below. */
13 isMerge: boolean
14}
15
16type Ref = { phase: number; active: boolean }
17type State = { ref: Ref }
18
19const STEP_MS = 110
20
21const Rail: ClientModule<Props, State> = (props, surface) => {
22 const { Box, Text } = surface.elements
23 const ref = surface.state?.ref ?? { phase: 0, active: props.active }
24 ref.active = props.active
25 if (surface.state === undefined) {
26 surface.setState({ ref })
27 surface.every(STEP_MS, () => {
28 if (ref.active) {
29 ref.phase += 1
30 surface.setState({ ref })
31 }
32 })
33 }
34
35 const width = Math.max(1, surface.columns || props.width)
36 const cells = Array.from({ length: width }, () => '─')
37 for (const m of props.marks) if (m >= 0 && m < width) cells[m] = props.isMerge ? '┴' : '┬'
38
39 if (!props.active) {
40 return (
41 <Box>
42 <Text color={props.dim}>{cells.join('')}</Text>
43 </Box>
44 )
45 }
46
47 // Two packets per 24 cells, a bright head and a trailing dot, moving left to right.
48 const lit = new Map<number, string>()
49 for (let base = 0; base < width + 24; base += 24) {
50 const head = (base + ref.phase) % (width + 24)
51 if (head < width) lit.set(head, '●')
52 if (head - 1 >= 0 && head - 1 < width) lit.set(head - 1, '•')
53 }
54 // Runs, not cells: consecutive cells of one kind share a Text, a handful of nodes per frame.
55 const runs: { text: string; isLit: boolean }[] = []
56 cells.forEach((ch, i) => {
57 const isLit = lit.has(i)
58 const last = runs[runs.length - 1]
59 const glyph = lit.get(i) ?? ch
60 if (last && last.isLit === isLit) last.text += glyph
61 else runs.push({ text: glyph, isLit })
62 })
63 return (
64 <Box>
65 {runs.map(r => (
66 <Text color={r.isLit ? props.color : props.dim} bold={r.isLit}>
67 {r.text}
68 </Text>
69 ))}
70 </Box>
71 )
72}
73
74export default Rail
75hooks/elapsed.tsx 38 lines1// A running agent's clock, ticking on the surface's frame clock so the pane need not redraw.
2// `since` and `now` come from the hooks module's $.clock; between redraws it adds its own ticks.
3import type { ClientModule } from 'claude-code'
4
5type Props = { since: number; now: number; endAt: number | null; color: string }
6type Ref = { base: number; ticks: number; lastNow: number; isRunning: boolean }
7type State = { ref: Ref }
8
9const fmt = (ms: number) => {
10 const s = Math.max(0, Math.floor(ms / 1000))
11 const m = Math.floor(s / 60)
12 return m < 60 ? `${m}:${String(s % 60).padStart(2, '0')}` : `${Math.floor(m / 60)}h${String(m % 60).padStart(2, '0')}`
13}
14
15const Elapsed: ClientModule<Props, State> = (props, surface) => {
16 const { Text } = surface.elements
17 const ref = surface.state?.ref ?? { base: 0, ticks: 0, lastNow: -1, isRunning: true }
18 if (props.now !== ref.lastNow) {
19 // A fresh reading from the hooks module: restart the local count from it.
20 ref.lastNow = props.now
21 ref.base = (props.endAt ?? props.now) - props.since
22 ref.ticks = 0
23 }
24 ref.isRunning = props.endAt === null
25 if (surface.state === undefined) {
26 surface.setState({ ref })
27 surface.every(1000, () => {
28 if (ref.isRunning) {
29 ref.ticks += 1
30 surface.setState({ ref })
31 }
32 })
33 }
34 return <Text color={props.color}>{fmt(ref.base + ref.ticks * 1000)}</Text>
35}
36
37export default Elapsed
38types/index.d.ts 126 lines1export type Moment = 'before a plan' | 'error repeats' | 'before done'
2
3export type Bucket = 'file' | 'shell' | 'other'
4
5/** rule: settings allowed it. ask: put to the decider, outcome pending. cleared: asked, then ran. deny: refused. */
6export type Verdict = 'rule' | 'ask' | 'cleared' | 'deny'
7
8export type Main = { model: string; effort: string; mode: string; steps: number; isRunning: boolean }
9
10export type Usage = {
11 pct: number | null
12 tokens: number | null
13 window: number
14 costUsd: number | null
15 limits: { kind: string; pct: number }[]
16 compactions: number
17 lastCompactAt: number | null
18}
19
20export type Consult = { id: string; at: number; endAt: number | null; moment: Moment; via: string }
21
22export type Architect = { consults: Consult[]; ids: string[]; seen: string[]; lastAdvice: string }
23
24export type Check = {
25 id: string
26 tool: string
27 bucket: Bucket
28 verdict: Verdict
29 inSubagent: boolean
30 detail: string
31 at: number
32}
33
34export type Tally = { rule: number; ask: number; cleared: number; deny: number }
35
36export type Gate = { recent: Check[]; totals: Record<Bucket, Tally> }
37
38export type ToolNote = { tool: string; text: string; isError: boolean }
39
40export type AgentCard = {
41 id: string
42 type: string
43 model: string
44 description: string
45 status: string
46 spawnedAt: number
47 endedAt: number | null
48 /** The agent's context now: input + cache read + cache write of its latest step. */
49 ctx: number
50 /** Output tokens summed over its steps. */
51 out: number
52 steps: number
53 lastStop: string | null
54 tools: ToolNote[]
55 answer: string
56}
57
58/** A model loop whose id matches no card: a workflow agent, a compaction or a memory fork. */
59export type Loop = { id: string; steps: number; firstAt: number; lastAt: number; isDone: boolean }
60
61export type LogLine = {
62 at: number
63 who: string
64 text: string
65 agentId: string | null
66 kind: 'info' | 'error' | 'consult' | 'done'
67}
68
69export type Turn = {
70 edits: number
71 errorStreak: number
72 errors: number
73 isReviewing: boolean
74 startedAt: number
75 costAtStart: number | null
76}
77
78export type Receipt = {
79 durationMs: number
80 agents: number
81 edits: number
82 errors: number
83 costDelta: number | null
84 reason: string
85}
86
87export type Layout = 'auto' | 'compact' | 'wide' | 'mini'
88
89export type View = { expanded: string | null; gateOpen: Bucket | null; layout: Layout | null }
90
91export type Roster = { architectTypes: string[] }
92
93/** A Pinboard todo: one action, done or not, at most one in progress. */
94export type Todo = { id: string; text: string; isDone: boolean; isActive?: boolean }
95
96/** A Pinboard question that waits on the user. */
97export type Decision = { id: string; text: string }
98
99/** A link Claude made (a PR, an issue, a published page). */
100export type Pin = { href: string; label: string }
101
102declare module 'claude-code' {
103 interface PluginState {
104 'flightdeck': {
105 meta: { schemaVersion: number }
106 main: Main
107 usage: Usage
108 architect: Architect
109 gate: Gate
110 agents: AgentCard[]
111 loops: Loop[]
112 log: LogLine[]
113 turn: Turn
114 receipt: Receipt | null
115 view: View
116 roster: Roster
117 /** Whether the pane is open; Mod Tools reads it for its Show column. */
118 paneOpen: boolean
119 /** Pinboard: the session's todos, open decisions and created links. */
120 todos: Todo[]
121 decisions: Decision[]
122 links: Pin[]
123 }
124 }
125}
126