Pane of open questions, items Claude left undone, and a cross-session scratch pad; answer, dismiss or fire off each one.

A Claude Code mod: one pane with a context gauge and handoff-and-clear, a live list of subagents, each with the macro steps its assignment asks for (planned once at spawn, ticked off as it works; running rows open, finished rows fold to a progress line), open questions pulled from each reply (this session only; a question clears itself once you answer it, through ✎ or in your own words), items left undone (with "do it" buttons), and a scratch pad of notes. Undone items and notes belong to the project directory and are kept across sessions and injected into the system prompt. The status line shows the counts only while the pane is off screen.
/plugin install agenda --marketplace djbrandl/claude-mods
Answer y to add the marketplace, pick the user scope. Then /agenda opens the pane, /note <text> adds a note, /handoff writes a handoff and clears.
Running subagents are listed live. One that has finished, or gone idle waiting for a message, folds to a single line, and at most four finished rows are kept. ✕ finished on the AGENTS heading clears them; a cleared agent reappears only if it is woken again. /clear starts the next session with an empty list.
When the pane holds more than fits, a scrollbar runs down its right edge. Scroll with the mouse wheel over the pane, or give it the keyboard (ctrl+x tab, or click it) and use the arrows, Page Up/Down, Home and End.
The installer asks for a Summary model. The pane runs a small background Claude call after each reply to pull out open questions and unfinished work, and to write the one-line subagent summaries. This setting picks which Claude does that chore. haiku (the default) is cheap, fast and enough; it has no effect on which model answers you in the main chat. Change it with /plugin configure agenda only if the one-liners read badly.
The first run writes ~/.claude/agenda.theme.json with the defaults. Edit it (colours as hex or terminal colour names, any text for glyphs and labels, the two context-gauge thresholds), then run /agenda to reload. Plugin updates replace the plugin, never that file, so your styling survives every update. Leave a key out to keep its default; delete the file to start over. The path is a plugin setting (themeFile) if you want it elsewhere.
claude --plugin-dir <this folder>
claude plugin validate .
claude plugin test .hooks/register.tsx 983 lines1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, Register } from 'claude-code'
3
4import type { AgendaItem, AgentRow, ContextGauge, Handoff, PlanStep, Theme } from '../types'
5import { DEFAULT_THEME, THEME_DOC, legend, mergeTheme } from './theme'
6
7const PANE = 'agenda'
8const TITLE = 'Agenda'
9const LEGACY_STORE_KEY = 'agenda:v1'
10const STORE_PREFIX = 'agenda:v2:'
11const MAX_PER_LIST = 60
12const MAX_DONE_AGENTS = 4
13const MAX_PLAN_STEPS = 8
14const SUMMARIZE_AFTER_TOOLS = 4
15
16// Looks come from the theme file (see hooks/theme.ts); T mirrors the state atom for the helpers.
17let T: Theme = DEFAULT_THEME
18
19const questions = atom({ plugin: 'agenda', key: 'questions' } as const, [])
20const undone = atom({ plugin: 'agenda', key: 'undone' } as const, [])
21const notes = atom({ plugin: 'agenda', key: 'notes' } as const, [])
22const agents = atom({ plugin: 'agenda', key: 'agents' } as const, [])
23// Agents whose row the person flipped from its default: running rows open, finished rows folded.
24const toggledAgents = atom({ plugin: 'agenda', key: 'toggledAgents' } as const, [])
25// Finished agents the person cleared; the engine keeps listing them, so they stay hidden unless they wake.
26const dismissedAgents = atom({ plugin: 'agenda', key: 'dismissedAgents' } as const, [])
27const context = atom({ plugin: 'agenda', key: 'context' } as const, null)
28const handoff = atom({ plugin: 'agenda', key: 'handoff' } as const, null)
29const scanning = atom({ plugin: 'agenda', key: 'scanning' } as const, false)
30const handingOff = atom({ plugin: 'agenda', key: 'handingOff' } as const, false)
31const theme = atom({ plugin: 'agenda', key: 'theme' } as const, DEFAULT_THEME)
32
33// Questions are the session's alone and live in $.state only. Undone, notes and the pending handoff
34// belong to the project directory and are stored under its path.
35type Stored = { undone: AgendaItem[]; notes: AgendaItem[]; handoff: Handoff | null }
36type ListName = 'questions' | 'undone' | 'notes'
37
38const EXTRACT_SYSTEM = `You read one reply from a coding assistant to its user, together with the user's request it answers, the open questions already recorded, and the list of unfinished items already recorded. You answer with four lists.
39
40"questions": every NEW question or decision the assistant is asking the USER to answer or decide, that the user still needs to respond to. Include requests for a choice, confirmation, missing information or a go/no-go. Exclude rhetorical questions, questions the assistant answered itself, questions directed at nobody, and anything already in the recorded open questions.
41
42"answered": the ids from the recorded open questions that the user's request answers or decides, or that this reply shows are settled, withdrawn, or no longer relevant. A user who tells the assistant what to do about a question has answered it even without using the word.
43
44"undone": ONLY work the user asked for that the assistant explicitly did not finish. A part of the request it dropped or skipped, a step it said it would do next but did not, a failing check it left broken. Most replies have ZERO undone items. Exclude all of these: caveats about what it could not verify from where it sits ("not verified live", "needs a real run", "tell me what you see"); optional suggestions, ideas, offers or follow-ups; work that waits on the user's decision (that is a question); explanations of how something works; anything that is already in the recorded list.
45
46"resolved": the ids from the recorded list that this reply shows are now finished, superseded, or no longer apply.
47
48Write each new item as one short self-contained sentence (max 160 characters) that makes sense without the reply. Do not invent items. Reply with JSON only, no prose, no code fence:
49{"questions":["..."],"answered":["id"],"undone":["..."],"resolved":["id"]}
50Empty lists are fine and usual.`
51
52const PLAN_SYSTEM = `You are given the assignment a coding subagent was just handed. List the macro steps it will have to carry out to finish: the outcomes a manager would track, not individual file reads or commands. Between 2 and 6 steps, in the order they will likely happen, each a short phrase of at most 60 characters in plain language, no tool names or paths unless they are the point. Reply with JSON only, no prose, no code fence:
53{"steps":["..."]}`
54
55const PROGRESS_SYSTEM = `You watch a coding subagent work against a numbered plan. You are given its assignment, the plan (number, state, step), and its latest activity (what it said and which tools it used, with the key argument of each). Decide what the activity shows: which steps are now finished, and which single step it is working on now. Add a new step ONLY if the agent is clearly doing substantial work that no planned step covers; phrase it like the others, max 60 characters. Reply with JSON only, no prose, no code fence:
56{"done":[1],"doing":2,"added":["..."]}
57"doing" is a step number or null; a step number may be from the plan or count on from the end for an added step.`
58
59const HANDOFF_PROMPT = `Write a handoff for a fresh session that will continue this work with none of this conversation. Plain Markdown, under 60 lines, no preamble. Sections, in this order:
60# Handoff
61## Goal
62What the user is trying to achieve, in their words where possible.
63## State
64What is done and verified, what is built but unverified, what is broken.
65## Decisions
66Choices the user made or confirmed, each with the reason, so they are not re-litigated.
67## Open questions
68Questions the user has not answered yet.
69## Left undone
70Work named but not finished, one line each.
71## Next step
72The single next action to take.
73## Files
74Paths touched or that the next session must read first.`
75
76function newId(): string {
77 return `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`
78}
79
80function norm(text: string): string {
81 return text.toLowerCase().replace(/[^a-z0-9 ]+/g, ' ').replace(/\s+/g, ' ').trim()
82}
83
84function merge(list: AgendaItem[], texts: string[], at: string): AgendaItem[] {
85 const seen = new Set(list.map(one => norm(one.text)))
86 const added: AgendaItem[] = []
87 for (const text of texts) {
88 const clean = text.trim()
89 if (!clean || seen.has(norm(clean))) continue
90 seen.add(norm(clean))
91 added.push({ id: newId(), text: clean, at })
92 }
93 return [...list, ...added].slice(-MAX_PER_LIST)
94}
95
96type Extracted = { questions: string[]; answered: string[]; undone: string[]; resolved: string[] }
97
98function parseExtract(text: string): Extracted {
99 const none: Extracted = { questions: [], answered: [], undone: [], resolved: [] }
100 const start = text.indexOf('{')
101 const end = text.lastIndexOf('}')
102 if (start < 0 || end <= start) return none
103 try {
104 const parsed = JSON.parse(text.slice(start, end + 1)) as Partial<Record<keyof Extracted, unknown>>
105 const strings = (value: unknown): string[] =>
106 Array.isArray(value) ? value.filter((one): one is string => typeof one === 'string') : []
107 return {
108 questions: strings(parsed.questions),
109 answered: strings(parsed.answered),
110 undone: strings(parsed.undone),
111 resolved: strings(parsed.resolved),
112 }
113 } catch {
114 return none
115 }
116}
117
118function asList(value: unknown): AgendaItem[] {
119 return Array.isArray(value)
120 ? value.filter(
121 (one): one is AgendaItem =>
122 typeof one === 'object' && one !== null && typeof (one as AgendaItem).text === 'string',
123 )
124 : []
125}
126
127let projectKey = ''
128
129async function projectStoreKey($: EngineInterface): Promise<string> {
130 if (!projectKey) {
131 const cwd = (await $.session.cwd()).replace(/[\/]+$/, '').toLowerCase()
132 projectKey = STORE_PREFIX + cwd
133 }
134 return projectKey
135}
136
137async function load($: EngineInterface): Promise<void> {
138 const key = await projectStoreKey($)
139 let raw = (await $.store.get(key)) as Partial<Stored> | undefined
140 if (!raw) {
141 // One-time migration of the pre-project store: its items were made in this project.
142 const legacy = (await $.store.get(LEGACY_STORE_KEY)) as Partial<Stored> | undefined
143 if (legacy) {
144 raw = legacy
145 await $.store.set(key, { undone: asList(legacy.undone), notes: asList(legacy.notes), handoff: legacy.handoff ?? null })
146 await $.store.delete(LEGACY_STORE_KEY)
147 }
148 }
149 await update($, questions, () => [])
150 await update($, undone, () => asList(raw?.undone))
151 await update($, notes, () => asList(raw?.notes))
152 const h = raw?.handoff
153 await update($, handoff, () => (h && typeof h.text === 'string' ? { text: h.text, at: String(h.at ?? '') } : null))
154}
155
156async function persist($: EngineInterface): Promise<void> {
157 const stored: Stored = {
158 undone: await read($, undone),
159 notes: await read($, notes),
160 handoff: await read($, handoff),
161 }
162 await $.store.set(await projectStoreKey($), stored)
163 await refreshStatus($)
164}
165
166// The status line carries the counts only while the pane is not on screen.
167async function refreshStatus($: EngineInterface): Promise<void> {
168 const panes = await $.ui.panes()
169 const mine = panes.find(one => one.id === PANE)
170 if (mine && mine.isPlaced && mine.isShown) {
171 $.ui.status(undefined)
172 return
173 }
174 const q = (await read($, questions)).length
175 const u = (await read($, undone)).length
176 $.ui.status(q + u === 0 ? undefined : `agenda: ${q} open question${q === 1 ? '' : 's'} · ${u} undone`)
177}
178
179async function setList($: EngineInterface, which: ListName, fn: (list: AgendaItem[]) => AgendaItem[]): Promise<void> {
180 if (which === 'questions') await update($, questions, fn)
181 else if (which === 'undone') await update($, undone, fn)
182 else await update($, notes, fn)
183 await persist($)
184}
185
186async function refreshContext($: EngineInterface): Promise<void> {
187 const usage = await $.session.usage()
188 const tokens = usage.context.tokens ?? 0
189 const window = usage.context.window
190 const gauge: ContextGauge = {
191 tokens,
192 window,
193 percent: usage.context.percent ?? (window ? Math.round((tokens / window) * 100) : 0),
194 usd: usage.cost?.usd ?? 0,
195 }
196 await update($, context, () => gauge)
197}
198
199async function refreshAgents($: EngineInterface): Promise<void> {
200 const [live, dismissed] = await Promise.all([$.agent.list(), read($, dismissedAgents)])
201 const now = Date.now()
202 const woke: string[] = []
203 await update($, agents, list => {
204 const byId = new Map(list.map(one => [one.id, one]))
205 for (const info of live) {
206 const prev = byId.get(info.id)
207 // An idle agent has finished its turn and waits for a message that may never come: it counts as done.
208 const isOver = info.status === 'completed' || info.status === 'failed' || info.status === 'killed' || info.status === 'idle'
209 if (dismissed.includes(info.id)) {
210 if (isOver) continue
211 woke.push(info.id)
212 }
213 byId.set(info.id, {
214 id: info.id,
215 description: info.description || prev?.description || info.type,
216 type: info.type,
217 status: info.status,
218 startedAt: prev?.startedAt ?? now,
219 endedAt: isOver ? (prev?.endedAt ?? now) : undefined,
220 plan: isOver && prev ? finishPlan(prev.plan, info.status === 'completed' || info.status === 'idle') : (prev?.plan ?? []),
221 })
222 }
223 const rows = [...byId.values()]
224 const active = rows.filter(one => one.endedAt === undefined)
225 const done = rows
226 .filter(one => one.endedAt !== undefined)
227 .sort((a, b) => (b.endedAt ?? 0) - (a.endedAt ?? 0))
228 .slice(0, MAX_DONE_AGENTS)
229 return [...active, ...done]
230 })
231 if (woke.length > 0) await update($, dismissedAgents, list => list.filter(id => !woke.includes(id)))
232}
233
234// Drops every finished row and keeps it hidden from later refreshes.
235async function clearFinishedAgents($: EngineInterface): Promise<void> {
236 const rows = await read($, agents)
237 const finished = rows.filter(one => one.endedAt !== undefined).map(one => one.id)
238 if (finished.length === 0) return
239 await update($, dismissedAgents, list => [...new Set([...list, ...finished])])
240 await update($, agents, list => list.filter(one => one.endedAt === undefined))
241}
242
243let lastPrompt = ''
244
245// The question the ✎ button put into the prompt box; cleared from the list when that prompt is sent.
246const ANSWER_PREFIX = 'Answering your earlier question '
247let pendingAnswer: AgendaItem | null = null
248
249// The pane's own estimate of its tree's height at the last draw, and how far the engine's count differed.
250let lastEstimate = 0
251let rowCorrection = 0
252
253async function scanAnswer($: EngineInterface, answer: string, model: string): Promise<void> {
254 await update($, scanning, () => true)
255 try {
256 const recorded = await read($, undone)
257 const open = await read($, questions)
258 const prompt = [
259 `User's request:\n${lastPrompt.trim().slice(0, 4000) || '(not captured)'}`,
260 open.length
261 ? `Recorded open questions (id: text):\n${open.map(one => `${one.id}: ${one.text}`).join('\n')}`
262 : 'Recorded open questions: none',
263 recorded.length
264 ? `Recorded unfinished items (id: text):\n${recorded.map(one => `${one.id}: ${one.text}`).join('\n')}`
265 : 'Recorded unfinished items: none',
266 `Assistant's reply:\n${answer.slice(0, 20000)}`,
267 ].join('\n\n')
268 const reply = await $.model.complete({ model, system: EXTRACT_SYSTEM, prompt, effort: 'low', maxTokens: 800, timeoutMs: 30000 })
269 if (!reply.isAnswered) return
270 const found = parseExtract(reply.text)
271 const answered = new Set(found.answered.filter(id => open.some(one => one.id === id)))
272 const resolved = new Set(found.resolved.filter(id => recorded.some(one => one.id === id)))
273 if (found.questions.length === 0 && found.undone.length === 0 && answered.size === 0 && resolved.size === 0) return
274 const at = new Date().toISOString()
275 await update($, questions, list => merge(list.filter(one => !answered.has(one.id)), found.questions, at))
276 await update($, undone, list => merge(list.filter(one => !resolved.has(one.id)), found.undone, at))
277 await persist($)
278 const parts: string[] = []
279 if (found.questions.length) parts.push(`${found.questions.length} open question${found.questions.length === 1 ? '' : 's'}`)
280 if (answered.size) parts.push(`${answered.size} answered`)
281 if (found.undone.length) parts.push(`${found.undone.length} undone`)
282 if (resolved.size) parts.push(`${resolved.size} resolved`)
283 $.ui.toast(`Agenda: ${parts.join(', ')}`)
284 } finally {
285 await update($, scanning, () => false)
286 }
287}
288
289type Activity = { lines: string[]; tools: number; inFlight: Promise<void> | null }
290const activity = new Map<string, Activity>()
291
292function keyArg(input: unknown): string {
293 if (typeof input !== 'object' || input === null) return ''
294 const o = input as Record<string, unknown>
295 for (const k of ['description', 'file_path', 'path', 'command', 'pattern', 'query', 'url', 'prompt', 'skill']) {
296 const v = o[k]
297 if (typeof v === 'string' && v.trim()) return v.replace(/\s+/g, ' ').slice(0, 120)
298 }
299 return ''
300}
301
302function noteActivity(agentId: string, blocks: readonly { type: string; [field: string]: unknown }[]): { isDue: boolean } {
303 const buf = activity.get(agentId) ?? { lines: [], tools: 0, inFlight: null }
304 activity.set(agentId, buf)
305 let hasNarration = false
306 for (const block of blocks) {
307 if (block.type === 'text' && typeof block.text === 'string') {
308 const text = block.text.replace(/\s+/g, ' ').trim()
309 if (text.length >= 20) {
310 buf.lines.push(`said: ${text.slice(0, 300)}`)
311 if (text.length >= 60) hasNarration = true
312 }
313 } else if (block.type === 'tool_use' && typeof block.name === 'string') {
314 const arg = keyArg(block.input)
315 buf.lines.push(arg ? `${block.name}: ${arg}` : block.name)
316 buf.tools += 1
317 }
318 }
319 return { isDue: hasNarration || buf.tools >= SUMMARIZE_AFTER_TOOLS }
320}
321
322function parseJson(text: string): Record<string, unknown> | null {
323 const start = text.indexOf('{')
324 const end = text.lastIndexOf('}')
325 if (start < 0 || end <= start) return null
326 try {
327 const parsed: unknown = JSON.parse(text.slice(start, end + 1))
328 return typeof parsed === 'object' && parsed !== null ? (parsed as Record<string, unknown>) : null
329 } catch {
330 return null
331 }
332}
333
334function stepTexts(value: unknown): string[] {
335 return Array.isArray(value)
336 ? value
337 .filter((one): one is string => typeof one === 'string')
338 .map(one => one.replace(/\s+/g, ' ').trim().replace(/^[-*\d.)\s]+/, ''))
339 .filter(one => one.length > 0)
340 .map(one => one.slice(0, 80))
341 : []
342}
343
344// The agent is over: whatever it was on is done when it completed, otherwise left where it stood.
345function finishPlan(plan: PlanStep[], isCompleted: boolean): PlanStep[] {
346 if (!isCompleted) return plan
347 return plan.map(step => (step.state === 'doing' ? { ...step, state: 'done' } : step))
348}
349
350// Called once per spawn with the assignment the subagent was handed.
351async function planAgent($: EngineInterface, agentId: string, description: string, assignment: string, model: string): Promise<void> {
352 const reply = await $.model.complete({
353 model,
354 system: PLAN_SYSTEM,
355 prompt: `Description: ${description}\n\nAssignment:\n${assignment.slice(0, 12000)}`,
356 effort: 'low',
357 maxTokens: 300,
358 timeoutMs: 20000,
359 })
360 if (!reply.isAnswered) return
361 const steps = stepTexts(parseJson(reply.text)?.steps).slice(0, MAX_PLAN_STEPS)
362 if (steps.length === 0) return
363 await update($, agents, list =>
364 list.map(one => {
365 if (one.id !== agentId) return one
366 // Progress may already have added steps; the plan goes in front of them.
367 const known = new Set(steps.map(norm))
368 const extra = one.plan.filter(step => !known.has(norm(step.text)))
369 const planned: PlanStep[] = steps.map(text => ({ text, state: one.plan.find(step => norm(step.text) === norm(text))?.state ?? 'todo' }))
370 return { ...one, plan: [...planned, ...extra].slice(0, MAX_PLAN_STEPS) }
371 }),
372 )
373}
374
375async function summarizeActivity($: EngineInterface, agentId: string, model: string): Promise<void> {
376 const buf = activity.get(agentId)
377 if (!buf || buf.lines.length === 0 || buf.inFlight) return
378 const lines = buf.lines.splice(0, buf.lines.length)
379 buf.tools = 0
380 const run = (async () => {
381 const row = (await read($, agents)).find(one => one.id === agentId)
382 const plan = row?.plan ?? []
383 const prompt = [
384 `Assignment: ${row?.description ?? agentId}`,
385 plan.length ? `Plan:\n${plan.map((step, i) => `${i + 1}. [${step.state}] ${step.text}`).join('\n')}` : 'Plan: none yet',
386 `Latest activity:\n${lines.map(one => `- ${one}`).join('\n')}`,
387 ].join('\n\n')
388 const reply = await $.model.complete({ model, system: PROGRESS_SYSTEM, prompt: prompt.slice(0, 12000), effort: 'low', maxTokens: 200, timeoutMs: 20000 })
389 if (!reply.isAnswered) return
390 const parsed = parseJson(reply.text)
391 if (!parsed) return
392 const done = new Set(Array.isArray(parsed.done) ? parsed.done.filter((one): one is number => Number.isInteger(one)) : [])
393 const doing = Number.isInteger(parsed.doing) ? (parsed.doing as number) : null
394 const added = stepTexts(parsed.added)
395 await update($, agents, list =>
396 list.map(one => {
397 if (one.id !== agentId) return one
398 const have = new Set(one.plan.map(step => norm(step.text)))
399 const extra: PlanStep[] = added.filter(text => !have.has(norm(text))).map(text => ({ text, state: 'todo' }))
400 const next = [...one.plan, ...extra].slice(0, MAX_PLAN_STEPS).map((step, i) => {
401 const n = i + 1
402 if (done.has(n)) return { ...step, state: 'done' as const }
403 if (n === doing) return { ...step, state: 'doing' as const }
404 // Moving on to a later step finishes the one it was on.
405 if (step.state === 'doing' && doing !== null && doing > n) return { ...step, state: 'done' as const }
406 return step
407 })
408 return { ...one, plan: next }
409 }),
410 )
411 })()
412 buf.inFlight = run
413 try {
414 await run
415 } finally {
416 buf.inFlight = null
417 }
418}
419
420async function writeHandoff($: EngineInterface): Promise<Handoff | null> {
421 await update($, handingOff, () => true)
422 try {
423 const qs = await read($, questions)
424 const us = await read($, undone)
425 const extra = [
426 qs.length ? `The agenda pane also holds these unanswered questions; include them under Open questions:\n${qs.map(one => `- ${one.text}`).join('\n')}` : '',
427 us.length ? `And these undone items; include them under Left undone:\n${us.map(one => `- ${one.text}`).join('\n')}` : '',
428 ]
429 .filter(Boolean)
430 .join('\n\n')
431 const reply = await $.model.fork({ prompt: extra ? `${HANDOFF_PROMPT}\n\n${extra}` : HANDOFF_PROMPT })
432 if (!reply.isAnswered) {
433 $.ui.toast(`Agenda: handoff failed (${reply.reason})`)
434 return null
435 }
436 const written: Handoff = { text: reply.text.trim(), at: new Date().toISOString() }
437 await update($, handoff, () => written)
438 await persist($)
439 const cwd = await $.session.cwd()
440 const path = `${cwd.replace(/[\\/]+$/, '')}/.claude/handoff.md`
441 try {
442 await $.fs.write(path, `${written.text}\n`)
443 } catch {
444 // The store copy is what the next session reads; the file is a courtesy.
445 }
446 return written
447 } finally {
448 await update($, handingOff, () => false)
449 }
450}
451
452function bar(percent: number, width: number): string {
453 const filled = Math.round((Math.max(0, Math.min(100, percent)) / 100) * width)
454 return T.gauge.filled.repeat(filled) + T.gauge.empty.repeat(Math.max(0, width - filled))
455}
456
457function gaugeColor(percent: number): string {
458 if (percent >= T.gauge.dangerAt) return T.gauge.danger
459 if (percent >= T.gauge.warnAt) return T.gauge.warn
460 return T.gauge.ok
461}
462
463/** Rows a word-wrapped Text takes at `width` cells, as the terminal wraps it. */
464function wrapRows(text: string, width: number): number {
465 const w = Math.max(1, width)
466 let rows = 0
467 for (const line of text.split('\n')) {
468 let used = 0
469 let lineRows = 1
470 for (const word of line.split(' ')) {
471 const len = [...word].length
472 if (used === 0) {
473 lineRows += Math.max(0, Math.ceil(len / w) - 1)
474 used = len % w || (len ? w : 0)
475 } else if (used + 1 + len <= w) {
476 used += 1 + len
477 } else {
478 lineRows += Math.ceil(Math.max(1, len) / w)
479 used = len % w || w
480 }
481 }
482 rows += lineRows
483 }
484 return rows
485}
486
487/** The thumb's first row and length on a track of `rows` rows over a tree of `content` rows. */
488function thumb(offset: number, rows: number, content: number): { start: number; size: number } {
489 const size = Math.max(1, Math.min(rows, Math.round((rows * rows) / content)))
490 const travel = Math.max(1, content - rows)
491 const start = Math.round((Math.min(Math.max(0, offset), travel) / travel) * (rows - size))
492 return { start, size }
493}
494
495function kTokens(n: number): string {
496 return n >= 1000 ? `${Math.round(n / 1000)}k` : String(n)
497}
498
499function elapsed(row: AgentRow, now: number): string {
500 const s = Math.max(0, Math.round(((row.endedAt ?? now) - row.startedAt) / 1000))
501 return s >= 60 ? `${Math.floor(s / 60)}m${s % 60}s` : `${s}s`
502}
503
504function agentGlyph(status: AgentRow['status']): { glyph: string; color: string } {
505 return T.status[status]
506}
507
508async function expandHome($: EngineInterface, path: string): Promise<string> {
509 if (!path.startsWith('~')) return path
510 const home = (await $.env.get('HOME')) ?? (await $.env.get('USERPROFILE')) ?? ''
511 return home.replace(/[\/]+$/, '') + path.slice(1)
512}
513
514/**
515 * Reads the theme file. A missing file is written with the defaults so there is something to edit;
516 * an unreadable or malformed one yields the defaults and a note of why.
517 */
518async function loadTheme($: EngineInterface, themeFile: string): Promise<{ theme: Theme; path: string; problem?: string; isNew?: boolean }> {
519 const path = await expandHome($, themeFile)
520 let exists = false
521 try {
522 exists = await $.fs.exists(path)
523 } catch {
524 return { theme: DEFAULT_THEME, path, problem: 'could not check the theme file' }
525 }
526 if (!exists) {
527 try {
528 await $.fs.write(path, JSON.stringify({ $doc: THEME_DOC, ...DEFAULT_THEME }, null, 2) + '\n')
529 return { theme: DEFAULT_THEME, path, isNew: true }
530 } catch {
531 return { theme: DEFAULT_THEME, path, problem: 'could not write the starter theme file' }
532 }
533 }
534 try {
535 const text = await $.fs.read(path)
536 return { theme: mergeTheme(JSON.parse(text)), path }
537 } catch {
538 return { theme: DEFAULT_THEME, path, problem: 'theme file is not valid JSON; using defaults' }
539 }
540}
541
542async function applyTheme($: EngineInterface, themeFile: string, isReload: boolean): Promise<void> {
543 const loaded = await loadTheme($, themeFile)
544 T = loaded.theme
545 await update($, theme, () => loaded.theme)
546 if (loaded.isNew) $.ui.toast(`Agenda: starter theme written to ${loaded.path}; edit it and run /agenda to reload`)
547 else if (loaded.problem) $.ui.toast(`Agenda: ${loaded.problem} (${loaded.path})`)
548 else if (isReload) $.ui.toast('Agenda: theme reloaded')
549}
550
551export const register: Register = (on, options) => {
552 const extractorModel = String(options.extractorModel ?? 'haiku')
553 const themeFile = String(options.themeFile ?? '~/.claude/agenda.theme.json')
554
555 let hasOpenedOnPrompt = false
556
557 on('session.start', async ($, e, next) => {
558 await applyTheme($, themeFile, false)
559 await load($)
560 await persist($)
561 await $.command.register({ name: 'agenda', description: 'Open the Agenda pane (agents, context, questions, undone, notes)' })
562 await $.command.register({ name: 'note', description: 'Add a note to the Agenda scratch pad: /note <text>' })
563 await $.command.register({ name: 'handoff', description: 'Write a handoff for the next session, then /clear' })
564 // Unasked, the engine seats a pane only on a terminal 144 columns or wider; narrower, it waits
565 // undrawn, and the first prompt.submit below opens it as the person's own ask, at any width.
566 void $.ui.open({ id: PANE, title: TITLE })
567 try {
568 await refreshContext($)
569 } catch {
570 // No usage yet; the gauge reads "no turn yet" until the first reply.
571 }
572 $.clock.every(3000, async () => {
573 const rows = await read($, agents)
574 if (rows.some(one => one.endedAt === undefined)) await refreshAgents($)
575 })
576 return next(e)
577 })
578
579 on('prompt.submit', async ($, e, next) => {
580 if (e.origin?.kind !== 'plugin') {
581 lastPrompt = e.text
582 const answering = pendingAnswer
583 if (answering && e.text.startsWith(ANSWER_PREFIX)) {
584 pendingAnswer = null
585 await setList($, 'questions', list => list.filter(one => one.id !== answering.id))
586 }
587 }
588 if (!hasOpenedOnPrompt) {
589 hasOpenedOnPrompt = true
590 const panes = await $.ui.panes()
591 const mine = panes.find(one => one.id === PANE)
592 if (!mine || !mine.isPlaced) void $.ui.open({ id: PANE, title: TITLE })
593 }
594 return next(e)
595 }).catch(($, e, next) => next(e))
596
597 on('session.end', async ($, e, next) => {
598 await update($, questions, () => [])
599 // A cleared session starts with an empty agents list; the old ones stay hidden if the engine still lists them.
600 const known = (await read($, agents)).map(one => one.id)
601 await update($, dismissedAgents, list => [...new Set([...list, ...known])])
602 await update($, agents, () => [])
603 await update($, toggledAgents, () => [])
604 return next(e)
605 })
606
607 on('ui.open', { id: PANE }, async ($, e, next) => {
608 const result = await next(e)
609 void refreshStatus($)
610 return result
611 }).catch(($, e, next) => next(e))
612
613 on('ui.close', { id: PANE }, async ($, e, next) => {
614 const result = await next(e)
615 void refreshStatus($)
616 return result
617 }).catch(($, e, next) => next(e))
618
619 on('command.run', { command: 'agenda' }, async $ => {
620 await applyTheme($, themeFile, true)
621 const opened = await $.ui.open({ id: PANE, title: TITLE, focus: true })
622 return { text: opened.isPlaced ? 'Agenda pane opened.' : 'Agenda pane could not be placed; widen the terminal.' }
623 })
624
625 on('command.run', { command: 'note' }, async ($, e) => {
626 const text = (e.args ?? '').trim()
627 if (!text) return { text: 'Usage: /note <text>' }
628 await setList($, 'notes', list => merge(list, [text], new Date().toISOString()))
629 return { text: `Noted: ${text}` }
630 })
631
632 on('command.run', { command: 'handoff' }, async $ => {
633 const written = await writeHandoff($)
634 if (!written) return { text: 'Handoff not written; nothing to hand off yet or the model did not answer.' }
635 void $.command.run({ command: 'clear' })
636 return { text: 'Handoff written to .claude/handoff.md and kept for the next session. Clearing.' }
637 })
638
639 on('agent.spawn', async ($, e, next) => {
640 const result = await next(e)
641 await refreshAgents($)
642 if (!result.deny && result.agentId) {
643 void planAgent($, result.agentId, e.description || e.subagentType, e.prompt, extractorModel)
644 }
645 return result
646 }).catch(($, e, next) => next(e))
647
648 on('session.append', { door: 'response' }, ($, e, next) => {
649 if (e.agentId && e.message.role === 'assistant') {
650 const { isDue } = noteActivity(e.agentId, e.message.content)
651 if (isDue) void summarizeActivity($, e.agentId, extractorModel)
652 }
653 return next(e)
654 }).catch(($, e, next) => next(e))
655
656 on('turn.complete', async ($, e, next) => {
657 const result = await next(e)
658 void refreshAgents($)
659 if (e.agentId) {
660 void summarizeActivity($, e.agentId, extractorModel)
661 return result
662 }
663 void refreshContext($)
664 // The first main-loop answer after a handoff was loaded has consumed it.
665 const pending = await read($, handoff)
666 if (pending && e.reason === 'answer') {
667 await update($, handoff, () => null)
668 await persist($)
669 }
670 if (e.reason === 'answer' && e.answer.trim().length >= 20) void scanAnswer($, e.answer, extractorModel)
671 return result
672 })
673
674 on('prompt.compose', async ($, e, next) => {
675 const composed = await next(e)
676 const sections = [...composed.sections]
677 const list = await read($, notes)
678 if (list.length > 0) {
679 sections.push({
680 id: 'agenda:notes',
681 scope: 'session',
682 text: [
683 '# Agenda scratch pad',
684 'Standing notes the user keeps for this project directory, across sessions, through the agenda pane. Treat them as context that must not be lost; honour any to-do or constraint listed here when it is relevant to the current work.',
685 ...list.map(one => `- ${one.text}`),
686 ].join('\n'),
687 })
688 }
689 const pending = await read($, handoff)
690 if (pending) {
691 sections.push({
692 id: 'agenda:handoff',
693 scope: 'session',
694 text: [
695 '# Handoff from the previous session',
696 `Written ${pending.at}. The previous session ended on purpose and this one continues it. Read this before acting, then pick up at "Next step". Do not re-ask the questions it lists as decided.`,
697 '',
698 pending.text,
699 ].join('\n'),
700 })
701 }
702 return { sections }
703 })
704
705 // The engine scrolls the pane body but draws no scrollbar, and the render hook is not told the tree's
706 // height. The pane estimates it; each scroll reports the true height, which calibrates the estimate.
707 on('ui.scroll', { component: 'Pane', requestId: PANE }, ($, e, next) => {
708 if (lastEstimate > 0) rowCorrection = e.contentRows - lastEstimate
709 return next(e)
710 }).catch(($, e, next) => next(e))
711
712 on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
713 const { Box, Text, Button } = $.ui.resolve(e)
714 const Input = e.surface === 'mobile' ? null : $.ui.resolve(e).Input
715 const qs = await read($, questions)
716 const us = await read($, undone)
717 const ns = await read($, notes)
718 const rows = await read($, agents)
719 const toggled = await read($, toggledAgents)
720 const gauge = await read($, context)
721 const pending = await read($, handoff)
722 const busy = await read($, scanning)
723 const isHandingOff = await read($, handingOff)
724 const t = await read($, theme)
725 T = t
726 const width = Math.max(24, e.props.bodyColumns)
727 const inner = width - 2
728 const now = Date.now()
729
730 const askAnswer = (item: AgendaItem) => async () => {
731 pendingAnswer = item
732 await $.prompt.fill({ text: `${ANSWER_PREFIX}"${item.text}": `, mode: 'replace' })
733 }
734 const dismiss = (which: ListName, item: AgendaItem) => () =>
735 void setList($, which, list => list.filter(one => one.id !== item.id))
736 const doUndone = (item: AgendaItem) => async () => {
737 await setList($, 'undone', list => list.filter(one => one.id !== item.id))
738 void $.prompt.submit({ text: `Do this item you left undone earlier, then verify it: ${item.text}` })
739 }
740 const doAllUndone = async () => {
741 const items = us.map(one => `- ${one.text}`)
742 await setList($, 'undone', () => [])
743 void $.prompt.submit({ text: `Do every item you left undone earlier, then verify each:\n${items.join('\n')}` })
744 }
745 const addNote = (value: string) => {
746 const text = value.trim()
747 if (!text) return
748 void setList($, 'notes', list => merge(list, [text], new Date().toISOString()))
749 }
750 const handoffAndClear = async () => {
751 const written = await writeHandoff($)
752 if (!written) return
753 $.ui.toast('Agenda: handoff written, clearing session')
754 void $.command.run({ command: 'clear' })
755 }
756 const toggleAgent = (id: string) => () =>
757 void update($, toggledAgents, list => (list.includes(id) ? list.filter(one => one !== id) : [...list, id]))
758 const dropHandoff = () => {
759 void (async () => {
760 await update($, handoff, () => null)
761 await persist($)
762 })()
763 }
764
765 const heading = (label: string, color: string, count: number, trailing?: JSX.Element) => (
766 <Box justifyContent="space-between" marginTop={1}>
767 <Box gap={1}>
768 <Text color={color} bold>
769 {label}
770 </Text>
771 <Text color={t.colors.dim}>{count}</Text>
772 </Box>
773 {trailing}
774 </Box>
775 )
776
777 const item = (one: AgendaItem, color: string, buttons: JSX.Element) => (
778 <Box key={one.id} paddingLeft={1} gap={1}>
779 <Text color={color}>{t.glyphs.bullet}</Text>
780 <Box flexGrow={1}>
781 <Text color={t.colors.text} wrap="wrap">
782 {one.text}
783 </Text>
784 </Box>
785 <Box gap={1} flexShrink={0}>
786 {buttons}
787 </Box>
788 </Box>
789 )
790
791 const empty = (text: string) => (
792 <Box paddingLeft={2}>
793 <Text color={t.colors.dim} italic>
794 {text}
795 </Text>
796 </Box>
797 )
798
799 const barWidth = Math.max(8, inner - 8)
800
801 // Height estimate mirroring the layout below, row for row; see the ui.scroll hook.
802 const cells = (text: string) => [...text].length
803 const itemRows = (one: AgendaItem, buttonCells: number) => wrapRows(one.text, inner - 4 - cells(t.glyphs.bullet) - buttonCells)
804 let estimate = 4 + (pending ? 1 : 0)
805 estimate += 2 + (rows.length === 0 ? 1 : 0)
806 for (const row of rows) {
807 const isDone = row.endedAt !== undefined
808 const isOpen = toggled.includes(row.id) ? isDone : !isDone
809 estimate += isOpen ? wrapRows(row.description, inner - 12) : 1
810 if (!isOpen) estimate += row.plan.length > 0 && (isDone || row.plan.some(step => step.state !== 'done')) ? 1 : 0
811 else if (row.plan.length === 0) estimate += 1
812 else for (const step of row.plan) estimate += wrapRows(step.text, inner - 6)
813 }
814 const pairCells = (a: string, b: string) => cells(a) + 1 + cells(b)
815 estimate += 2 + (qs.length === 0 ? 1 : 0) + qs.reduce((n, one) => n + itemRows(one, pairCells(t.glyphs.answer, t.glyphs.dismiss)), 0)
816 estimate += 2 + (us.length === 0 ? 1 : 0) + us.reduce((n, one) => n + itemRows(one, pairCells(t.glyphs.do, t.glyphs.dismiss)), 0)
817 estimate += 2 + ns.reduce((n, one) => n + itemRows(one, cells(t.glyphs.dismiss)), 0)
818 estimate += 1 + 1 + wrapRows(legend(t), inner)
819 lastEstimate = estimate
820 const contentRows = Math.max(1, estimate + rowCorrection)
821 const view = e.props.scroll
822 const overflows = contentRows > view.bodyRows && view.bodyRows > 1
823 const track = overflows ? thumb(view.offset, view.bodyRows, contentRows) : null
824
825 return (
826 <Box flexDirection="column" width={width} backgroundColor={t.colors.background} paddingX={1}>
827 <Box justifyContent="space-between">
828 <Text color={t.sections.context} bold>
829 {t.labels.context}
830 </Text>
831 {gauge && (
832 <Text color={t.colors.muted}>
833 {kTokens(gauge.tokens)} / {kTokens(gauge.window)} · API-equiv ${gauge.usd.toFixed(2)}
834 </Text>
835 )}
836 </Box>
837 {gauge ? (
838 <Box gap={1}>
839 <Text color={gaugeColor(gauge.percent)}>{bar(gauge.percent, barWidth)}</Text>
840 <Text color={gaugeColor(gauge.percent)} bold>
841 {gauge.percent}%
842 </Text>
843 </Box>
844 ) : (
845 empty('no turn yet')
846 )}
847 <Box gap={1} marginTop={1}>
848 <Button
849 key="handoff"
850 label={isHandingOff ? 'writing handoff…' : t.labels.handoff}
851 variant="primary"
852 hotkey="h"
853 onPress={handoffAndClear}
854 />
855 {pending && <Button key="drop-handoff" label={t.labels.dropHandoff} onPress={dropHandoff} />}
856 </Box>
857 {pending && (
858 <Box paddingLeft={2}>
859 <Text color={t.colors.success}>handoff loaded, consumed on the next reply</Text>
860 </Box>
861 )}
862
863 {heading(
864 t.labels.agents,
865 t.sections.agents,
866 rows.filter(one => one.endedAt === undefined).length,
867 rows.some(one => one.endedAt !== undefined) ? (
868 <Button key="clear-agents" plain label={t.glyphs.clearFinished} dimColor onPress={() => void clearFinishedAgents($)} />
869 ) : undefined,
870 )}
871 {rows.length === 0 && empty('no subagents')}
872 {rows.map(row => {
873 const { glyph, color } = agentGlyph(row.status)
874 const isDone = row.endedAt !== undefined
875 // Running rows open by default so the plan is in view; finished rows fold to one line.
876 const isOpen = toggled.includes(row.id) ? isDone : !isDone
877 const doneCount = row.plan.filter(step => step.state === 'done').length
878 const current = row.plan.find(step => step.state === 'doing') ?? row.plan.find(step => step.state === 'todo')
879 const folded = row.plan.length === 0 ? '' : isDone ? `${doneCount}/${row.plan.length} steps` : current ? `${doneCount}/${row.plan.length} · ${current.text}` : ''
880 return (
881 <Box key={row.id} flexDirection="column" paddingLeft={1}>
882 <Box gap={1}>
883 <Text color={color}>{glyph}</Text>
884 <Button key={`ag-${row.id}`} plain label={isOpen ? t.glyphs.collapse : t.glyphs.expand} onPress={toggleAgent(row.id)} />
885 <Box width={inner - 12}>
886 <Text color={isDone ? t.colors.dim : t.colors.text} bold={!isDone} wrap={isOpen ? 'wrap' : 'truncate-end'}>
887 {row.description}
888 </Text>
889 </Box>
890 <Text color={t.colors.dim}>{elapsed(row, now)}</Text>
891 </Box>
892 {!isOpen && folded && (
893 <Box paddingLeft={4} width={inner - 4}>
894 <Text color={t.colors.muted} wrap="truncate-end">
895 {folded}
896 </Text>
897 </Box>
898 )}
899 {isOpen && row.plan.length === 0 && (
900 <Box paddingLeft={4}>
901 <Text color={t.colors.dim} italic>
902 {isDone ? 'no plan recorded' : 'reading its assignment…'}
903 </Text>
904 </Box>
905 )}
906 {isOpen &&
907 row.plan.map((step, i) => (
908 <Box key={`${row.id}-${i}`} paddingLeft={4} width={inner - 4} gap={1}>
909 <Text color={step.state === 'done' ? t.colors.success : step.state === 'doing' ? t.colors.text : t.colors.dim}>
910 {step.state === 'done' ? t.glyphs.stepDone : step.state === 'doing' ? t.glyphs.stepDoing : t.glyphs.stepTodo}
911 </Text>
912 <Box width={inner - 6}>
913 <Text color={step.state === 'doing' ? t.colors.text : step.state === 'done' ? t.colors.muted : t.colors.dim} bold={step.state === 'doing'} wrap="wrap">
914 {step.text}
915 </Text>
916 </Box>
917 </Box>
918 ))}
919 </Box>
920 )
921 })}
922
923 {heading(t.labels.questions, t.sections.questions, qs.length, busy ? <Text color={t.colors.dim}>scanning…</Text> : undefined)}
924 {qs.length === 0 && empty('none pending')}
925 {qs.map(one =>
926 item(
927 one,
928 t.sections.questions,
929 <>
930 <Button key={`qa-${one.id}`} plain label={t.glyphs.answer} variant="primary" onPress={askAnswer(one)} />
931 <Button key={`qx-${one.id}`} plain label={t.glyphs.dismiss} dimColor onPress={dismiss('questions', one)} />
932 </>,
933 ),
934 )}
935
936 {heading(t.labels.undone, t.sections.undone, us.length, us.length > 1 ? (
937 <Box gap={1}>
938 <Button key="do-all" plain label={t.glyphs.doAll} onPress={doAllUndone} />
939 <Button key="dismiss-all" plain label={t.glyphs.dismissAll} dimColor onPress={() => void setList($, 'undone', () => [])} />
940 </Box>
941 ) : undefined)}
942 {us.length === 0 && empty('nothing left undone')}
943 {us.map(one =>
944 item(
945 one,
946 t.sections.undone,
947 <>
948 <Button key={`ud-${one.id}`} plain label={t.glyphs.do} variant="primary" onPress={doUndone(one)} />
949 <Button key={`ux-${one.id}`} plain label={t.glyphs.dismiss} dimColor onPress={dismiss('undone', one)} />
950 </>,
951 ),
952 )}
953
954 {heading(t.labels.notes, t.sections.notes, ns.length)}
955 {ns.map(one => item(one, t.sections.notes, <Button key={`nx-${one.id}`} plain label={t.glyphs.dismiss} dimColor onPress={dismiss('notes', one)} />))}
956 <Box paddingLeft={1}>
957 {Input ? (
958 <Input key="new-note" placeholder="add a project note, kept across sessions" submitLabel="add" onSubmit={addNote} />
959 ) : (
960 <Text color={t.colors.dim}>add notes with /note from a terminal or desktop</Text>
961 )}
962 </Box>
963 <Box marginTop={1}>
964 <Text color={t.colors.dim}>{legend(t)}</Text>
965 </Box>
966 {track && (
967 // Painted over the right padding column, pinned to the rows the window shows.
968 <Box key="scrollbar" position="absolute" top={Math.max(0, Math.min(view.offset, contentRows - view.bodyRows))} right={0} width={1} flexDirection="column">
969 {Array.from({ length: view.bodyRows }, (_, i) => {
970 const isThumb = i >= track.start && i < track.start + track.size
971 return (
972 <Text key={`sb-${i}`} color={isThumb ? t.scrollbar.thumbColor : t.scrollbar.trackColor}>
973 {isThumb ? t.scrollbar.thumb : t.scrollbar.track}
974 </Text>
975 )
976 })}
977 </Box>
978 )}
979 </Box>
980 )
981 })
982}
983hooks/theme.ts 75 lines1import type { Theme } from '../types'
2
3export const THEME_DOC =
4 'Styling for the Claude Code agenda pane. Edit any value, then run /agenda to reload. Colours are hex or terminal names; glyphs are any text. Plugin updates never touch this file. Delete it to get the defaults back.'
5
6// Deep Space palette (Tokyo Night Moon derived), matching the author's WezTerm background.
7export const DEFAULT_THEME: Theme = {
8 colors: { background: '#0a0d1a', text: '#c8d3f5', dim: '#545c7e', muted: '#828bb8', success: '#c3e88d' },
9 sections: { context: '#c099ff', agents: '#82aaff', questions: '#ffc777', undone: '#ff757f', notes: '#86e1fc' },
10 gauge: { ok: '#c099ff', warn: '#ffc777', danger: '#ff757f', warnAt: 50, dangerAt: 75, filled: '█', empty: '░' },
11 status: {
12 pending: { glyph: '○', color: '#828bb8' },
13 running: { glyph: '●', color: '#82aaff' },
14 waiting: { glyph: '◐', color: '#ffc777' },
15 idle: { glyph: '◐', color: '#ffc777' },
16 completed: { glyph: '✓', color: '#c3e88d' },
17 failed: { glyph: '✗', color: '#ff757f' },
18 killed: { glyph: '✗', color: '#ff757f' },
19 },
20 glyphs: {
21 answer: '✎',
22 do: '▶',
23 doAll: '▶▶ all',
24 dismiss: '✕',
25 dismissAll: '✕ all',
26 clearFinished: '✕ finished',
27 expand: '▸',
28 collapse: '▾',
29 bullet: '▎',
30 stepTodo: '○',
31 stepDoing: '◉',
32 stepDone: '✓',
33 },
34 labels: {
35 context: 'CONTEXT',
36 agents: 'AGENTS',
37 questions: 'QUESTIONS',
38 undone: 'UNDONE',
39 notes: 'NOTES',
40 handoff: 'handoff + clear',
41 dropHandoff: 'drop pending handoff',
42 },
43 scrollbar: { thumb: '┃', track: '│', thumbColor: '#828bb8', trackColor: '#2f334d' },
44}
45
46function isRecord(value: unknown): value is Record<string, unknown> {
47 return typeof value === 'object' && value !== null && !Array.isArray(value)
48}
49
50/** Fills a partial theme in over the defaults, keeping only values of the right type. */
51function fill<T>(base: T, raw: unknown): T {
52 if (!isRecord(raw) || !isRecord(base)) return base
53 const out: Record<string, unknown> = { ...base }
54 for (const key of Object.keys(base)) {
55 const want = (base as Record<string, unknown>)[key]
56 const got = raw[key]
57 if (got === undefined) continue
58 if (isRecord(want)) out[key] = fill(want, got)
59 else if (typeof want === typeof got && (typeof got !== 'string' || got.length > 0)) out[key] = got
60 }
61 return out as T
62}
63
64export function mergeTheme(raw: unknown): Theme {
65 const theme = fill(DEFAULT_THEME, raw)
66 theme.gauge.warnAt = Math.max(0, Math.min(100, theme.gauge.warnAt))
67 theme.gauge.dangerAt = Math.max(theme.gauge.warnAt, Math.min(100, theme.gauge.dangerAt))
68 return theme
69}
70
71export function legend(theme: Theme): string {
72 const g = theme.glyphs
73 return `${g.answer} answer · ${g.do} do · ${g.dismiss} dismiss · ${g.expand} expand`
74}
75types/index.d.ts 91 lines1export type AgendaItem = {
2 id: string
3 text: string
4 /** ISO date the item was captured. */
5 at: string
6}
7
8export type AgentRow = {
9 id: string
10 /** The Agent call's own few-word description of the task. */
11 description: string
12 type: string
13 status: 'pending' | 'running' | 'waiting' | 'idle' | 'completed' | 'failed' | 'killed'
14 startedAt: number
15 endedAt?: number
16 /** The macro steps its assignment asks for, in order, each ticked off as its activity shows progress. */
17 plan: PlanStep[]
18}
19
20export type PlanStep = {
21 text: string
22 state: 'todo' | 'doing' | 'done'
23}
24
25export type ContextGauge = {
26 tokens: number
27 window: number
28 percent: number
29 /** API list-price equivalent of the session so far; the user is on a subscription, shown for comparison. */
30 usd: number
31}
32
33export type Handoff = {
34 text: string
35 /** ISO date the handoff was written. */
36 at: string
37}
38
39declare module 'claude-code' {
40 interface PluginState {
41 agenda: {
42 questions: AgendaItem[]
43 undone: AgendaItem[]
44 notes: AgendaItem[]
45 agents: AgentRow[]
46 toggledAgents: string[]
47 dismissedAgents: string[]
48 context: ContextGauge | null
49 handoff: Handoff | null
50 scanning: boolean
51 handingOff: boolean
52 theme: Theme
53 }
54 }
55}
56
57export type StatusLook = { glyph: string; color: string }
58
59/** Everything a person may restyle; read from the theme file, defaults filled in. */
60export type Theme = {
61 colors: { background: string; text: string; dim: string; muted: string; success: string }
62 sections: { context: string; agents: string; questions: string; undone: string; notes: string }
63 gauge: { ok: string; warn: string; danger: string; warnAt: number; dangerAt: number; filled: string; empty: string }
64 status: {
65 pending: StatusLook
66 running: StatusLook
67 waiting: StatusLook
68 idle: StatusLook
69 completed: StatusLook
70 failed: StatusLook
71 killed: StatusLook
72 }
73 glyphs: {
74 answer: string
75 do: string
76 doAll: string
77 dismiss: string
78 dismissAll: string
79 /** Clears the finished rows from the agents list. */
80 clearFinished: string
81 expand: string
82 collapse: string
83 bullet: string
84 stepTodo: string
85 stepDoing: string
86 stepDone: string
87 }
88 labels: { context: string; agents: string; questions: string; undone: string; notes: string; handoff: string; dropHandoff: string }
89 scrollbar: { thumb: string; track: string; thumbColor: string; trackColor: string }
90}
91