Consult multiple AI coding agents (Gemini, OpenAI, Grok, Perplexity, Kimi, any model OpenRouter routes to, plus codex, antigravity, grok, kimi and cursor CLIs…

A Claude Code plugin that asks AI coding agents the same question in parallel. Compare their answers when one model's bias could mislead you: architecture decisions, debugging dead ends, security reviews, or framework choices.
You need curl and jq on macOS, Linux, or Windows through Git Bash.
/plugin marketplace add hex/claude-marketplace
/plugin install claude-council
Give it at least one provider in the shell you start Claude Code from:
export OPENAI_API_KEY="..."
# Or GEMINI_API_KEY, XAI_API_KEY, PERPLEXITY_API_KEY,
# KIMI_API_KEY, OPENROUTER_API_KEY
The codex, agy (Antigravity), grok, kimi, and cursor-agent CLIs use your existing subscriptions without an API key. Claude Code itself, the Copilot CLI and OpenCode can sit too, when named in --providers. A local ollama model needs no key or external network. With none of these, --local uses Claude subagents. See provider selection and local councils.
Read what gets sent and saved before asking about your code.
/claude-council:status
/claude-council:ask "Should I use UUID or BIGINT primary keys for a SaaS users table?"
Each provider answers independently. Claude writes a synthesis of their agreement, disagreements, and recommendation. Agreement is not verification: the models share your description and its assumptions. The synthesis names the premise that could change the answer.
| Capability | Guide |
|---|---|
| Ask providers together, or name one in plain words | Command examples |
| Choose providers and pin a standing roster | Provider selection |
| Assign specialist roles | Roles |
| Have providers challenge each other's answers | Debate |
| Gather code context with agents before asking | Agent mode |
| Use Claude subagents without an external provider | Local council |
| Include relevant files or choose your own | Auto-context |
| Attach a screenshot | Image input |
| Ask about the current conversation | /advise |
| Run in the background and fetch the result | Background jobs |
| Export the answers to a file | Export |
| Show only the synthesis | Quiet mode |
| Watch answers arrive and retry failed seats | The pane |
| Get a note from one seat while Claude works | Heads-up side-check |
| Have a second model review the diff before Claude stops | Stop-gate review |
| Call the scripts without Claude Code | Direct script usage |
The reference lists every flag, variable, model default, and limit. Architecture covers the implementation. TESTING.md covers tests, releases, and adding a provider.
Opt in through the "Heads-up side-check" row in /config or the project's .claude/council-heads-up.json. One seat, codex by default, checks recent turns and tool results while Claude works. For a Write or an Edit, it gets the text Claude wrote. The note shows what went where. Learn more expands it; Tell Claude puts a draft in the prompt without sending it. Read the data limits and off switch and the heads-up guide.
With CLAUDE_CODE_ENABLE_FUNCTION_HOOKS=1, the pane opens inside Claude Code, as in the animation above. Each seat has one row with its model, a bar for its state, its time, and a button for what it does now: cancel, retry, open, or fold. When the run ends, the synthesis opens at the top with the answers folded below it. Reopen the last run with /council-pane. Inside tmux, the mod asks once which pane you want.
Mods are early access. The mod guide lists keys, settings, and limits. It also lets Claude call the council as a tool; every call asks you first.
The mod makes no network calls of its own. It starts the programs below from an argument array, never a shell string, and never hands bash -c a script. Your text reaches model providers only through the first two:
bash scripts/run-council.sh when Claude calls the council tool and you choose Send to the council. It sends your question to the providers you set up.bash scripts/heads-up.sh, only with the heads-up side-check on. It reads this session's transcript (by default the last 5 turns and up to 8 tool results of 2,000 characters each) and sends that digest to one seat, codex unless you pick another. The run directory keeps digest.md and prompt.md, exactly what left the machine, until the mod reads the result and removes it. The codex seat runs in that directory under a codex home of its own: your model and effort, a link to your auth.json so a token refresh reaches your login (without one, your CODEX_API_KEY or OPENAI_API_KEY signs codex in), and none of your plugins, hooks, AGENTS.md, skills or MCP servers.bash scripts/seat-info.sh discover, model <seat> or allowlisted <seat> during /heads-up setup and /heads-up on <seat>. It checks which seats this machine can run and sends nothing.codex debug models during /heads-up setup with the codex seat, to list its models. That command belongs to codex, and so does any request it makes.kill -0 <pid> to check a council run is still alive. It sends no signal.rm -rf and mv -f on its own run directories under $TMPDIR/council-mod.<session id>, to clean up a finished run and to answer the retry offer.It writes files in that $TMPDIR directory, including model.json and avoid.txt, which heads-up.sh reads. Outside it, it writes one file, .claude/council-heads-up.json in the project, and only from /heads-up setup, /heads-up on, /heads-up off or a note's Turn off. That file is the heads-up switch. Claude Code itself does not read it.
It touches the prompt in two places. With wake_on_async_done on, it submits The background council job <id> has finished. Fetch it with /claude-council:result <id> and summarise it. once a background job finishes. A note's Tell Claude puts a draft in the prompt box, and you decide whether to send it.
It reads the text of each Bash command Claude runs, only to spot a call to run-council.sh. Just before that call it sets COUNCIL_MOD_PANE_DIR, so the run draws in this pane, and clears it when tmux owns the pane. It reads TMPDIR and TMUX. It turns on the claude-council.heads_up setting only when you pick "every project" in /heads-up setup.
Without the mod, tmux opens a side pane that streams answers and each provider's status. It offers to retry failed seats. Esc closes it. --no-pane or COUNCIL_NO_PANE=1 turns it off. Outside both pane modes, answers arrive in the chat. See terminal integration.
The council and tmux animations show real answers to "Should a single-node demo app use SQLite or Postgres?" Codex and Antigravity use subscriptions; Gemini and OpenAI use their APIs. Kimi is a rate-limit fixture. The heads-up animation uses a fake seat and a real Claude Code host. Capture scripts and raw frames record how to reproduce them.
Every CLI seat runs from an empty directory, $TMPDIR/claude-council-<uid>/seat, where <uid> is your numeric user id. The CLAUDE.md, AGENTS.md, rules, skills, hooks and MCP servers of the project you ask from don't reach it. The directory doesn't limit what a seat can read: codex, for example, can still open any file by its full path.
The directory is read-only. That stops a seat writing a file there, but not a seat that changes the mode first. A seat also refuses to start when it finds anything in it, and names the path so you can look before you remove it. A file that lands while other seats are running can reach them; the next seat to start refuses.
The seats below also run under a home of their own, in $TMPDIR/claude-council-<uid>/seat-home. It links only to what the CLI needs to sign in and start. Only you can open either directory, and a seat refuses to start when one of them belongs to another user or is a symlink.
| Seat | No longer loads | Still loads |
|---|---|---|
cursor-cli | Skills and plugins from ~/.cursor, ~/.claude, ~/.codex, ~/.grok and ~/.agents, Cursor and Claude hooks, ~/.cursor/mcp.json | Team commands from your Cursor dashboard (read from the CLI's bundle, not seen in a run) |
grok-cli | Claude plugins, ~/.agents skills, grok's memory across sessions | Your ~/.grok config and the hooks in ~/.grok/hooks, since no grok setting turns them off. The seat home links your login keychain (macOS) and ~/.docker/run, for Docker Desktop's socket |
antigravity | On macOS: your ~/.gemini rules, skills, MCP servers and saved conversations | On Linux: everything under ~/.gemini, because where agy keeps its login there is not confirmed |
opencode | The ~/.claude and ~/.agents skills, agents and CLAUDE.md | Your login and session history in ~/.local/share/opencode |
codex | Your plugins, hooks, skills, memories and MCP servers. Each question gets its own codex home with your model, your effort and a link to auth.json | Nothing. codex can't read a login kept only in the system keyring from another home, so then the seat runs under your own codex home and the answer starts with a note. Set cli_auth_credentials_store = "file" and run codex login again to isolate it. With no login at all, the seat stops and says so |
claude-cli | The git status and commit instructions a repository adds | Admin policy and your organisation's instructions |
kimi-cli, copilot-cli | The project's files | Your home: kimi's hooks in ~/.kimi-code/config.toml, copilot's skills in ~/.copilot and ~/.agents |
Cursor and Antigravity keep the model you picked in their own config: the seat reads it from your real home and passes it on. On Windows the seats keep your home, because the native CLIs find it through USERPROFILE. Seat isolation has each seat's details.
| Problem | Fix |
|---|---|
| Cloned the repo and nothing loads | Don't clone into ~/.claude/plugins/. pluginDirectories is not a setting. Follow running from a local clone. |
| No providers found | Run /claude-council:status. Export keys in the shell that starts Claude Code, or use --local. |
| A different model answered | A header such as grok-4.7 (grok-latest unavailable) records a model fallback. Setting that provider's _MODEL variable disables fallback. |
| No pane | Use tmux or set CLAUDE_CODE_ENABLE_FUNCTION_HOOKS=1 for the pane inside Claude Code. |
| Updating | Run /plugin update claude-council, then restart Claude Code. |
mods/council-pane/hooks/pane.tsx 1159 lines1// ABOUTME: Hooks module that draws a council run's progress and answers in a Claude Code pane
2// ABOUTME: Polls the watch dir run-council.sh writes when COUNCIL_MOD_PANE_DIR is exported
3import { atom, read, update } from 'claude-code'
4import type { Elements, EngineInterface, Register, RenderChildren, Timer } from 'claude-code'
5import {
6 applyAnswer, avoidList, bandView, checkLine, CONFIG_FILE, decide, onCadence, FRESH_SESSION, mergeMemory, parseConfig, parseMemory, parseRunResult, pressed, settle, STORE_KEY, tellClaudeDraft, typedPast,
7 addedTokens, bumped, COMMAND as HEADS_UP_COMMAND, COUNTS_KEY, TOKENS_KEY, parseTokens, headsUpCommand, INTRO_KEY as HEADS_UP_INTRO_KEY, introTail, parseCounts, headsUpStatus, statusText, withEnabled, type Counts, type HeadsUpStatus,
8 seatsFromDiscovery, seatOptions, seatFromAnswer, everyFromAnswer, SCOPE, SCOPE_QUESTION, SEAT_QUESTION, EVERY_QUESTION, EVERY_LABELS, receiptLine, modelFile, type HeadsUpConfig, modelOptions, modelFromAnswer, effortOptions, effortFromAnswer, MODEL_QUESTION, EFFORT_QUESTION, type SeatPick,
9 tagMark, toastLine, type Answer, type BandView, type Memory, type RunResult,
10 EMPTY_MEMORY, acknowledgePause, pausedLine, storedSession,
11} from './heads-up'
12import type { Note, Paused, Session } from '../types'
13import { decideHost, HOST_LABELS, HOST_QUESTION, HOST_STORE_KEY, hostFrom, hostRowLabel, isCouncilRun, paneCommand, type HostSetting, type PaneHost } from './host'
14import { abandonedNotice, FINISH_NOTICE_MS, finishNotice, jobOutcome, noticeIsLive, reopenReply, runPid, wakePrompt, type FinishNotice, progressBand } from './notices'
15import { paneOptions, type PaneOptions } from './options'
16import { parseRetryOffer, retrySection, type RetryOffer, type RetrySection } from './retry'
17import { readText, readView, type Files } from './snapshot'
18import { confirmOutcome, confirmQuestion, councilArgs, KEEP_LABEL, SEND_LABEL, TOOL_DESCRIPTION, TOOL_NAME, TOOL_SCHEMA } from './tool'
19import { extractSynthesis } from './synthesis'
20import { fitTables } from './tables'
21import { isMoving, markdownBlocks, paneSections, queryingSince, seatFolds, seatsToCancel, unseenRun, type RunView, type Section } from './view'
22import { COLOR, FILL } from './theme'
23import { parseCatalog } from './catalog'
24
25const PANE_ID = 'council'
26const REOPEN_COMMAND = 'council-pane'
27const RUN_TIMEOUT_MS = 600_000
28const POLL_MS = 500
29// Ten frames a second: the band's and the live seats' sweeps and clocks.
30const FRAME_MS = 100
31// The worker records its result seconds after .done; a worker killed outright
32// leaves its record at running, so the wait for it ends.
33const WAKE_WAIT_MS = 120_000
34// How often a run still going is asked whether its process is alive.
35const PID_CHECK_MS = 5_000
36// The store keys a specialists feature once kept; its records are removed at
37// session start until none is left, then this list can go.
38const SPECIALIST_STORE_KEYS = ['specialist-runs', 'specialists-latest', 'specialists-intro-shown']
39// Every colour comes from theme.ts; DESIGN.md says which one serves what.
40// A section header's mark: open shows its text, closed only the header.
41const OPEN_MARK = '\u25be'
42const CLOSED_MARK = '\u25b8'
43// A seat row's first cell, in the vendor's colour: identity without a fill.
44const EDGE_MARK = '\u258c'
45// The bands above the prompt start where Claude Code's own footer lines do.
46const BAND_INDENT = 2
47// A seat row's action column: two cells of gap, then the widest a
48// bracketed Button draws, the longest verb inside its brackets.
49const ACTION_COLUMNS = 2 + '[ cancel ]'.length
50// The heads-up runner forks and returns its pid; anything slower is a fault.
51const HEADS_UP_LAUNCH_MS = 10_000
52// A seat question reads the provider scripts and a config file or two.
53const SEAT_INFO_MS = 15_000
54
55// The heads-up side-check's session state is the host's (its contract is
56// types/index.d.ts), so a hot reload keeps a check in flight and a note on
57// screen; the band reads it while drawing.
58const HEADS_UP = { plugin: 'claude-council', key: 'headsUp' } as const
59const headsUp = atom(HEADS_UP, FRESH_SESSION)
60
61type PaneState = {
62 root: string
63 runDir?: string
64 view?: RunView
65 drawn: string
66 isPolling: boolean
67 shown: Set<string>
68 lastError: string
69 pidCheckedAtMs: number
70 // When the heads-up check's worker was last asked whether it is alive.
71 headsUpCheckedAtMs: number
72 // The heads-up's own poll, from a launch until the check settles and its failure notice is gone.
73 headsUpTimer?: Timer
74 isPollingHeadsUp: boolean
75 // The last config problem logged, so a broken file is reported once.
76 headsUpProblem: string
77 // The last heads-up failure logged (see logFailure).
78 lastFailure: string
79 // The intro tail on the prompt hint; '' once typed past, turned on, or never due.
80 headsUpTip: string
81 // A model request is in flight: a command's text reply waits for the turn, a toast does not.
82 turnInFlight: boolean
83 // The last check that found nothing, on the prompt hint until a keystroke or the next check.
84 headsUpReceipt: string
85 // The last skipped check logged; the same reason on the next cadence point is not logged again.
86 headsUpSkipped: string
87 // The last check that failed, drawn in red above the prompt for a while; the transcript keeps the reason.
88 headsUpFailure?: FinishNotice
89 // The note whose Turn off was pressed once; the second press turns the check off for this project.
90 headsUpTurnOffArmed: string
91 pendingWake?: { prompt: string; jobFile: string; untilMs: number }
92 retry?: { offer: RetryOffer; seenAtMs: number }
93 retryShown?: RetrySection
94 synthesis?: string
95 finished?: FinishNotice
96 frame: number
97 nowMs: number
98 queryingSinceMs: Record<string, number>
99 // The sections the person closed, by their fold; each run starts with all open.
100 closed: Set<string>
101 // When the pane picked the live run up; the progress band's clock.
102 runStartedMs?: number
103 // Each section's Markdown blocks, for the text they were cut from: a frame
104 // redraws the tree, not the markdown.
105 fitted: Map<string, { text: string; blocks: string[] }>
106 // Each answer as rewritten for the pane's width (wide tables as records),
107 // for the width it was rewritten at: a resize starts it over.
108 tableFit: { columns: number; byText: Map<string, string> }
109}
110
111// The engine refuses $.fs passed as a value, so the snapshot reader gets the
112// three calls it needs spelled out.
113function files($: EngineInterface): Files {
114 return {
115 exists: path => $.fs.exists(path),
116 read: path => $.fs.read(path),
117 list: dir => $.fs.list(dir),
118 }
119}
120
121// The model and effort lists come from Codex itself; a failure is kept as the
122// catalog's error, never an empty list.
123async function readCatalog($: EngineInterface) {
124 const run = await $.process.run(['codex', 'debug', 'models'], { timeoutMs: 15_000 })
125 .catch((err: unknown) => ({ exitCode: 127, stdout: '', stderr: String(err) }))
126 return parseCatalog(run)
127}
128
129// The engine's own dialogs: scope, seat, cadence, then the seat's model and,
130// for codex, its effort. The file is
131// written first; "every project" then sets the /config row, which reloads
132// this module, so the status that follows may not print.
133// The setup dialog's outcome: a reply to print, or the file written and
134// whether the /config row for every project still has to be switched on. The
135// hook makes that settings call itself: the directory reads a config.set only
136// when it sits in the hook with its own engine and a fixed key.
137type SetupOutcome = { readonly text: string } | { readonly turnRowOn: boolean }
138
139async function setupHeadsUp($: EngineInterface, state: PaneState, settings: PaneOptions): Promise<SetupOutcome> {
140 const ask = (question: string, options: string[]) => $.ui.ask(question, { header: 'Heads-up', options }).catch(() => undefined)
141 const closed = { text: 'Setup closed; nothing changed.' }
142 const scope = await ask(SCOPE_QUESTION, [SCOPE.project, SCOPE.all, SCOPE.off])
143 if (scope === undefined) return closed
144 const file = await headsUpFile($)
145 if (scope === SCOPE.off) {
146 await $.fs.write(file.path, withEnabled(file.text, false))
147 return { turnRowOn: false }
148 }
149 if (scope !== SCOPE.project && scope !== SCOPE.all) return { text: `Setup closed: ${JSON.stringify(scope)} is not one of the choices; nothing changed.` }
150 // The council's own discovery, so the seats offered are the ones this machine can run.
151 const discovered = await seatInfo($, 'discover')
152 if (discovered.exitCode !== 0) return { text: `Setup closed: seat discovery exited ${discovered.exitCode}: ${discovered.stderr.trim()}; nothing changed.` }
153 const seatAnswer = await ask(SEAT_QUESTION, seatOptions(seatsFromDiscovery(discovered.stdout)))
154 if (seatAnswer === undefined) return closed
155 const everyAnswer = await ask(EVERY_QUESTION, [...EVERY_LABELS])
156 if (everyAnswer === undefined) return closed
157 const chosen = seatFromAnswer(seatAnswer)
158 if ('why' in chosen) return { text: `Setup closed: ${chosen.why}; nothing changed.` }
159 const { seat } = chosen
160 const unknown = await notASeat($, seat)
161 if (unknown !== undefined) return { text: `Setup closed: ${unknown}; nothing changed.` }
162 const every = everyFromAnswer(everyAnswer)
163 if ('why' in every) return { text: `Setup closed: ${every.why}; nothing changed.` }
164 // The seat's model; codex also takes an effort, from its own catalog.
165 const lookup = await seatInfo($, 'model', seat)
166 if (lookup.exitCode !== 0) return { text: `Setup closed: reading ${seat}'s model exited ${lookup.exitCode}: ${lookup.stderr.trim()}; nothing changed.` }
167 const current = lookup.stdout.trim()
168 const catalog = seat === 'codex' ? await readCatalog($) : undefined
169 const slugs = catalog !== undefined && 'models' in catalog ? catalog.models.filter(m => m.listed).map(m => m.slug) : undefined
170 const modelAnswer = await ask(MODEL_QUESTION(seat), modelOptions(current, slugs))
171 if (modelAnswer === undefined) return closed
172 const model = modelFromAnswer(modelAnswer)
173 let pick: SeatPick = model === undefined ? {} : { model }
174 if (seat === 'codex' && catalog !== undefined && 'models' in catalog) {
175 const entry = catalog.models.find(m => m.slug === (model ?? current))
176 const effortAnswer = await ask(EFFORT_QUESTION, effortOptions(entry?.efforts ?? [], entry?.defaultEffort ?? ''))
177 if (effortAnswer === undefined) return closed
178 const effort = effortFromAnswer(effortAnswer)
179 if ('why' in effort) return { text: `Setup closed: ${effort.why}; nothing changed.` }
180 if (effort.effort !== undefined) pick = { ...pick, effort: effort.effort }
181 }
182 // "Keep <current>" with no effort is no pick at all: the file's own model
183 // stays, and withEnabled drops it only when the seat changed.
184 await $.fs.write(file.path, withEnabled(file.text, scope === SCOPE.project ? true : undefined, seat, every.every, Object.keys(pick).length === 0 ? undefined : pick))
185 state.headsUpTip = ''
186 return { turnRowOn: scope === SCOPE.all && !settings.headsUp }
187}
188
189// What /heads-up status prints, from the project file as it stands.
190async function readHeadsUpStatus($: EngineInterface, rowOn: boolean): Promise<HeadsUpStatus> {
191 const { text } = await headsUpFile($)
192 return headsUpStatus(parseConfig(text, rowOn), rowOn, text, parseCounts(await $.store.get(COUNTS_KEY)), parseTokens(await $.store.get(TOKENS_KEY)), storedSession(await read($, headsUp)).paused)
193}
194
195// The status as the command's reply; mid-turn the reply waits for the turn to
196// end, so a toast carries its one-line form at once.
197async function headsUpReply($: EngineInterface, state: PaneState, rowOn: boolean): Promise<string> {
198 const status = await readHeadsUpStatus($, rowOn)
199 if (state.turnInFlight) $.ui.toast(toastLine(status), { timeoutMs: 8000 })
200 return statusText(status)
201}
202
203// Once per install, while the check is off: the store flag is shared by every session.
204async function introduceHeadsUp($: EngineInterface, state: PaneState, settings: PaneOptions): Promise<void> {
205 const intro = introTail({ shown: (await $.store.get(HEADS_UP_INTRO_KEY)) === true, enabled: (await readHeadsUpConfig($, state, settings)).enabled })
206 if (intro.tail !== undefined) {
207 state.headsUpTip = intro.tail
208 $.ui.invalidate('ui.render')
209 }
210 if (intro.markShown) await $.store.set(HEADS_UP_INTRO_KEY, true)
211}
212
213// Submits the wake prompt once the job's record says completed. A job that
214// failed, or whose record never settles, wakes nobody: the prompt would send
215// the model to fetch a result that is not there.
216async function wakeWhenFetchable($: EngineInterface, state: PaneState): Promise<void> {
217 const pending = state.pendingWake
218 if (!pending) return
219 const outcome = jobOutcome(await readText(files($), pending.jobFile))
220 if (outcome === 'running' && (await $.clock.now()) < pending.untilMs) return
221 state.pendingWake = undefined
222 if (outcome === 'completed') await $.prompt.submit({ text: pending.prompt })
223 else $.ui.log(`council job record ${pending.jobFile} did not complete (${outcome}); no wake prompt sent`)
224}
225
226// .done comes from the run's EXIT trap, which a SIGKILL skips. A run whose
227// process is gone and that left no .done will never write one; without this
228// the pane would follow it for the rest of the session and see no later run.
229// lastCheck: which clock throttles the check, so the council run and the
230// heads-up worker are each asked at the pid cadence.
231async function runHasDied($: EngineInterface, state: PaneState, runDir: string, now: number, lastCheck: 'pidCheckedAtMs' | 'headsUpCheckedAtMs' = 'pidCheckedAtMs'): Promise<boolean> {
232 if (now - state[lastCheck] < PID_CHECK_MS) return false
233 state[lastCheck] = now
234 const pid = runPid(await readText(files($), `${runDir}/pid`))
235 if (!pid) return false
236 const alive = await $.process.run(['kill', '-0', pid])
237 if (alive.exitCode === 0) return false
238 // The trap writes .done and then the process goes: look once more, so a run
239 // that ended normally between the two reads is not called dead.
240 return !(await $.fs.exists(`${runDir}/.done`))
241}
242
243async function poll($: EngineInterface, state: PaneState, settings: PaneOptions): Promise<void> {
244 // Temp cleaners remove the root under a long session; runs find it again
245 // only if it exists, so it is put back rather than reported.
246 if (!(await $.fs.exists(state.root))) {
247 await $.fs.write(`${state.root}/.keep`, '')
248 state.runDir = undefined
249 return
250 }
251 const now = await $.clock.now()
252 state.nowMs = now
253 if (state.finished && !noticeIsLive(state.finished, now)) {
254 state.finished = undefined
255 $.ui.invalidate('ui.render')
256 }
257 if (state.pendingWake) await wakeWhenFetchable($, state)
258 if (!state.runDir) {
259 const name = unseenRun(await $.fs.list(state.root), state.shown)
260 if (!name) return
261 state.shown.add(name)
262 state.runDir = `${state.root}/${name}`
263 state.synthesis = undefined
264 state.finished = undefined
265 state.queryingSinceMs = {}
266 state.closed = new Set()
267 state.runStartedMs = now
268 state.fitted.clear()
269 await $.ui.open({ id: PANE_ID, title: 'Council' })
270 }
271 const runDir = state.runDir
272 state.view = await readView(files($), runDir)
273 state.queryingSinceMs = queryingSince(state.queryingSinceMs, state.view.providers, now)
274 state.view.queryingSinceMs = state.queryingSinceMs
275 if (state.synthesis) state.view.synthesis = state.synthesis
276 // The run waits on its offer for a window of seconds; the offer file going
277 // away (accepted, declined or expired) withdraws the buttons.
278 const offer = parseRetryOffer(await readText(files($), `${runDir}/retry-offer`))
279 if (!offer) state.retry = undefined
280 else if (!state.retry) state.retry = { offer, seenAtMs: now }
281 state.retryShown = state.retry ? retrySection(state.retry.offer, state.retry.seenAtMs, now) : undefined
282 const text = JSON.stringify([state.view, state.retryShown])
283 if (text !== state.drawn) {
284 state.drawn = text
285 $.ui.invalidate('ui.render')
286 }
287 const hasDied = !state.view.isDone && (await runHasDied($, state, runDir, now))
288 // A dead run is drawn as over: the clocks stop and the summary leads.
289 if (hasDied) state.view = { ...state.view, isDone: true }
290 // The run is over once .done lands: its dir is removed so the next run is
291 // picked up, and the pane keeps the last view until the person closes it.
292 if (state.view.isDone) {
293 // A toast is one unstyled line for four seconds, easy to miss under a
294 // streaming reply; the band holds the notice where the offer was.
295 // The run's dir is visible before the run writes its job files, so they
296 // are read now, when they are certain to be there.
297 const jobId = (await readText(files($), `${runDir}/job-id`)).trim()
298 const notice = hasDied ? abandonedNotice(state.view, jobId) : finishNotice(state.view, jobId)
299 state.finished = { text: notice, untilMs: now + FINISH_NOTICE_MS, isFailure: hasDied }
300 $.ui.invalidate('ui.render')
301 // .done lands before the worker records where the result is, so the wake
302 // waits for the job record to say the result can be fetched.
303 const wake = settings.wakesOnAsyncDone && !hasDied ? wakePrompt(jobId) : undefined
304 const jobFile = (await readText(files($), `${runDir}/job-file`)).trim()
305 if (wake && jobFile) state.pendingWake = { prompt: wake, jobFile, untilMs: now + WAKE_WAIT_MS }
306 await $.process.run(['rm', '-rf', runDir])
307 state.runDir = undefined
308 state.retry = undefined
309 state.retryShown = undefined
310 }
311}
312
313// Advances the band's and the live seats' sweeps and the clock the elapsed
314// times read, only while the run is moving; an idle pane costs no redraws.
315async function animate($: EngineInterface, state: PaneState): Promise<void> {
316 const view = state.view
317 if (!view || !isMoving(view)) return
318 state.frame += 1
319 state.nowMs = await $.clock.now()
320 $.ui.invalidate('ui.render')
321}
322
323// Settles where this run's pane goes, asking once when the setting says ask
324// and nothing is remembered. A dismissed dialog or a headless run stores
325// nothing and the pane is drawn here, so the question comes back.
326async function paneHost($: EngineInterface, setting: HostSetting): Promise<PaneHost> {
327 const remembered = hostFrom(await $.store.get(HOST_STORE_KEY))
328 const decided = decideHost({ setting, remembered, isInTmux: Boolean(await $.env.get('TMUX')) })
329 if (decided !== 'ask') return decided
330 let asked: PaneHost | undefined
331 try {
332 asked = hostFrom(await $.ui.ask(HOST_QUESTION, { header: 'Council pane', options: [HOST_LABELS.mod, HOST_LABELS.tmux] }))
333 } catch {
334 asked = undefined
335 }
336 if (asked) await $.store.set(HOST_STORE_KEY, asked)
337 return asked ?? 'mod'
338}
339
340// Points the next run at this mod's pane or away from it; a Bash child reads
341// the variable when it starts, so this runs just before one does.
342// The watch root and the two timers start with the first council run, not the
343// session: a session that never convenes the council pays no polling and
344// leaves no directory behind.
345async function watchRoot($: EngineInterface): Promise<string> {
346 const tmp = ((await $.env.get('TMPDIR')) ?? '/tmp').replace(/\/+$/, '')
347 return `${tmp}/council-mod.${await $.session.id()}`
348}
349
350async function startWatching($: EngineInterface, state: PaneState, settings: PaneOptions): Promise<void> {
351 if (state.root) return
352 state.root = await watchRoot($)
353 await $.fs.write(`${state.root}/.keep`, '')
354 $.clock.every(FRAME_MS, () => { void animate($, state) })
355 $.clock.every(POLL_MS, () => { void pollOnce($, state, settings) })
356}
357
358async function aimRun($: EngineInterface, state: PaneState, settings: PaneOptions): Promise<void> {
359 await startWatching($, state, settings)
360 const host = await paneHost($, settings.host)
361 await $.env.set('COUNCIL_MOD_PANE_DIR', host === 'mod' ? state.root : undefined)
362}
363
364// Logs a line once per distinct text: a condition that persists across polls or
365// steps is told once, and told again when it changes or returns after clearing.
366function logOnChange($: EngineInterface, state: PaneState, key: 'lastFailure' | 'lastError' | 'headsUpProblem' | 'headsUpSkipped', line: string): void {
367 if (line !== '' && line !== state[key]) $.ui.log(line)
368 state[key] = line
369}
370
371// A heads-up background failure is logged once per distinct message, never dropped.
372async function logFailure($: EngineInterface, state: PaneState, work: () => Promise<void>): Promise<void> {
373 try {
374 await work()
375 state.lastFailure = ''
376 } catch (error) {
377 logOnChange($, state, 'lastFailure', `heads-up: ${String(error)}`)
378 }
379}
380
381async function pollOnce($: EngineInterface, state: PaneState, settings: PaneOptions): Promise<void> {
382 if (state.isPolling) return
383 state.isPolling = true
384 try {
385 await poll($, state, settings)
386 state.lastError = ''
387 } catch (error) {
388 // The poll repeats twice a second: a failure that persists is logged once.
389 logOnChange($, state, 'lastError', String(error))
390 } finally {
391 state.isPolling = false
392 }
393}
394
395// Every session shares the heads-up memory: a write merges the lists with
396// what another session wrote meanwhile and keeps this session's counters.
397async function loadMemory($: EngineInterface): Promise<Memory> {
398 return parseMemory(await $.store.get(STORE_KEY))
399}
400
401async function saveMemory($: EngineInterface, ours: Memory): Promise<void> {
402 await $.store.set(STORE_KEY, mergeMemory(await loadMemory($), ours))
403}
404
405async function recordAnswer($: EngineInterface, topic: string, answer: Answer): Promise<void> {
406 await saveMemory($, applyAnswer(await loadMemory($), topic, answer))
407 await count($, answer === 'typed-past' ? 'typedPast' : answer === 'turn-off' ? 'turnOff' : answer)
408}
409
410// Read, add one, write: a count, never a lock (see Counts).
411async function count($: EngineInterface, ...keys: (keyof Counts)[]): Promise<void> {
412 await $.store.set(COUNTS_KEY, bumped(parseCounts(await $.store.get(COUNTS_KEY)), ...keys))
413}
414
415// Read, add the check's tokens, write: never a lock (see Tokens).
416async function tallyTokens($: EngineInterface, result: RunResult): Promise<void> {
417 await $.store.set(TOKENS_KEY, addedTokens(parseTokens(await $.store.get(TOKENS_KEY)), result))
418}
419
420// The runner's seat questions, answered by its shipped script with fixed
421// subcommands, so the mod never hands bash an inline script.
422function seatInfo($: EngineInterface, ...args: ['discover'] | ['model' | 'allowlisted', string]) {
423 return $.process.run(['bash', `${$.plugin.root}/scripts/seat-info.sh`, ...args], { timeoutMs: SEAT_INFO_MS })
424}
425
426// The runner's own allowlist (a providers/<seat>.sh exists) decides what a
427// seat is, so no second list lives here; the refusal names the real ones.
428// Exit 1 is the refusal; any other failure is the check's own and says so.
429async function notASeat($: EngineInterface, seat: string): Promise<string | undefined> {
430 const ok = await seatInfo($, 'allowlisted', seat)
431 if (ok.exitCode === 0) return undefined
432 if (ok.exitCode !== 1) return `checking ${JSON.stringify(seat)} exited ${ok.exitCode}: ${ok.stderr.trim()}`
433 const names = (await $.fs.list(`${$.plugin.root}/scripts/providers`)).map(entry => entry.name).filter(name => name.endsWith('.sh')).map(name => name.slice(0, -3)).sort()
434 return `${JSON.stringify(seat)} is not a council seat; one of ${names.join(', ')}`
435}
436
437// The project file is the consent and the only switch; it is read at each
438// step, so turning it on or off needs no reload. A broken file is logged once.
439async function headsUpFile($: EngineInterface): Promise<{ path: string; text: string | undefined }> {
440 const path = `${await $.session.cwd()}/${CONFIG_FILE}`
441 return { path, text: (await $.fs.exists(path)) ? await $.fs.read(path) : undefined }
442}
443
444async function readHeadsUpConfig($: EngineInterface, state: PaneState, settings: PaneOptions) {
445 const config = parseConfig((await headsUpFile($)).text, settings.headsUp)
446 logOnChange($, state, 'headsUpProblem', config.enabled ? '' : config.problem ?? '')
447 return config
448}
449
450// Writes the avoid list and forks the runner, which returns once its worker
451// is detached; an exit that is not 0 leaves nothing behind and is reported.
452async function launchHeadsUp($: EngineInterface, config: Extract<HeadsUpConfig, { enabled: true }>, runDir: string, avoidFile: string): Promise<void> {
453 const args = ['--run-dir', runDir, '--session', await $.session.id(), '--seat', config.seat, '--avoid-file', avoidFile]
454 const pick = modelFile(config)
455 if (pick !== '') {
456 await $.fs.write(`${runDir}/model.json`, pick)
457 args.push('--model', `${runDir}/model.json`)
458 }
459 const run = await $.process.run(['bash', `${$.plugin.root}/scripts/heads-up.sh`, ...args], { timeoutMs: HEADS_UP_LAUNCH_MS })
460 if (run.exitCode === 0) return
461 await $.process.run(['rm', '-rf', runDir])
462 throw new Error(`heads-up.sh exited ${run.exitCode}: ${run.stderr.trim()}`)
463}
464
465// One main-loop step: decide, write the session when it changed, and launch
466// on a cadence point. The session says checking before the fork, so a step
467// that lands while the runner starts cannot launch a second check.
468async function stepHeadsUp($: EngineInterface, state: PaneState, settings: PaneOptions, step: { turnId: string; index: number }): Promise<void> {
469 const config = await readHeadsUpConfig($, state, settings)
470 // decide skips these two before reading anything else, so most steps cost
471 // one file read and nothing more.
472 if (!config.enabled || !onCadence(config.every, step.index)) return
473 const memory = await loadMemory($)
474 const now = await $.clock.now()
475 const held = await $.state.get(HEADS_UP)
476 const current = storedSession(held.value ?? FRESH_SESSION)
477 const decision = decide(config, current, memory, step, now)
478 if (decision.kind === 'skip' && decision.why === 'backoff') await saveMemory($, decision.memory)
479 if (decision.kind !== 'launch') return
480 const runDir = `${await watchRoot($)}/heads-up/${decision.checkId}`
481 // The run dir exists before the session says `checking`: a poll that lands
482 // in between would otherwise read a dir that is not there yet as a run
483 // that vanished, and idle the session under the launch.
484 const avoidFile = `${runDir}/avoid.txt`
485 await $.fs.write(avoidFile, avoidList(memory))
486 const session: Session = { ...current, phase: { kind: 'checking', turnId: step.turnId, checkId: decision.checkId, runDir, startedMs: now, resumes: current.resumes } }
487 // A press or a poll wrote in between: this step's reading is stale, and
488 // the next step decides again on the new session.
489 const written = await $.state.set(HEADS_UP, session, { ifVersion: held.version })
490 if (!written.isSet) {
491 await $.process.run(['rm', '-rf', runDir])
492 return
493 }
494 watchHeadsUp($, state)
495 try {
496 await launchHeadsUp($, config, runDir, avoidFile)
497 } catch (error) {
498 await update($, headsUp, (s): Session => (s.phase.kind === 'checking' && s.phase.checkId === decision.checkId ? { ...s, phase: { kind: 'idle' } } : s))
499 // A check that never started is a failed check to the person: red above the prompt, counted as one, and logged by the caller.
500 state.headsUpFailure = { text: `heads-up: failed · ${String(error)}`, untilMs: now + FINISH_NOTICE_MS, isFailure: true }
501 $.ui.invalidate('ui.render')
502 await count($, 'failed')
503 await tallyTokens($, { kind: 'failed', payloadBytes: 0, seats: [] })
504 throw error
505 }
506}
507
508// The heads-up check polls on its own timer, so a check starts none of the
509// council's: started at a launch, and again at session.start when a reload
510// finds a check in flight. It stops once nothing is checking and no failure
511// notice is left to expire.
512function watchHeadsUp($: EngineInterface, state: PaneState): void {
513 if (state.headsUpTimer) return
514 state.headsUpTimer = $.clock.every(POLL_MS, () => { void logFailure($, state, () => headsUpTick($, state)) })
515}
516
517async function headsUpTick($: EngineInterface, state: PaneState): Promise<void> {
518 if (state.isPollingHeadsUp) return
519 state.isPollingHeadsUp = true
520 try {
521 const now = await $.clock.now()
522 if (state.headsUpFailure && !noticeIsLive(state.headsUpFailure, now)) {
523 state.headsUpFailure = undefined
524 $.ui.invalidate('ui.render')
525 }
526 const phase = (await read($, headsUp)).phase
527 if (phase.kind === 'checking') await pollHeadsUp($, state, phase, now)
528 else if (!state.headsUpFailure) {
529 state.headsUpTimer?.cancel()
530 state.headsUpTimer = undefined
531 }
532 } finally {
533 state.isPollingHeadsUp = false
534 }
535}
536
537// A result once .done lands, or a failure when the worker or its dir is gone
538// without one. Every check's dir is removed.
539async function pollHeadsUp($: EngineInterface, state: PaneState, phase: Extract<Session['phase'], { kind: 'checking' }>, now: number): Promise<void> {
540 const { runDir, checkId } = phase
541 const lost = (detail: string): RunResult => ({ kind: 'failed', payloadBytes: 0, seats: [{ seat: 'runner', outcome: 'error', elapsedMs: now - phase.startedMs, detail }] })
542 let result: RunResult
543 if (await $.fs.exists(`${runDir}/.done`)) result = parseRunResult(checkId, await readText(files($), `${runDir}/result.json`))
544 else if (!(await $.fs.exists(runDir))) result = lost(`its run dir ${runDir} is gone`)
545 else if (await runHasDied($, state, runDir, now, 'headsUpCheckedAtMs')) result = lost('heads-up.sh stopped without writing a result')
546 else return
547 // settle reads memory only to spot a repeated note.
548 const memory = result.kind === 'note' ? await loadMemory($) : EMPTY_MEMORY
549 const settled = await update($, headsUp, s => (s.phase.kind === 'checking' && s.phase.checkId === checkId ? settle(storedSession(s), memory, result) : s))
550 if (result.kind === 'failed') {
551 $.ui.log(checkLine(result))
552 state.headsUpFailure = { text: checkLine(result), untilMs: now + FINISH_NOTICE_MS, isFailure: true }
553 $.ui.invalidate('ui.render')
554 }
555 if (result.kind === 'none') {
556 state.headsUpReceipt = receiptLine(result)
557 $.ui.invalidate('ui.render')
558 }
559 // Told once, here: the pause stops every later check, and its red row reads
560 // the session. A check launched before /heads-up on paused nothing, so it says nothing.
561 if (result.kind === 'quota' && settled.paused !== null) {
562 $.ui.log(checkLine(result))
563 $.ui.invalidate('ui.render')
564 }
565 // Nobody to warn is not a fault: one log line per reason, no band, no outcome counted.
566 logOnChange($, state, 'headsUpSkipped', result.kind === 'skipped' ? checkLine(result) : '')
567 const drawn = settled.phase.kind === 'showing' && settled.phase.note.id === checkId
568 if (result.kind !== 'skipped') {
569 await count($, result.kind !== 'note' ? result.kind : drawn ? 'notes' : 'repeats')
570 await tallyTokens($, result)
571 }
572 await $.process.run(['rm', '-rf', runDir])
573}
574
575// A press on the band: the session moves, and the shown topic is recorded.
576// Tell Claude puts a draft in the prompt box, as the builtin does, so the
577// person sees what Claude will get and sends it themselves; nothing is hidden
578// and nothing is sent. A box that cannot take it (a dialog up, headless) is
579// reported once, since the note is gone by then.
580async function pressHeadsUp($: EngineInterface, answer: Exclude<Answer, 'typed-past'>): Promise<void> {
581 const shown: { note?: Note } = {}
582 await update($, headsUp, s => {
583 shown.note = s.phase.kind === 'showing' ? s.phase.note : undefined
584 return pressed(s, answer)
585 })
586 if (shown.note === undefined) return
587 await recordAnswer($, shown.note.topic, answer)
588 if (answer === 'turn-off') {
589 const file = await headsUpFile($)
590 await $.fs.write(file.path, withEnabled(file.text, false))
591 $.ui.log(`heads-up: off for this project (${CONFIG_FILE}); /${HEADS_UP_COMMAND} on turns it back on`)
592 return
593 }
594 if (answer !== 'tell') return
595 const filled = await $.prompt.fill({ text: tellClaudeDraft(shown.note), mode: 'replace' })
596 if (!filled.isFilled) throw new Error(`the prompt box did not take the note: ${tellClaudeDraft(shown.note)}`)
597}
598
599// The person's own prompt while a note shows: it is typed past.
600async function personSubmitted($: EngineInterface): Promise<void> {
601 const seen: { topic?: string } = {}
602 await update($, headsUp, s => {
603 seen.topic = s.phase.kind === 'showing' ? s.phase.note.topic : undefined
604 return typedPast(s)
605 })
606 if (seen.topic !== undefined) await recordAnswer($, seen.topic, 'typed-past')
607}
608
609// The pause row's Dismiss: the row goes, the session stays paused.
610function dismissPause($: EngineInterface, state: PaneState): void {
611 void logFailure($, state, async () => {
612 await update($, headsUp, s => acknowledgePause(storedSession(s)))
613 })
614}
615
616// Turn off takes two presses, as the builtin's Disable does: the first arms it
617// for this note, any other press disarms it.
618function headsUpPresses($: EngineInterface, state: PaneState, noteId: string): Record<Exclude<Answer, 'typed-past'>, () => void> {
619 const press = (answer: Exclude<Answer, 'typed-past'>) => () => {
620 state.headsUpTurnOffArmed = ''
621 void logFailure($, state, () => pressHeadsUp($, answer))
622 }
623 const turnOff = () => {
624 if (state.headsUpTurnOffArmed === noteId) return press('turn-off')()
625 state.headsUpTurnOffArmed = noteId
626 $.ui.invalidate('ui.render')
627 }
628 return { learn: press('learn'), tell: press('tell'), knew: press('knew'), understood: press('understood'), dismiss: press('dismiss'), 'turn-off': turnOff }
629}
630
631// The note, in the shape of Claude Code's own heads-up: the mark in the
632// council colour, the tag bold, the sentence plain and wrapped under its
633// first word, then the choices drawn plain (`1: Learn more`, as a survey's row) with
634// the seat line dimmed after them. A narrow pane cuts the seat line, never a choice.
635function headsUpRow(
636 ui: Pick<Elements['terminal'], 'Box' | 'Button' | 'Text'>,
637 band: BandView,
638 press: Record<Exclude<Answer, 'typed-past'>, () => void>,
639 turnOffArmed: boolean,
640) {
641 const { more } = band
642 const turnOff = <ui.Button key="heads-up:turn-off" hotkey="3" label={turnOffArmed ? 'Press again to turn off' : 'Turn off'} plain dimColor onPress={press['turn-off']} />
643 // Collapsed: Learn more, Knew this already, Dismiss. Expanded: Understood, Tell Claude, Close.
644 const [first, second, last] = more === null
645 ? [
646 <ui.Button key="heads-up:learn" hotkey="1" label="Learn more" plain onPress={press.learn} />,
647 <ui.Button key="heads-up:knew" hotkey="2" label="Knew this already" plain onPress={press.knew} />,
648 <ui.Button key="heads-up:dismiss" hotkey="0" label="Dismiss" plain role="dismiss" onPress={press.dismiss} />,
649 ]
650 : [
651 <ui.Button key="heads-up:understood" hotkey="1" label="Understood" plain onPress={press.understood} />,
652 <ui.Button key="heads-up:tell" hotkey="2" label="Tell Claude" plain onPress={press.tell} />,
653 <ui.Button key="heads-up:close" hotkey="0" label="Close" plain role="dismiss" onPress={press.dismiss} />,
654 ]
655 return (
656 <ui.Box key="heads-up" flexDirection="column" marginTop={1} paddingLeft={BAND_INDENT}>
657 <ui.Box flexDirection="row">
658 <ui.Box flexShrink={0}><ui.Text bold color={COLOR.onFill} backgroundColor={FILL.orange}>{` ${tagMark(band.tag)} `}</ui.Text><ui.Text>{' '}</ui.Text></ui.Box>
659 <ui.Box flexGrow={1} flexShrink={1} flexDirection="column">
660 <ui.Text wrap="wrap"><ui.Text bold>{band.tag}</ui.Text>{` \u00b7 ${band.headline}`}</ui.Text>
661 {more !== null && (
662 <ui.Box flexDirection="column" marginTop={1} marginBottom={1}>
663 {more.title !== '' && <ui.Text bold wrap="wrap">{more.title}</ui.Text>}
664 {more.points.map((point, at) => (
665 <ui.Text key={`heads-up:point:${at}`} wrap="wrap" bold={at === more.points.length - 1}>{`- ${point}`}</ui.Text>
666 ))}
667 </ui.Box>
668 )}
669 <ui.Box flexDirection="row">
670 <ui.Box flexShrink={0} flexDirection="row">
671 {first}
672 <ui.Text>{' '}</ui.Text>
673 {second}
674 <ui.Text>{' '}</ui.Text>
675 {turnOff}
676 <ui.Text>{' '}</ui.Text>
677 {last}
678 </ui.Box>
679 <ui.Box flexShrink={1}>
680 <ui.Text color={COLOR.hint} wrap="truncate-end">{` ${band.meta}`}</ui.Text>
681 </ui.Box>
682 </ui.Box>
683 </ui.Box>
684 </ui.Box>
685 </ui.Box>
686 )
687}
688
689// The pause, red as a failed check is, on one row: a narrow pane cuts the
690// seat's words, never the choice, drawn plain as the note's are.
691function pausedRow(ui: Pick<Elements['terminal'], 'Box' | 'Button' | 'Text'>, paused: Paused, dismiss: () => void) {
692 return (
693 <ui.Box key="heads-up-paused" flexDirection="row" marginTop={1} paddingLeft={BAND_INDENT}>
694 <ui.Box flexShrink={1}>
695 <ui.Text bold color={COLOR.danger} wrap="truncate-end">{`\u2717 ${pausedLine(paused)}`}</ui.Text>
696 </ui.Box>
697 <ui.Box flexShrink={0}>
698 <ui.Text>{' '}</ui.Text>
699 <ui.Button key="heads-up-paused:dismiss" hotkey="0" label="Dismiss" plain role="dismiss" onPress={dismiss} />
700 </ui.Box>
701 </ui.Box>
702 )
703}
704
705// A band's head: the run's state as a glyph and a word in the state's colour,
706// then the COUNCIL label in bold. Plain text, so it draws alike in every terminal.
707function bandHead(ui: Pick<Elements['terminal'], 'Box' | 'Text'>, key: string, glyph: string, word: string, color: string) {
708 return (
709 <ui.Box key={key} flexDirection="row" flexShrink={0}>
710 <ui.Text color={color}>{`${glyph} ${word}`}</ui.Text>
711 <ui.Text bold>{' COUNCIL'}</ui.Text>
712 </ui.Box>
713 )
714}
715
716// A row's press is a marker query-council.sh polls for while it waits on its
717// seats: cancel/<seat> ends a seat that is out, and the row reads cancelling
718// until the run logs it; retry/<seat> re-queries a seat the run offers in
719// retriable/, and the row reads retrying until the run relaunches it.
720function pressSeat($: EngineInterface, state: PaneState, press: 'cancel' | 'retry', name: string): void {
721 const runDir = state.runDir
722 if (!runDir) return
723 void $.fs.write(`${runDir}/${press}/${name}`, '').catch((err: unknown) => $.ui.log(`${press} ${name}: ${String(err)}`))
724}
725
726// One marker per seat; the run cancels them one by one, as it would rows
727// pressed in turn. A press reads the seats again, since one may have
728// answered since the band or the pane was drawn.
729function cancelAll($: EngineInterface, state: PaneState): void {
730 if (state.view) for (const name of seatsToCancel(state.view)) pressSeat($, state, 'cancel', name)
731}
732
733// A section header's press: close it if open, open it if closed.
734function toggleSection($: EngineInterface, state: PaneState, fold: string): void {
735 if (!state.closed.delete(fold)) state.closed.add(fold)
736 $.ui.invalidate('ui.render')
737}
738
739function retryPresses($: EngineInterface, runDir: string) {
740 return {
741 accept: () => { void $.process.run(['mv', '-f', `${runDir}/retry-offer`, `${runDir}/.retry`]) },
742 skip: () => { void $.fs.write(`${runDir}/.retry-declined`, '') },
743 }
744}
745
746// The offer's two buttons and its countdown. The keys work once the person has
747// given the site the keyboard (a click, ctrl+x tab); a click works at any time.
748function retryRow(
749 ui: Pick<Elements['terminal'], 'Box' | 'Button' | 'Text'>,
750 offer: RetrySection,
751 press: { accept: () => void; skip: () => void },
752) {
753 return (
754 <ui.Box key="retry" flexDirection="row" marginTop={1} paddingLeft={BAND_INDENT}>
755 {/* Only the notice and the how-to give way when narrow. */}
756 {bandHead(ui, 'head', '\u2717', 'retry', COLOR.danger)}
757 <ui.Box flexShrink={1}>
758 <ui.Text bold color={COLOR.danger} wrap="truncate-end">{` ${offer.notice} `}</ui.Text>
759 </ui.Box>
760 <ui.Box flexShrink={0} flexDirection="row">
761 {/* No letters in the labels: r and s answer only once the band holds the focus. */}
762 <ui.Button key="retry:accept" hotkey="r" label="retry" onPress={press.accept} />
763 <ui.Text>{' '}</ui.Text>
764 <ui.Button key="retry:skip" hotkey="s" label="skip" onPress={press.skip} />
765 <ui.Text color={COLOR.accent}>{` ${offer.bar}`}</ui.Text>
766 <ui.Text dimColor>{` ${offer.remaining}s`}</ui.Text>
767 </ui.Box>
768 <ui.Box flexShrink={1}>
769 <ui.Text dimColor wrap="truncate-end">{' click, or ctrl+x tab then r / s'}</ui.Text>
770 </ui.Box>
771 </ui.Box>
772 )
773}
774
775export const register: Register = (on, options) => {
776 const settings = paneOptions(options)
777 const state: PaneState = { root: '', drawn: '', isPolling: false, shown: new Set(), lastError: '', pidCheckedAtMs: 0, headsUpCheckedAtMs: 0, isPollingHeadsUp: false, headsUpProblem: '', lastFailure: '', headsUpTip: '',
778 turnInFlight: false, headsUpReceipt: '', headsUpSkipped: '', headsUpTurnOffArmed: '', frame: 0, nowMs: 0, queryingSinceMs: {}, closed: new Set(), fitted: new Map(), tableFit: { columns: 0, byText: new Map() } }
779
780 on('session.start', async ($, e, next) => {
781 await $.command.register({ name: REOPEN_COMMAND, description: 'Reopen the council pane, or forget where it was told to open', argumentHint: '[ask]', immediate: true })
782 await $.command.register({ name: HEADS_UP_COMMAND, description: 'Heads-up side-check: set it up in a few questions, switch it on for this project naming the seat, or off, or show its state and counts', argumentHint: '[setup | on [seat] | off | status]', immediate: true })
783 if (settings.offersTool) await $.tool.register({ name: TOOL_NAME, description: TOOL_DESCRIPTION, inputSchema: TOOL_SCHEMA })
784 void logFailure($, state, () => introduceHeadsUp($, state, settings))
785 // A reload drops the heads-up timer; a check still in flight needs it back.
786 if ((await read($, headsUp)).phase.kind === 'checking') watchHeadsUp($, state)
787 // Nothing after depends on these, so the request is not held up for them.
788 void Promise.all(SPECIALIST_STORE_KEYS.map(key => $.store.delete(key))).catch((err: unknown) => $.ui.log(`store cleanup: ${String(err)}`))
789 return next(e)
790 })
791
792 // The synthesis is written into the reply after the run ends; nothing on disk
793 // holds it, so it is lifted from the main loop's final message.
794 on('turn.complete', async ($, e, next) => {
795 // Cleared first, so a later hook that throws cannot leave it set.
796 if (e.agentId === undefined) state.turnInFlight = false
797 const result = await next(e)
798 const view = state.view
799 const synthesis = e.agentId === undefined && view && !state.synthesis ? extractSynthesis(e.answer) : undefined
800 if (view && synthesis) {
801 state.synthesis = synthesis
802 state.view = { ...view, synthesis }
803 // The answers close so the synthesis reads near the top; each opens again on a press.
804 state.closed = new Set(seatFolds(paneSections(state.view)))
805 state.drawn = JSON.stringify([state.view, state.retryShown])
806 $.ui.invalidate('ui.render')
807 }
808 return result
809 })
810
811 // The heads-up check rides the main loop's steps. The request goes first and
812 // is never held up: the check's own work runs beside it.
813 on('turn.step', async function* ($, e, next) {
814 const response = next(e)
815 if (e.agentId === undefined) {
816 state.turnInFlight = true
817 const step = { turnId: e.turnId, index: e.index }
818 void logFailure($, state, () => stepHeadsUp($, state, settings, step))
819 }
820 return yield* response
821 })
822
823 // Only the person's own prompt types past a note; a plugin's submit or a
824 // notification does not.
825 on('prompt.submit', async ($, e, next) => {
826 if (e.origin.kind === 'composer' || e.origin.kind === 'bridge') await logFailure($, state, () => personSubmitted($))
827 return next(e)
828 })
829
830 on('tool.call', { tool: 'Bash' }, async ($, e, next) => {
831 if (isCouncilRun(e.command)) await aimRun($, state, settings)
832 return next(e)
833 })
834
835 // The settings row says ask while an answer is remembered; its label says which.
836 on('config.describe', async ($, e, next) => {
837 const row = await next(e)
838 if (!e.key.endsWith('.pane_host')) return row
839 return { ...row, label: hostRowLabel(row.label, settings.host, hostFrom(await $.store.get(HOST_STORE_KEY))) }
840 })
841
842 // The generated types list the tools connected when they were written, so a
843 // tool registered at run time is matched by pattern.
844 on('tool.call', { tool: /^mcp__claude-council__ask$/ }, async ($, e) => {
845 // `e` is flat: the tool's input fields sit beside `tool` and `tool_use_id`.
846 // Its declared type is the union of the listed tools, none of them this one.
847 const input = e as unknown as Record<string, unknown>
848 const parsed = councilArgs(input)
849 if ('deny' in parsed) return { deny: parsed.deny }
850 const script = `${$.plugin.root}/scripts/run-council.sh`
851 if (!(await $.fs.exists(script))) return { deny: `council script not found at ${script}` }
852 // The question goes to third-party providers, so the user confirms every
853 // call; this gate holds even where the tool itself needs no permission.
854 let answer: string | undefined
855 try {
856 answer = await $.ui.ask(confirmQuestion(input), { header: 'Council', options: [SEND_LABEL, KEEP_LABEL] })
857 } catch {
858 answer = undefined
859 }
860 const outcome = confirmOutcome(answer)
861 if ('deny' in outcome) return { deny: outcome.deny }
862 if ('reply' in outcome) return { result: outcome.reply }
863 await aimRun($, state, settings)
864 const run = await $.process.run(['bash', script, ...parsed.args], { timeoutMs: RUN_TIMEOUT_MS })
865 const saved = run.stdout.trim().split('\n').pop() ?? ''
866 if (run.exitCode !== 0 || !saved) return { result: run.stderr || 'council run failed', isError: true }
867 return { result: await $.fs.read(saved) }
868 })
869
870 on('command.run', { command: HEADS_UP_COMMAND }, async ($, e) => {
871 const command = headsUpCommand(e.args)
872 if (command.action === 'unknown') return { text: `${command.why}. Usage: /${HEADS_UP_COMMAND} [on [seat] | off | setup | status]; one seat, a provider name such as codex, gemini or grok-cli.` }
873 if (command.action === 'setup') {
874 const outcome = await setupHeadsUp($, state, settings)
875 if ('text' in outcome) return outcome
876 if (outcome.turnRowOn) {
877 const written = await $.config.set({ key: 'claude-council.heads_up', value: true })
878 if (written.deny) return { text: `The file is written, but the /config row was refused: ${written.deny}` }
879 return { text: await headsUpReply($, state, true) }
880 }
881 } else if (command.action !== 'status') {
882 const unknown = command.action === 'on' && command.seat !== undefined ? await notASeat($, command.seat) : undefined
883 if (unknown !== undefined) return { text: `${unknown}; nothing changed.` }
884 const file = await headsUpFile($)
885 await $.fs.write(file.path, withEnabled(file.text, command.action === 'on', command.action === 'on' ? command.seat : undefined))
886 // On is the one way to resume a session the seat's credits paused; off leaves the pause.
887 if (command.action === 'on') {
888 await update($, headsUp, s => {
889 const current = storedSession(s)
890 return { ...current, paused: null, resumes: current.resumes + 1 }
891 })
892 }
893 state.headsUpTip = ''
894 }
895 return { text: await headsUpReply($, state, settings.headsUp) }
896 })
897
898 on('command.run', { command: REOPEN_COMMAND }, async ($, e) => {
899 const command = paneCommand(e.args)
900 if (command.action === 'forget') {
901 await $.store.delete(HOST_STORE_KEY)
902 return { text: 'Forgotten. With the setting on ask, the next council run inside tmux asks where to open its pane.' }
903 }
904 if (command.action === 'unknown') return { text: 'Usage: /council-pane [ask]. Choose the pane in /config, row "Pane opens in".' }
905 if (state.view) await $.ui.open({ id: PANE_ID, title: 'Council' })
906 return { text: reopenReply(state.view !== undefined) }
907 })
908
909 // The intro rides the dim hint under the prompt while it is empty; the
910 // first typed character retires it for good.
911 on('ui.render', { component: 'PromptHint' }, async ($, e, next) => {
912 const tail = state.headsUpTip !== '' ? state.headsUpTip : state.headsUpReceipt
913 if (tail === '') return next(e)
914 if (e.props.isDraft) {
915 state.headsUpTip = ''
916 state.headsUpReceipt = ''
917 return next(e)
918 }
919 return next({ ...e, props: { ...e.props, tail } })
920 })
921
922 on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
923 // The band sits on the prompt, so the offer stays in view however far the
924 // pane has scrolled; a survey owns the band while it runs.
925 const retry = state.retryShown
926 const runDir = state.runDir
927 if (e.props.hasSurvey) return next(e)
928 const finished = state.finished
929 if (finished && !retry) {
930 const ui = $.ui.resolve(e)
931 return (
932 <ui.Box key="finished" flexDirection="row" marginTop={1} paddingLeft={BAND_INDENT}>
933 {finished.isFailure ? bandHead(ui, 'head', '\u2717', 'failed', COLOR.danger) : bandHead(ui, 'head', '\u2713', 'done', COLOR.success)}
934 {/* Only the notice gives way when narrow, so the buttons stay on the line. */}
935 <ui.Box flexShrink={1}>
936 <ui.Text bold wrap="truncate-end" {...(finished.isFailure ? { color: COLOR.danger } : {})}>{` ${finished.text} `}</ui.Text>
937 </ui.Box>
938 <ui.Button key="finished:open" hotkey="o" label="open pane" onPress={() => { void $.ui.open({ id: PANE_ID, title: 'Council' }) }} />
939 <ui.Text>{' '}</ui.Text>
940 <ui.Button
941 key="finished:dismiss"
942 hotkey="x"
943 label="dismiss"
944 onPress={() => {
945 state.finished = undefined
946 $.ui.invalidate('ui.render')
947 }}
948 />
949 </ui.Box>
950 )
951 }
952 if (retry && runDir) return retryRow($.ui.resolve(e), retry, retryPresses($, runDir))
953 const failure = state.headsUpFailure
954 if (failure) {
955 const ui = $.ui.resolve(e)
956 return (
957 <ui.Box key="heads-up-failure" flexDirection="row" marginTop={1} paddingLeft={BAND_INDENT}>
958 <ui.Text bold color={COLOR.danger}>{`\u2717 ${failure.text} `}</ui.Text>
959 <ui.Button
960 key="heads-up-failure:dismiss"
961 hotkey="x"
962 label="dismiss"
963 onPress={() => {
964 state.headsUpFailure = undefined
965 $.ui.invalidate('ui.render')
966 }}
967 />
968 </ui.Box>
969 )
970 }
971 // A note is one row and time-sensitive: the progress band waits for its
972 // answer. Reading the session here subscribes the band to its changes.
973 const session = storedSession(await read($, headsUp))
974 if (session.paused !== null && !session.paused.acknowledged) return pausedRow($.ui.resolve(e), session.paused, () => dismissPause($, state))
975 const band = bandView(session.phase)
976 if (band) return headsUpRow($.ui.resolve(e), band, headsUpPresses($, state, band.id), state.headsUpTurnOffArmed === band.id)
977 const view = state.view
978 const progress = view ? progressBand(view, state.runStartedMs, state.nowMs, state.frame) : undefined
979 if (!view || !progress) return next(e)
980 const ui = $.ui.resolve(e)
981 return (
982 <ui.Box key="progress" flexDirection="row" marginTop={1} paddingLeft={BAND_INDENT}>
983 {/* Only the event gives way when narrow. */}
984 {bandHead(ui, 'head', '\u25cf', 'running', COLOR.accent)}
985 <ui.Box flexShrink={0}>
986 <ui.Text>
987 <ui.Text color={COLOR.accent}>{` ${progress.bar}`}</ui.Text>
988 {progress.clock ? <ui.Text dimColor>{` ${progress.clock}`}</ui.Text> : null}
989 </ui.Text>
990 </ui.Box>
991 <ui.Box flexGrow={1} flexShrink={1}>
992 <ui.Text color={COLOR.hint} wrap="truncate-end">{` ${progress.event} `}</ui.Text>
993 </ui.Box>
994 {seatsToCancel(view).length > 0 && (
995 <ui.Box flexShrink={0}>
996 <ui.Button key="progress:cancel" hotkey="c" label="cancel all" onPress={() => cancelAll($, state)} />
997 <ui.Text>{' '}</ui.Text>
998 </ui.Box>
999 )}
1000 <ui.Box flexShrink={0}>
1001 <ui.Button key="progress:open" hotkey="o" label="open pane" onPress={() => { void $.ui.open({ id: PANE_ID, title: 'Council' }) }} />
1002 </ui.Box>
1003 </ui.Box>
1004 )
1005 })
1006
1007 on('ui.render', { component: 'Pane' }, ($, e, next) => {
1008 if (e.requestId !== PANE_ID || !state.view) return next(e)
1009 const { Box, Button, Markdown, Text } = $.ui.resolve(e)
1010 const columns = e.props.bodyColumns
1011 // Answers are rewritten for this width before the pane's text budget is
1012 // counted, which only a render can do: it alone knows the width. The
1013 // rewrites of the last frame are reused while the width holds, and only
1014 // the ones this frame asked for are kept.
1015 const lastFits = state.tableFit.columns === columns ? state.tableFit.byText : new Map<string, string>()
1016 const fits = new Map<string, string>()
1017 const fitText = (text: string) => {
1018 const fitted = lastFits.get(text) ?? fitTables(text, columns)
1019 fits.set(text, fitted)
1020 return fitted
1021 }
1022 const sections = paneSections(state.view, { ...settings, nowMs: state.nowMs, frame: state.frame, fitText, closed: state.closed })
1023 state.tableFit = { columns, byText: fits }
1024 const fit = (sectionKey: string, text: string) => {
1025 const kept = state.fitted.get(sectionKey)
1026 if (kept && kept.text === text) return kept.blocks
1027 const blocks = markdownBlocks(text)
1028 state.fitted.set(sectionKey, { text, blocks })
1029 return blocks
1030 }
1031 // A closable section's header: a press opens or closes it, and its text leads with the mark.
1032 const toggle = (section: { fold: string }, children: RenderChildren) => (
1033 <Button key={`toggle:${section.fold}`} plain onPress={() => toggleSection($, state, section.fold)}>{children}</Button>
1034 )
1035 const mark = (open: boolean) => (open ? OPEN_MARK : CLOSED_MARK)
1036 // Folding closes the sections that have text now, so an answer that lands
1037 // later still arrives open; expanding opens them all.
1038 const foldAll = ({ label, folds }: { label: 'fold' | 'expand'; folds: string[] }) => {
1039 state.closed = label === 'fold' ? new Set([...state.closed, ...folds]) : new Set()
1040 $.ui.invalidate('ui.render')
1041 }
1042 const draw = (section: Section, index: number) => {
1043 const key = `section-${index}`
1044 switch (section.kind) {
1045 case 'note':
1046 return <Text key={key} dimColor>{section.text}</Text>
1047 case 'seat': {
1048 const action = section.action
1049 // The model takes the slack and gives way when narrow, so the bar,
1050 // the time and the action sit in the same columns on every row. An
1051 // open seat's row is a header on its provider's colour, darkened, in
1052 // white, so each answer starts where the eye can find it.
1053 // Each cell's ink, chosen once: on the fill every cell is white.
1054 const white = { color: COLOR.onFill }
1055 const ink = section.open
1056 ? { name: white, model: white, dim: white, state: white, label: white }
1057 : { name: {}, model: { color: COLOR.hint }, dim: { dimColor: true }, state: { color: section.stateColor }, label: {} }
1058 return (
1059 <Box key={section.key} flexDirection="row" width={columns} {...(section.open ? { backgroundColor: section.fill } : {})}>
1060 <Box flexShrink={0}>
1061 <Text>
1062 <Text color={section.vendor}>{EDGE_MARK}</Text>
1063 <Text bold {...ink.name}>{` ${section.name} `}</Text>
1064 </Text>
1065 </Box>
1066 <Box flexDirection="row" flexGrow={1} flexShrink={1}>
1067 <Box flexShrink={1}>
1068 <Text {...ink.model} wrap="truncate-end">{section.model}</Text>
1069 </Box>
1070 {section.note === '' ? null : (
1071 <Box flexShrink={0}>
1072 <Text>
1073 {section.model === '' ? null : <Text {...ink.dim}>{' \u00b7 '}</Text>}
1074 <Text {...ink.state}>{section.note}</Text>
1075 </Text>
1076 </Box>
1077 )}
1078 </Box>
1079 <Box flexShrink={0}>
1080 <Text>
1081 <Text {...ink.state}>{` ${section.bar}`}</Text>
1082 <Text {...ink.dim}>{` ${section.time}`}</Text>
1083 </Text>
1084 </Box>
1085 <Box flexShrink={0} width={ACTION_COLUMNS} paddingLeft={2}>
1086 {action ? (
1087 // Not plain: a plain Button draws its hotkey beside the label, and
1088 // the row draws no number. A Button takes no colour of its own, so
1089 // the label is a Text child, white on a header fill.
1090 <Button
1091 key={`${action.press}:${action.seat}`}
1092 label={action.press}
1093 {...(section.digit ? { hotkey: section.digit } : {})}
1094 onPress={() => (action.press === 'cancel' || action.press === 'retry' ? pressSeat($, state, action.press, action.seat) : toggleSection($, state, section.fold))}
1095 >
1096 <Text {...ink.label}>{action.press}</Text>
1097 </Button>
1098 ) : null}
1099 </Box>
1100 </Box>
1101 )
1102 }
1103 case 'summary':
1104 return <Text key={key} bold>{section.text}</Text>
1105 case 'footer': {
1106 const { fold } = section
1107 return (
1108 // Not plain, so no letter is drawn: a and c still press them once the pane holds the focus.
1109 <Box key={key} flexDirection="row" flexWrap="wrap" justifyContent="flex-end" width={columns} marginTop={1}>
1110 {fold && <Button key="footer:fold" hotkey="a" label={fold.label} onPress={() => foldAll(fold)} />}
1111 {fold && <Text>{' '}</Text>}
1112 {section.cancelAll && <Button key="footer:cancel" hotkey="c" label="cancel all" onPress={() => cancelAll($, state)} />}
1113 {section.cancelAll && <Text>{' '}</Text>}
1114 {/* The pane's own close mark, which the engine draws and answers. */}
1115 <Text dimColor>{'\u2715 close'}</Text>
1116 </Box>
1117 )
1118 }
1119 case 'synthesis':
1120 return (
1121 <Box key={section.key} flexDirection="column" marginTop={section.open ? 1 : 0}>
1122 <Box flexDirection="row" paddingX={1} width={columns} backgroundColor={FILL.orange}>
1123 {toggle(section, <Text bold color={COLOR.onFill} backgroundColor={FILL.orange}>{`${mark(section.open)} SYNTHESIS`}</Text>)}
1124 </Box>
1125 {section.open && fit(key, section.text).map((block, part) => (
1126 <Markdown key={`${key}-${part}`} text={block} />
1127 ))}
1128 </Box>
1129 )
1130 case 'body':
1131 // The text arrives fitted to the pane's width and within its budget.
1132 // A fallback's reason already took the blank line above it. A blank
1133 // line follows when another section does; the footer brings its own.
1134 return (
1135 <Box key={key} flexDirection="column" marginTop={sections[index - 1]?.kind === 'reason' ? 0 : 1} marginBottom={sections[index + 1] !== undefined && sections[index + 1]?.kind !== 'footer' ? 1 : 0}>
1136 {fit(key, section.text).map((block, part) => (
1137 <Markdown key={`${key}-${part}`} text={block} />
1138 ))}
1139 </Box>
1140 )
1141 case 'reason':
1142 return (
1143 <Box key={key} marginTop={1}>
1144 <Text color={COLOR.muted}>{section.text}</Text>
1145 </Box>
1146 )
1147 }
1148 }
1149 const retry = state.retryShown
1150 const runDir = state.runDir
1151 return (
1152 <Box flexDirection="column">
1153 {e.surface !== 'terminal' && retry && runDir ? [retryRow($.ui.resolve(e), retry, retryPresses($, runDir))] : []}
1154 {sections.map(draw)}
1155 </Box>
1156 )
1157 })
1158}
1159mods/council-pane/hooks/heads-up.ts 756 lines1// ABOUTME: Pure policy for the heads-up side-check: cadence, backoff, memory, the runner's result and the band's words
2// ABOUTME: No engine calls, so every rule runs under bun test; pane.tsx is the shell that feeds events in
3
4import type { Note, Paused, Phase, Session, Tag } from '../types'
5import { isRecord } from './json'
6
7/** Fire when the message index within the turn is a positive multiple of this; the builtin's number. */
8export const DEFAULT_EVERY = 3
9/** seen and known each keep this many topics, newest last; the builtin's cap. */
10export const TOPIC_CAP = 50
11export const TOPIC_CHARS = 140
12export const TITLE_CHARS = 80
13export const POINT_CHARS = 200
14export const MAX_POINTS = 6
15export const HEADLINE_CHARS = 200
16/** A seat name becomes a script path in the runner, so it is only ever a plain word here. */
17const SEAT_SHAPE = /^[a-z][a-z0-9-]+$/
18
19export const CONFIG_FILE = '.claude/council-heads-up.json'
20export const STORE_KEY = 'heads-up'
21export const COUNTS_KEY = 'heads-up-counts'
22export const TOKENS_KEY = 'heads-up-tokens'
23export const INTRO_KEY = 'heads-up-intro-shown'
24export const COMMAND = 'heads-up'
25
26/** The seat's picks: the model goes to its *_MODEL variable, the effort to codex's -c flag; other seats ignore it. */
27export type SeatPick = { readonly model?: string; readonly effort?: string }
28
29/** The effective setting. Only parseConfig builds one; `seat` is a shape-checked word, the runner owns the allowlist. */
30export type HeadsUpConfig =
31 | { enabled: true; seat: string; every: number; model?: SeatPick }
32 | { enabled: false; problem?: string }
33
34const DEFAULT_SEAT = 'codex'
35const EFFORT_SHAPE = /^[a-z]+$/
36
37/**
38 * Two switches, the /config row and the project file: on when the file says
39 * `enabled: true`, or when the row is on and the file does not say
40 * `enabled: false`. The file's seat, model and every apply either way. Malformed
41 * JSON, a non-object, an `enabled` that is not a boolean, a seat that is not a
42 * plain word, a `seats` or `models` key, or an `every` below 2 -> off with a
43 * problem the shell logs once, whatever the row says: a side-agent that never
44 * fires should say why. An empty `model` reads as no pick.
45 */
46export function parseConfig(text: string | undefined, rowOn: boolean): HeadsUpConfig {
47 if (text === undefined) return rowOn ? { enabled: true, seat: DEFAULT_SEAT, every: DEFAULT_EVERY } : { enabled: false }
48 const off = (why: string): HeadsUpConfig => ({ enabled: false, problem: `${CONFIG_FILE}${why}; heads-up is off` })
49 let raw: unknown
50 try {
51 raw = JSON.parse(text)
52 } catch {
53 return off(' is not valid JSON')
54 }
55 if (!isRecord(raw)) return off(' must hold a JSON object')
56 if (raw.enabled !== undefined && typeof raw.enabled !== 'boolean') return off(': enabled must be true or false')
57 if (raw.seats !== undefined) return off(': seats is not a key; one seat goes under "seat"')
58 if (raw.models !== undefined) return off(': models is not a key; the seat\'s pick goes under "model"')
59 const seat = raw.seat ?? DEFAULT_SEAT
60 if (typeof seat !== 'string' || !SEAT_SHAPE.test(seat)) return off(`: seat ${JSON.stringify(seat)} is not a plain lowercase word`)
61 const every = raw.every ?? DEFAULT_EVERY
62 if (typeof every !== 'number' || !Number.isInteger(every) || every < 2) return off(`: every must be a whole number of at least 2, got ${JSON.stringify(every)}`)
63 let model: SeatPick | undefined
64 if (raw.model !== undefined) {
65 const pick = raw.model
66 if (!isRecord(pick)) return off(': model must be an object of {model, effort}')
67 if (pick.model !== undefined && typeof pick.model !== 'string') return off(`: model for ${seat} must be a string, got ${JSON.stringify(pick.model)}`)
68 if (pick.effort !== undefined && (typeof pick.effort !== 'string' || !EFFORT_SHAPE.test(pick.effort))) return off(`: effort for ${seat} must be lowercase letters, got ${JSON.stringify(pick.effort)}`)
69 if (pick.model !== undefined || pick.effort !== undefined) model = { ...(pick.model === undefined ? {} : { model: pick.model }), ...(pick.effort === undefined ? {} : { effort: pick.effort }) }
70 }
71 if (raw.enabled === false || (raw.enabled === undefined && !rowOn)) return { enabled: false }
72 return { enabled: true, seat, every, ...(model === undefined ? {} : { model }) }
73}
74
75/**
76 * Usage on this machine, in $.store under COUNTS_KEY, shared by every
77 * session. Each bump reads, adds one and writes, so two sessions bumping at
78 * once can lose one; the numbers guide a decision, they are not billing.
79 */
80export type Counts = {
81 readonly none: number
82 readonly notes: number
83 /** A seat's note on a topic already seen or known: nothing drawn. */
84 readonly repeats: number
85 readonly failed: number
86 /** The seat was out of credits; the session paused. */
87 readonly quota: number
88 readonly learn: number
89 readonly tell: number
90 readonly knew: number
91 readonly understood: number
92 readonly dismiss: number
93 readonly turnOff: number
94 readonly typedPast: number
95}
96export const COUNT_KEYS = ['none', 'notes', 'repeats', 'failed', 'quota', 'learn', 'tell', 'knew', 'understood', 'dismiss', 'turnOff', 'typedPast'] as const
97export const EMPTY_COUNTS: Counts = { none: 0, notes: 0, repeats: 0, failed: 0, quota: 0, learn: 0, tell: 0, knew: 0, understood: 0, dismiss: 0, turnOff: 0, typedPast: 0 }
98
99export function parseCounts(raw: unknown): Counts {
100 if (!isRecord(raw)) return EMPTY_COUNTS
101 return Object.fromEntries(COUNT_KEYS.map(key => [key, countOr0(raw[key])])) as Record<keyof Counts, number>
102}
103
104export function bumped(c: Counts, ...keys: (keyof Counts)[]): Counts {
105 return keys.reduce((counts, key) => ({ ...counts, [key]: counts[key] + 1 }), c)
106}
107
108/** "checks 13 · none 8 · notes 2 · repeats 1 · failed 1 · out of credits 1": checks is the outcomes added up, so it cannot drift from them. */
109export function countsLine(c: Counts): string {
110 return `checks ${c.none + c.notes + c.repeats + c.failed + c.quota} · none ${c.none} · notes ${c.notes} · repeats ${c.repeats} · failed ${c.failed} · out of credits ${c.quota}`
111}
112
113/** "learn 2 · tell 1 · knew 0 · understood 1 · dismiss 1 · turned off 0 · typed past 3" */
114export function pressesLine(c: Counts): string {
115 return `learn ${c.learn} · tell ${c.tell} · knew ${c.knew} · understood ${c.understood} · dismiss ${c.dismiss} · turned off ${c.turnOff} · typed past ${c.typedPast}`
116}
117
118/**
119 * The tokens checks used on this machine, in $.store under TOKENS_KEY, shared
120 * by every session, kept apart from Counts because a check adds amounts here,
121 * not one. Each check reads, adds and writes, so two sessions adding at once
122 * can lose one check's tokens; the totals guide a decision, they are not
123 * billing. Kept from the version that began counting them, so they cover
124 * fewer checks than Counts: `checks + unreported` is every check counted
125 * since. `checks` reported usage; `unreported` did not (a seat whose output
126 * carries no counts, a timeout, a check that failed before its seat
127 * answered). cached and reasoning sum only the checks that gave that split,
128 * which cachedChecks and reasoningChecks count; a vendor that leaves a zero
129 * split out is among those that did not.
130 */
131export type Tokens = {
132 readonly checks: number
133 readonly input: number
134 readonly cached: number
135 readonly cachedChecks: number
136 readonly output: number
137 readonly reasoning: number
138 readonly reasoningChecks: number
139 readonly unreported: number
140}
141const TOKEN_KEYS = ['checks', 'input', 'cached', 'cachedChecks', 'output', 'reasoning', 'reasoningChecks', 'unreported'] as const
142export const EMPTY_TOKENS: Tokens = { checks: 0, input: 0, cached: 0, cachedChecks: 0, output: 0, reasoning: 0, reasoningChecks: 0, unreported: 0 }
143
144export function parseTokens(raw: unknown): Tokens {
145 if (!isRecord(raw)) return EMPTY_TOKENS
146 return Object.fromEntries(TOKEN_KEYS.map(key => [key, countOr0(raw[key])])) as Record<keyof Tokens, number>
147}
148
149/** A finished check's tokens added in; one more unreported when no seat gave any; a skipped check, which is not counted, adds nothing. */
150export function addedTokens(t: Tokens, r: RunResult): Tokens {
151 if (r.kind === 'skipped') return t
152 const usages = r.seats.flatMap(seat => (seat.usage === undefined ? [] : [seat.usage]))
153 if (usages.length === 0) return { ...t, unreported: t.unreported + 1 }
154 const sum = (split: (u: Usage) => number | null) => usages.reduce((total, u) => total + (split(u) ?? 0), 0)
155 const gave = (split: (u: Usage) => number | null) => (usages.some(u => split(u) !== null) ? 1 : 0)
156 return {
157 checks: t.checks + 1,
158 input: t.input + sum(u => u.input),
159 cached: t.cached + sum(u => u.cached),
160 cachedChecks: t.cachedChecks + gave(u => u.cached),
161 output: t.output + sum(u => u.output),
162 reasoning: t.reasoning + sum(u => u.reasoning),
163 reasoningChecks: t.reasoningChecks + gave(u => u.reasoning),
164 unreported: t.unreported,
165 }
166}
167
168/** "999", "35.4k", "1.48M": the k band stops where one decimal would round up to 1000.0k. */
169export function tokenCount(n: number): string {
170 if (n < 1000) return String(n)
171 if (n < 999_950) return `${(n / 1000).toFixed(1)}k`
172 return `${(n / 1_000_000).toFixed(2)}M`
173}
174
175/**
176 * "42 of 45 checks reported since this version · 1.48M in, 820.0k cached on 40 of 42 · 9.1k out, 6.2k reasoning
177 * on 30 of 42 · 35.6k per check", the average taken over the reported checks. With every check reported the head
178 * is "45 checks since this version". A split every reported check gave drops its "on X of Y"; one none gave drops out.
179 */
180export function tokensLine(t: Tokens): string {
181 const counted = t.checks + t.unreported
182 if (counted === 0) return 'none since this version'
183 const checks = `${counted} ${counted === 1 ? 'check' : 'checks'}`
184 const parts = [t.unreported === 0 ? `${checks} since this version` : `${t.checks} of ${checks} reported since this version`]
185 if (t.checks > 0) {
186 const split = (amount: number, gave: number, name: string) => (gave === 0 ? '' : `, ${tokenCount(amount)} ${name}${gave < t.checks ? ` on ${gave} of ${t.checks}` : ''}`)
187 parts.push(
188 `${tokenCount(t.input)} in${split(t.cached, t.cachedChecks, 'cached')}`,
189 `${tokenCount(t.output)} out${split(t.reasoning, t.reasoningChecks, 'reasoning')}`,
190 `${tokenCount(Math.round((t.input + t.output) / t.checks))} per check`,
191 )
192 }
193 return parts.join(' \u00b7 ')
194}
195
196export type HeadsUpCommand =
197 | { action: 'status' }
198 | { action: 'on'; seat?: string }
199 | { action: 'off' }
200 | { action: 'setup' }
201 | { action: 'unknown'; why: string }
202
203/**
204 * The /heads-up argument: nothing or status shows the state; on, with the
205 * one seat to ask or none to keep the file's, and off write the project file.
206 * The seat is checked here as the file's is; two seats are refused.
207 */
208export function headsUpCommand(args: string): HeadsUpCommand {
209 const [word = '', ...rest] = args.trim().toLowerCase().split(/[\s,]+/).filter(part => part !== '')
210 if (word === '' || word === 'status') return { action: 'status' }
211 if (word === 'off') return rest.length === 0 ? { action: 'off' } : { action: 'unknown', why: 'off takes no words' }
212 if (word === 'setup') return rest.length === 0 ? { action: 'setup' } : { action: 'unknown', why: 'setup takes no words' }
213 if (word !== 'on') return { action: 'unknown', why: `unknown word ${JSON.stringify(word)}` }
214 if (rest.length > 1) return { action: 'unknown', why: `on takes one seat, got ${rest.length}: ${rest.join(', ')}` }
215 const [seat] = rest
216 if (seat === undefined) return { action: 'on' }
217 if (!SEAT_SHAPE.test(seat)) return { action: 'unknown', why: `seat ${JSON.stringify(seat)} is not a plain lowercase word` }
218 return { action: 'on', seat }
219}
220
221/**
222 * The project file with `enabled` set (or dropped, so the row decides) and,
223 * when given, the seat, cadence and pick; its other fields kept. A pick
224 * belongs to its seat, so a different seat drops the file's `model`; an empty
225 * `model` is never written. A missing or unreadable file starts over. One
226 * line of JSON, as the docs show it.
227 */
228export function withEnabled(text: string | undefined, on: boolean | undefined, seat?: string, every?: number, model?: SeatPick): string {
229 let kept: Record<string, unknown> = {}
230 if (text !== undefined) {
231 try {
232 const raw: unknown = JSON.parse(text)
233 if (isRecord(raw)) kept = raw
234 } catch {
235 kept = {}
236 }
237 }
238 // The keys parseConfig refuses go too, so a write always leaves a file that reads.
239 const { enabled: _dropped, seats: _seats, models: _models, ...rest } = kept
240 if (seat !== undefined) {
241 if (seat !== (rest.seat ?? DEFAULT_SEAT)) delete rest.model
242 rest.seat = seat
243 }
244 if (every !== undefined) rest.every = every
245 if (model !== undefined) rest.model = model
246 if (isRecord(rest.model) && Object.keys(rest.model).length === 0) delete rest.model
247 const json = (value: unknown): string => {
248 if (Array.isArray(value)) return `[${value.map(item => JSON.stringify(item)).join(', ')}]`
249 if (isRecord(value)) return `{${Object.entries(value).map(([key, item]) => `${JSON.stringify(key)}: ${json(item)}`).join(', ')}}`
250 return JSON.stringify(value)
251 }
252 const entries = Object.entries(on === undefined ? rest : { enabled: on, ...rest }).map(([key, value]) => `${JSON.stringify(key)}: ${json(value)}`)
253 return `{${entries.join(', ')}}\n`
254}
255
256/**
257 * What /heads-up status prints: a headline with the effective state, then one
258 * aligned row per fact: which switch set it, the seat and cadence, this
259 * session's pause, the counts and tokens kept on this machine.
260 */
261export type HeadsUpStatus = { state: string; rows: [string, string][] }
262
263export function headsUpStatus(config: HeadsUpConfig, rowOn: boolean, fileText: string | undefined, counts: Counts, tokens: Tokens, paused: Paused | null): HeadsUpStatus {
264 const row = rowOn ? 'on' : 'off'
265 const file = fileText === undefined ? undefined : fileEnabled(fileText)
266 const fileNote = fileText === undefined ? `no ${CONFIG_FILE} here` : `${CONFIG_FILE} leaves it to the row`
267 const rows: [string, string][] = []
268 let state: string
269 if (!config.enabled && config.problem !== undefined) {
270 state = 'off'
271 rows.push(['problem', config.problem])
272 } else if (config.enabled) {
273 state = file === true ? 'on for this project' : 'on for every project'
274 rows.push(['by', file === true ? `${CONFIG_FILE} (the /config row is ${row})` : `the /config row (${fileNote})`])
275 rows.push(['seat', seatLabel(config.seat, config.model)], ['every', `${config.every} requests`])
276 } else if (file === false) {
277 state = 'off for this project'
278 rows.push(['by', `${CONFIG_FILE} (the /config row is ${row})`], ['turn on', `/${COMMAND} on [seat] turns it on here`])
279 } else {
280 state = 'off'
281 rows.push(['by', `the /config row is off, ${fileNote}`], ['turn on', `/${COMMAND} on [seat] for this project, the /config row "Heads-up side-check" for every project`])
282 }
283 if (paused !== null) rows.push(['paused', `${paused.seat} out of credits this session · /${COMMAND} on to resume`])
284 rows.push(['checks', countsLine(counts)], ['tokens', tokensLine(tokens)], ['presses', pressesLine(counts)])
285 return { state, rows }
286}
287
288export function statusText({ state, rows }: HeadsUpStatus): string {
289 const width = Math.max(...rows.map(([label]) => label.length))
290 return [`Heads-up side-check: ${state}`, ...rows.map(([label, value]) => ` ${label.padEnd(width)} ${value}`)].join('\n')
291}
292
293/**
294 * The status on one line for a toast: its first line, then the seat, cadence,
295 * pause and checks rows joined with dots; the presses and the switch stay out. A
296 * command typed while a turn runs gets its reply drawn only when the turn
297 * ends, so the toast is what the person sees at once.
298 */
299export function toastLine({ state, rows }: HeadsUpStatus): string {
300 const kept = new Set(['seat', 'every', 'paused', 'checks'])
301 const parts = rows.flatMap(([label, value]) => (kept.has(label) ? [label === 'every' ? `every ${value}` : value] : []))
302 return [`Heads-up side-check: ${state}`, ...parts].join(' \u00b7 ')
303}
304
305/** The /heads-up setup dialogs: scope, seat, cadence. */
306export const SCOPE = { project: 'This project', all: 'Every project', off: 'Off for this project' } as const
307export const SCOPE_QUESTION = 'Where should the heads-up side-check run?'
308export const SEAT_QUESTION = 'Which seat should reread the turn?'
309export const EVERY_QUESTION = 'How often should a long turn be checked?'
310export const EVERY_LABELS = ['Every 3 requests', 'Every 6 requests', 'Every 9 requests'] as const
311
312/**
313 * The seats discover_providers printed, the council's own test for what is set
314 * up here: codex first, and the router's numbered seats as the one seat they
315 * share a script with.
316 */
317export function seatsFromDiscovery(stdout: string): string[] {
318 const seats = [...new Set(stdout.split(/\s+/).filter(name => name !== '').map(name => (/^openrouter-\d+$/.test(name) ? 'openrouter' : name)))]
319 return seats.includes(DEFAULT_SEAT) ? [DEFAULT_SEAT, ...seats.filter(seat => seat !== DEFAULT_SEAT)] : seats
320}
321
322/** The dialog takes two to four options; the person types any other seat under Other. */
323export function seatOptions(available: readonly string[]): string[] {
324 const picks = available.slice(0, 4)
325 return picks.length >= 2 ? picks : ['codex', 'gemini']
326}
327
328/** The dialog's answer: one label, or a typed seat name. */
329export function seatFromAnswer(answer: string): { seat: string } | { why: string } {
330 const words = answer.toLowerCase().split(/[\s,]+/).filter(part => part !== '')
331 const [seat] = words
332 if (seat === undefined) return { why: 'no seat named' }
333 if (words.length > 1) return { why: `one seat, got ${words.length}: ${words.join(', ')}` }
334 return SEAT_SHAPE.test(seat) ? { seat } : { why: `seat ${JSON.stringify(seat)} is not a plain lowercase word` }
335}
336
337export function everyFromAnswer(answer: string): { every: number } | { why: string } {
338 const digits = /^(?:every\s+)?(\d+)(?:\s+requests?)?$/i.exec(answer.trim())
339 const every = digits === null ? NaN : Number(digits[1])
340 return Number.isInteger(every) && every >= 2 ? { every } : { why: `every must be a whole number of at least 2, got ${JSON.stringify(answer.trim())}` }
341}
342
343export const MODEL_QUESTION = (seat: string) => `Which model should ${seat} use?`
344export const EFFORT_QUESTION = 'How hard should codex think?'
345const KEEP = 'Keep '
346const TYPE_ONE = 'Type a model id under Other'
347
348/** The current model first; then the catalog's others, four in all; or a prompt to type one. */
349export function modelOptions(current: string, catalog: readonly string[] | undefined): string[] {
350 const keep = `${KEEP}${current}`
351 if (catalog === undefined || catalog.length === 0) return [keep, TYPE_ONE]
352 return [keep, ...catalog.filter(slug => slug !== current)].slice(0, 4)
353}
354
355/** The chosen model, or undefined to keep the provider's own. */
356export function modelFromAnswer(answer: string): string | undefined {
357 const text = answer.trim()
358 return text === '' || text.startsWith(KEEP) || text === TYPE_ONE ? undefined : text
359}
360
361export function effortOptions(efforts: readonly string[], defaultEffort: string): string[] {
362 const others = efforts.filter(effort => effort !== defaultEffort)
363 if (defaultEffort === '') return (others.length > 0 ? others : ['low', 'medium', 'high', 'xhigh']).slice(0, 4)
364 return [`${defaultEffort} (default)`, ...others].slice(0, 4)
365}
366
367/** The chosen effort, {} to keep codex's default, or why the answer is unusable. */
368export function effortFromAnswer(answer: string): { effort?: string } | { why: string } {
369 const text = answer.trim()
370 if (text.endsWith(' (default)')) return {}
371 return EFFORT_SHAPE.test(text) ? { effort: text } : { why: `effort must be lowercase letters, got ${JSON.stringify(text)}` }
372}
373
374/** What a check that found nothing leaves on the prompt hint: "heads-up: gemini read 8.5 KB in 11 s, nothing to flag". */
375export function receiptLine(r: Extract<RunResult, { kind: 'none' }>): string {
376 const ms = r.seats.reduce((total, seat) => total + seat.elapsedMs, 0)
377 return `heads-up: ${r.seats.map(seat => seat.seat).join(', ')} read ${kilobytes(r.payloadBytes)} in ${seconds(ms)}, nothing to flag`
378}
379
380/** "codex (gpt-6.1-sol, high)", "gemini (gemini-2.5-pro)", or the bare name. */
381export function seatLabel(seat: string, pick: SeatPick | undefined): string {
382 const parts = [pick?.model, pick?.effort].filter((part): part is string => part !== undefined && part !== '')
383 return parts.length === 0 ? seat : `${seat} (${parts.join(', ')})`
384}
385
386/** The runner's --model file: the seat's pick, '' when there is none. */
387export function modelFile(config: Extract<HeadsUpConfig, { enabled: true }>): string {
388 return config.model === undefined ? '' : JSON.stringify(config.model)
389}
390
391// The file's own `enabled`, when it parses; undefined when absent or not a boolean.
392function fileEnabled(text: string): boolean | undefined {
393 try {
394 const raw: unknown = JSON.parse(text)
395 return isRecord(raw) && typeof raw.enabled === 'boolean' ? raw.enabled : undefined
396 } catch {
397 return undefined
398 }
399}
400
401/**
402 * The once-per-install introduction: a dim tail on the prompt's hint line
403 * while the prompt is empty, only while the check is off; marked shown either
404 * way so it never repeats on this machine.
405 */
406export function introTail(p: { shown: boolean; enabled: boolean }): { tail?: string; markShown: boolean } {
407 if (p.shown) return { markShown: false }
408 if (p.enabled) return { markShown: true }
409 return { tail: `Tip: /${COMMAND} on lets another model watch long turns and flag what Claude missed`, markShown: true }
410}
411
412/** Persisted in $.store under STORE_KEY, shared across sessions (read-merge-write). */
413export type Memory = {
414 /** Topics already shown, any answer. Newest last. */
415 readonly seen: readonly string[]
416 /** Topics the person said they knew. Newest last. */
417 readonly known: readonly string[]
418 /** Notes the person typed past, in a row. */
419 readonly typedPastInARow: number
420 /** Checks still to skip because of typedPastInARow. */
421 readonly looksToSkip: number
422}
423export const EMPTY_MEMORY: Memory = { seen: [], known: [], typedPastInARow: 0, looksToSkip: 0 }
424
425/** Whatever the store holds -> Memory; a field off its shape takes the empty value. */
426export function parseMemory(raw: unknown): Memory {
427 if (!isRecord(raw)) return EMPTY_MEMORY
428 const topics = (value: unknown): string[] => (Array.isArray(value) && value.every(item => typeof item === 'string') ? value : [])
429 return { seen: topics(raw.seen), known: topics(raw.known), typedPastInARow: countOr0(raw.typedPastInARow), looksToSkip: countOr0(raw.looksToSkip) }
430}
431
432const fold = (topic: string) => topic.trim().toLowerCase()
433
434// Each topic once by its folded form, the later copy kept, then the newest TOPIC_CAP.
435function newestUnique(topics: readonly string[]): string[] {
436 const kept = topics.filter((topic, at) => !topics.slice(at + 1).some(later => fold(later) === fold(topic)))
437 return kept.slice(-TOPIC_CAP)
438}
439
440// Appends a topic not yet held; a held one stays where it is, so a second press changes nothing.
441function withTopic(topics: readonly string[], topic: string): readonly string[] {
442 return topics.some(held => fold(held) === fold(topic)) ? topics : [...topics, topic].slice(-TOPIC_CAP)
443}
444
445/** Two sessions wrote at once: lists are union-merged newest last and capped, counters are ours. */
446export function mergeMemory(stored: Memory, ours: Memory): Memory {
447 return { ...ours, seen: newestUnique([...stored.seen, ...ours.seen]), known: newestUnique([...stored.known, ...ours.known]) }
448}
449
450export type Answer = 'learn' | 'tell' | 'knew' | 'understood' | 'dismiss' | 'turn-off' | 'typed-past'
451
452/**
453 * The builtin's transitions:
454 * - any press: typedPastInARow = 0, looksToSkip = 0; the topic joins seen (and known on 'knew' or 'understood')
455 * - typed-past: typedPastInARow += 1, looksToSkip = typedPastInARow; the topic joins seen
456 * 'learn' and 'tell' are one note's two presses; the lists take the topic once.
457 * 'turn-off' (the second press of the band's Turn off) is a dismiss here; the shell writes the file off.
458 * Idempotent on the lists (dedupe by case-folded topic); the shell applies it once per note id.
459 */
460export function applyAnswer(m: Memory, topic: string, a: Answer): Memory {
461 const seen = withTopic(m.seen, topic)
462 if (a === 'typed-past') return { ...m, seen, typedPastInARow: m.typedPastInARow + 1, looksToSkip: m.typedPastInARow + 1 }
463 return { seen, known: a === 'knew' || a === 'understood' ? withTopic(m.known, topic) : m.known, typedPastInARow: 0, looksToSkip: 0 }
464}
465
466/** The runner's `avoid.txt`: seen and known, one per line, for the prompt's AVOID slot. */
467export function avoidList(m: Memory): string {
468 const topics = [...m.seen, ...m.known].filter((topic, at, all) => all.findIndex(other => fold(other) === fold(topic)) === at)
469 return topics.map(topic => `${topic}\n`).join('')
470}
471
472export const FRESH_SESSION: Session = { offeredTurn: null, phase: { kind: 'idle' }, paused: null, resumes: 0 }
473
474type Checking = Extract<Phase, { kind: 'checking' }>
475type StoredSession = Omit<Session, 'paused' | 'resumes' | 'phase'> & {
476 readonly paused?: Paused | null
477 readonly resumes?: number
478 readonly phase: Exclude<Phase, Checking> | (Omit<Checking, 'resumes'> & { readonly resumes?: number })
479}
480
481/** The session as $.state holds it: one written without `paused` reads as not paused, and without `resumes`, session or check, as never resumed. */
482export function storedSession(stored: StoredSession): Session {
483 const { phase } = stored
484 return { ...stored, paused: stored.paused ?? null, resumes: stored.resumes ?? 0, phase: phase.kind === 'checking' ? { ...phase, resumes: phase.resumes ?? 0 } : phase }
485}
486
487/** The red row's Dismiss: the row goes, the pause stays. */
488export function acknowledgePause(s: Session): Session {
489 return s.paused === null ? s : { ...s, paused: { ...s.paused, acknowledged: true } }
490}
491
492/** The red row above the prompt while the pause is not dismissed. */
493export function pausedLine(p: Paused): string {
494 return `heads-up paused · ${p.seat}: ${p.detail}`
495}
496
497/** What turn.step carries that the rules read: the turn, and this request's position in it, from 0. */
498export type StepFacts = { turnId: string; index: number }
499
500/** The request's index in its turn is a positive multiple of every. */
501export function onCadence(every: number, index: number): boolean {
502 return index > 0 && index % every === 0
503}
504
505export type Decision =
506 | { kind: 'skip'; why: 'disabled' | 'off-cadence' | 'paused' | 'showing' | 'checking' | 'offered-this-turn' }
507 | { kind: 'skip'; why: 'backoff'; memory: Memory }
508 | { kind: 'launch'; checkId: string }
509
510/**
511 * The builtin's rules in order. The check fires when the request's index in
512 * its turn is a positive multiple of every (the engine's own count; the
513 * conversation's messageCount is not a per-step fact, it grows by whatever the
514 * request carries). Backoff consumes one looksToSkip and returns the memory to
515 * write. A launch does not stamp offeredTurn: a NONE result leaves later
516 * cadence points of the turn free; `checking` alone stops overlap. A seat out
517 * of credits pauses the session: every later check would fail the same way.
518 */
519export function decide(cfg: HeadsUpConfig, s: Session, m: Memory, e: StepFacts, nowMs: number): Decision {
520 if (!cfg.enabled) return { kind: 'skip', why: 'disabled' }
521 if (!onCadence(cfg.every, e.index)) return { kind: 'skip', why: 'off-cadence' }
522 if (s.paused !== null) return { kind: 'skip', why: 'paused' }
523 if (s.phase.kind === 'showing') return { kind: 'skip', why: 'showing' }
524 if (s.phase.kind === 'checking') return { kind: 'skip', why: 'checking' }
525 if (s.offeredTurn === e.turnId) return { kind: 'skip', why: 'offered-this-turn' }
526 if (m.looksToSkip > 0) return { kind: 'skip', why: 'backoff', memory: { ...m, looksToSkip: m.looksToSkip - 1 } }
527 return { kind: 'launch', checkId: `check-${nowMs}` }
528}
529
530/**
531 * The tokens one seat call used, in OpenAI's convention so seats add up: input
532 * holds the cached tokens and cache writes, output the reasoning; cached and
533 * reasoning are null when the vendor gave no such split.
534 */
535export type Usage = { readonly input: number; readonly cached: number | null; readonly output: number; readonly reasoning: number | null }
536
537export type SeatOutcome = {
538 readonly seat: string
539 readonly outcome: 'none' | 'note' | 'error' | 'timeout' | 'quota'
540 readonly elapsedMs: number
541 readonly detail?: string
542 /** Absent when the seat reported none. */
543 readonly usage?: Usage
544}
545
546/** result.json, read once at the boundary into this. */
547export type RunResult =
548 | { kind: 'note'; note: Note; seats: readonly SeatOutcome[] }
549 | { kind: 'none'; payloadBytes: number; seats: readonly SeatOutcome[] }
550 /** The seat is out of credits; `seat` and `detail` are those of its quota outcome. */
551 | { kind: 'quota'; seat: string; detail: string; payloadBytes: number; seats: readonly SeatOutcome[] }
552 /** The runner found nobody to warn (a transcript holding no prompt) and asked no seat. */
553 | { kind: 'skipped'; detail: string }
554 | { kind: 'failed'; payloadBytes: number; seats: readonly SeatOutcome[] }
555
556/**
557 * Wire shape: {kind, bytes, seat?, model?, ms?, tag?, topic?, headline?, title?, points?, detail?, seats:[{seat,outcome,ms,detail?,usage?}]}.
558 * A skipped check carries only its detail: no seat ran and nothing left the machine.
559 * A quota check carries its seat and words in the seat outcome marked quota.
560 * A text that does not parse to it is `failed` naming the text, so a runner
561 * change can never read as "no note". A headline is cut to HEADLINE_CHARS, one line.
562 */
563export function parseRunResult(checkId: string, text: string): RunResult {
564 const unread: RunResult = {
565 kind: 'failed', payloadBytes: 0,
566 seats: [{ seat: 'runner', outcome: 'error', elapsedMs: 0, detail: `result.json does not read as a run result: ${JSON.stringify(cut(text, UNREAD_CHARS))}` }],
567 }
568 let raw: unknown
569 try {
570 raw = JSON.parse(text)
571 } catch {
572 return unread
573 }
574 if (!isRecord(raw) || !isCount(raw.bytes) || !Array.isArray(raw.seats)) return unread
575 const seats = raw.seats.map(seatOutcome)
576 if (!seats.every((seat): seat is SeatOutcome => seat !== undefined)) return unread
577 if (raw.kind === 'none') return { kind: 'none', payloadBytes: raw.bytes, seats }
578 if (raw.kind === 'quota') {
579 const out = seats.find(seat => seat.outcome === 'quota')
580 if (out?.detail === undefined || out.detail === '') return unread
581 return { kind: 'quota', seat: out.seat, detail: out.detail, payloadBytes: raw.bytes, seats }
582 }
583 // A failure or skip before any seat ran names its reason at the top level.
584 const detail = typeof raw.detail === 'string' && raw.detail !== '' ? raw.detail : undefined
585 if (raw.kind === 'skipped') return detail === undefined ? unread : { kind: 'skipped', detail }
586 if (raw.kind === 'failed') {
587 // A failure before any seat ran (no transcript) is read as the runner's own outcome.
588 const runner: SeatOutcome[] = detail === undefined ? [] : [{ seat: 'runner', outcome: 'error', elapsedMs: 0, detail }]
589 return { kind: 'failed', payloadBytes: raw.bytes, seats: [...runner, ...seats] }
590 }
591 if (raw.kind !== 'note') return unread
592 const { seat, ms, topic, headline, title, points } = raw
593 if (typeof seat !== 'string' || !isCount(ms) || typeof topic !== 'string' || typeof headline !== 'string' || typeof title !== 'string') return unread
594 if (!Array.isArray(points) || !points.every((point): point is string => typeof point === 'string')) return unread
595 const note: Note = {
596 id: checkId, tag: tagOf(raw.tag), seat, model: typeof raw.model === 'string' ? raw.model.trim() : '', payloadBytes: raw.bytes, elapsedMs: ms,
597 topic: topic.trim().slice(0, TOPIC_CHARS),
598 headline: cut(headline.replace(/\s+/g, ' ').trim(), HEADLINE_CHARS),
599 title: plainLinks(title).trim().slice(0, TITLE_CHARS),
600 points: points.map(point => plainLinks(point).trim().slice(0, POINT_CHARS)).filter(point => point !== '').slice(0, MAX_POINTS),
601 }
602 if (note.topic === '' || note.headline === '') return unread
603 return { kind: 'note', note, seats }
604}
605
606// The band draws plain text, so a markdown link a seat wrote anyway becomes "text (address)".
607const plainLinks = (text: string) => text.replace(/\[([^\]]+)\]\((https?:\/\/[^)\s]+)\)/g, '$1 ($2)')
608
609// A seat's tag, case-folded; anything but the builtin's two reads as Heads up,
610// the tag for this session's own work, which is what the check is asked for.
611function tagOf(raw: unknown): Tag {
612 return typeof raw === 'string' && raw.trim().toLowerCase() === 'you should know' ? 'You should know' : 'Heads up'
613}
614
615// How much of an unreadable result.json its failure quotes.
616const UNREAD_CHARS = 200
617
618// Cut to at most `chars`, the last one an ellipsis when anything was left out.
619function cut(text: string, chars: number): string {
620 return text.length <= chars ? text : `${text.slice(0, chars - 1)}…`
621}
622
623function isCount(value: unknown): value is number {
624 return typeof value === 'number' && Number.isInteger(value) && value >= 0
625}
626
627// A stored counter off its shape reads as 0.
628const countOr0 = (value: unknown): number => (isCount(value) ? value : 0)
629
630const OUTCOMES: readonly SeatOutcome['outcome'][] = ['none', 'note', 'error', 'timeout', 'quota']
631
632// A seat outcome off its shape, usage included, makes the whole result
633// unreadable: the runner checks usage before writing it, so a bad one is a
634// runner bug, and a dropped one would undercount the tokens without a word.
635function seatOutcome(raw: unknown): SeatOutcome | undefined {
636 if (!isRecord(raw) || typeof raw.seat !== 'string' || !isCount(raw.ms)) return undefined
637 const outcome = OUTCOMES.find(known => known === raw.outcome)
638 if (!outcome) return undefined
639 if (raw.detail !== undefined && typeof raw.detail !== 'string') return undefined
640 const usage = raw.usage === undefined ? undefined : usageOf(raw.usage)
641 if (usage === null) return undefined
642 return { seat: raw.seat, outcome, elapsedMs: raw.ms, ...(raw.detail === undefined ? {} : { detail: raw.detail }), ...(usage === undefined ? {} : { usage }) }
643}
644
645// The runner's usage record, or null when it is off the shape lib/usage.sh writes: a split no larger than its whole.
646function usageOf(raw: unknown): Usage | null {
647 if (!isRecord(raw) || !isCount(raw.input) || !isCount(raw.output)) return null
648 const { input, output, cached, reasoning } = raw
649 if (!(cached === null || (isCount(cached) && cached <= input))) return null
650 if (!(reasoning === null || (isCount(reasoning) && reasoning <= output))) return null
651 return { input, cached, output, reasoning }
652}
653
654/** A seat repeated a topic in seen or known anyway (case-folded, trimmed). */
655export function isRepeat(m: Memory, topic: string): boolean {
656 return [...m.seen, ...m.known].some(held => fold(held) === fold(topic))
657}
658
659/**
660 * The poller's transition. A note stamps offeredTurn with the turn the check
661 * was launched in, so one landing after its turn ended counts against the
662 * right turn; a repeat, none or failed returns to idle; quota returns to idle
663 * paused, the red row not yet dismissed, unless /heads-up on resumed the
664 * session after the check launched. Not checking -> unchanged.
665 */
666export function settle(s: Session, m: Memory, r: RunResult): Session {
667 if (s.phase.kind !== 'checking') return s
668 if (r.kind === 'note' && !isRepeat(m, r.note.topic)) return { ...s, offeredTurn: s.phase.turnId, phase: { kind: 'showing', note: r.note, expanded: false } }
669 if (r.kind === 'quota' && s.phase.resumes === s.resumes) return { ...s, phase: { kind: 'idle' }, paused: { seat: r.seat, detail: r.detail, acknowledged: false } }
670 return { ...s, phase: { kind: 'idle' } }
671}
672
673/** A person's own prompt while a note shows: the note goes; the caller records typed-past in memory. */
674export function typedPast(s: Session): Session {
675 return s.phase.kind === 'showing' ? { ...s, phase: { kind: 'idle' } } : s
676}
677
678/**
679 * A press. learn: the band expands and stays; tell, knew, understood, dismiss and a close
680 * from the expanded band: idle. The shell puts tell's draft in the prompt box.
681 */
682export function pressed(s: Session, a: Exclude<Answer, 'typed-past'>): Session {
683 if (s.phase.kind !== 'showing') return s
684 if (a === 'learn') return { ...s, phase: { ...s.phase, expanded: true } }
685 return { ...s, phase: { kind: 'idle' } }
686}
687
688/** What the band draws; null yields to the next hook. */
689export type BandView = {
690 /** Drawn bold after the mark: "Heads up" or "You should know". */
691 readonly tag: Tag
692 /** The seat's sentence, after the tag and a dot. */
693 readonly headline: string
694 /** "codex · gpt-6.1-sol · 12.4 KB · 27 s"; the model is left out when the runner named none. */
695 readonly meta: string
696 /** Non-null once expanded: the bold title and the bullets, the last one the action; the band then offers Understood, Tell Claude and Close instead of the three choices. */
697 readonly more: { readonly title: string; readonly points: readonly string[] } | null
698 /** The note's id, so the shell knows whether its armed Turn off belongs to this note. */
699 readonly id: string
700}
701/** The band's mark for a tag: a badge of one ASCII letter on Claude's orange, drawn on every terminal. */
702export function tagMark(tag: Tag): '!' | '?' {
703 return tag === 'Heads up' ? '!' : '?'
704}
705
706export function bandView(p: Phase): BandView | null {
707 if (p.kind !== 'showing') return null
708 const { note } = p
709 return {
710 tag: note.tag,
711 headline: note.headline,
712 meta: [note.seat, note.model, kilobytes(note.payloadBytes), seconds(note.elapsedMs)].filter(part => part !== '').join(' · '),
713 more: p.expanded ? { title: note.title, points: note.points } : null,
714 id: note.id,
715 }
716}
717
718const seconds = (ms: number) => `${Math.round(ms / 1000)} s`
719
720/** One line per finished check, drawn or not: "heads-up: codex · none · 12.4 KB · 27 s". */
721export function checkLine(r: RunResult): string {
722 if (r.kind === 'note') return `heads-up: ${r.note.seat} · note · ${kilobytes(r.note.payloadBytes)} · ${seconds(r.note.elapsedMs)}`
723 if (r.kind === 'none') {
724 const ms = r.seats.reduce((total, seat) => total + seat.elapsedMs, 0)
725 return `heads-up: ${r.seats.map(seat => seat.seat).join(', ')} · none · ${kilobytes(r.payloadBytes)} · ${seconds(ms)}`
726 }
727 if (r.kind === 'skipped') return `heads-up: skipped · ${r.detail}`
728 if (r.kind === 'quota') {
729 const ms = r.seats.reduce((total, seat) => total + seat.elapsedMs, 0)
730 return `heads-up: paused · ${r.seat} after ${seconds(ms)}: ${r.detail} · /${COMMAND} on resumes`
731 }
732 const reasons = r.seats.map(seat => `${seat.seat} ${seat.outcome} after ${seconds(seat.elapsedMs)}${seat.detail ? `: ${seat.detail}` : ''}`)
733 return `heads-up: failed · ${kilobytes(r.payloadBytes)} · ${reasons.join('; ')}`
734}
735
736/**
737 * The draft tell Claude puts in the prompt box, for the person to send or
738 * edit: the main agent learns of a note only through the person's own prompt.
739 * The headline opens, the title and bullets follow as a list, and the close
740 * asks for a check before any action: a Heads up is a claim to verify, a
741 * You should know is a fact to weigh against the plan.
742 */
743export function tellClaudeDraft(n: Note): string {
744 const raised = `A side check by ${n.seat} (not you) flagged this: ${n.headline}`
745 const more = [n.title, ...n.points.map(point => `- ${point}`)].filter(part => part !== '').join('\n')
746 const close = n.tag === 'Heads up'
747 ? `Treat this as a claim, not a conclusion. Before continuing: verify it against the evidence, report what you find, and only then act on ${n.points.length === 0 ? 'it' : 'the last bullet'}.`
748 : 'Take this into account before continuing and say whether it changes your plan.'
749 return [raised, more, close].filter(part => part !== '').join('\n\n')
750}
751
752/** "12.4 KB" style, one decimal. */
753export function kilobytes(bytes: number): string {
754 return `${(bytes / 1024).toFixed(1)} KB`
755}
756mods/council-pane/hooks/host.ts 56 lines1// ABOUTME: Where a council run's pane is drawn: inside Claude Code by this mod, or in tmux
2// ABOUTME: The pane_host setting decides; on ask the answer is asked once, kept in the plugin store, and forgotten with /council-pane ask
3
4export type PaneHost = 'mod' | 'tmux'
5
6export const HOST_STORE_KEY = 'pane_host'
7
8export const HOST_QUESTION = 'Where should the council pane open?'
9
10export const HOST_LABELS: Record<PaneHost, string> = {
11 mod: 'Inside Claude Code',
12 tmux: 'tmux pane',
13}
14
15// A query starts a pane; fetching, cancelling or listing jobs, listing models
16// and asking for help do not, and neither does a command that only names the
17// script (a grep, a cat): the script has to be what bash is given to run.
18export function isCouncilRun(command: string): boolean {
19 return /\bbash\s+["']?[^\s"']*run-council\.sh\b/.test(command) && !/--(result|cancel|jobs|help|list-[a-z-]+)(=|\s|$)/.test(command)
20}
21
22export function hostFrom(value: unknown): PaneHost | undefined {
23 if (value === 'mod' || value === HOST_LABELS.mod) return 'mod'
24 if (value === 'tmux' || value === HOST_LABELS.tmux) return 'tmux'
25 return undefined
26}
27
28export type HostSetting = 'ask' | 'claude-code' | 'tmux'
29
30export function hostSetting(value: unknown): HostSetting {
31 return value === 'claude-code' || value === 'tmux' ? value : 'ask'
32}
33
34// The settings row decides outright unless it says ask; then the remembered
35// answer does, and with none the person is asked. Outside tmux the pane in
36// Claude Code is the only one there is, so nothing is asked there.
37export function decideHost(facts: { setting: HostSetting; remembered: PaneHost | undefined; isInTmux: boolean }): PaneHost | 'ask' {
38 if (facts.setting === 'claude-code') return 'mod'
39 if (facts.setting === 'tmux') return 'tmux'
40 if (!facts.isInTmux) return 'mod'
41 return facts.remembered ?? 'ask'
42}
43
44export function hostRowLabel(label: string, setting: HostSetting, remembered: PaneHost | undefined): string {
45 if (setting !== 'ask' || !remembered) return label
46 return `${label} \u2192 ${remembered === 'mod' ? 'Claude' : 'tmux'}`
47}
48
49export type PaneCommand = { action: 'reopen' } | { action: 'forget' } | { action: 'unknown' }
50
51export function paneCommand(args: string): PaneCommand {
52 const word = args.trim().toLowerCase()
53 if (word === '') return { action: 'reopen' }
54 return word === 'ask' ? { action: 'forget' } : { action: 'unknown' }
55}
56mods/council-pane/hooks/notices.ts 95 lines1// ABOUTME: Words for a council run outside the pane: the finish notice, the wake prompt, the reopen reply
2// ABOUTME: Pure functions over the run's provider states
3
4import { bar, BAND_CELLS } from './bar'
5import { ANSWERED_STATES, count, ENDED_STATES, type ProviderStatus } from './status'
6
7type RunProgress = { providers: ProviderStatus[]; isDone: boolean }
8
9export function finishNotice({ providers }: RunProgress, jobId = ''): string {
10 const errors = count(providers, 'error')
11 const cancelled = count(providers, 'cancelled')
12 // The band draws the COUNCIL label ahead of this, so the text does not repeat the name.
13 const subject = jobId ? `job ${jobId} finished` : 'finished'
14 const answered = `${count(providers, ...ANSWERED_STATES)} of ${providers.length} answered`
15 return `${subject}: ${answered}${errors > 0 ? `, ${errors} error` : ''}${cancelled > 0 ? `, ${cancelled} cancelled` : ''}`
16}
17
18
19// An m:ss clock, h:mm:ss past an hour. Args: when the run started, now.
20function runClock(startedMs: number, nowMs: number): string {
21 const secs = Math.max(0, Math.floor((nowMs - startedMs) / 1000))
22 const hours = Math.floor(secs / 3600)
23 const mins = Math.floor((secs % 3600) / 60)
24 const ss = String(secs % 60).padStart(2, '0')
25 return hours > 0 ? `${hours}:${String(mins).padStart(2, '0')}:${ss}` : `${mins}:${ss}`
26}
27
28// The band above the prompt while a run is live: a bar sweeping on the frame,
29// an m:ss clock, and how many providers finished (an error or a cancel
30// included) with the latest event after it. `startedAtMs` is when the pane
31// picked the run up; before that there is no clock.
32export function progressBand(
33 { providers, isDone, latest }: RunProgress & { latest?: string },
34 startedAtMs: number | undefined,
35 nowMs: number,
36 frame: number,
37): { bar: string; clock?: string; event: string } | undefined {
38 if (isDone || providers.length === 0) return undefined
39 const finished = count(providers, ...ENDED_STATES)
40 return {
41 bar: bar({ kind: 'sweep', frame }, BAND_CELLS),
42 ...(startedAtMs === undefined ? {} : { clock: runClock(startedAtMs, nowMs) }),
43 event: `${finished} of ${providers.length} done${latest ? ` \u00b7 ${latest}` : ''}`,
44 }
45}
46
47// A run whose process died without writing .done: what the band says instead.
48export function abandonedNotice({ providers }: RunProgress, jobId = ''): string {
49 const subject = jobId ? `job ${jobId} stopped` : 'stopped'
50 return `${subject} before it finished: ${count(providers, ...ANSWERED_STATES)} of ${providers.length} answered`
51}
52
53// The pid a run left in its watch dir, fit to hand to kill -0: digits, not zero.
54export function runPid(text: string): string | undefined {
55 const pid = text.trim()
56 return /^[1-9]\d*$/.test(pid) ? pid : undefined
57}
58
59export function wakePrompt(jobId: string): string | undefined {
60 if (!jobId) return undefined
61 return `The background council job ${jobId} has finished. Fetch it with /claude-council:result ${jobId} and summarise it.`
62}
63
64export function reopenReply(hasRun: boolean): string {
65 return hasRun
66 ? 'Council pane reopened with the last run.'
67 : 'No council run in this session yet. Start one with /claude-council:ask.'
68}
69
70export type FinishNotice = { text: string; untilMs: number; isFailure?: boolean }
71
72export const FINISH_NOTICE_MS = 20_000
73
74export function noticeIsLive(notice: FinishNotice | undefined, nowMs: number): boolean {
75 return notice !== undefined && nowMs < notice.untilMs
76}
77
78export type JobOutcome = 'completed' | 'failed' | 'running'
79
80// Reads a job record as run-council.sh --result does: completed can be
81// fetched, queued and running cannot yet, anything else never will. A record
82// cut off mid-write is read again on the next poll; one that is gone or is
83// not a record is over.
84export function jobOutcome(record: string): JobOutcome {
85 if (!record.trim()) return 'failed'
86 let status: unknown
87 try {
88 status = (JSON.parse(record) as { status?: unknown }).status
89 } catch {
90 return 'running'
91 }
92 if (status === 'completed') return 'completed'
93 return status === 'queued' || status === 'running' ? 'running' : 'failed'
94}
95mods/council-pane/hooks/options.ts 28 lines1// ABOUTME: Reads the pane's settings from the options the engine passes to register
2// ABOUTME: Field names match plugin.json's userConfig; a missing or mistyped value takes the default
3
4import { hostSetting, type HostSetting } from './host'
5
6export type PaneOptions = {
7 host: HostSetting
8 collapsesWhenDone: boolean
9 wakesOnAsyncDone: boolean
10 offersTool: boolean
11 // The heads-up side-check's global switch; a project file can still say no.
12 headsUp: boolean
13}
14
15function flag(value: unknown, fallback: boolean): boolean {
16 return typeof value === 'boolean' ? value : fallback
17}
18
19export function paneOptions(options: Record<string, unknown>): PaneOptions {
20 return {
21 host: hostSetting(options.pane_host),
22 collapsesWhenDone: flag(options.collapse_when_done, true),
23 wakesOnAsyncDone: flag(options.wake_on_async_done, false),
24 offersTool: flag(options.council_tool, true),
25 headsUp: flag(options.heads_up, false),
26 }
27}
28mods/council-pane/hooks/retry.ts 26 lines1// ABOUTME: Reads the retry offer a council run leaves in its watch dir and shapes the pane's countdown for it
2// ABOUTME: The run waits on the offer; the pane accepts by renaming it to .retry or declines with .retry-declined
3
4import { bar, BAND_CELLS } from './bar'
5
6export type RetryOffer = { seconds: number; providers: string[] }
7
8export type RetrySection = { kind: 'retry'; notice: string; remaining: number; bar: string }
9
10
11export function parseRetryOffer(text: string): RetryOffer | undefined {
12 const [window = '', ...rest] = text.split('\n').map(line => line.trim())
13 const providers = rest.filter(Boolean)
14 if (!/^[1-9]\d*$/.test(window) || providers.length === 0) return undefined
15 return { seconds: Number(window), providers }
16}
17
18export function retrySection(offer: RetryOffer, seenAtMs: number, nowMs: number): RetrySection {
19 const remaining = Math.max(0, offer.seconds - Math.floor((nowMs - seenAtMs) / 1000))
20 const { providers } = offer
21 // Rounded up, so the countdown empties only when no time is left.
22 const filled = Math.ceil((remaining / offer.seconds) * BAND_CELLS)
23 const notice = providers.length === 1 ? `${providers[0]} failed` : `${providers.length} providers failed: ${providers.join(', ')}`
24 return { kind: 'retry', notice, remaining, bar: bar({ kind: 'share', filled, total: BAND_CELLS }, BAND_CELLS) }
25}
26mods/council-pane/hooks/snapshot.ts 56 lines1// ABOUTME: Reads one snapshot of a run's watch dir: statuses, answers, errors, colors, and whether it is done
2// ABOUTME: Takes the engine's file access as a parameter so a scripted one can stand in
3
4import { lastEvent, parseStatus } from './status'
5import { parseColors, type RunView } from './view'
6
7export type Files = {
8 exists: (path: string) => Promise<boolean>
9 read: (path: string) => Promise<string>
10 list: (dir: string) => Promise<{ kind: string; name: string }[]>
11}
12
13export async function readText(fs: Files, path: string): Promise<string> {
14 return (await fs.exists(path)) ? await fs.read(path) : ''
15}
16
17async function readFolder(fs: Files, dir: string, suffix: string): Promise<Record<string, string>> {
18 const texts: Record<string, string> = {}
19 if (!(await fs.exists(dir))) return texts
20 for (const entry of await fs.list(dir)) {
21 if (entry.kind !== 'file' || entry.name.startsWith('.') || !entry.name.endsWith(suffix)) continue
22 texts[entry.name.slice(0, -suffix.length)] = await fs.read(`${dir}/${entry.name}`)
23 }
24 return texts
25}
26
27// The names of a folder's plain files; a marker is its name, with nothing to read.
28async function fileNames(fs: Files, dir: string): Promise<string[]> {
29 if (!(await fs.exists(dir))) return []
30 return (await fs.list(dir)).filter(entry => entry.kind === 'file' && !entry.name.startsWith('.')).map(entry => entry.name)
31}
32
33export async function readView(fs: Files, runDir: string): Promise<RunView> {
34 // .done is the run's last write, so it is looked for first: files read
35 // after it was seen are final, where a run ending mid-read would otherwise
36 // be called done over a snapshot taken before its last answer.
37 const isDone = await fs.exists(`${runDir}/.done`)
38 const status = await readText(fs, `${runDir}/status`)
39 const latest = lastEvent(status)
40 // The three marker folders depend on nothing else, so they are read together.
41 const [cancels, retries, retriable] = await Promise.all(['cancel', 'retry', 'retriable'].map(folder => fileNames(fs, `${runDir}/${folder}`)))
42 return {
43 providers: parseStatus(status),
44 responses: await readFolder(fs, `${runDir}/responses`, '.md'),
45 errors: await readFolder(fs, `${runDir}/errors`, '.txt'),
46 // The seats the pane pressed for cancel; a marker stays until the run logs the seat as cancelled.
47 cancels: cancels ?? [],
48 // The seats pressed for retry on their error row, and the seats the run says such a press can re-query.
49 retries: retries ?? [],
50 retriable: retriable ?? [],
51 colors: parseColors(await readText(fs, `${runDir}/colors`)),
52 isDone,
53 ...(latest ? { latest } : {}),
54 }
55}
56mods/council-pane/hooks/tool.ts 66 lines1// ABOUTME: The council tool the model can call: its schema, and its input turned into run-council.sh arguments
2// ABOUTME: Input is model-written, so it is validated here before it reaches a command line
3
4export const TOOL_NAME = 'ask'
5
6export const TOOL_DESCRIPTION =
7 'Ask the council of external AI models one question and get each answer back. ' +
8 'Call this when the user asks for the council, or when a decision would benefit from outside perspectives. ' +
9 'The user is asked to confirm before anything is sent; a refusal comes back as the result; do not retry unless the reply asks for a change.'
10
11export const TOOL_SCHEMA = {
12 type: 'object',
13 properties: {
14 question: { type: 'string', description: 'The question, self-contained: the council sees nothing else.' },
15 providers: { type: 'array', items: { type: 'string' }, description: 'Provider names; omit for every configured provider.' },
16 verbosity: { type: 'string', enum: ['brief', 'standard', 'detailed'] },
17 },
18 required: ['question'],
19 additionalProperties: false,
20}
21
22const VERBOSITIES = ['brief', 'standard', 'detailed']
23
24export const SEND_LABEL = 'Send to the council'
25export const KEEP_LABEL = "Don't send"
26
27// The dialog shows a question of this many characters at most; the run still
28// receives the whole question.
29const QUOTED_MAX = 300
30
31// The confirmation the user answers before the question leaves the machine.
32// Called on input councilArgs has already accepted.
33export function confirmQuestion(input: Record<string, unknown>): string {
34 const question = String(input.question)
35 const quoted = question.length > QUOTED_MAX ? `${question.slice(0, QUOTED_MAX)}\u2026` : question
36 const who = Array.isArray(input.providers) ? input.providers.join(', ') : 'every configured provider'
37 return `Send "${quoted}" to ${who}?`
38}
39
40// Only the exact send label sends. `answer` is undefined when the dialog
41// rejected: dismissed, or a run with no one to ask. Free text typed under
42// Other goes back to the model as a plain result, not a refusal: it is
43// usually an instruction, and a refusal is drawn as an error.
44export function confirmOutcome(answer: string | undefined): { send: true } | { deny: string } | { reply: string } {
45 if (answer === SEND_LABEL) return { send: true }
46 if (answer === undefined) return { deny: 'The user was not asked (dialog dismissed or no one to ask), so nothing was sent to the council.' }
47 if (answer === KEEP_LABEL) return { deny: 'The user chose not to send this to the council.' }
48 return { reply: `The user did not send this to the council and said: ${answer}` }
49}
50
51export function councilArgs(input: Record<string, unknown>): { args: string[] } | { deny: string } {
52 const { question, providers, verbosity } = input
53 if (typeof question !== 'string' || question.trim() === '') return { deny: 'question must be a non-empty string' }
54 const flags: string[] = []
55 if (providers !== undefined) {
56 const isNames = Array.isArray(providers) && providers.length > 0 && providers.every(name => typeof name === 'string' && /^[a-z][a-z0-9-]*$/.test(name))
57 if (!isNames) return { deny: 'providers must be names like codex or openrouter-2' }
58 flags.push(`--providers=${(providers as string[]).join(',')}`)
59 }
60 if (verbosity !== undefined) {
61 if (typeof verbosity !== 'string' || !VERBOSITIES.includes(verbosity)) return { deny: 'verbosity must be brief, standard or detailed' }
62 flags.push(`--verbosity=${verbosity}`)
63 }
64 return { args: [...flags, '--', question] }
65}
66mods/council-pane/hooks/synthesis.ts 14 lines1// ABOUTME: Lifts the council synthesis out of the assistant's reply so the pane can show it
2// ABOUTME: Nothing on disk holds the synthesis; the reply's "## 🧭 Synthesis" section is its only source
3
4export function extractSynthesis(reply: string): string | undefined {
5 const lines = reply.split('\n')
6 // The transcript writes the header with its compass; a reply from before it has none.
7 const start = lines.findIndex(line => /^#{1,6}\s+(?:🧭\s+)?Synthesis\s*$/u.test(line))
8 if (start < 0) return undefined
9 const rest = lines.slice(start + 1)
10 const saved = rest.findIndex(line => line.includes('Full output saved'))
11 const body = (saved < 0 ? rest : rest.slice(0, saved)).join('\n').replace(/\n-{3,}\s*$/, '').trim()
12 return body.replace(/^-{3,}$/, '').trim() || undefined
13}
14mods/council-pane/hooks/tables.ts 58 lines1// ABOUTME: Rewrites markdown tables too wide for the pane as one labelled record per row
2// ABOUTME: The engine lays a table out to the terminal's width, so a wide one wraps into noise in a narrower pane
3
4const SEPARATOR = /^\s*\|?\s*:?-{1,}:?\s*(\|\s*:?-{1,}:?\s*)*\|?\s*$/
5const FENCE = /^\s*(```|~~~)/
6
7function cells(row: string): string[] {
8 const inner = row.trim().replace(/^\|/, '').replace(/\|$/, '')
9 return inner.split(/(?<!\\)\|/).map(cell => cell.trim())
10}
11
12// Each column takes its longest cell plus a border and two spaces of padding.
13function drawnWidth(rows: string[][]): number {
14 const columns = Math.max(...rows.map(row => row.length))
15 let width = 1
16 for (let column = 0; column < columns; column++) {
17 width += Math.max(...rows.map(row => (row[column] ?? '').length)) + 3
18 }
19 return width
20}
21
22function records(header: string[], body: string[][]): string[] {
23 const lines: string[] = []
24 body.forEach((row, index) => {
25 if (index > 0) lines.push('')
26 const label = row[0] ?? ''
27 lines.push(/^\*\*.*\*\*$/.test(label) ? label : `**${label}**`)
28 for (let column = 1; column < header.length; column++) {
29 lines.push(`- ${header[column]}: ${row[column] ?? ''}`)
30 }
31 })
32 return lines
33}
34
35export function fitTables(markdown: string, paneColumns: number): string {
36 const lines = markdown.split('\n')
37 const out: string[] = []
38 let isFenced = false
39 for (let i = 0; i < lines.length; i++) {
40 const line = lines[i] ?? ''
41 if (FENCE.test(line)) isFenced = !isFenced
42 const separator = lines[i + 1] ?? ''
43 const isTable = !isFenced && line.includes('|') && separator.includes('-') && SEPARATOR.test(separator)
44 if (!isTable) {
45 out.push(line)
46 continue
47 }
48 let end = i + 2
49 while (end < lines.length && (lines[end] ?? '').includes('|') && (lines[end] ?? '').trim() !== '') end++
50 const header = cells(line)
51 const body = lines.slice(i + 2, end).map(cells)
52 if (drawnWidth([header, ...body]) <= paneColumns) out.push(...lines.slice(i, end))
53 else out.push(...records(header, body))
54 i = end - 1
55 }
56 return out.join('\n')
57}
58mods/council-pane/hooks/view.ts 342 lines1// ABOUTME: Decides which council run the pane shows and turns its state into the markdown drawn there
2// ABOUTME: Pure functions over plain values, so they run without the engine
3import { bar, type BarFill } from './bar'
4import { ANSWERED_STATES, count, type ProviderStatus } from './status'
5import { COLOR } from './theme'
6
7export type RunView = {
8 providers: ProviderStatus[]
9 responses: Record<string, string>
10 errors: Record<string, string>
11 // Seats pressed for cancel in the pane, from the watch dir's cancel folder.
12 cancels?: string[]
13 // Seats pressed for retry on their error row, from the watch dir's retry
14 // folder, and the seats the run offers for it, from its retriable folder.
15 retries?: string[]
16 retriable?: string[]
17 colors: Record<string, string>
18 isDone: boolean
19 // The status log's last event in words, for the band.
20 latest?: string
21 synthesis?: string
22 // When the pane first saw each provider querying; the status log carries no clock.
23 queryingSinceMs?: Record<string, number>
24}
25
26type DirEntry = { name: string; kind: string }
27
28export function unseenRun(entries: readonly DirEntry[], shown: ReadonlySet<string>): string | undefined {
29 return entries.find(entry => entry.kind === 'dir' && entry.name.startsWith('run.') && !shown.has(entry.name))?.name
30}
31
32// What a seat row's digit does now: end the seat, re-query it, or open or
33// close the text under it.
34type SeatAction = { press: 'cancel' | 'retry' | 'open' | 'fold'; seat: string }
35type SeatNote = '' | 'cached' | 'fell back'
36
37export type Section =
38 | { kind: 'summary'; text: string }
39 // One row per seat, its status and its fold header at once, with the name
40 // padded to the column and the action's seat unpadded. A closed seat, or one
41 // with nothing to show, is the row alone: no reason or body follows it.
42 | { kind: 'seat'; key: string; fold: string; digit: string; stateColor: string; vendor: string; fill: string; name: string; model: string; note: SeatNote; bar: string; time: string; open: boolean; action?: SeatAction }
43 | { kind: 'reason'; text: string }
44 | { kind: 'body'; text: string }
45 | { kind: 'synthesis'; key: string; fold: string; open: true; text: string }
46 | { kind: 'synthesis'; key: string; fold: string; open: false }
47 // The pane's keys that apply now, last.
48 // a folds or expands two or more sections, c cancels every seat still out.
49 | { kind: 'footer'; fold?: { label: 'fold' | 'expand'; folds: string[] }; cancelAll: boolean }
50 // The empty run's one line.
51 | { kind: 'note'; text: string }
52
53// The bar's shape and colour are the seat's state: a sweep while live, since a
54// live seat has no share to show, full once answered, a stub on an error, bare
55// once cancelled.
56type SeatLook = { color: string; note: SeatNote; fill: (frame: number) => BarFill }
57const SWEEP = (frame: number): BarFill => ({ kind: 'sweep', frame })
58const FULL = (): BarFill => ({ kind: 'share', filled: 1, total: 1 })
59const LIVE: SeatLook = { color: COLOR.accent, note: '', fill: SWEEP }
60const SET_ASIDE: SeatLook = { color: COLOR.muted, note: '', fill: () => ({ kind: 'empty' }) }
61// Only a seat that answered some other way than asking says so in words. A state the pane does not know is drawn live.
62const SEAT_LOOKS: Record<string, SeatLook> = {
63 querying: LIVE,
64 retrying: LIVE,
65 complete: { color: COLOR.success, note: '', fill: FULL },
66 cached: { color: COLOR.info, note: 'cached', fill: FULL },
67 fallback: { color: COLOR.accent, note: 'fell back', fill: FULL },
68 error: { color: COLOR.danger, note: '', fill: () => ({ kind: 'stub' }) },
69 cancelled: SET_ASIDE,
70 cancelling: SET_ASIDE,
71}
72// Frames between one seat's sweep and the next one's, so the live rows do not move in step.
73const SWEEP_STAGGER = 7
74// A provider with no colour of its own; a data colour, like the vendors' own.
75const NEUTRAL_RGB = '113;113;122'
76
77// An open seat's header fill is its provider's colour at seven tenths, so
78// white letters on it clear 4.5:1 for the vendor palette's mid-tones.
79const HEADER_SHADE = 0.7
80
81// A provider's `r;g;b` as a colour, scaled toward black by `shade`.
82function rgb(triple: string, shade = 1): string {
83 return `rgb(${triple.split(';').map(part => Math.round(Number(part) * shade)).join(',')})`
84}
85
86const jumpKey = (name: string) => `jump:${name}`
87const fold = (kind: 'seat' | 'synthesis', key: string) => `${kind}:${key}`
88
89function seconds(ms: number | undefined): string {
90 return ms === undefined ? '' : `${(ms / 1000).toFixed(1)}s`
91}
92
93export function parseColors(log: string): Record<string, string> {
94 const colors: Record<string, string> = {}
95 for (const line of log.split('\n')) {
96 const [name, rgb] = line.replace(/\r$/, '').split('\t')
97 if (name && rgb && /^\d+;\d+;\d+$/.test(rgb)) colors[name] = rgb
98 }
99 return colors
100}
101
102// The seats whose error row can be retried: the ones the run offers, in the
103// log's order, less any already pressed. The run offers a seat while its
104// loop can still honour a press, and withdraws it at the relaunch.
105export function seatsToRetry({ providers, retries = [], retriable = [], isDone }: Pick<RunView, 'providers' | 'retries' | 'retriable' | 'isDone'>): string[] {
106 if (isDone) return []
107 return providers.filter(({ name }) => retriable.includes(name) && !retries.includes(name)).map(({ name }) => name)
108}
109
110// What the band's cancel all presses: every seat a live run still has
111// querying whose cancel has not been pressed yet, in the log's order.
112export function seatsToCancel({ providers, cancels = [], isDone }: Pick<RunView, 'providers' | 'cancels' | 'isDone'>): string[] {
113 if (isDone) return []
114 return providers.filter(({ name, state }) => state === 'querying' && !cancels.includes(name)).map(({ name }) => name)
115}
116
117function summaryText(providers: ProviderStatus[]): string {
118 const tally = (state: string, word: string) => (count(providers, state) > 0 ? `${count(providers, state)} ${word}` : '')
119 const slowest = Math.max(0, ...providers.map(provider => provider.ms ?? 0))
120 return [
121 `${count(providers, ...ANSWERED_STATES)} of ${providers.length} answered`,
122 tally('error', 'error'),
123 tally('cancelled', 'cancelled'),
124 tally('fallback', 'fell back'),
125 tally('cached', 'cached'),
126 slowest > 0 ? seconds(slowest) : '',
127 ].filter(Boolean).join(' \u00b7 ')
128}
129
130// When each provider now querying was first seen querying. One that stops
131// loses its entry, so a provider the person retries starts a fresh clock.
132export function queryingSince(since: Record<string, number>, providers: ProviderStatus[], nowMs: number): Record<string, number> {
133 const next: Record<string, number> = {}
134 for (const { name, state } of providers) {
135 if (state === 'querying') next[name] = since[name] ?? nowMs
136 }
137 return next
138}
139
140type SeatMarks = Pick<RunView, 'cancels' | 'retries' | 'retriable' | 'isDone'>
141
142// A seat still querying as far as the log knows, with its marker in the
143// watch dir, is cancelling: the run removes the marker once it logs the seat.
144function seatState({ name, state }: ProviderStatus, { cancels = [], retries = [], retriable = [], isDone }: SeatMarks): string {
145 return state === 'querying' && cancels.includes(name) ? 'cancelling'
146 : retriable.includes(name) && retries.includes(name) && !isDone ? 'retrying'
147 : state
148}
149
150// Whether a live run's pane and band move: a seat querying or waiting on its
151// retry runs a clock and a sweep, and so does the band.
152export function isMoving(view: Pick<RunView, 'providers'> & SeatMarks): boolean {
153 return !view.isDone && view.providers.some(provider => provider.state === 'querying' || seatState(provider, view) === 'retrying')
154}
155
156// A run that is live lists its seats with any open answers under them and
157// the synthesis last. A finished one leads with its summary, and, collapsing
158// when done, with the synthesis, the seats below it.
159export function paneSections(
160 { providers, responses, errors, cancels = [], retries = [], retriable = [], colors, isDone, synthesis, queryingSinceMs = {} }: RunView,
161 { collapsesWhenDone = true, nowMs = 0, frame = 0, fitText = (text: string) => text, closed = new Set<string>() }: { collapsesWhenDone?: boolean; nowMs?: number; frame?: number; fitText?: (text: string) => string; closed?: ReadonlySet<string> } = {},
162): Section[] {
163 if (providers.length === 0) {
164 return [{ kind: 'note', text: isDone ? 'Council finished with no answers.' : 'Waiting for the council...' }]
165 }
166 const shownState = (provider: ProviderStatus) => seatState(provider, { cancels, retries, retriable, isDone })
167 // A querying provider's time runs from when the pane first saw it, in whole tenths.
168 const elapsed = (name: string) => {
169 const since = queryingSinceMs[name]
170 return since === undefined ? '' : `${(Math.floor(Math.max(0, nowMs - since) / 100) / 10).toFixed(1)}s`
171 }
172 const shownTime = (provider: ProviderStatus) => {
173 const state = shownState(provider)
174 return state === 'querying' || state === 'retrying' ? elapsed(provider.name) : seconds(provider.ms)
175 }
176 // What hangs under a seat's row while it is open, built only then: its
177 // answer, or the error of a seat that ended on one. A seat querying again
178 // after a failure keeps its first error file and shows nothing.
179 const textOf = ({ name, state }: ProviderStatus): (() => Section[]) | undefined => {
180 const response = responses[name]
181 const error = errors[name]
182 if (response !== undefined) {
183 // A seat whose API sibling answered has both files: the error is why
184 // the seat itself did not, and it belongs above that answer. The state
185 // decides, since a seat that failed and then answered on a retry keeps
186 // its first attempt's error file. fitText rewrites an answer for the
187 // pane's width before the budget is counted: a wide table becomes
188 // records that repeat every header, which can lengthen it several times over.
189 return () => [
190 ...(state === 'fallback' && error !== undefined ? [{ kind: 'reason' as const, text: noticeText(`${name} fell back: ${error}`) }] : []),
191 { kind: 'body', text: fitText(response) },
192 ]
193 }
194 return state === 'error' && error !== undefined ? () => [{ kind: 'body', text: noticeText(error) }] : undefined
195 }
196 // Columns are padded here so the rows line up whatever the surface's layout does.
197 const width = (texts: string[]) => Math.max(...texts.map(text => text.length))
198 const names = width(providers.map(provider => provider.name))
199 const times = width(providers.map(shownTime))
200 const cancellable = seatsToCancel({ providers, cancels, isDone })
201 const retriableNow = seatsToRetry({ providers, retries, retriable, isDone })
202 const folds: string[] = []
203 const seats = providers.flatMap((provider, index): Section[] => {
204 const { name, model } = provider
205 const key = jumpKey(name)
206 const seatFold = fold('seat', key)
207 const text = textOf(provider)
208 if (text) folds.push(seatFold)
209 const open = text !== undefined && !closed.has(seatFold)
210 const look = SEAT_LOOKS[shownState(provider)] ?? LIVE
211 const press = cancellable.includes(name) ? 'cancel' : retriableNow.includes(name) ? 'retry' : text ? (open ? 'fold' : 'open') : undefined
212 const row: Section = {
213 kind: 'seat',
214 key,
215 fold: seatFold,
216 // The keyboard's number row: 1 to 9, then 0 for the tenth seat.
217 digit: index < 10 ? String((index + 1) % 10) : '',
218 stateColor: look.color,
219 vendor: rgb(colors[name] ?? NEUTRAL_RGB),
220 fill: rgb(colors[name] ?? NEUTRAL_RGB, HEADER_SHADE),
221 name: name.padEnd(names),
222 model: model ?? '',
223 note: look.note,
224 bar: bar(look.fill(frame + index * SWEEP_STAGGER)),
225 time: shownTime(provider).padStart(times),
226 open,
227 ...(press ? { action: { press, seat: name } } : {}),
228 }
229 return text && open ? [row, ...text()] : [row]
230 })
231 const synthesisKey = jumpKey('synthesis')
232 const synthesisFold = fold('synthesis', synthesisKey)
233 const synthesisSection: Section[] = !synthesis ? []
234 : closed.has(synthesisFold) ? [{ kind: 'synthesis', key: synthesisKey, fold: synthesisFold, open: false }]
235 : [{ kind: 'synthesis', key: synthesisKey, fold: synthesisFold, open: true, text: fitText(synthesis) }]
236 if (synthesis) folds.push(synthesisFold)
237 return withinTextBudget([
238 ...(isDone ? [{ kind: 'summary' as const, text: summaryText(providers) }] : []),
239 ...(isDone && collapsesWhenDone ? [...synthesisSection, ...seats] : [...seats, ...synthesisSection]),
240 footer(folds, closed, cancellable.length > 0),
241 ])
242}
243
244// With two or more sections to fold, a folds them while any is open, else
245// expands them all; c cancels every seat still out.
246function footer(folds: string[], closed: ReadonlySet<string>, cancelAll: boolean): Section {
247 return {
248 kind: 'footer',
249 ...(folds.length > 1 ? { fold: { label: folds.some(each => !closed.has(each)) ? 'fold' : 'expand', folds } } : {}),
250 cancelAll,
251 }
252}
253
254// The open seats' folds, which close once the synthesis lands so it reads
255// near the top; the synthesis stays open, and a seat with nothing to show yet
256// stays foldable-open, so its answer arrives open.
257export function seatFolds(sections: Section[]): string[] {
258 return sections.flatMap(section => (section.kind === 'seat' && section.open ? [section.fold] : []))
259}
260
261// Claude Code refuses a Pane render carrying more than 100000 characters of
262// text and draws its own. The budget sits under that with room for what the
263// pane draws around the sections (the retry row, the action labels, the footer's keys).
264const PANE_TEXT_BUDGET = 80000
265const CLIPPED = (more: number) => `\n\n_\u2026 ${more} more characters; the whole answer is in the result (/claude-council:result)_`
266
267// An error or a fallback reason is drawn as its opening only: a provider can
268// hand back a whole HTML error page. The section carries what is drawn, so
269// the budget below counts that and no more.
270const NOTICE_LIMIT = 2000
271const noticeText = (text: string) => markdownBlocks(text, NOTICE_LIMIT)[0] ?? ''
272
273// Every string a section carries, counted without copying any of them: this
274// runs on each frame of a live pane.
275const sectionLength = (section: Section) => {
276 let length = 0
277 for (const value of Object.values(section)) if (typeof value === 'string') length += value.length
278 return length
279}
280
281// Cuts the bodies, and only them, until the pane fits the budget: the
282// synthesis, the seat rows and the reasons keep their text, and the bodies
283// (the answers, and the errors already cut to their opening) share what is left. A body within an even share is left whole and its unused
284// room goes to the longer ones, which are all cut to the same length, so one
285// long answer beside short ones is cut only as far as the budget demands.
286export function withinTextBudget(sections: Section[], budget: number = PANE_TEXT_BUDGET): Section[] {
287 const total = sections.reduce((sum, section) => sum + sectionLength(section), 0)
288 if (total <= budget) return sections
289 const lengths = sections.flatMap(section => (section.kind === 'body' ? [section.text.length] : [])).sort((a, b) => a - b)
290 let room = budget - (total - lengths.reduce((sum, length) => sum + length, 0))
291 let left = lengths.length
292 for (const length of lengths) {
293 if (length * left > room) break
294 room -= length
295 left--
296 }
297 const cap = Math.max(0, Math.floor(room / Math.max(1, left)))
298 return sections.map(section => (section.kind !== 'body' || section.text.length <= cap ? section : { kind: 'body', text: clipped(section.text, cap) }))
299}
300
301const FENCE_CLOSE = '\n```'
302
303// The opening of an answer and a note saying how much is left out, together
304// within `room`. The room set aside is for the longest the note can be and a
305// closing fence, so the result never runs past it. The cut does not fall
306// between the two halves of one character, and a code block it lands in is
307// closed first (a backtick fence; a tilde one is rare enough to leave), so the
308// note reads as text and the rest of the pane is not drawn as code.
309function clipped(text: string, room: number): string {
310 let cut = Math.max(0, room - CLIPPED(text.length).length - FENCE_CLOSE.length)
311 const last = cut > 0 ? text.charCodeAt(cut - 1) : 0
312 if (last >= 0xd800 && last <= 0xdbff) cut--
313 const kept = text.slice(0, cut)
314 const isInsideFence = (kept.match(/^ {0,3}```/gm)?.length ?? 0) % 2 === 1
315 return kept + (isInsideFence ? FENCE_CLOSE : '') + CLIPPED(text.length - cut)
316}
317
318// A Markdown element takes at most this many characters, tab and newline its
319// only control characters; a tree holding one that breaks either rule is not drawn.
320const MARKDOWN_LIMIT = 10000
321
322export function markdownBlocks(text: string, limit: number = MARKDOWN_LIMIT): string[] {
323 const clean = text.replace(/\r\n?/g, '\n').replace(/[\u0000-\u0008\u000b-\u001f\u007f]/g, '')
324 const blocks: string[] = []
325 let block = ''
326 for (const paragraph of clean.split('\n\n')) {
327 const joined = block ? `${block}\n\n${paragraph}` : paragraph
328 if (joined.length <= limit) {
329 block = joined
330 continue
331 }
332 if (block) blocks.push(block)
333 block = paragraph
334 while (block.length > limit) {
335 blocks.push(block.slice(0, limit))
336 block = block.slice(limit)
337 }
338 }
339 if (block) blocks.push(block)
340 return blocks
341}
342mods/council-pane/hooks/theme.ts 29 lines1// ABOUTME: The mod's design identity: every colour it draws, named by what it means
2// ABOUTME: Theme keys follow the person's light, dark or colourblind theme; each fixed colour says why it is fixed
3
4// Engine theme keys. Each resolves per theme, so text in them keeps its
5// contrast on a light and a dark terminal (DESIGN.md has the measurements).
6export const COLOR = {
7 // Claude's orange: the progress bar and the heads-up mark. Under 4.5:1 on a
8 // light theme, so never body text.
9 accent: 'claude',
10 success: 'success',
11 danger: 'error',
12 info: 'suggestion',
13 // Secondary text that must stay readable; plain dimColor serves the rest.
14 muted: 'inactive',
15 // The heads-up note's seat line: lighter than dimColor on the user's own call, below 4.5:1 (DESIGN.md).
16 hint: 'subtle',
17 // Letters on a filled label.
18 onFill: 'white',
19} as const
20
21// Fills carry white letters, and a theme key would turn light on a dark theme
22// under them, so these are fixed and dark enough for 4.5:1 or better.
23export const FILL = {
24 // Claude's orange, the one fill: the SYNTHESIS header and the heads-up badge.
25 // White on it is 3.1:1, a choice for the brand over 4.5:1; fixed so a dark
26 // theme cannot lighten it under the white letters.
27 orange: 'rgb(215,119,87)',
28} as const
29