SLOPSHOPPER

deck

Deck: live agent and APEX dashboard on demand (/deck, aliases /apex-pane and /task-board). The APEX run on top while one is live (phases, alerts, background…

panerowsguardcommandpromptprocess
★ 1v0.1.0MITupdated 2026-10-21AlxWrtl/NixConfig/home/claude-code/mods/deck
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · deck
│ ┃ Deck ✕ › fix the failing auth test and add an audit log call │ ┃ DECK · — IDLE │ ┃ ■ main ■ agents ⏺ Read(src/auth.ts) │ ┃ ╭─────────────────────────────────────────── ⎿ Read 6 lines │ ┃ │ — · main ⏺ Update(src/auth.ts) │ ┃ │ effort ▯▯▯▯ — 0 req ⎿ Added 2 lines, removed 1 line │ ┃ │ ctx ▰▰▰▰▰▱▱▱▱▱ 49% 97k/200k ⏺ Bash(bun test) │ ┃ │ $0.42 5h ▰▰▱▱▱ 31% ⎿ 3 pass, 1 fail │ ┃ ╰─────────────────────────────────────────── │ ┃ ▣ client module ./rail.tsx ● Done. refresh now rejects expired claims and logs an audit event. │ ┃ ╭─────────────────────────────────────────── │ ┃ │ ✓ last turn 42s · 0 agents · 3 edits · 1 e ✻ Worked for 42s · done 4:20 PM │ ┃ ╰─────────────────────────────────────────── │ ┃ ╭─────────────────────────────────────────── › /deck │ ┃ │ session log ⎿ deck: Deck opened. Focus it with ctrl+x tab; 1-6 expand cards. │ ┃ │ 08:53:20 main Edit → src/auth.ts │ ┃ │ 08:53:20 main Write → src/audit.ts │ ┃ │ 08:53:20 main Write → src/cache.ts │ ┃ │ 08:53:20 main Bash → bun test ✗ │ ┃ ╰─────────────────────────────────────────── │ ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Pane · Deck
DECK · — IDLE ■ main ■ agents ╭──────────────────────────────────────────────────────╮ │ — · main ○ idle │ │ effort ▯▯▯▯ — 0 req │ │ ctx ▰▰▰▰▰▱▱▱▱▱ 49% 97k/200k │ │ $0.42 5h ▰▰▱▱▱ 31% │ ╰──────────────────────────────────────────────────────╯ ▣ client module ./rail.tsx ╭──────────────────────────────────────────────────────╮ │ ✓ last turn 42s · 0 agents · 3 edits · 1 error │ ╰──────────────────────────────────────────────────────╯ ╭──────────────────────────────────────────────────────╮ │ session log │ │ 08:53:20 main Edit → src/auth.ts │ │ 08:53:20 main Write → src/audit.ts │ │ 08:53:20 main Write → src/cache.ts │ │ 08:53:20 main Bash → bun test ✗ │ ╰──────────────────────────────────────────────────────╯
README

deck

A live dashboard pane for Claude Code, opened on demand only: /deck (aliases /apex-pane, /task-board). It never opens by itself and draws no status line: nothing above the prompt unless you open it.

  • APEX block (first, full width, only while an APEX run of the session's folder is live): APEX · <branch or title> · <tier>, one dot per phase (● done, ◐ current, ○ pending, ✗ failed, · skipped) with its approximate tokens, what asks you to act (a failed step, a red external verification, a spent correction budget) and the background shells with their live duration. Each phase move is written to the session log as apex.
  • Panels (from Flightdeck): main model vitals, the on-call architect, subagent cards and swimlanes (keys 1-6 expand a card), the turn receipt, the session log.
  • Background agents (ours, only while one exists): the dispatched abduco sessions of the current project (its subfolders and .claude/worktrees/ count), read from ~/.claude/session-state/<name>.json (written by hooks/session-state.js) while the pane is open (the 12 newest files per 5 s poll; links, temp files and names outside claude-dispatch's rule skipped). Needs you first (with its notice line), then waiting, idle, working, other (an unknown state, by its word), done; a session silent 24 h leaves, done or not (the deck does not ask abduco, so a crashed session stays up to 24 h); 6 rows, then +N more. A pressed name unfolds its first prompt and last notice. Inline, one summary row (bg: 1 needs you · 2 working). Each row not done carries ↗ afficher: pressed, it runs /etc/profiles/per-user/alx/bin/agent-pane pick <name> (argument vector, no shell, 5 s at most, one run per name at a time), which shows that session in the agent screen's top pane; the outcome goes to the session log as bg.

/deck close, /deck reset, /deck layout auto|compact|wide|mini. Options (/config, or pluginConfigs.deck.options): architectPattern, architectLabel, panels, motion, moments, matchDescriptions, maxCards, layout, palette.

It observes: every hook returns the event's result unchanged, and it never writes a file. Its one action is that button, the mod's only host command: hooks/pick.ts holds the single call checks/claude-mods.nix (M5) allows there, character for character, and nowhere else. It reads <cwd>/.claude/output/apex/*/00-context.md, the run's external-verify.json, ~/.claude/apex-correction-budget/, .git/HEAD and, while the pane is open, ~/.claude/session-state/*.json.

Attribution

Built from Flightdeck v0.3.2 by Stephen Casella, MIT licensed (see LICENSE). The permission gate and other-loops panels were removed; the APEX block is ours.

Source 10 files
hooks/register.tsx 1946 lines
1// deck: one live dashboard pane, opened on demand only (/deck, aliases /apex-pane and
2// /task-board); it never opens by itself and draws no status line: nothing above the prompt
3// unless you open it.
4// From Flightdeck v0.3.2 (MIT, Stephen Casella): main model vitals, the on-call architect,
5// subagent cards and swimlanes, a turn receipt and a session log. Ours: the APEX block on top,
6// drawn only while an APEX run of the session's folder is live (header, phase dots, what asks
7// the user to act, background shells), its phase changes written to the log as `apex`.
8// Observes: every hook but the commands and the pane returns next(e)'s result unchanged, and it
9// never writes a file. The run folders are polled every 5 s only while the pane is open, and once
10// per prompt and per finished main turn otherwise; the background sessions (~/.claude/session-state)
11// only while it is open. A poll writes nothing that did not change. One action: « ↗ afficher »
12// pressed on a background row not done runs `agent-pane pick <name>` (hooks/pick.ts), its outcome
13// logged.
14import { atom, read, update } from 'claude-code'
15import type { EngineInterface, Register, Timer } from 'claude-code'
16
17import type {
18  DeckAgentCard,
19  DeckApexAlert,
20  DeckApexBudget,
21  DeckApexRun,
22  DeckApexSessionRun,
23  DeckApexShell,
24  DeckApexSteps,
25  DeckApexVerdict,
26  DeckArchitect,
27  DeckLayout,
28  DeckLogLine,
29  DeckMain,
30  DeckRoster,
31  DeckTurn,
32  DeckUsage,
33  DeckView,
34  DeckApexStepName,
35  DeckBgAgent,
36  DeckBgKind,
37} from '../types'
38import {
39  DEFAULT_ARCHITECT,
40  DEFAULT_MAIN,
41  DEFAULT_ROSTER,
42  DEFAULT_TURN,
43  DEFAULT_USAGE,
44  DEFAULT_VIEW,
45  EDIT_TOOLS,
46  afterCall,
47  applyStep,
48  cardTitle,
49  titleLines,
50  consultTimeline,
51  contextFill,
52  describeInput,
53  endConsult,
54  fitLegend,
55  fmtClock,
56  fmtDuration,
57  fmtTimer,
58  fmtUsd,
59  plural,
60  gauge,
61  isAdvising,
62  kTokens,
63  lanes,
64  limitLabel,
65  listOf,
66  logRows,
67  momentOf,
68  normalize,
69  normalizeCard,
70  normalizeLog,
71  noteTool,
72  PALETTES,
73  SVG_COLORS,
74  parseConfig,
75  prettyModel,
76  promptLine,
77  handbackOf,
78  adviceLine,
79  receiptOf,
80  shorten,
81  startConsult,
82  upsertCard,
83} from './core'
84import type { Config, Panel } from './core'
85import {
86  NO_STEPS,
87  PHASE_GLYPH,
88  apexHeader,
89  bareShown,
90  callSwitch,
91  classifyAgent,
92  classifyCall,
93  endAgent,
94  headBranch,
95  isLive,
96  modelFamily,
97  newestStep,
98  onBranch,
99  parseCodex,
100  parseContext,
101  parseReview,
102  parseVerdict,
103  phaseNote,
104  runFromFiles,
105  runSwitch,
106  isSessionDir,
107  seeStep,
108  sessionKey,
109  sessionRunOf,
110  settleRun,
111  startSteps,
112  stepCells,
113  stepDetail,
114  answerLines,
115  explainStep,
116  gateEvidence,
117  isMergeCall,
118  pathTail,
119  reviewLines,
120  runEndedAt,
121  shipEvidence,
122} from './apex'
123import type { StepCell, StepMark } from './apex'
124import { STEP_ORDER as STEP_NAMES } from './apex'
125import {
126  addShell,
127  clearFinished,
128  closeBySnapshot,
129  shellsAfterTurn,
130  finishByNotification,
131  parseTaskNotifications,
132  runningShells,
133  stopShell,
134} from './shells'
135import type { Notification } from './shells'
136import { alertsOf, budgetOf, pickVerdict } from './signals'
137import { BG_ORDER, SESSION_NAME, bgSummary, bgWord, inProject, parseSessionState, recentBg, sortBg } from './background'
138import { pickSession } from './pick'
139
140const PANE = 'deck'
141const TITLE = 'Deck'
142const PANE_COLUMNS = 66
143const POLL_MS = 5000
144// The two names the external verification is written under, in a run dir.
145const VERIFY_NAMES = ['04-external-verify.json', 'external-verify.json']
146// Finished shells shown under the running ones; the rest fold into « +N earlier ».
147const DONE_SHELLS = 3
148// Background sessions: state files read per poll (the newest), rows drawn in the panel.
149const BG_READS = 12
150const BG_ROWS = 6
151// A state file over this is skipped: session-state.js never writes one (its MAX_STATE).
152const BG_MAX_BYTES = 64 * 1024
153// `view.expanded` of an unfolded background row: `bg:<id>` (a card's id never starts so).
154const BG_OPEN = 'bg:'
155
156// ---------------------------------------------------------------- state
157
158const main = atom({ plugin: 'deck', key: 'main' } as const, DEFAULT_MAIN)
159const usage = atom({ plugin: 'deck', key: 'usage' } as const, DEFAULT_USAGE)
160const architect = atom({ plugin: 'deck', key: 'architect' } as const, DEFAULT_ARCHITECT)
161const agents = atom({ plugin: 'deck', key: 'agents' } as const, [])
162const log = atom({ plugin: 'deck', key: 'log' } as const, [])
163const turn = atom({ plugin: 'deck', key: 'turn' } as const, DEFAULT_TURN)
164const receipt = atom({ plugin: 'deck', key: 'receipt' } as const, null)
165const view = atom({ plugin: 'deck', key: 'view' } as const, DEFAULT_VIEW)
166const roster = atom({ plugin: 'deck', key: 'roster' } as const, DEFAULT_ROSTER)
167const run = atom({ plugin: 'deck', key: 'run' } as const, null)
168const apexSteps = atom({ plugin: 'deck', key: 'apexSteps' } as const, NO_STEPS)
169const verdict = atom({ plugin: 'deck', key: 'verdict' } as const, null)
170const budget = atom({ plugin: 'deck', key: 'budget' } as const, null)
171const shells = atom({ plugin: 'deck', key: 'shells' } as const, [])
172const sessionRun = atom({ plugin: 'deck', key: 'sessionRun' } as const, null)
173const openStep = atom({ plugin: 'deck', key: 'openStep' } as const, null)
174const background = atom({ plugin: 'deck', key: 'background' } as const, [])
175
176// Module-level: a hot reload drops the environment and its timer with it.
177let timer: Timer | undefined
178// The pane is open: the 5 s timer runs only then.
179let isPaneOpen = false
180// Polls in a row that missed the run shown (settleRun).
181let misses = 0
182// The last run dir a poll found this session (kept through a miss or an ended run), or null:
183// a different one is a new run, which clears the finished cards and shells.
184let lastRunDir: string | null = null
185// The poll under way (its number), or null: a second one waits, unless the first is stuck for
186// STUCK_TICKS ticks, when it is given up and polling goes on.
187let pollCount = 0
188let pollUnderWay: number | null = null
189let skippedTicks = 0
190const STUCK_TICKS = 6
191
192type ServerBlock = { type: string; id?: string; name?: string; tool_use_id?: string }
193
194// Every read goes through these, so a value saved under an older shape still reads.
195async function getMain($: EngineInterface): Promise<DeckMain> {
196  return normalize(DEFAULT_MAIN, await read($, main))
197}
198async function getUsage($: EngineInterface): Promise<DeckUsage> {
199  return normalize(DEFAULT_USAGE, await read($, usage))
200}
201async function getArchitect($: EngineInterface): Promise<DeckArchitect> {
202  const a = normalize(DEFAULT_ARCHITECT, await read($, architect))
203  return { ...a, consults: listOf(a.consults), ids: listOf(a.ids), seen: listOf(a.seen) }
204}
205async function getCards($: EngineInterface): Promise<DeckAgentCard[]> {
206  return listOf<unknown>(await read($, agents)).map(normalizeCard)
207}
208async function getLog($: EngineInterface): Promise<DeckLogLine[]> {
209  return normalizeLog(await read($, log))
210}
211async function getTurn($: EngineInterface): Promise<DeckTurn> {
212  return normalize(DEFAULT_TURN, await read($, turn))
213}
214async function getView($: EngineInterface): Promise<DeckView> {
215  return normalize(DEFAULT_VIEW, await read($, view))
216}
217async function getRoster($: EngineInterface): Promise<DeckRoster> {
218  const r = normalize(DEFAULT_ROSTER, await read($, roster))
219  return { architectTypes: listOf(r.architectTypes) }
220}
221async function getShells($: EngineInterface): Promise<DeckApexShell[]> {
222  return listOf<DeckApexShell>(await read($, shells))
223}
224async function getBackground($: EngineInterface): Promise<DeckBgAgent[]> {
225  // A row saved under an older kind (the jobs reader's) is dropped: the next poll reads it anew.
226  return listOf<DeckBgAgent>(await read($, background))
227    .filter(j => BG_ORDER.includes(j.kind))
228    .map(j => ({ ...j, intent: typeof j.intent === 'string' ? j.intent : '', detail: typeof j.detail === 'string' ? j.detail : '' }))
229}
230
231async function say($: EngineInterface, who: string, text: string, kind: DeckLogLine['kind'] = 'info', agentId: string | null = null) {
232  const line: DeckLogLine = { at: await $.clock.now(), who, text, kind, agentId }
233  await update($, log, list => [...normalizeLog(list), line].slice(-60))
234}
235
236async function whoIs($: EngineInterface, agentId: string | undefined) {
237  if (!agentId) return 'main'
238  const card = (await getCards($)).find(c => c.id === agentId)
239  return card ? shorten(cardTitle(card), 14) : 'agent'
240}
241
242async function consultStarted($: EngineInterface, cfg: Config, id: string, via: string) {
243  const t = await getTurn($)
244  const moment = momentOf(t)
245  const at = await $.clock.now()
246  await update($, architect, a => startConsult(normalize(DEFAULT_ARCHITECT, a), { id, at, moment, via }))
247  if (moment === 'before done') await update($, turn, x => ({ ...normalize(DEFAULT_TURN, x), isReviewing: true }))
248  await say($, cfg.architectLabel.toLowerCase(), cfg.moments ? `${moment} · ${via}` : `consulted · ${via}`, 'consult')
249}
250
251async function consultEnded($: EngineInterface, cfg: Config, advice: string | null, id?: string) {
252  const at = await $.clock.now()
253  const first = advice?.split('\n').find(l => l.trim()) ?? null
254  const text = first ? shorten(first.replace(/^[#>*\s-]+/, ''), 160) : null
255  await update($, architect, a => endConsult(normalize(DEFAULT_ARCHITECT, a), at, text, id))
256  await update($, turn, t => ({ ...normalize(DEFAULT_TURN, t), isReviewing: false }))
257  await say($, cfg.architectLabel.toLowerCase(), text ? `advice: ${shorten(text, 60)}` : 'advice returned', 'consult')
258}
259
260async function noteAdvice($: EngineInterface, cfg: Config, advice: string) {
261  await update($, architect, x => ({ ...normalize(DEFAULT_ARCHITECT, x), lastAdvice: advice }))
262  await say($, cfg.architectLabel.toLowerCase(), `advice: ${shorten(advice, 60)}`, 'consult')
263}
264
265async function isArchitectType($: EngineInterface, cfg: Config, type: string) {
266  return cfg.architect.test(type) || (await getRoster($)).architectTypes.includes(type)
267}
268
269async function openPane($: EngineInterface) {
270  // columns apply when docked beside the transcript, rows when seated inline above the prompt.
271  const opened = await $.ui.open({ id: PANE, title: TITLE, columns: PANE_COLUMNS, rows: 8 })
272  // Open, even when not placed yet (seated once a surface places it): polled from now on.
273  isPaneOpen = true
274  startPolling($)
275  return opened
276}
277
278async function resetAll($: EngineInterface) {
279  await update($, main, m => ({ ...DEFAULT_MAIN, model: normalize(DEFAULT_MAIN, m).model, mode: normalize(DEFAULT_MAIN, m).mode }))
280  await update($, architect, () => DEFAULT_ARCHITECT)
281  await update($, agents, () => [])
282  await update($, log, () => [])
283  await update($, turn, () => DEFAULT_TURN)
284  await update($, receipt, () => null)
285  await update($, view, () => DEFAULT_VIEW)
286  // The context gauge waits for the next measurement rather than showing the pre-clear fill.
287  await update($, usage, x => ({ ...normalize(DEFAULT_USAGE, x), pct: null, tokens: null }))
288  // The run comes back on the next poll; its live steps start over.
289  await update($, run, () => null)
290  await update($, apexSteps, () => NO_STEPS)
291  await update($, verdict, () => null)
292  await update($, budget, () => null)
293  await update($, shells, () => [])
294  await update($, sessionRun, () => null)
295  await update($, openStep, () => null)
296}
297
298/** The session's cost read fresh, not from the last measurement: the receipt subtracts two of these. */
299async function costNow($: EngineInterface): Promise<number | null> {
300  const u = await $.session.usage().catch(() => null)
301  return u?.cost?.usd ?? null
302}
303
304async function noteMode($: EngineInterface, mode: string | undefined) {
305  if (mode) await update($, main, m => (normalize(DEFAULT_MAIN, m).mode === mode ? normalize(DEFAULT_MAIN, m) : { ...normalize(DEFAULT_MAIN, m), mode }))
306}
307
308// ---------------------------------------------------------------- APEX run (polled)
309
310// Reads a field of an engine record whose shape varies per tool; a value that is not a
311// non-empty string reads as undefined.
312function stringField(record: unknown, key: string): string | undefined {
313  if (typeof record !== 'object' || record === null) return undefined
314  const value: unknown = Reflect.get(record, key)
315  return typeof value === 'string' && value !== '' ? value : undefined
316}
317
318function numberField(record: unknown, key: string): number | undefined {
319  if (typeof record !== 'object' || record === null) return undefined
320  const value: unknown = Reflect.get(record, key)
321  return typeof value === 'number' && Number.isFinite(value) ? value : undefined
322}
323
324// A row's text: a string as is, else its text blocks joined; another shape reads as empty.
325function rowText(content: unknown): string {
326  if (typeof content === 'string') return content
327  if (!Array.isArray(content)) return ''
328  const parts: string[] = []
329  for (const block of content) {
330    const text = stringField(block, 'type') === 'text' ? stringField(block, 'text') : undefined
331    if (text !== undefined) parts.push(text)
332  }
333  return parts.join('\n')
334}
335
336// A run folder: its name, its newest time (with a context file: that file's or its newest .md
337// file's; without: its newest step file's), its context file's mtime when it has one, its .md files.
338type RunDir = { dir: string; mtimeMs: number; context?: number; files: { name: string; mtimeMs: number }[] }
339
340// Folders listed per poll: the LISTED_DIRS ranked newest that are runs, plus the newest with a
341// context file wherever it ranks. Cost before that: 1 stat per folder with a context file, 2 per
342// folder without (the failed context stat, then the folder's own).
343const LISTED_DIRS = 3
344
345// The newest run folder, or undefined. Ranked by its context file's mtime, else by the folder's
346// own (adding a file moves it; editing one does not), then listed in rank order and the newest
347// time of each decides. A folder without a context file and without a step file is no run: it
348// takes no slot and is never chosen.
349async function newestRun($: EngineInterface, root: string): Promise<RunDir | undefined> {
350  let entries
351  try {
352    entries = await $.fs.list(root)
353  } catch {
354    // No .claude/output/apex here (or unreadable): no run to show.
355    return undefined
356  }
357  const ranked: { dir: string; key: number; context?: number }[] = []
358  for (const entry of entries) {
359    if (entry.kind !== 'dir') continue
360    try {
361      const stat = await $.fs.stat(`${root}/${entry.name}/00-context.md`)
362      ranked.push({ dir: entry.name, key: stat.mtimeMs, context: stat.mtimeMs })
363      continue
364    } catch {
365      // No context file: the folder ranks by its own mtime, read below.
366    }
367    try {
368      ranked.push({ dir: entry.name, key: (await $.fs.stat(`${root}/${entry.name}`)).mtimeMs })
369    } catch {
370      // Vanished between list and stat: skipped.
371    }
372  }
373  ranked.sort((a, b) => b.key - a.key)
374  const newestContext = ranked.find(r => r.context !== undefined)
375  let best: RunDir | undefined
376  let slots = 0
377  for (const candidate of ranked) {
378    if (slots >= LISTED_DIRS && candidate !== newestContext) continue
379    let files: { name: string; mtimeMs: number }[]
380    try {
381      files = (await $.fs.list(`${root}/${candidate.dir}`))
382        .filter(e => e.kind === 'file' && e.name.endsWith('.md'))
383        .map(e => ({ name: e.name, mtimeMs: e.mtimeMs }))
384    } catch {
385      // Unreadable folder: its context file's time alone, if any.
386      files = []
387    }
388    const mtimeMs =
389      candidate.context === undefined ? newestStep(files) : Math.max(candidate.context, ...files.map(f => f.mtimeMs))
390    // Without a context file, a folder with no step file is not a run: no slot, never chosen.
391    if (mtimeMs === -Infinity) continue
392    slots += 1
393    if (best !== undefined && mtimeMs <= best.mtimeMs) continue
394    best = { dir: candidate.dir, mtimeMs, files, ...(candidate.context === undefined ? {} : { context: candidate.context }) }
395  }
396  return best
397}
398
399// HEAD's branch, or undefined: no repo here, or a worktree whose .git is a file.
400async function readHead($: EngineInterface, cwd: string): Promise<string | undefined> {
401  try {
402    return headBranch(await $.fs.read(`${cwd}/.git/HEAD`))
403  } catch {
404    // Unreadable HEAD: branch unknown, shown.
405    return undefined
406  }
407}
408
409// The session's last main-loop Skill(apex) call, or null (an older shape reads as none).
410async function getSessionRun($: EngineInterface): Promise<DeckApexSessionRun | null> {
411  const value: unknown = await read($, sessionRun)
412  const startedAt = numberField(value, 'startedAt')
413  const lastAt = numberField(value, 'lastAt')
414  if (startedAt === undefined || lastAt === undefined) return null
415  const turnEndAt = numberField(value, 'turnEndAt')
416  const merged = Reflect.get(Object(value), 'merged') === true
417  return { startedAt, lastAt, args: stringField(value, 'args') ?? '', turnEndAt: turnEndAt ?? null, merged }
418}
419
420// One change to the session run, written only when there is one and the change moved something.
421async function changeSessionRun($: EngineInterface, fn: (value: DeckApexSessionRun) => DeckApexSessionRun): Promise<void> {
422  await record(async () => {
423    const current = await getSessionRun($)
424    if (current === null) return
425    const next = fn(current)
426    if (JSON.stringify(next) !== JSON.stringify(current)) await update($, sessionRun, () => next)
427  })
428}
429
430// New activity (a main turn start, a tool call, an agent spawn): the run clock runs again.
431const wakeRun = ($: EngineInterface): Promise<void> =>
432  changeSessionRun($, x => (x.turnEndAt === null || x.turnEndAt === undefined ? x : { ...x, turnEndAt: null }))
433
434// The open step, or none (an unknown name reads as none).
435async function getOpenStep($: EngineInterface): Promise<DeckApexStepName | null> {
436  const value: unknown = await read($, openStep)
437  return STEP_NAMES.find(n => n === value) ?? null
438}
439
440// The live run folder, else the session's Skill(apex) call (HEAD read only when there is one).
441async function scan($: EngineInterface): Promise<DeckApexRun | null> {
442  const cwd = await $.session.cwd()
443  const folder = await scanFolder($, cwd)
444  if (folder !== null) return folder
445  const at = await getSessionRun($)
446  if (at === null) return null
447  return sessionRunOf(at, await readHead($, cwd), await $.clock.now())
448}
449
450async function scanFolder($: EngineInterface, cwd: string): Promise<DeckApexRun | null> {
451  const root = `${cwd}/.claude/output/apex`
452  const newest = await newestRun($, root)
453  if (newest === undefined) return null
454  let parsed: DeckApexRun
455  let liveMs: number
456  if (newest.context !== undefined) {
457    let text: string
458    try {
459      text = await $.fs.read(`${root}/${newest.dir}/00-context.md`)
460    } catch {
461      // Vanished between stat and read, or over 4 MiB: nothing shown this round.
462      return null
463    }
464    parsed = parseContext(text, newest.dir)
465    liveMs = newest.context
466  } else {
467    parsed = runFromFiles(newest.dir, newest.files)
468    // Only a finish step file: the run ended.
469    if (parsed.currentStep === undefined) return null
470    liveMs = newest.mtimeMs
471  }
472  const now = await $.clock.now()
473  if (!isLive(parsed, liveMs, now)) return null
474  const head = await readHead($, cwd)
475  // Without a context file the header names the folder (no branch); hidden on the trunk, live 1 h.
476  if (newest.context === undefined && !bareShown(parsed, liveMs, head, now)) return null
477  return onBranch(parsed, head) ? { ...parsed, dir: newest.dir } : null
478}
479
480// The state library reads and writes named atoms only: one writer per atom, each writing
481// only when the value changed.
482async function putVerdict($: EngineInterface, value: DeckApexVerdict | null): Promise<void> {
483  if (JSON.stringify(await read($, verdict)) === JSON.stringify(value)) return
484  await update($, verdict, () => value)
485}
486
487async function putBudget($: EngineInterface, value: DeckApexBudget | null): Promise<void> {
488  if (JSON.stringify(await read($, budget)) === JSON.stringify(value)) return
489  await update($, budget, () => value)
490}
491
492// The live steps, or none (an older shape reads as none).
493async function getSteps($: EngineInterface): Promise<DeckApexSteps> {
494  const s = normalize(NO_STEPS, await read($, apexSteps))
495  return { runKey: typeof s.runKey === 'string' ? s.runKey : null, steps: listOf(s.steps), current: s.current ?? null }
496}
497
498// One change to the live steps, written only when it changed something. Steps count only while
499// a run is live: a Skill(apex) call set the key, else the shown run folder gives it.
500async function changeSteps($: EngineInterface, fn: (value: DeckApexSteps, runKey: string) => DeckApexSteps): Promise<void> {
501  await record(async () => {
502    const current = await getSteps($)
503    const runKey = current.runKey ?? (await read($, run))?.dir ?? null
504    if (runKey === null) return
505    const next = fn(current, runKey)
506    if (next !== current) await update($, apexSteps, () => next)
507  })
508}
509
510async function changeShells($: EngineInterface, fn: (value: DeckApexShell[]) => DeckApexShell[]): Promise<void> {
511  const current = await getShells($)
512  if (fn(current) === current) return
513  await update($, shells, list => fn(listOf<DeckApexShell>(list)))
514}
515
516// The run's external verification, from whichever of its two names was written last;
517// re-read only when that file's mtime moved.
518async function refreshVerdict($: EngineInterface, found: DeckApexRun | null): Promise<void> {
519  const dir = found?.dir
520  // A session run has no folder: nothing to list.
521  if (dir === undefined || isSessionDir(dir)) return putVerdict($, null)
522  const runDir = `${await $.session.cwd()}/.claude/output/apex/${dir}`
523  let newest: { name: string; mtimeMs: number } | null = null
524  try {
525    for (const entry of await $.fs.list(runDir)) {
526      if (entry.kind !== 'file' || !VERIFY_NAMES.includes(entry.name)) continue
527      newest = pickVerdict(newest, { name: entry.name, mtimeMs: entry.mtimeMs })
528    }
529  } catch {
530    // The run directory vanished: no verification to show.
531    newest = null
532  }
533  if (newest === null) return putVerdict($, null)
534  const current = await read($, verdict)
535  if (current !== null && current.dir === dir && current.mtimeMs === newest.mtimeMs) return
536  let next: DeckApexVerdict | null = null
537  try {
538    const parsed = parseVerdict(await $.fs.read(`${runDir}/${newest.name}`))
539    if (parsed !== null) next = { dir, mtimeMs: newest.mtimeMs, ...parsed }
540  } catch {
541    // Vanished between list and read, or over 4 MiB: shown as pending.
542    next = null
543  }
544  await putVerdict($, next)
545}
546
547// The run's correction budget, from the names in ~/.claude/apex-correction-budget (one file
548// per round used or granted).
549async function refreshBudget($: EngineInterface, found: DeckApexRun | null): Promise<void> {
550  const dir = found?.dir
551  const home = await $.env.get('HOME')
552  if (dir === undefined || isSessionDir(dir) || home === undefined || home === '') return putBudget($, null)
553  let names: string[]
554  try {
555    names = (await $.fs.list(`${home}/.claude/apex-correction-budget`)).map(entry => entry.name)
556  } catch {
557    // No round was ever claimed on this machine: no budget to show.
558    names = []
559  }
560  await putBudget($, budgetOf(names, dir))
561}
562
563// A subagent's still running shells close once it is killed, fails or leaves the agent list:
564// their notification would only ever reach that loop. Read only while such a shell runs.
565async function snapshotShells($: EngineInterface): Promise<void> {
566  const list = await getShells($)
567  if (!list.some(s => s.status === 'running' && s.ownerAgentId !== undefined)) return
568  const listed = await $.agent.list()
569  const owners = listed.map(a => ({ id: a.id, type: a.type, status: a.status }))
570  const [cards, a] = await Promise.all([getCards($), getArchitect($)])
571  const known = [...cards.map(c => c.id), ...a.ids]
572  const at = await $.clock.now()
573  await changeShells($, current => closeBySnapshot(current, owners, known, at))
574}
575
576// A new run: the finished cards and shells go, the running ones stay; receipt, log, main untouched.
577async function clearForNewRun($: EngineInterface): Promise<void> {
578  const cards = await getCards($)
579  if (clearFinished(cards, []).cards !== cards) {
580    await update($, agents, list => clearFinished(listOf<unknown>(list).map(normalizeCard), []).cards)
581  }
582  await changeShells($, current => clearFinished([], current).shells)
583  await update($, openStep, () => null)
584}
585
586// Background sessions of the current project (its subfolders and worktrees): the BG_READS newest
587// ~/.claude/session-state/<name>.json (ranked by the listing's mtime). A missing or linked folder,
588// a link, a dotted temp file, a stem that is no session name, an oversized or vanished file:
589// nothing, never an error.
590async function refreshBackground($: EngineInterface): Promise<void> {
591  const home = await $.env.get('HOME')
592  const root = `${home ?? ''}/.claude/session-state`
593  const isDir =
594    home !== undefined &&
595    home !== '' &&
596    (await $.fs.stat(root).then(
597      st => st.kind === 'dir' && !st.isLink,
598      () => {
599        // No dispatched session ever ran here: an empty panel.
600        return false
601      },
602    ))
603  const entries = isDir
604    ? await $.fs.list(root).catch(() => {
605        // Vanished or unreadable between stat and list: an empty panel.
606        return []
607      })
608    : []
609  const ranked = entries
610    .filter(e => e.kind === 'file' && !e.isLink && e.size <= BG_MAX_BYTES && e.name.endsWith('.json') && SESSION_NAME.test(e.name.slice(0, -5)))
611    .sort((a, b) => b.mtimeMs - a.mtimeMs)
612  const found: DeckBgAgent[] = []
613  for (const entry of ranked.slice(0, BG_READS)) {
614    const path = `${root}/${entry.name}`
615    let text: string
616    try {
617      // Swapped for a link since the listing: skipped, never followed.
618      const st = await $.fs.stat(path)
619      if (st.isLink || st.kind !== 'file' || st.size > BG_MAX_BYTES) continue
620      text = await $.fs.read(path)
621    } catch {
622      // Vanished between list and read: skipped.
623      continue
624    }
625    const parsed = parseSessionState(entry.name.slice(0, -5), text)
626    if (parsed !== null) found.push(parsed.updatedAt > 0 ? parsed : { ...parsed, updatedAt: entry.mtimeMs })
627  }
628  const next = sortBg(recentBg(inProject(found, await $.session.cwd()), await $.clock.now()))
629  if (JSON.stringify(await getBackground($)) !== JSON.stringify(next)) await update($, background, () => next)
630}
631
632// A background row pressed: it unfolds, or folds when it was the one open (one slot with the
633// cards).
634async function toggleBgRow($: EngineInterface, id: string): Promise<void> {
635  const key = `${BG_OPEN}${id}`
636  await update($, view, x => {
637    const current = normalize(DEFAULT_VIEW, x)
638    return { ...current, expanded: current.expanded === key ? null : key }
639  })
640}
641
642// « ↗ afficher » pressed on a row: agent-pane shows that session in the top pane, the outcome goes
643// to the log. A press while the same name is under way does nothing.
644async function pickRow($: EngineInterface, name: string): Promise<void> {
645  const o = await pickSession($, name)
646  if (o === null) return
647  await record(() => say($, 'bg', `${name} ${o.text}`, o.ok ? 'done' : 'error'))
648}
649
650// One poll: background sessions (pane open only), run (its phase moves to the log), phases,
651// verdict, budget, owned shells.
652async function refresh($: EngineInterface): Promise<void> {
653  // Its own reads and write: a failure there leaves the run scan below untouched.
654  if (isPaneOpen) await record(() => refreshBackground($))
655  const scanned = await scan($)
656  const prev = await read($, run)
657  const settled = settleRun(prev, scanned, misses)
658  misses = settled.misses
659  const found = settled.run
660  if (JSON.stringify(prev) !== JSON.stringify(found)) await update($, run, () => found)
661  const note = phaseNote(prev, found)
662  if (note !== null) await say($, 'apex', note)
663  const sw = runSwitch(lastRunDir, found?.dir ?? null)
664  lastRunDir = sw.last
665  if (sw.isNew) await clearForNewRun($)
666  await refreshVerdict($, found)
667  await refreshBudget($, found)
668  await snapshotShells($)
669}
670
671function onTick($: EngineInterface): void {
672  if (pollUnderWay !== null && skippedTicks < STUCK_TICKS) {
673    skippedTicks += 1
674    return
675  }
676  pollCount += 1
677  const mine = pollCount
678  pollUnderWay = mine
679  skippedTicks = 0
680  refresh($)
681    .catch(() => {
682      // A failed scan or a refused write leaves the figures as they were; the next tick tries again.
683    })
684    .finally(() => {
685      // A poll given up as stuck no longer owns the slot when it settles at last.
686      if (pollUnderWay === mine) pollUnderWay = null
687    })
688}
689
690// One poll now, and the 5 s timer while the pane is open.
691function startPolling($: EngineInterface): void {
692  if (timer === undefined) timer = $.clock.every(POLL_MS, () => onTick($))
693  pollOnce($)
694}
695
696function stopPolling(): void {
697  timer?.cancel()
698  timer = undefined
699}
700
701// A single poll (a prompt, a finished main turn): the log's apex lines fill with the pane closed.
702function pollOnce($: EngineInterface): void {
703  $.clock.after(0, () => onTick($))
704}
705
706// Runs `write`; a refused state write leaves the figures as they were (an observer never fails
707// the event it watches).
708async function record(write: () => Promise<void>): Promise<void> {
709  try {
710    await write()
711  } catch {
712    // Figures only: the next step, call or poll writes again.
713  }
714}
715
716/**
717 * The run's live step a tool call stands for: edits from every loop, gate / Codex / ship from the
718 * main loop's Bash only. A refused call, or a failed edit, is no step. Called from the one
719 * unmatched tool.call observer (the engine allows one per event).
720 */
721async function noteCallStep($: EngineInterface, e: unknown, ran: { result?: unknown; isError?: boolean }): Promise<void> {
722  const isRefused = ran.result === undefined && ran.isError !== true
723  const tool = stringField(e, 'tool') ?? ''
724  const input = { file_path: stringField(e, 'file_path'), notebook_path: stringField(e, 'notebook_path'), command: stringField(e, 'command') }
725  const name = isRefused ? null : classifyCall(tool, input, stringField(e, 'agentId') !== undefined)
726  const isFailedEdit = (name === 'edit' || name === 'plan') && ran.isError === true
727  if (name === null || isFailedEdit) return
728  const stdout = stringField(ran.result, 'stdout') ?? ''
729  const command = input.command ?? ''
730  const path = input.file_path ?? input.notebook_path
731  const codex = name === 'Codex' ? parseCodex(stdout) : null
732  const out = { stdout, stderr: stringField(ran.result, 'stderr') ?? '', returnCodeInterpretation: stringField(ran.result, 'returnCodeInterpretation') ?? '' }
733  const evidence =
734    name === 'Codex'
735      ? (codex ?? {})
736      : name === 'gate'
737        ? gateEvidence(command, out, ran.isError === true)
738        : name === 'ship'
739          ? shipEvidence(command, stdout)
740          : path === undefined
741            ? {}
742            : { files: [pathTail(path)] }
743  const at = await $.clock.now()
744  await changeSteps($, (s, key) => seeStep(s, key, name, at, evidence))
745  if (name === 'ship' && ran.isError !== true && isMergeCall(command)) await changeSessionRun($, x => (x.merged === true ? x : { ...x, merged: true }))
746}
747
748/** An implementer, test-runner or reviewer started: its step, with what it does and on which model. */
749async function noteAgentStep($: EngineInterface, subagentType: string, description: string, agentId: string, model: string): Promise<void> {
750  const name = classifyAgent(subagentType)
751  if (name === null) return
752  const at = await $.clock.now()
753  const detail = `${description} (${modelFamily(model)})`
754  await changeSteps($, (s, key) => seeStep(s, key, name, at, { agentId, detail }))
755}
756
757/** A step's agent ended: a reviewer's verdict (anchored) and the lines after it, else its answer's first lines. */
758async function endAgentStep($: EngineInterface, agentId: string, answer: string, reason: string): Promise<void> {
759  const at = await $.clock.now()
760  const isReview = (await getSteps($)).steps.some(x => x.agentId === agentId && x.name === 'review')
761  const verdict = isReview ? parseReview(answer) : null
762  const lines = isReview ? reviewLines(answer) : answerLines(answer)
763  await changeSteps($, s => endAgent(s, agentId, at, verdict, { lines, isFailed: reason !== 'answer' }))
764}
765
766const alertText = (a: DeckApexAlert) =>
767  a.kind === 'step'
768    ? `✗ step ${a.step} failed`
769    : a.kind === 'verify'
770      ? `✗ external verify ${a.verdict} · ${plural(a.findings, 'finding')}`
771      : `■ correction budget spent · ${a.rounds}/${a.cap} rounds`
772
773/** /deck and its aliases: open (the default), close, reset, layout <auto|compact|wide|mini>. */
774async function runCommand($: EngineInterface, args: string) {
775  const [verb = 'open', arg = ''] = args.trim().split(/\s+/)
776  if (verb === 'close') {
777    await $.ui.close({ id: PANE })
778    isPaneOpen = false
779    stopPolling()
780    return { text: 'Deck closed.' }
781  }
782  if (verb === 'reset') {
783    await resetAll($)
784    return { text: 'Deck reset.' }
785  }
786  if (verb === 'layout') {
787    const layout: DeckLayout | null = arg === 'compact' || arg === 'wide' || arg === 'auto' || arg === 'mini' ? arg : null
788    if (!layout) return { text: 'Usage: /deck layout auto|compact|wide|mini' }
789    await update($, view, v => ({ ...normalize(DEFAULT_VIEW, v), layout }))
790    const opened = await openPane($)
791    return { text: opened.isPlaced ? `Deck layout: ${layout}.` : `Layout set to ${layout}; the pane is not shown yet: ${opened.reason}` }
792  }
793  const opened = await openPane($)
794  if (!opened.isPlaced) return { text: `Deck is not shown yet: ${opened.reason}` }
795  return { text: 'Deck opened. Focus it with ctrl+x tab; 1-6 expand cards.' }
796}
797
798// ---------------------------------------------------------------- hooks
799
800export const register: Register = (on, options) => {
801  const cfg = parseConfig(options)
802  const C = PALETTES[cfg.palette]
803
804  on('session.start', async ($, e, next) => {
805    // Each command on its own: one refused leaves the others registered.
806    try {
807      await $.command.register({
808        name: 'deck',
809        description: 'Deck, the live agent and APEX dashboard: open, close, reset, or set the layout',
810        argumentHint: '[open|close|reset|layout auto|compact|wide|mini]',
811      })
812    } catch {
813      // Refused: no /deck this session; the aliases and the observers still run.
814    }
815    try {
816      await $.command.register({ name: 'apex-pane', description: 'Opens the deck pane (alias of /deck)' })
817    } catch {
818      // Refused: no /apex-pane this session; /deck still opens the pane.
819    }
820    try {
821      await $.command.register({ name: 'task-board', description: 'Opens the deck pane (alias of /deck)' })
822    } catch {
823      // Refused: no /task-board this session; /deck still opens the pane.
824    }
825    // A host without usage (headless, an SDK host, a session not yet bound) just starts without it.
826    const u = await $.session.usage().catch(() => null)
827    if (u) {
828      // A refused read measures against the model's window, as an unset variable does.
829      const raw = await $.env.get('CLAUDE_CODE_AUTO_COMPACT_WINDOW').catch(() => undefined)
830      const fill = contextFill(u.context, raw)
831      await update($, usage, x => ({
832        ...normalize(DEFAULT_USAGE, x),
833        ...fill,
834        tokens: u.context.tokens ?? null,
835        costUsd: u.cost?.usd ?? null,
836        limits: u.rateLimits.map(r => ({ kind: r.kind, pct: r.percentUsed })),
837      }))
838    }
839    return next(e)
840  })
841
842  on('session.end', async ($, e, next) => {
843    // The next session's first run is no new run.
844    lastRunDir = null
845    if (e.reason === 'clear') {
846      // A /clear starts every figure over; the poll is kept for it.
847      misses = 0
848      await resetAll($)
849    } else {
850      isPaneOpen = false
851      stopPolling()
852    }
853    return next(e)
854  })
855
856  // The pane closed (its close button, /deck close, another plugin): the 5 s poll stops.
857  on('ui.close', async ($, e, next) => {
858    const closed = await next(e)
859    if (e.id === PANE) {
860      isPaneOpen = false
861      stopPolling()
862    }
863    return closed
864  })
865
866  on('command.run', { command: 'deck' }, async ($, e) => runCommand($, e.args))
867  on('command.run', { command: 'apex-pane' }, async ($, e) => runCommand($, e.args))
868  on('command.run', { command: 'task-board' }, async ($, e) => runCommand($, e.args))
869
870  on('prompt.submit', ($, e, next) => {
871    pollOnce($)
872    return next(e)
873  })
874
875  on('classic.UserPromptSubmit', async ($, e, next) => {
876    await noteMode($, e.permission_mode)
877    return next(e)
878  })
879
880  on('agent.offer', async ($, e, next) => {
881    const offered = await next(e)
882    if (cfg.architect.test(e.agent) || (cfg.matchDescriptions && cfg.architect.test(e.description))) {
883      await update($, roster, r => {
884        const x = normalize(DEFAULT_ROSTER, r)
885        return x.architectTypes.includes(e.agent) ? x : { architectTypes: [...listOf<string>(x.architectTypes), e.agent].slice(-20) }
886      })
887    }
888    return offered
889  })
890
891  on('turn.start', async ($, e, next) => {
892    const [now, cost] = await Promise.all([$.clock.now(), costNow($)])
893    await update($, turn, () => ({ ...DEFAULT_TURN, startedAt: now, costAtStart: cost }))
894    await update($, main, m => ({ ...normalize(DEFAULT_MAIN, m), isRunning: true }))
895    if (stringField(e, 'agentId') === undefined) await wakeRun($)
896    // A background architect's report reaches the main loop as the text opening this turn. The
897    // SubagentHandback tool call (in tool.call) normally carries it first; this is the fallback.
898    const back = e.text ? handbackOf(e.text) : null
899    const a = back ? await getArchitect($) : null
900    if (back && a && a.ids.includes(back.from)) {
901      const advice = adviceLine(back.body)
902      if (advice && advice !== a.lastAdvice) await noteAdvice($, cfg, advice)
903    } else if (e.text) {
904      const p = promptLine(e.text)
905      await say($, p.who, p.text)
906    }
907    return next(e)
908  })
909
910  on('turn.step', async function* ($, e, next) {
911    // The main loop's model is known when its request starts; a long first request shouldn't read "—".
912    if (!e.agentId) {
913      await update($, main, m => {
914        const x = normalize(DEFAULT_MAIN, m)
915        return { ...x, model: e.model, effort: String(e.effort ?? x.effort), steps: x.steps + 1 }
916      })
917    }
918    const result = yield* next(e)
919    const id = e.agentId
920    if (!id) return result
921    const cards = await getCards($)
922    if (cards.some(c => c.id === id)) {
923      const step = { model: e.model, usage: result.usage, stopReason: result.stopReason }
924      await update($, agents, list => listOf<unknown>(list).map(normalizeCard).map(c => (c.id === id ? applyStep(c, step) : c)))
925      if (result.stopReason === 'max_tokens') await say($, await whoIs($, id), 'hit max_tokens', 'error', id)
926    }
927    return result
928  })
929
930  on('session.measure', async ($, e, next) => {
931    const raw = await $.env.get('CLAUDE_CODE_AUTO_COMPACT_WINDOW').catch(() => undefined)
932    const fill = contextFill(e.context, raw)
933    await update($, usage, x => ({
934      ...normalize(DEFAULT_USAGE, x),
935      ...fill,
936      tokens: e.context.tokens ?? null,
937      costUsd: e.cost?.usd ?? null,
938      limits: e.rateLimits.map(r => ({ kind: r.kind, pct: r.percentUsed })),
939    }))
940    return next(e)
941  })
942
943  on('session.compact', async ($, e, next) => {
944    const done = await next(e)
945    if (!e.agentId && e.trigger !== 'precompute') {
946      const now = await $.clock.now()
947      await update($, usage, x => {
948        const u = normalize(DEFAULT_USAGE, x)
949        return { ...u, compactions: u.compactions + 1, lastCompactAt: now }
950      })
951      await say($, 'main', `context compacted (${e.trigger})`)
952    }
953    return done
954  })
955
956  on('tool.call', async ($, e, next) => {
957    const ran = await next(e)
958    await wakeRun($)
959    await noteCallStep($, e, ran)
960    // A refused call carries neither a result nor an error. An inference, not the refusal's own
961    // field: a tool that answers with an undefined result would read as refused too (log text only).
962    const isRefused = ran.result === undefined && ran.isError !== true
963    // A background agent hands its report back through this tool; an architect's report is its advice.
964    if (String(e.tool) === 'SubagentHandback') {
965      const message = (e as unknown as { message?: unknown }).message
966      const a = e.agentId ? await getArchitect($) : null
967      if (a && e.agentId && a.ids.includes(e.agentId) && typeof message === 'string') {
968        const advice = adviceLine(message)
969        if (advice && advice !== a.lastAdvice) await noteAdvice($, cfg, advice)
970      }
971      return ran
972    }
973    if (e.tool === 'Agent') return ran
974    const hasFailed = !isRefused && ran.isError === true
975    const isEdit = !hasFailed && !isRefused && EDIT_TOOLS.has(e.tool)
976    const t0 = await getTurn($)
977    if (isEdit || hasFailed || (!e.agentId && t0.errorStreak > 0)) {
978      await update($, turn, t => afterCall(normalize(DEFAULT_TURN, t), { inSubagent: Boolean(e.agentId), hasFailed, isEdit }))
979    }
980    const text = shorten(describeInput(e.tool, e), 64)
981    if (e.agentId) {
982      const id = e.agentId
983      await update($, agents, list =>
984        listOf<unknown>(list)
985          .map(normalizeCard)
986          .map(c => (c.id === id ? noteTool(c, { tool: e.tool, text, isError: hasFailed || isRefused }) : c)),
987      )
988    }
989    // The log keeps what is worth a glance: refusals, errors and edits; the rest is on the cards.
990    if (isRefused) await say($, await whoIs($, e.agentId), `${text}  refused`, 'error', e.agentId ?? null)
991    else if (hasFailed) await say($, await whoIs($, e.agentId), `${text}  ✗`, 'error', e.agentId ?? null)
992    else if (isEdit) await say($, await whoIs($, e.agentId), text, 'info', e.agentId ?? null)
993    return ran
994  })
995
996  // Background shell: run_in_background, or ctrl+B / auto-background, all answer a backgroundTaskId.
997  on('tool.call', { tool: 'Bash' }, async ($, e, next) => {
998    const ran = await next(e)
999    const id = stringField(ran.result, 'backgroundTaskId')
1000    if (id !== undefined) {
1001      await record(async () => {
1002        const startedAt = await $.clock.now()
1003        const label = stringField(e, 'description') ?? stringField(e, 'command') ?? 'shell'
1004        const toolUseId = stringField(e, 'tool_use_id')
1005        // Set only inside a subagent loop: its shells close with it.
1006        const ownerAgentId = stringField(e, 'agentId')
1007        await changeShells($, current =>
1008          addShell(current, {
1009            id,
1010            label,
1011            startedAt,
1012            ...(toolUseId === undefined ? {} : { toolUseId }),
1013            ...(ownerAgentId === undefined ? {} : { ownerAgentId }),
1014          }),
1015        )
1016      })
1017    }
1018    return ran
1019  }).catch(($, e, next) => next(e))
1020
1021  // A main-loop Skill(apex) call that ran: a run without a folder (yet), a new run once any run
1022  // was seen. A subagent's call, another skill, a failed or refused call: nothing.
1023  on('tool.call', { tool: 'Skill' }, async ($, e, next) => {
1024    const ran = await next(e)
1025    if (stringField(e, 'skill') === 'apex' && !e.agentId && ran.isError !== true && ran.result !== undefined) {
1026      await record(async () => {
1027        const now = await $.clock.now()
1028        const sw = callSwitch(lastRunDir, sessionKey(now))
1029        lastRunDir = sw.last
1030        if (sw.isNew) await clearForNewRun($)
1031        await update($, sessionRun, () => ({ startedAt: now, lastAt: now, args: shorten(stringField(e, 'args') ?? '', 40) }))
1032        // Each call starts the run's live steps over, keyed as the session run.
1033        await update($, apexSteps, () => startSteps(sessionKey(now)))
1034        await update($, openStep, () => null)
1035      })
1036      pollOnce($)
1037    }
1038    return ran
1039  }).catch(($, e, next) => next(e))
1040
1041  // A shell stopped by TaskStop gets no notification row: closed as killed. TaskStop also stops
1042  // agents; stopShell leaves those alone.
1043  on('tool.call', { tool: 'TaskStop' }, async ($, e, next) => {
1044    const ran = await next(e)
1045    if (ran.isError !== true && ran.result !== undefined) {
1046      const id = stringField(ran.result, 'task_id') ?? stringField(e, 'task_id') ?? stringField(e, 'shell_id')
1047      if (id !== undefined) {
1048        await record(async () => {
1049          const at = await $.clock.now()
1050          await changeShells($, current => stopShell(current, id, at))
1051        })
1052      }
1053    }
1054    return ran
1055  }).catch(($, e, next) => next(e))
1056
1057  // A background shell's notification row: the one completion signal a shell has. A render hook
1058  // never writes state, so the write is deferred to a timer; the row itself is drawn unchanged.
1059  on('ui.render', { component: 'UserMessage', props: { origin: { kind: 'task-notification' } } }, ($, e, next) => {
1060    const task: unknown = e.props.task
1061    const note: Notification = {}
1062    const id = stringField(task, 'id')
1063    const toolUseId = stringField(task, 'toolUseId')
1064    const status = stringField(task, 'status')
1065    const durationMs = numberField(task, 'durationMs')
1066    if (id !== undefined) note.id = id
1067    if (toolUseId !== undefined) note.toolUseId = toolUseId
1068    if (status !== undefined) note.status = status
1069    if (durationMs !== undefined) note.durationMs = durationMs
1070    if (note.status !== undefined) {
1071      $.clock.after(0, () => {
1072        $.clock
1073          .now()
1074          .then(at => changeShells($, current => finishByNotification(current, note, at)))
1075          .catch(() => {
1076            // State refused: the shell stays running until its owner's end or a later redraw.
1077          })
1078      })
1079    }
1080    return next(e)
1081  })
1082
1083  // A server-side review tool never reaches tool.call: it shows only in the assistant's rows.
1084  // A subagent's shell notifies that subagent's loop only: its row never reaches the main
1085  // transcript, so it is read here. Read before next: the row is relayed unchanged.
1086  on('session.append', async ($, e, next) => {
1087    const agentId = e.agentId
1088    if (agentId !== undefined && agentId !== '' && e.origin.kind === 'task-notification') {
1089      const notes = parseTaskNotifications(rowText(e.message.content))
1090      if (notes.length > 0) {
1091        await record(async () => {
1092          const at = await $.clock.now()
1093          await changeShells($, current => notes.reduce((list, note) => finishByNotification(list, note, at), current))
1094        })
1095      }
1096    }
1097    if (!e.agentId && e.message.type === 'assistant') {
1098      const a = await getArchitect($)
1099      // Consults this row opened: their result may be in the same row, after the stale read above.
1100      const opened = new Set<string>()
1101      for (const block of e.message.content as unknown as readonly ServerBlock[]) {
1102        if (block.type === 'server_tool_use' && block.name && block.id && cfg.architect.test(block.name)) {
1103          if (a.seen.includes(block.id)) continue
1104          const id = block.id
1105          await update($, architect, x => {
1106            const y = normalize(DEFAULT_ARCHITECT, x)
1107            return { ...y, seen: [...listOf<string>(y.seen), id].slice(-60) }
1108          })
1109          opened.add(id)
1110          await consultStarted($, cfg, id, `${block.name} tool`)
1111        } else if (block.type.endsWith('_tool_result') && block.tool_use_id) {
1112          const id = block.tool_use_id
1113          const isOpen = opened.has(id) || (await getArchitect($)).consults.some(c => c.id === id && c.endAt === null)
1114          if (isOpen) await consultEnded($, cfg, null, id)
1115        }
1116      }
1117    }
1118    return next(e)
1119  })
1120
1121  on('agent.spawn', async ($, e, next) => {
1122    const started = await next(e)
1123    if (!e.parentAgentId) await noteMode($, e.permissionMode)
1124    if (!started.agentId) return started
1125    const id = started.agentId
1126    await wakeRun($)
1127    await noteAgentStep($, e.subagentType, e.description, id, started.model)
1128    if (await isArchitectType($, cfg, e.subagentType)) {
1129      await update($, architect, a => {
1130        const x = normalize(DEFAULT_ARCHITECT, a)
1131        return x.ids.includes(id) ? x : { ...x, ids: [...listOf<string>(x.ids), id].slice(-40) }
1132      })
1133      await consultStarted($, cfg, id, e.subagentType.split(':').pop() ?? 'agent')
1134      return started
1135    }
1136    const at = await $.clock.now()
1137    const fresh: DeckAgentCard = { ...normalizeCard({}), id, type: e.name ?? e.subagentType, model: started.model, description: e.description, spawnedAt: at }
1138    // The prior card is read inside the write: a ctx/steps/tools update landing meanwhile is kept.
1139    let resumed = false
1140    const stored = await update($, agents, list => {
1141      const l = listOf<unknown>(list).map(normalizeCard)
1142      const p = l.find(c => c.id === id)
1143      resumed = p !== undefined
1144      return upsertCard(l, p ? { ...p, model: started.model, description: e.description, status: 'running', endedAt: null, answer: '', lastStop: null, spawnedAt: at } : fresh)
1145    })
1146    const card = listOf<unknown>(stored).map(normalizeCard).find(c => c.id === id) ?? fresh
1147    await say($, shorten(cardTitle(card), 12), `${resumed ? 'resumed' : 'spawned'} · ${card.type}`, 'info', id)
1148    return started
1149  })
1150
1151  on('turn.complete', async ($, e, next) => {
1152    const done = await next(e)
1153    const id = e.agentId
1154    const now = await $.clock.now()
1155    if (!id) {
1156      const [t, cards, cost] = await Promise.all([getTurn($), getCards($), costNow($)])
1157      const r = receiptOf(t, {
1158        durationMs: e.durationMs,
1159        agentsSince: cards.filter(c => c.spawnedAt >= t.startedAt).length,
1160        costNow: cost,
1161        reason: e.reason,
1162      })
1163      await update($, receipt, () => r)
1164      await update($, main, m => ({ ...normalize(DEFAULT_MAIN, m), isRunning: false }))
1165      // The main turn's end: the run clock stops here once no agent or shell of the run runs.
1166      await changeSessionRun($, x => ({ ...x, turnEndAt: now }))
1167      pollOnce($)
1168      return done
1169    }
1170    // Any subagent, the architect too: its still running shells could only ever notify it.
1171    await record(() => changeShells($, current => shellsAfterTurn(current, id, e.reason, now)))
1172    await endAgentStep($, id, e.answer, e.reason)
1173    if ((await getArchitect($)).ids.includes(id)) {
1174      await consultEnded($, cfg, e.answer, id)
1175      return done
1176    }
1177    const cards = await getCards($)
1178    if (cards.some(c => c.id === id)) {
1179      const status = e.reason === 'answer' ? 'done' : e.reason === 'aborted' ? 'stopped' : 'failed'
1180      await update($, agents, list =>
1181        listOf<unknown>(list)
1182          .map(normalizeCard)
1183          .map(c => (c.id === id ? { ...c, status, endedAt: now, answer: shorten(e.answer, 400) } : c)),
1184      )
1185      const card = cards.find(c => c.id === id)
1186      const took = card ? fmtDuration(now - card.spawnedAt) : ''
1187      await say($, await whoIs($, id), status === 'done' ? `done · ${took}` : status, status === 'done' ? 'done' : 'error', id)
1188    }
1189    return done
1190  })
1191
1192  // ---------------------------------------------------------------- drawing
1193
1194  on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
1195    // Drawn means open (a hot reload forgets the flag; the surface does not): polled while it is.
1196    if (!isPaneOpen) {
1197      isPaneOpen = true
1198      startPolling($)
1199    }
1200    const els = $.ui.resolve(e)
hooks/core.ts 428 lines
1// Pure data: defaults, reducers, formatting and layout math. Nothing here touches `$`, so every
2// behaviour is testable directly (the test kit cannot raise a subagent's tool call; these
3// functions are what the hooks apply). From Flightdeck v0.3.2 (MIT, Stephen Casella).
4import type {
5  DeckAgentCard,
6  DeckArchitect,
7  DeckLayout,
8  DeckLogLine,
9  DeckMain,
10  DeckMoment,
11  DeckReceipt,
12  DeckRoster,
13  DeckToolNote,
14  DeckTurn,
15  DeckUsage,
16  DeckView,
17} from '../types'
18
19// ---------------------------------------------------------------- defaults
20
21export const DEFAULT_MAIN: DeckMain = { model: '', effort: '', mode: '', steps: 0, isRunning: false }
22export const DEFAULT_USAGE: DeckUsage = {
23  pct: null,
24  tokens: null,
25  window: 0,
26  costUsd: null,
27  limits: [],
28  compactions: 0,
29  lastCompactAt: null,
30}
31export const DEFAULT_ARCHITECT: DeckArchitect = { consults: [], ids: [], seen: [], lastAdvice: '' }
32export const DEFAULT_TURN: DeckTurn = { edits: 0, errorStreak: 0, errors: 0, isReviewing: false, startedAt: 0, costAtStart: null }
33export const DEFAULT_VIEW: DeckView = { expanded: null, layout: null }
34export const DEFAULT_ROSTER: DeckRoster = { architectTypes: [] }
35
36const isObject = (v: unknown): v is Record<string, unknown> => typeof v === 'object' && v !== null && !Array.isArray(v)
37
38/** A stored object merged over its defaults, so a value saved under an older shape still reads. */
39export const normalize = <T extends object>(def: T, stored: unknown): T =>
40  isObject(stored) ? ({ ...def, ...stored } as T) : def
41
42/** A stored list, or empty when what is stored is not a list. */
43export const listOf = <T>(stored: unknown): T[] => (Array.isArray(stored) ? (stored as T[]) : [])
44
45// The window context fill is measured against: CLAUDE_CODE_AUTO_COMPACT_WINDOW read as the
46// engine reads it (leading integer, clamped to 100k–1M, capped at the model's window), else the
47// model's window. Same text in the status-bar and deck mods: keep them in step.
48export function compactWindow(modelWindow: number, raw: string | undefined): number {
49  const set = raw === undefined ? Number.NaN : Number.parseInt(raw, 10)
50  if (!Number.isFinite(set)) return modelWindow
51  const clamped = Math.min(Math.max(set, 100_000), 1_000_000)
52  return modelWindow > 0 ? Math.min(clamped, modelWindow) : clamped
53}
54
55// The context fill against that window, 0 to 100; the engine's own percent when no token count.
56export function contextFill(
57  context: { tokens?: number; window: number; percent?: number },
58  raw: string | undefined,
59): { window: number; pct: number | null } {
60  const window = compactWindow(context.window, raw)
61  if (context.tokens === undefined || window <= 0) return { window, pct: context.percent ?? null }
62  return { window, pct: Math.min(100, (context.tokens / window) * 100) }
63}
64
65export const normalizeCard = (stored: unknown): DeckAgentCard =>
66  normalize<DeckAgentCard>(
67    {
68      id: '',
69      type: 'agent',
70      model: '',
71      description: '',
72      status: 'running',
73      spawnedAt: 0,
74      endedAt: null,
75      ctx: 0,
76      out: 0,
77      steps: 0,
78      lastStop: null,
79      tools: [],
80      answer: '',
81    },
82    stored,
83  )
84
85/** A spawn's card: a resumed id replaces its old card (one card, one set of keys per id), last in line. */
86export const upsertCard = (list: DeckAgentCard[], card: DeckAgentCard, max = 24): DeckAgentCard[] =>
87  [...list.filter(c => c.id !== card.id), card].slice(-max)
88
89export const normalizeLog = (stored: unknown): DeckLogLine[] =>
90  listOf<Record<string, unknown>>(stored).map(l => ({
91    at: typeof l.at === 'number' ? l.at : 0,
92    who: String(l.who ?? ''),
93    text: String(l.text ?? ''),
94    agentId: typeof l.agentId === 'string' ? l.agentId : null,
95    kind: l.kind === 'error' || l.kind === 'consult' || l.kind === 'done' ? l.kind : 'info',
96  }))
97
98// ---------------------------------------------------------------- config
99
100export type Panel = 'main' | 'architect' | 'agents' | 'background' | 'receipt' | 'log'
101const PANELS: readonly Panel[] = ['main', 'architect', 'agents', 'background', 'receipt', 'log']
102
103export type Config = {
104  architect: RegExp
105  architectLabel: string
106  panels: Panel[]
107  motion: boolean
108  moments: boolean
109  matchDescriptions: boolean
110  maxCards: number
111  layout: DeckLayout
112  palette: Palette
113}
114
115const safeRegExp = (source: string, fallback: string) => {
116  try {
117    return new RegExp(source || fallback, 'i')
118  } catch {
119    return new RegExp(fallback, 'i')
120  }
121}
122
123/** The plugin's `/config` values, read leniently: anything malformed falls back to the default. */
124export const parseConfig = (o: Readonly<Record<string, unknown>>): Config => {
125  const str = (k: string, d: string) => (typeof o[k] === 'string' && o[k] !== '' ? (o[k] as string) : d)
126  const bool = (k: string, d: boolean) => (typeof o[k] === 'boolean' ? (o[k] as boolean) : d)
127  const panels = str('panels', PANELS.join(','))
128    .split(',')
129    .map(s => s.trim())
130    .filter((p): p is Panel => (PANELS as readonly string[]).includes(p))
131  const layout = str('layout', 'auto')
132  const max = typeof o.maxCards === 'number' ? Math.round(o.maxCards) : 3
133  return {
134    architect: safeRegExp(str('architectPattern', ''), 'advisor|architect'),
135    architectLabel: str('architectLabel', 'ARCHITECT'),
136    panels: panels.length > 0 ? [...new Set(panels)] : [...PANELS],
137    motion: str('motion', 'while-active') !== 'off',
138    moments: bool('moments', true),
139    matchDescriptions: bool('matchDescriptions', false),
140    maxCards: Math.min(6, Math.max(1, max)),
141    layout: layout === 'compact' || layout === 'wide' || layout === 'mini' ? layout : 'auto',
142    palette: str('palette', 'theme') === 'pastel' ? 'pastel' : 'theme',
143  }
144}
145
146// ---------------------------------------------------------------- palette
147
148export type Palette = 'theme' | 'pastel'
149export type Colors = Record<'main' | 'agent' | 'ok' | 'arch' | 'apex' | 'amber' | 'warn' | 'dim' | 'faint' | 'text', string>
150
151/**
152 * `theme` names the person's own theme colours (they follow light, dark and colour-blind themes);
153 * `pastel` is fixed hex tuned for dark terminals.
154 */
155export const PALETTES: Record<Palette, Colors> = {
156  theme: {
157    main: 'claude',
158    agent: 'suggestion',
159    ok: 'success',
160    arch: 'merged',
161    apex: 'planMode',
162    amber: 'warning',
163    warn: 'error',
164    dim: 'inactive',
165    faint: 'subtle',
166    text: 'text',
167  },
168  pastel: {
169    main: '#7dd3fc',
170    agent: '#93c5fd',
171    ok: '#86efac',
172    arch: '#c4b5fd',
173    apex: '#fdba74',
174    amber: '#fcd34d',
175    warn: '#fca5a5',
176    dim: '#6b7280',
177    faint: '#3f4654',
178    text: '#e5e7eb',
179  },
180}
181
182/** SVG cannot name theme keys: mid-tone colours that read on light and dark backgrounds. */
183export const SVG_COLORS = { running: '#3b82f6', done: '#16a34a', failed: '#dc2626', other: '#8b5cf6', label: '#6b7280' }
184
185// ---------------------------------------------------------------- formatting
186
187/**
188 * A model id as people say it, from any provider's spelling: `claude-opus-5-5[1m]` → `Opus 5.5 1M`,
189 * `us.anthropic.claude-sonnet-4-5-20250929-v1:0` → `Sonnet 4.5`, `claude-3-5-haiku-20241022` →
190 * `Haiku 3.5`. Anything else is shown as given, cut to 22 characters.
191 */
192export const prettyModel = (id: string) => {
193  if (!id) return '—'
194  const cap = (f: string) => f.charAt(0).toUpperCase() + f.slice(1)
195  const big = /\[1m\]|-1m\b/i.test(id) ? ' 1M' : ''
196  const now = /claude-([a-z]+)-(\d+)(?:-(\d{1,2}))?(?:-\d{8})?(?![\d])/i.exec(id)
197  if (now?.[1] && !/^\d/.test(now[1])) return `${cap(now[1].toLowerCase())} ${now[2]}${now[3] ? `.${now[3]}` : ''}${big}`
198  const old = /claude-(\d+)(?:-(\d))?-([a-z]+)/i.exec(id)
199  if (old?.[3]) return `${cap(old[3].toLowerCase())} ${old[1]}${old[2] ? `.${old[2]}` : ''}${big}`
200  return shorten(id, 22)
201}
202
203export const shorten = (s: string, n: number) => {
204  const one = s.replace(/\s+/g, ' ').trim()
205  return n <= 0 ? '' : one.length > n ? `${one.slice(0, Math.max(0, n - 1)).trimEnd()}…` : one
206}
207
208export const kTokens = (n: number) =>
209  n >= 1_000_000 ? `${(n / 1_000_000).toFixed(1)}M` : n >= 1000 ? `${Math.round(n / 1000)}k` : String(n)
210
211export const fmtDuration = (ms: number) => {
212  const s = Math.max(0, Math.round(ms / 1000))
213  if (s < 60) return `${s}s`
214  const m = Math.floor(s / 60)
215  return m < 60 ? `${m}m${String(s % 60).padStart(2, '0')}s` : `${Math.floor(m / 60)}h${String(m % 60).padStart(2, '0')}m`
216}
217
218/** A running clock as the live cards draw it: m:ss, or XhYY past an hour. */
219export const fmtTimer = (ms: number) => {
220  const s = Math.max(0, Math.floor(ms / 1000))
221  const m = Math.floor(s / 60)
222  return m < 60 ? `${m}:${String(s % 60).padStart(2, '0')}` : `${Math.floor(m / 60)}h${String(m % 60).padStart(2, '0')}`
223}
224
225export const fmtClock = (ms: number) => (ms > 0 ? new Date(ms).toTimeString().slice(0, 8) : '--:--:--')
226
227/** `1 error`, `2 errors`. */
228export const plural = (n: number, word: string) => `${n} ${word}${n === 1 ? '' : 's'}`
229
230export const fmtUsd = (n: number) => (n >= 100 ? `$${Math.round(n)}` : `$${n.toFixed(2)}`)
231
232/** A gauge of `width` cells: ▰ filled, ▱ empty. */
233export const gauge = (pct: number, width: number) => {
234  const full = Math.max(0, Math.min(width, Math.round((pct / 100) * width)))
235  return { on: '▰'.repeat(full), off: '▱'.repeat(width - full) }
236}
237
238/** A rate-limit window's short name: `five_hour` → `5h`, `seven_day_opus` → `7d opus`. */
239export const limitLabel = (kind: string) =>
240  kind
241    .replace(/five[_ -]?hours?/i, '5h')
242    .replace(/seven[_ -]?days?/i, '7d')
243    .replace(/[_-]+/g, ' ')
244    .trim()
245
246// ---------------------------------------------------------------- redaction
247
248const SECRETS: [RegExp, string][] = [
249  [/(authorization\s*[:=]\s*)(bearer\s+|basic\s+)?\S+/gi, '$1$2•••'],
250  [/\b(bearer)\s+[A-Za-z0-9._~+/-]{8,}=*/gi, '$1 •••'],
251  [/\b(sk|pk|rk|ghp|gho|ghs|github_pat|xox[abprs])[-_][A-Za-z0-9_-]{8,}/g, '•••'],
252  [/((?:api[_-]?key|access[_-]?token|token|secret|password|passwd|pwd)\s*[=:]\s*)("[^"]*"|'[^']*'|\S+)/gi, '$1•••'],
253  [/(--(?:token|password|api-key|secret)[= ])\S+/gi, '$1•••'],
254  [/(\b[A-Z][A-Z0-9_]*(?:KEY|TOKEN|SECRET|PASSWORD)=)\S+/g, '$1•••'],
255  [/(\b[a-z][a-z0-9+.-]*:\/\/[^\s/:@]+:)[^\s@]+@/gi, '$1•••@'],
256]
257
258/** What the log and the cards may store: credentials masked before anything is written to state. */
259export const redact = (s: string) => SECRETS.reduce((t, [re, to]) => t.replace(re, to), s)
260
261// ---------------------------------------------------------------- tools
262
263export const EDIT_TOOLS = new Set(['Edit', 'Write', 'NotebookEdit'])
264
265/** One line saying what a call was about: its command, path or pattern; redacted. */
266export const describeInput = (tool: string, input: unknown) => {
267  const i = isObject(input) ? input : {}
268  const path = typeof i.file_path === 'string' ? i.file_path.split(/[\\/]/).slice(-2).join('/') : ''
269  const what =
270    typeof i.command === 'string'
271      ? i.command
272      : path || (typeof i.pattern === 'string' ? i.pattern : typeof i.url === 'string' ? i.url : typeof i.description === 'string' ? i.description : '')
273  return redact(what ? `${tool} → ${what}` : tool)
274}
275
276// ---------------------------------------------------------------- turn and architect
277
278/**
279 * The turn after one tool call. Errors count in the main loop only (a subagent's failure is its
280 * own); edits count from every loop, so delegated work still reaches "before done".
281 */
282export const afterCall = (t: DeckTurn, c: { inSubagent: boolean; hasFailed: boolean; isEdit: boolean }): DeckTurn => ({
283  ...t,
284  errorStreak: c.inSubagent ? t.errorStreak : c.hasFailed ? t.errorStreak + 1 : 0,
285  errors: t.errors + (!c.inSubagent && c.hasFailed ? 1 : 0),
286  edits: t.edits + (c.isEdit ? 1 : 0),
287})
288
289/** Which of the architect's three moments a consult falls at: an inference over this turn so far. */
290export const momentOf = (t: Pick<DeckTurn, 'edits' | 'errorStreak'>): DeckMoment =>
291  t.errorStreak >= 2 ? 'error repeats' : t.edits === 0 ? 'before a plan' : 'before done'
292
293export const startConsult = (a: DeckArchitect, c: { id: string; at: number; moment: DeckMoment; via: string }): DeckArchitect =>
294  a.consults.some(x => x.id === c.id) ? a : { ...a, consults: [...a.consults, { ...c, endAt: null }].slice(-40) }
295
296/** Ends the open consult (the latest without an end), or the one named. */
297export const endConsult = (a: DeckArchitect, at: number, advice: string | null, id?: string): DeckArchitect => {
298  const open = [...a.consults].reverse().find(c => c.endAt === null && (id === undefined || c.id === id))
299  return {
300    ...a,
301    consults: a.consults.map(c => (c === open ? { ...c, endAt: at } : c)),
302    lastAdvice: advice ?? a.lastAdvice,
303  }
304}
305
306export const isAdvising = (a: DeckArchitect) => a.consults.some(c => c.endAt === null)
307
308/** A one-row timeline of consults across `width` cells: ◆ a consult, ━ while it ran. */
309export const consultTimeline = (a: DeckArchitect, now: number, width: number) => {
310  if (a.consults.length === 0 || width < 4) return '─'.repeat(Math.max(0, width))
311  const first = a.consults[0]?.at ?? now
312  const span = Math.max(1, now - first)
313  const cells = Array.from({ length: width }, () => '─')
314  for (const c of a.consults) {
315    const from = Math.min(width - 1, Math.floor(((c.at - first) / span) * (width - 1)))
316    const to = Math.min(width - 1, Math.floor((((c.endAt ?? now) - first) / span) * (width - 1)))
317    for (let i = from + 1; i <= to; i += 1) cells[i] = '━'
318    cells[from] = '◆'
319  }
320  return cells.join('')
321}
322
323export const receiptOf = (t: DeckTurn, o: { durationMs: number; agentsSince: number; costNow: number | null; reason: string }): DeckReceipt => ({
324  durationMs: o.durationMs,
325  agents: o.agentsSince,
326  edits: t.edits,
327  errors: t.errors,
328  costDelta: o.costNow !== null && t.costAtStart !== null && o.costNow - t.costAtStart >= 0.005 ? o.costNow - t.costAtStart : null,
329  reason: o.reason,
330})
331
332// ---------------------------------------------------------------- agents
333
334type StepUsage = { input_tokens?: number; cache_read_input_tokens?: number; cache_creation_input_tokens?: number; output_tokens?: number } | null
335
336/** A card after one of its model requests: its context is the latest step's whole input; output adds up. */
337export const applyStep = (c: DeckAgentCard, s: { model: string; usage: StepUsage; stopReason: string | null }): DeckAgentCard => {
338  const u = s.usage ?? {}
339  const ctx = (u.input_tokens ?? 0) + (u.cache_read_input_tokens ?? 0) + (u.cache_creation_input_tokens ?? 0)
340  return {
341    ...c,
342    model: c.model || s.model,
343    steps: c.steps + 1,
344    ctx: ctx > 0 ? ctx : c.ctx,
345    out: c.out + (u.output_tokens ?? 0),
346    lastStop: s.stopReason,
347  }
348}
349
350export const noteTool = (c: DeckAgentCard, n: DeckToolNote): DeckAgentCard => ({ ...c, tools: [...c.tools, n].slice(-3) })
351
352/** Swimlane geometry: each agent's bar on one shared axis from the first spawn to now. */
353export const lanes = (cards: DeckAgentCard[], now: number, width: number) => {
354  const start = Math.min(...cards.map(c => c.spawnedAt).filter(n => n > 0), now)
355  const span = Math.max(1, now - start)
356  return cards.map(c => {
357    const from = Math.floor(((Math.max(c.spawnedAt, start) - start) / span) * width)
358    const to = Math.max(from + 1, Math.ceil((((c.endedAt ?? now) - start) / span) * width))
359    return { id: c.id, before: Math.min(from, width), bar: Math.min(to, width) - Math.min(from, width), after: width - Math.min(to, width) }
360  })
361}
362
363// ---------------------------------------------------------------- layout
364
365/** How many log lines fit: what the other panels leave, never fewer than 4 nor more than 8. */
366export const logRows = (bodyRows: number, used: number) => Math.max(4, Math.min(8, bodyRows - used - 3))
367
368/** Legend items that fit on one row of `width` cells, in order; the rest are dropped. */
369export const fitLegend = <T extends { label: string }>(items: T[], width: number) => {
370  const out: T[] = []
371  let used = 0
372  for (const it of items) {
373    const w = it.label.length + 4
374    if (used + w > width) break
375    out.push(it)
376    used += w
377  }
378  return out
379}
380
381/** A card's title row: the task in the agent's own words, the type only when there is none. */
382export const cardTitle = (c: DeckAgentCard) => c.description || c.type
383
384/** A title split over two rows at a word boundary: `first` cells on row one, `rest` on row two. */
385export const titleLines = (title: string, first: number, rest: number): [string, string] => {
386  const t = title.replace(/\s+/g, ' ').trim()
387  if (t.length <= first) return [t, '']
388  const cut = t.lastIndexOf(' ', first)
389  const at = cut > 0 ? cut : first
390  return [t.slice(0, at).trim(), shorten(t.slice(at), rest)]
391}
392
393/**
394 * What a turn's opening text was, for the log: the person's words, or for a turn the engine
395 * opened with a tagged message (a subagent's hand-back, a task notification), that message's kind.
396 */
397export const promptLine = (text: string): { who: string; text: string } => {
398  const tag = /^\s*<([a-z][\w-]*)/i.exec(text)?.[1]
399  if (!tag) return { who: 'you', text: shorten(text, 70) }
400  const from = /\bfrom="([^"]+)"/.exec(text)?.[1]
401  return { who: 'engine', text: shorten(`${tag.replace(/[-_]/g, ' ')}${from ? ` from ${from.slice(0, 8)}` : ''}`, 70) }
402}
403
404/**
405 * A subagent's hand-back message: who sent it and the first line of what it said. The report
406 * follows a framing header in the message; without one, the first line after the opening tag.
407 */
408export const handbackOf = (text: string): { from: string; body: string } | null => {
409  const from = /^\s*<agent-message\s+from="([^"]+)"/.exec(text)?.[1]
410  if (!from) return null
411  const afterHeader = text.split(/The report follows:\s*\n/)[1]
412  const rest = afterHeader ?? text.replace(/^\s*<agent-message[^>]*>/, '')
413  const body =
414    rest
415      .split('\n')
416      .map(l => l.trim())
417      .find(l => l && !l.startsWith('[') && !l.startsWith('<') && !l.startsWith('</')) ?? ''
418  return body ? { from, body } : null
419}
420
421/** The advice line a pane shows for a report: its first real line, markdown markers stripped, cut to 160. */
422export const adviceLine = (report: string) => {
423  const first = report.split('\n').map(l => l.trim()).find(l => l && !l.startsWith('[') && !l.startsWith('<')) ?? ''
424  return shorten(first.replace(/\*\*|__/g, '').replace(/^[#>*\s-]+/, ''), 160)
425}
426
427export const elapsedOf = (c: DeckAgentCard, now: number) => (c.endedAt ?? now) - c.spawnedAt
428
hooks/apex.ts 614 lines
1// Pure reading of an APEX run: its 00-context.md (header and Progress table, every drifted
2// spelling tolerated), its liveness rule, the live steps its tool calls stand for, the external
3// verdict file, and what the block and the log show of it. No `$`, no clock, no I/O.
4
5import type {
6  DeckApexLiveStep,
7  DeckApexRun,
8  DeckApexSessionRun,
9  DeckApexStep,
10  DeckApexStepKind,
11  DeckApexStepName,
12  DeckApexSteps,
13} from '../types'
14import { fmtTimer, shorten } from './core'
15
16// ---------------------------------------------------------------- context file
17
18/** A run is live only while its context file moved in the last 6 hours. */
19export const STALE_MS = 6 * 60 * 60 * 1000
20
21const clean = (value: string): string => value.replace(/\*\*/g, '').replace(/`/g, '').trim()
22
23export function statusKind(status: string): DeckApexStepKind {
24  const s = clean(status).toLowerCase()
25  if (/^(complete|done|✅)/.test(s)) return 'done'
26  if (/^pending/.test(s)) return 'pending'
27  if (/^(in[ _]progress|en cours|running)/.test(s)) return 'running'
28  if (/^(skipped|supprimé|n\/a)/.test(s)) return 'skipped'
29  if (/^(red|failed|échoué)(?![a-z])/.test(s)) return 'failed'
30  return 'other'
31}
32
33// "Key: value", "**Key:** value", "**Key**: value", "- Key: value".
34const FIELD = /^\s*(?:[-*]\s+)?\**\s*([A-Za-zÀ-ÿ][A-Za-zÀ-ÿ ]*?)\s*\**\s*:\s*(.*)$/
35
36/** A header value's head: `Standard (mods UI) — files…` → `Standard`. */
37function headOf(value: string): string {
38  const head = value.split(/\s+—\s+|\s+→\s+|\s*\(|;|\.\s/)[0] ?? value
39  return head.trim()
40}
41
42function readSteps(lines: readonly string[]): DeckApexStep[] {
43  const start = lines.findIndex(l => /^##\s+progress\b/i.test(l))
44  if (start < 0) return []
45  const steps: DeckApexStep[] = []
46  for (const line of lines.slice(start + 1)) {
47    if (/^##\s/.test(line)) break
48    if (!line.trim().startsWith('|')) continue
49    if (/^[\s|:-]+$/.test(line)) continue
50    const cells = line.split('|').slice(1, -1).map(clean)
51    const step = cells[0] ?? ''
52    const status = cells[1] ?? ''
53    if (step === '' || /^step$/i.test(step)) continue
54    steps.push({ step, status, kind: statusKind(status) })
55  }
56  return steps
57}
58
59export function currentStep(steps: readonly DeckApexStep[]): string | undefined {
60  return (steps.find(s => s.kind === 'running') ?? steps.find(s => s.kind === 'pending'))?.step
61}
62
63export function parseContext(text: string, dirName: string): DeckApexRun {
64  const lines = text.replace(/\r\n?/g, '\n').split('\n')
65  const headerEnd = lines.findIndex(l => /^##\s/.test(l))
66  const header = headerEnd < 0 ? lines : lines.slice(0, headerEnd)
67
68  const heading = header.find(l => /^#\s+\S/.test(l))
69  const headingText = heading === undefined ? undefined : clean(heading.replace(/^#\s+/, ''))
70  const apexTitle = headingText?.match(/^APEX\s*[:—–-]\s*(.+)$/i)?.[1]
71  const title = clean(apexTitle ?? headingText ?? '') || dirName
72
73  const fields = new Map<string, string>()
74  for (const line of header) {
75    const match = FIELD.exec(line)
76    const key = match?.[1]?.trim().toLowerCase()
77    const value = match?.[2]
78    if (key === undefined || value === undefined || fields.has(key)) continue
79    fields.set(key, clean(value))
80  }
81
82  const tierField = fields.get('tier')
83  const modeField = fields.get('mode')
84  const flags = fields.get('flags') ?? fields.get('flags résolus')
85  const tier =
86    tierField !== undefined && tierField !== ''
87      ? headOf(tierField)
88      : modeField !== undefined && modeField !== ''
89        ? headOf(modeField)
90        : flags?.match(/\bmode\s+([^\s,;)]+)/i)?.[1]
91
92  const branch = (fields.get('branch') ?? fields.get('branche'))?.split(/\s+/)[0]
93
94  const run: DeckApexRun = { title, steps: readSteps(lines) }
95  if (tier !== undefined && tier !== '') run.tier = tier
96  if (branch !== undefined && branch !== '') run.branch = branch
97  const current = currentStep(run.steps)
98  if (current !== undefined) run.currentStep = current
99  return run
100}
101
102/**
103 * Live: modified in the last `staleMs` (STALE_MS by default), its 09-finish row neither done nor
104 * skipped, and, when it has a Progress table, a pending or running row left.
105 */
106export function isLive(run: DeckApexRun, mtimeMs: number, now: number, staleMs: number = STALE_MS): boolean {
107  if (now - mtimeMs >= staleMs) return false
108  const finish = run.steps.find(s => /finish/i.test(s.step))
109  if (finish !== undefined && (finish.kind === 'done' || finish.kind === 'skipped')) return false
110  if (run.steps.length === 0) return true
111  return run.steps.some(s => s.kind === 'pending' || s.kind === 'running')
112}
113
114/** APEX's main steps in order: the pending dots of a run read from its files. */
115export const KNOWN_STEPS: readonly string[] = [
116  '00-init',
117  '01-analyze',
118  '02-plan',
119  '03-execute',
120  '04-validate',
121  '05-examine',
122  '06-resolve',
123  '07-tests',
124  '08-run-tests',
125  '09-finish',
126]
127
128// A step file: `NN-name.md` or `NNx-name.md`; 00-context.md is the run's header, not a step.
129const STEP_FILE = /^(?!00-context\.md$)(\d\d[a-z]?-.+)\.md$/
130const FINISH = /^\d\d[a-z]?-finish$/
131
132/** A run folder without 00-context.md is live only while one of its step files moved in the last hour. */
133export const BARE_STALE_MS = 60 * 60 * 1000
134
135/** The newest step file's mtime among `files`, or -Infinity when none is a step file. */
136export function newestStep(files: readonly { name: string; mtimeMs: number }[]): number {
137  return Math.max(-Infinity, ...files.filter(f => STEP_FILE.test(f.name)).map(f => f.mtimeMs))
138}
139
140/**
141 * A run folder without 00-context.md is shown only off the trunk (HEAD neither master nor main)
142 * and while its newest step file is under BARE_STALE_MS old; the rest is isLive's rule.
143 */
144export function bareShown(run: DeckApexRun, stepMs: number, head: string | undefined, now: number): boolean {
145  if (head === 'master' || head === 'main') return false
146  return isLive(run, stepMs, now, BARE_STALE_MS)
147}
148
149/**
150 * The run dir a poll found against the last one seen this session: new only when a previous run
151 * was seen and the dir differs. `last` survives a poll with no run (a miss, an ended run), so the
152 * same run coming back is not new. From a session key the poll never finds a new run: the call
153 * that set it already counted (callSwitch), and the folder it then writes is that same run.
154 */
155export function runSwitch(last: string | null, dir: string | null): { isNew: boolean; last: string | null } {
156  if (dir === null) return { isNew: false, last }
157  return { isNew: last !== null && last !== dir && !isSessionDir(last), last: dir }
158}
159
160// ---------------------------------------------------------------- session run
161
162// A session run's key, in the run dir's place: never a folder name (a folder holds no colon here).
163const SESSION_PREFIX = 'session:'
164
165/** The run key of the main-loop Skill(apex) call started at `startedAt`. */
166export const sessionKey = (startedAt: number): string => `${SESSION_PREFIX}${startedAt}`
167
168/** A run key set by a Skill(apex) call rather than by a folder under .claude/output/apex. */
169export const isSessionDir = (dir: string): boolean => dir.startsWith(SESSION_PREFIX)
170
171/** A main-loop Skill(apex) call: a new run once any run was seen this session. */
172export function callSwitch(last: string | null, key: string): { isNew: boolean; last: string } {
173  return { isNew: last !== null, last: key }
174}
175
176/**
177 * The run a main-loop Skill(apex) call stands for while no run folder is live: shown off the
178 * trunk (HEAD neither master nor main) and under BARE_STALE_MS after the last call; HEAD as
179 * header, no tier, one current `apex` row.
180 */
181export function sessionRunOf(at: DeckApexSessionRun | null, head: string | undefined, now: number): DeckApexRun | null {
182  if (at === null || head === 'master' || head === 'main' || now - at.lastAt >= BARE_STALE_MS) return null
183  const run: DeckApexRun = {
184    title: 'apex',
185    steps: [{ step: 'apex', status: 'in progress', kind: 'running' }],
186    currentStep: 'apex',
187    dir: sessionKey(at.startedAt),
188  }
189  if (head !== undefined) run.branch = head
190  return run
191}
192
193/**
194 * A run folder without 00-context.md, read from its step files: title the folder, no tier, each
195 * present step done, the most recently modified one current (a finish file never: the run ended),
196 * the known steps after it pending.
197 */
198export function runFromFiles(dirName: string, files: readonly { name: string; mtimeMs: number }[]): DeckApexRun {
199  const present = new Map<string, number>()
200  for (const file of files) {
201    const step = STEP_FILE.exec(file.name)?.[1]
202    if (step !== undefined) present.set(step, Math.max(present.get(step) ?? 0, file.mtimeMs))
203  }
204  let current: string | undefined
205  let newest = -Infinity
206  for (const [step, mtimeMs] of present) {
207    // A finish file ends the run: done, never current.
208    if (FINISH.test(step)) continue
209    if (mtimeMs > newest || (mtimeMs === newest && current !== undefined && step > current)) {
210      current = step
211      newest = mtimeMs
212    }
213  }
214  const names = new Set(present.keys())
215  if (current !== undefined) for (const step of KNOWN_STEPS) if (step > current) names.add(step)
216  const steps: DeckApexStep[] = [...names].sort().map(step =>
217    step === current
218      ? { step, status: 'in progress', kind: 'running' }
219      : present.has(step)
220        ? { step, status: 'complete', kind: 'done' }
221        : { step, status: 'pending', kind: 'pending' },
222  )
223  const run: DeckApexRun = { title: dirName, steps }
224  if (current !== undefined) run.currentStep = current
225  return run
226}
227
228/** The branch a .git/HEAD file names, or undefined (detached HEAD, anything unrecognised). */
229export function headBranch(text: string): string | undefined {
230  const name = /^ref:\s*refs\/heads\/(\S+)\s*$/.exec(text.trim())?.[1]
231  return name === undefined || name === '' ? undefined : name
232}
233
234/** Off-branch only when both the run's branch and HEAD's are known and differ. */
235export function onBranch(run: DeckApexRun, head: string | undefined): boolean {
236  return run.branch === undefined || head === undefined || run.branch === head
237}
238
239// ---------------------------------------------------------------- live steps
240
241/** The steps in the order the row shows them; edit, gate and ship always, the rest once seen. */
242export const STEP_ORDER: readonly DeckApexStepName[] = ['plan', 'edit', 'implement', 'tests', 'gate', 'Codex', 'review', 'ship']
243const ALWAYS: ReadonlySet<DeckApexStepName> = new Set<DeckApexStepName>(['edit', 'gate', 'ship'])
244
245const EDITING = new Set(['Edit', 'Write', 'NotebookEdit'])
246const PLAN_PATH = /(^|\/)\.claude\/output\/apex\//
247const CODEX = /apex-verify-external/
248const SHIP = /\bgit\s+(commit|push)\b|\bgh\s+pr\s+(create|merge)\b/
249const GATE = /nix flake check|pnpm (verify|test|typecheck|lint)|claude plugin (test|validate)|\btsc\b|cargo (check|test)/
250
251/**
252 * The step a tool call stands for, or null. Edits count from every loop; Bash (gate, Codex, ship)
253 * from the main loop only: a reviewer's probes are no gate.
254 */
255export function classifyCall(
256  tool: string,
257  input: { file_path?: string; notebook_path?: string; command?: string },
258  inSubagent: boolean,
259): DeckApexStepName | null {
260  if (EDITING.has(tool)) {
261    const path = input.file_path ?? input.notebook_path ?? ''
262    return PLAN_PATH.test(path) ? 'plan' : 'edit'
263  }
264  if (tool !== 'Bash' || inSubagent) return null
265  const command = input.command ?? ''
266  if (CODEX.test(command)) return 'Codex'
267  if (SHIP.test(command)) return 'ship'
268  if (GATE.test(command)) return 'gate'
269  return null
270}
271
272const IMPLEMENTERS = new Set(['frontend-expert', 'backend-expert', 'nix-expert', 'debugger', 'quick-fix'])
273const REVIEWERS = new Set(['code-reviewer', 'security-auditor'])
274
275/** The step a spawned agent stands for (its type's last `:` segment), or null. */
276export function classifyAgent(subagentType: string): 'implement' | 'tests' | 'review' | null {
277  const type = subagentType.split(':').pop() ?? subagentType
278  if (IMPLEMENTERS.has(type)) return 'implement'
279  if (type === 'test-runner') return 'tests'
280  if (REVIEWERS.has(type)) return 'review'
281  return null
282}
283
284/** The external verification's verdict line in a Bash output, or null. */
285export function parseCodex(output: string): { verdict: string; findings: number } | null {
286  const match = /EXTERNAL-VERIFY (PASS|FAIL|BLOCKED)\b(?:.*?findings=(\d+))?/.exec(output)
287  const verdict = match?.[1]
288  if (verdict === undefined) return null
289  return { verdict, findings: Number(match?.[2] ?? 0) }
290}
291
292// A report line without its markdown: `**`, heading `#`s, list bullets' leading spaces.
293const bare = (line: string): string => line.replace(/\*\*/g, '').replace(/^\s*#+\s*/, '').trim()
294const LABELLED = /^\s*verdict\s*:\s*(APPROVED|NEEDS_FIXES|BLOCKED)\b/i
295const LEADING = /^(APPROVED|NEEDS_FIXES|BLOCKED)\b/
296
297const nonEmpty = (text: string): string[] => text.replace(/\r\n?/g, '\n').split('\n').filter(l => l.trim() !== '')
298
299// The verdict and the index (among the non-empty lines) of the line that carries it.
300function reviewVerdict(lines: readonly string[]): { verdict: string; at: number } | null {
301  // A labelled `Verdict: X` line wins: a first line may open with the word as prose ("BLOCKED by X").
302  for (const [at, line] of lines.entries()) {
303    const word = LABELLED.exec(bare(line))?.[1]
304    if (word !== undefined) return { verdict: word.toUpperCase(), at }
305  }
306  const first = lines[0]
307  const word = first === undefined ? undefined : LEADING.exec(bare(first))?.[1]
308  return word === undefined ? null : { verdict: word, at: 0 }
309}
310
311/**
312 * A reviewer's verdict, anchored: a `Verdict: X` line, else a first non-empty line that is (or
313 * starts with) APPROVED, NEEDS_FIXES or BLOCKED; else null. The word in later prose is ignored.
314 */
315export function parseReview(answer: string): string | null {
316  return reviewVerdict(nonEmpty(answer))?.verdict ?? null
317}
318
319/** The first 3 non-empty lines of a review after its verdict line (from the top without one), shortened. */
320export function reviewLines(answer: string): string[] {
321  const lines = nonEmpty(answer)
322  const v = reviewVerdict(lines)
323  return lines.slice(v === null ? 0 : v.at + 1, (v === null ? 0 : v.at + 1) + 3).map(l => shorten(l, 100))
324}
325
326/** The first 2 non-empty lines of an agent's final answer, shortened. */
327export function answerLines(answer: string): string[] {
328  return nonEmpty(answer)
329    .slice(0, 2)
330    .map(l => shorten(l, 100))
331}
332
333/** A path's last two segments: `hooks/apex.ts`. */
334export function pathTail(path: string): string {
335  return path.split('/').filter(p => p !== '').slice(-2).join('/')
336}
337
338type BashOutput = { stdout?: string; stderr?: string; returnCodeInterpretation?: string }
339
340const lastLineOf = (text: string): string | undefined => {
341  const last = nonEmpty(text).pop()
342  return last === undefined ? undefined : shorten(last, 100)
343}
344
345/** A gate call's evidence: its command, the exit code its output names, its error flag, its last output line. */
346export function gateEvidence(
347  command: string,
348  out: BashOutput,
349  isError: boolean,
350): Pick<DeckApexLiveStep, 'command' | 'exitCode' | 'isError' | 'lastLine'> {
351  const all = [out.stdout ?? '', out.stderr ?? '', out.returnCodeInterpretation ?? ''].join('\n')
352  const code = /\bexit(?:ed with)?(?: code| status)?[\s:]+(\d+)\b/i.exec(all)?.[1]
353  const last = lastLineOf(`${out.stdout ?? ''}\n${out.stderr ?? ''}`)
354  return {
355    command: shorten(command, 80),
356    ...(code === undefined ? {} : { exitCode: Number(code) }),
357    isError,
358    ...(last === undefined ? {} : { lastLine: last }),
359  }
360}
361
362/** A ship call's evidence: its command, the commit subject `-m` gives (a heredoc's first line too), a PR URL. */
363export function shipEvidence(command: string, stdout: string): Pick<DeckApexLiveStep, 'command' | 'subject' | 'url'> {
364  const heredoc = /\bgit\s+commit\b[\s\S]*?-m\s+["']?\$\(cat\s+<<-?\s*['"]?\w+['"]?\s*\n\s*([^\n]+)/.exec(command)?.[1]
365  const quoted = /\bgit\s+commit\b[^\n]*?\s-m\s*(?:"([^"\n]*)"|'([^'\n]*)'|([^\s"'$][^\s]*))/.exec(command)
366  const subject = heredoc ?? quoted?.[1] ?? quoted?.[2] ?? quoted?.[3]
367  const url = /https:\/\/github\.com\/[^\s/]+\/[^\s/]+\/pull\/\d+/.exec(stdout)?.[0]
368  return {
369    command: shorten(command.split('\n')[0] ?? command, 80),
370    ...(subject === undefined || subject.trim() === '' ? {} : { subject: shorten(subject, 80) }),
371    ...(url === undefined ? {} : { url }),
372  }
373}
374
375/** A `gh pr merge` call: the run is at rest once its turn completes. */
376export const isMergeCall = (command: string): boolean => /\bgh\s+pr\s+merge\b/.test(command)
377
378/**
379 * When the run came to rest, or null while it is busy: the main turn completed (`turnEndAt`) and
380 * no agent card or shell of the run (started since `startedAt`) still runs, or a merge was seen.
381 * The rest time is the latest of the turn end, an agent end, a shell end.
382 */
383export function runEndedAt(
384  run: { startedAt: number; turnEndAt?: number | null; merged?: boolean },
385  cards: readonly { spawnedAt: number; endedAt: number | null; status: string }[],
386  shells: readonly { startedAt: number; endedAt?: number; status: string }[],
387): number | null {
388  const turnEnd = run.turnEndAt
389  if (turnEnd === undefined || turnEnd === null) return null
390  const ownCards = cards.filter(c => c.spawnedAt >= run.startedAt)
391  const ownShells = shells.filter(x => x.startedAt >= run.startedAt)
392  const isBusy = ownCards.some(c => c.status === 'running') || ownShells.some(x => x.status === 'running')
393  if (isBusy && run.merged !== true) return null
394  const ends = [...ownCards.map(c => c.endedAt), ...ownShells.map(x => x.endedAt)].filter((t): t is number => typeof t === 'number')
395  return Math.max(turnEnd, ...ends)
396}
397
398/** A model id's family (`Opus`), else the id itself. */
399export function modelFamily(id: string): string {
400  const family = /(opus|sonnet|haiku|fable)/i.exec(id)?.[1]
401  return family === undefined ? id : family.charAt(0).toUpperCase() + family.slice(1).toLowerCase()
402}
403
404export const NO_STEPS: DeckApexSteps = { runKey: null, steps: [], current: null }
405
406/** A run's steps, none seen yet. */
407export const startSteps = (runKey: string): DeckApexSteps => ({ runKey, steps: [], current: null })
408
409/** Step `name` seen at `at` in run `runKey` (another run's steps start over); it becomes current. */
410export function seeStep(
411  s: DeckApexSteps,
412  runKey: string,
413  name: DeckApexStepName,
414  at: number,
415  extra: Omit<DeckApexLiveStep, 'name' | 'status' | 'at'> = {},
416): DeckApexSteps {
417  const base = s.runKey === runKey ? s : startSteps(runKey)
418  const prev = base.steps.find(x => x.name === name)
419  // Files add up (distinct, bounded); a ship's subject and PR URL survive its later calls.
420  const files = [...new Set([...(prev?.files ?? []), ...(extra.files ?? [])])].slice(0, MAX_FILES)
421  const subject = extra.subject ?? prev?.subject
422  const url = extra.url ?? prev?.url
423  const step: DeckApexLiveStep = {
424    name,
425    status: 'seen',
426    at,
427    ...extra,
428    ...(files.length === 0 ? {} : { files }),
429    ...(subject === undefined ? {} : { subject }),
430    ...(url === undefined ? {} : { url }),
431  }
432  return { runKey, steps: [...base.steps.filter(x => x.name !== name), step], current: name }
433}
434
435// Distinct files a step keeps: enough to count « +N more » past the 6 shown.
436const MAX_FILES = 40
437const SHOWN_FILES = 6
438
439/**
440 * Agent `agentId`'s step ended at `at`, with its verdict if any and what its answer said; the same
441 * reference when no step is its.
442 */
443export function endAgent(
444  s: DeckApexSteps,
445  agentId: string,
446  at: number,
447  verdict: string | null,
448  end: Pick<DeckApexLiveStep, 'lines' | 'isFailed'> = {},
449): DeckApexSteps {
450  if (!s.steps.some(x => x.agentId === agentId && x.endedAt === undefined)) return s
451  return {
452    ...s,
453    steps: s.steps.map(x =>
454      x.agentId === agentId && x.endedAt === undefined ? { ...x, endedAt: at, ...(verdict === null ? {} : { verdict }), ...end } : x,
455    ),
456  }
457}
458
459const WARN_VERDICTS = new Set(['FAIL', 'BLOCKED', 'ERROR', 'NEEDS_FIXES'])
460
461export type StepMark = 'done' | 'current' | 'pending'
462
463export type StepCell = { name: DeckApexStepName; label: string; mark: StepMark; isWarn: boolean }
464
465const isRunning = (x: DeckApexLiveStep): boolean => x.agentId !== undefined && x.endedAt === undefined
466
467// A step with a verdict is done; the current one, or one whose agent still runs, is ◐.
468const markOf = (s: DeckApexSteps, x: DeckApexLiveStep): StepMark =>
469  x.verdict !== undefined ? 'done' : x.name === s.current || isRunning(x) ? 'current' : 'done'
470
471/** The step row: label (with its verdict and findings), mark, warn colour. */
472export function stepCells(s: DeckApexSteps): StepCell[] {
473  const cells: StepCell[] = []
474  for (const name of STEP_ORDER) {
475    const x = s.steps.find(y => y.name === name)
476    if (x === undefined) {
477      if (ALWAYS.has(name)) cells.push({ name, label: name, mark: 'pending', isWarn: false })
478      continue
479    }
480    const findings = x.findings !== undefined && x.findings > 0 ? ` ${x.findings}` : ''
481    const label = x.verdict === undefined ? name : `${name} ${x.verdict}${findings}`
482    cells.push({ name, label, mark: markOf(s, x), isWarn: x.verdict !== undefined && WARN_VERDICTS.has(x.verdict) })
483  }
484  return cells
485}
486
487export type StepDetail = { name: DeckApexStepName; mark: StepMark; text: string; since?: number }
488
489const detailOf = (s: DeckApexSteps, x: DeckApexLiveStep): StepDetail | null => {
490  if (isRunning(x) && x.detail !== undefined) return { name: x.name, mark: markOf(s, x), text: `${x.name} : ${x.detail}`, since: x.at }
491  if (x.verdict === undefined) return null
492  const findings = x.findings !== undefined && x.findings > 0 ? ` · ${x.findings} findings` : ''
493  return { name: x.name, mark: markOf(s, x), text: `${x.name} : ${x.verdict}${findings}` }
494}
495
496/** The line under the row: the current step's agent (running) or verdict, else a still running agent's. */
497export function stepDetail(s: DeckApexSteps): StepDetail | null {
498  const current = s.steps.find(x => x.name === s.current)
499  const own = current === undefined ? null : detailOf(s, current)
500  if (own !== null) return own
501  const running = [...s.steps].reverse().find(x => isRunning(x) && x.detail !== undefined)
502  return running === undefined ? null : detailOf(s, running)
503}
504
505/** A step's explanation box: its lines, and when a still running agent started (its live clock). */
506export type StepExplain = { lines: string[]; since?: number }
507
508// An agent step's head line: description (model), status, duration once ended.
509const agentLine = (x: DeckApexLiveStep): string => {
510  const what = x.detail ?? x.name
511  if (x.endedAt === undefined) return `${what} · running`
512  return `${what} · ${x.isFailed === true ? 'failed' : 'done'} · ${fmtTimer(x.endedAt - x.at)}`
513}
514
515/** What a step did, as its explanation box shows it; a step never seen is not reached yet. */
516export function explainStep(s: DeckApexSteps, name: DeckApexStepName): StepExplain {
517  const x = s.steps.find(y => y.name === name)
518  if (x === undefined) return { lines: ['not reached yet'] }
519  const running = x.agentId !== undefined && x.endedAt === undefined ? { since: x.at } : {}
520  switch (name) {
521    case 'plan':
522    case 'edit': {
523      const files = x.files ?? []
524      if (files.length === 0) return { lines: [name === 'plan' ? 'run files written' : 'files edited'] }
525      const more = files.length > SHOWN_FILES ? ` +${files.length - SHOWN_FILES} more` : ''
526      return { lines: [`${files.slice(0, SHOWN_FILES).join(', ')}${more}`] }
527    }
528    case 'implement':
529    case 'tests':
530      return { lines: [agentLine(x), ...(x.lines ?? []).slice(0, 2)], ...running }
531    case 'review': {
532      const head = x.endedAt === undefined ? agentLine(x) : `${x.verdict ?? 'no verdict'} · ${agentLine(x)}`
533      return { lines: [head, ...(x.lines ?? []).slice(0, 3)], ...running }
534    }
535    case 'gate': {
536      const status = x.exitCode !== undefined ? `exit ${x.exitCode}` : x.isError === true ? 'failed' : 'ok'
537      const tail = x.lastLine === undefined ? '' : ` · ${x.lastLine}`
538      return { lines: [`$ ${x.command ?? 'gate'}`, `${status}${tail}`] }
539    }
540    case 'Codex': {
541      if (x.verdict === undefined) return { lines: ['no verdict (ran in background)'] }
542      return { lines: [`${x.verdict} · ${x.findings ?? 0} findings`] }
543    }
544    case 'ship': {
545      const head = x.subject !== undefined ? `commit: ${x.subject}` : `$ ${x.command ?? 'ship'}`
546      return { lines: [head, ...(x.url === undefined ? [] : [`PR: ${x.url}`])] }
547    }
548  }
549}
550
551// ---------------------------------------------------------------- verdict
552
553const VERDICTS = new Set(['PASS', 'FAIL', 'BLOCKED', 'ERROR'])
554
555/** The verdict word and findings count of an external-verify.json text, or null when it is not one. */
556export function parseVerdict(text: string): { verdict: string; findings: number } | null {
557  let data: unknown
558  try {
559    data = JSON.parse(text)
560  } catch {
561    // Not JSON (half-written, or another file): no verdict to show.
562    return null
563  }
564  if (typeof data !== 'object' || data === null) return null
565  const word: unknown = Reflect.get(data, 'verdict')
566  const findings: unknown = Reflect.get(data, 'findings')
567  if (typeof word !== 'string' || !VERDICTS.has(word)) return null
568  return { verdict: word, findings: Array.isArray(findings) ? findings.length : 0 }
569}
570
571// ---------------------------------------------------------------- what the block and the log show
572
573export type PhaseMark = 'done' | 'current' | 'pending' | 'failed' | 'skipped'
574
575/** A step's dot: ● done, ◐ current, ○ pending; a failed step ✗, a skipped one ·. */
576export function phaseMark(step: DeckApexStep, current: string | undefined): PhaseMark {
577  if (step.kind === 'failed') return 'failed'
578  if (step.step === current || step.kind === 'running') return 'current'
579  if (step.kind === 'done') return 'done'
580  if (step.kind === 'skipped') return 'skipped'
581  return 'pending'
582}
583
584export const PHASE_GLYPH: Record<PhaseMark, string> = { done: '●', current: '◐', pending: '○', failed: '✗', skipped: '·' }
585
586/** The block's header: `APEX · <branch, else title> · <tier>`. */
587export function apexHeader(run: DeckApexRun): string {
588  return ['APEX', run.branch ?? run.title, run.tier].filter((p): p is string => p !== undefined && p !== '').join(' · ')
589}
590
591/**
592 * The log line a poll owes: a run found (its current step), a step that moved, a run gone; null
593 * when nothing moved. Only the current step and the run's directory count.
594 */
595export function phaseNote(prev: DeckApexRun | null, next: DeckApexRun | null): string | null {
596  if (next === null) return prev === null ? null : 'run ended'
597  if (prev === null || prev.dir !== next.dir) return `${next.branch ?? next.title} · ${next.currentStep ?? 'started'}`
598  if (prev.currentStep === next.currentStep) return null
599  return `${prev.currentStep ?? '—'} → ${next.currentStep ?? 'done'}`
600}
601
602/** Polls in a row that must miss a live run before it counts as ended: one failed read is not an end. */
603export const END_MISSES = 2
604
605/**
606 * The run a poll keeps: what it found, or, while a run shown before is missed fewer than
607 * END_MISSES times in a row, that run still; `misses` is the count carried to the next poll.
608 */
609export function settleRun(prev: DeckApexRun | null, found: DeckApexRun | null, misses: number): { run: DeckApexRun | null; misses: number } {
610  if (found !== null || prev === null) return { run: found, misses: 0 }
611  const missed = misses + 1
612  return missed >= END_MISSES ? { run: null, misses: 0 } : { run: prev, misses: missed }
613}
614
hooks/shells.ts 161 lines
1// Pure reducer of the session's background shells: no `$`, no clock, no I/O.
2// Every function returns the SAME array reference when nothing changed, so a
3// caller can skip the state write (and the redraw it causes).
4
5import type { DeckApexShell, DeckApexShellStatus } from '../types'
6
7export type Shell = DeckApexShell
8
9export const CAP = 50
10
11// What a task-notification row carries (UserMessage `e.props.task`).
12export type Notification = {
13  id?: string
14  toolUseId?: string
15  status?: string
16  durationMs?: number
17}
18
19// One agent of `$.agent.list()`, reduced to what the shells read.
20export type OwnerSnap = { id: string; type: string; status: string }
21
22const TEAMMATE = 'teammate'
23
24// An ended status word, or undefined for anything else (still running, or a
25// word this build does not name: the shell keeps `running`).
26export type EndedStatus = Exclude<DeckApexShellStatus, 'running'>
27
28function endedStatus(word: string | undefined): EndedStatus | undefined {
29  if (word === 'completed' || word === 'failed' || word === 'killed') return word
30  return undefined
31}
32
33// Running first (oldest first), then finished (most recent end first); past
34// CAP the oldest finished go, then the oldest running.
35function normalize(shells: Shell[]): Shell[] {
36  const running = shells.filter(t => t.status === 'running').sort((a, b) => a.startedAt - b.startedAt)
37  const done = shells
38    .filter(t => t.status !== 'running')
39    .sort((a, b) => (b.endedAt ?? b.startedAt) - (a.endedAt ?? a.startedAt))
40  return [...running.slice(-CAP), ...done].slice(0, CAP)
41}
42
43export function addShell(
44  shells: Shell[],
45  shell: { id: string; label: string; startedAt: number; toolUseId?: string; ownerAgentId?: string },
46): Shell[] {
47  if (shells.some(t => t.id === shell.id)) return shells
48  const row: Shell = {
49    id: shell.id,
50    label: shell.label,
51    startedAt: shell.startedAt,
52    status: 'running',
53    ...(shell.toolUseId === undefined ? {} : { toolUseId: shell.toolUseId }),
54    ...(shell.ownerAgentId === undefined ? {} : { ownerAgentId: shell.ownerAgentId }),
55  }
56  return normalize([...shells, row])
57}
58
59function replaceAt(shells: Shell[], index: number, shell: Shell): Shell[] {
60  return normalize(shells.map((t, i) => (i === index ? shell : t)))
61}
62
63// A background shell's notification: matched by id, else by tool_use_id.
64// Unknown shell, unknown status word, or a shell already ended: no change
65// (a notification row is drawn again on every redraw and on a resume).
66export function finishByNotification(shells: Shell[], note: Notification, now: number): Shell[] {
67  const status = endedStatus(note.status)
68  if (status === undefined) return shells
69  let index = note.id === undefined ? -1 : shells.findIndex(t => t.id === note.id)
70  if (index < 0 && note.toolUseId !== undefined) {
71    index = shells.findIndex(t => t.toolUseId === note.toolUseId)
72  }
73  const shell = index < 0 ? undefined : shells[index]
74  if (shell === undefined || shell.status !== 'running') return shells
75  const endedAt = note.durationMs === undefined ? now : shell.startedAt + note.durationMs
76  return replaceAt(shells, index, { ...shell, status, endedAt })
77}
78
79// A task-notification row's text, as a subagent's transcript keeps it:
80// `<task-id>…</task-id>` and `<status>…</status>`. A missing id, or a status
81// word that is not an end, reads as undefined.
82export function parseTaskNotification(text: string): { id: string; status: EndedStatus } | undefined {
83  const id = /<task-id>([^<]*)<\/task-id>/.exec(text)?.[1]?.trim()
84  const status = endedStatus(/<status>([^<]*)<\/status>/.exec(text)?.[1]?.trim())
85  if (id === undefined || id === '' || status === undefined) return undefined
86  return { id, status }
87}
88
89// Every `<task-notification>…</task-notification>` block of a row: a row
90// delivered while the loop was busy may batch several. A malformed block is
91// skipped.
92export function parseTaskNotifications(text: string): Array<{ id: string; status: EndedStatus }> {
93  const notes: Array<{ id: string; status: EndedStatus }> = []
94  for (const block of text.matchAll(/<task-notification>([\s\S]*?)<\/task-notification>/g)) {
95    const note = parseTaskNotification(block[1] ?? '')
96    if (note !== undefined) notes.push(note)
97  }
98  return notes
99}
100
101// A shell stopped by TaskStop: only a running shell closes, as killed; an
102// agent id (TaskStop accepts both) or an unknown one is a no-op.
103export function stopShell(shells: Shell[], id: string, now: number): Shell[] {
104  const index = shells.findIndex(t => t.id === id)
105  const shell = shells[index]
106  if (shell === undefined || shell.status !== 'running') return shells
107  return replaceAt(shells, index, { ...shell, status: 'killed', endedAt: now })
108}
109
110// A subagent's background shell notifies that subagent's loop, never the
111// main one: once the owner ends killed or failed, or leaves the agent list,
112// its still running shells are closed as `killed`. An owner that completed
113// keeps them (it may resume on the shell's notification).
114export function closeOrphanShells(shells: Shell[], ownerId: string, endedAt: number): Shell[] {
115  const isOrphan = (t: Shell): boolean => t.status === 'running' && t.ownerAgentId === ownerId
116  if (!shells.some(isOrphan)) return shells
117  return normalize(shells.map(t => (isOrphan(t) ? { ...t, status: 'killed', endedAt } : t)))
118}
119
120// A `$.agent.list()` snapshot applied to the shells: a listed owner ended
121// killed or failed (a teammate aside), or an owner among `known` (the
122// subagent loops this session saw) gone from the list, closes its shells.
123export function closeBySnapshot(
124  shells: Shell[],
125  agents: readonly OwnerSnap[],
126  known: readonly string[],
127  now: number,
128): Shell[] {
129  let out = shells
130  for (const agent of agents) {
131    const ended = endedStatus(agent.status)
132    if ((ended === 'killed' || ended === 'failed') && agent.type !== TEAMMATE) out = closeOrphanShells(out, agent.id, now)
133  }
134  const listed = new Set(agents.map(a => a.id))
135  for (const id of known) {
136    if (!listed.has(id)) out = closeOrphanShells(out, id, now)
137  }
138  return out
139}
140
141export function runningShells(shells: readonly Shell[]): number {
142  return shells.filter(t => t.status === 'running').length
143}
144
145// A new run began: finished agent cards (any status but running) and ended shells go, running
146// ones stay. Each list is the SAME reference when nothing went.
147export function clearFinished<C extends { status: string }>(cards: C[], shells: Shell[]): { cards: C[]; shells: Shell[] } {
148  const keptCards = cards.filter(c => c.status === 'running')
149  const keptShells = shells.filter(t => t.status === 'running')
150  return {
151    cards: keptCards.length === cards.length ? cards : keptCards,
152    shells: keptShells.length === shells.length ? shells : keptShells,
153  }
154}
155
156// A subagent's turn ended with `reason`: unless it answered, its still running shells close as
157// killed (their notification could only ever reach that loop). Any subagent, the architect too.
158export function shellsAfterTurn(shells: Shell[], agentId: string, reason: string, at: number): Shell[] {
159  return reason === 'answer' ? shells : closeOrphanShells(shells, agentId, at)
160}
161
hooks/signals.ts 68 lines
1// Pure reading of what asks the user to act (a failed step, a red external
2// verification, a spent correction budget).
3// No `$`, no clock, no I/O: the hooks module lists and reads, this decides.
4
5import type { DeckApexAlert, DeckApexBudget, DeckApexRun, DeckApexVerdict } from '../types'
6
7// Rounds every run gets before the user must grant one more
8// (hooks/correction-budget.js MAX_ROUNDS).
9export const MAX_ROUNDS = 2
10
11const ROUND = /^(.+)\.round([1-9][0-9]*)$/
12const GRANT = /^(.+)\.grant([1-9][0-9]*)$/
13
14// The correction budget of run `dir`, from the names of the budget folder:
15// one `<dir>.round<n>` file per round used, one `<dir>.grant<n>` per round
16// the user granted. Another run's files (even a longer name sharing the
17// prefix) are not counted; null when the run has none.
18export function budgetOf(names: readonly string[], dir: string): DeckApexBudget | null {
19  let rounds = 0
20  let grants = 0
21  for (const name of names) {
22    if (ROUND.exec(name)?.[1] === dir) rounds += 1
23    else if (GRANT.exec(name)?.[1] === dir) grants += 1
24  }
25  return rounds === 0 && grants === 0 ? null : { dir, rounds, grants }
26}
27
28export const budgetCap = (b: DeckApexBudget): number => MAX_ROUNDS + b.grants
29
30// True once every round the run may take is used.
31export function isBudgetSpent(b: DeckApexBudget | null): boolean {
32  return b !== null && b.rounds >= budgetCap(b)
33}
34
35// The newer of two candidates by mtime (the verify file has two names:
36// <run>/04-external-verify.json and <run>/external-verify.json); on a tie
37// the first.
38export function pickVerdict<T extends { mtimeMs: number }>(a: T | null, b: T | null): T | null {
39  if (a === null) return b
40  if (b === null) return a
41  return b.mtimeMs > a.mtimeMs ? b : a
42}
43
44type RedVerdict = 'FAIL' | 'BLOCKED' | 'ERROR'
45
46function redVerdict(word: string): RedVerdict | undefined {
47  if (word === 'FAIL' || word === 'BLOCKED' || word === 'ERROR') return word
48  return undefined
49}
50
51// What the user must act on for `run`, most urgent first: each failed step,
52// then a red external verification, then a spent correction budget. A
53// verdict or budget of another run directory is ignored; no run, no alert.
54export function alertsOf(
55  run: DeckApexRun | null,
56  verdict: DeckApexVerdict | null,
57  budget: DeckApexBudget | null,
58): DeckApexAlert[] {
59  if (run === null) return []
60  const alerts: DeckApexAlert[] = run.steps.filter(s => s.kind === 'failed').map((s): DeckApexAlert => ({ kind: 'step', step: s.step }))
61  const red = verdict !== null && verdict.dir === run.dir ? redVerdict(verdict.verdict) : undefined
62  if (red !== undefined && verdict !== null) alerts.push({ kind: 'verify', verdict: red, findings: verdict.findings })
63  if (budget !== null && budget.dir === run.dir && isBudgetSpent(budget)) {
64    alerts.push({ kind: 'budget', rounds: budget.rounds, cap: budgetCap(budget) })
65  }
66  return alerts
67}
68
hooks/background.ts 116 lines
1// Pure helpers for the background agents panel: no `$`, no clock, no I/O. Each session is one
2// ~/.claude/session-state/<name>.json, written by hooks/session-state.js for an abduco session
3// that claude-dispatch named: parsed defensively, an entry that does not read is skipped rather
4// than drawn wrong.
5import type { DeckBgAgent, DeckBgKind } from '../types'
6
7import { redact } from './core'
8
9export type { DeckBgKind }
10
11/** A session name as claude-dispatch gives it and session-state.js checks it. */
12export const SESSION_NAME = /^[a-z0-9][a-z0-9-]{0,47}$/
13
14/** A session silent this long leaves the panel, a finished one included. */
15export const BG_KEEP_MS = 24 * 60 * 60 * 1000
16
17/** The panel's order: what waits on you first, what ended last. */
18export const BG_ORDER: readonly DeckBgKind[] = ['needs-you', 'waiting', 'idle', 'working', 'other', 'done']
19
20/**
21 * The state word as session-state.js writes it (exact case): Notification `needs-you`, Stop
22 * `waiting`, SessionStart `idle`, UserPromptSubmit `working`, SessionEnd `done`; any other word
23 * is `other`.
24 */
25export function sessionKind(state: string): DeckBgKind {
26  switch (state) {
27    case 'needs-you':
28    case 'waiting':
29    case 'idle':
30    case 'working':
31    case 'done':
32      return state
33    default:
34      return 'other'
35  }
36}
37
38const oneLine = (s: string) => s.replace(/\s+/g, ' ').trim()
39
40/** A cwd's project: its last folder, a `<repo>/.claude/worktrees/<x>` read as `<repo>`. */
41export function projectOf(cwd: string): string {
42  const path = cwd.replace(/\/+$/, '')
43  const repo = /^(.*)\/\.claude\/worktrees\/[^/]+$/.exec(path)?.[1] ?? path
44  return repo.split('/').pop() || cwd
45}
46
47/** A cwd's repo root: the path without a trailing `/.claude/worktrees/<x>`. */
48const rootOf = (cwd: string) => cwd.replace(/\/+$/, '').replace(/\/\.claude\/worktrees\/[^/]+$/, '')
49
50/** The sessions of the project at `cwd`: same repo root, or a folder under it. */
51export const inProject = (list: DeckBgAgent[], cwd: string): DeckBgAgent[] => {
52  const root = rootOf(cwd)
53  return list.filter(a => rootOf(a.cwd) === root || rootOf(a.cwd).startsWith(`${root}/`))
54}
55
56/**
57 * One `<name>.json` (`name` its file stem), or null when the stem is no session name, the text
58 * no JSON object, `state` or `cwd` no string, or its own `name` another than the stem.
59 */
60export function parseSessionState(name: string, text: string): DeckBgAgent | null {
61  if (!SESSION_NAME.test(name)) return null
62  let value: unknown
63  try {
64    value = JSON.parse(text)
65  } catch {
66    // Not JSON (the writer renames whole files, so never half a file): skipped this poll.
67    return null
68  }
69  if (typeof value !== 'object' || value === null || Array.isArray(value)) return null
70  const state: unknown = Reflect.get(value, 'state')
71  const cwd: unknown = Reflect.get(value, 'cwd')
72  if (typeof state !== 'string' || typeof cwd !== 'string') return null
73  if (Reflect.get(value, 'name') !== name) return null
74  const notice: unknown = Reflect.get(value, 'notice')
75  const intent: unknown = Reflect.get(value, 'intent')
76  const updated: unknown = Reflect.get(value, 'updatedAt')
77  const at = typeof updated === 'string' ? Date.parse(updated) : Number.NaN
78  return {
79    id: name,
80    name,
81    cwd,
82    project: projectOf(cwd),
83    state,
84    kind: sessionKind(state),
85    detail: typeof notice === 'string' ? redact(oneLine(notice)) : '',
86    intent: typeof intent === 'string' ? redact(oneLine(intent)) : '',
87    updatedAt: Number.isFinite(at) ? at : 0,
88  }
89}
90
91/**
92 * Without the sessions silent over BG_KEEP_MS: a finished one, or one whose session died without
93 * its SessionEnd (the deck does not ask abduco).
94 */
95export const recentBg = (list: DeckBgAgent[], now: number): DeckBgAgent[] => list.filter(a => now - a.updatedAt <= BG_KEEP_MS)
96
97/** In BG_ORDER, newest update first within a kind. */
98export const sortBg = (list: DeckBgAgent[]): DeckBgAgent[] =>
99  [...list].sort((a, b) => BG_ORDER.indexOf(a.kind) - BG_ORDER.indexOf(b.kind) || b.updatedAt - a.updatedAt)
100
101/** How many sessions of each kind. */
102export function bgCounts(list: DeckBgAgent[]): Record<DeckBgKind, number> {
103  const counts: Record<DeckBgKind, number> = { 'needs-you': 0, waiting: 0, idle: 0, working: 0, other: 0, done: 0 }
104  for (const a of list) counts[a.kind] += 1
105  return counts
106}
107
108/** The word a row shows: `needs you`, the kind, or an unknown state's own word. */
109export const bgWord = (a: Pick<DeckBgAgent, 'kind' | 'state'>) => (a.kind === 'needs-you' ? 'needs you' : a.kind === 'other' ? a.state : a.kind)
110
111/** The one-line summary's parts, in BG_ORDER, kinds with none left out: `1 needs you`, `2 working`. */
112export const bgSummary = (list: DeckBgAgent[]): { kind: DeckBgKind; text: string }[] => {
113  const counts = bgCounts(list)
114  return BG_ORDER.filter(k => counts[k] > 0).map(k => ({ kind: k, text: `${counts[k]} ${k === 'needs-you' ? 'needs you' : k}` }))
115}
116
hooks/pick.ts 46 lines
1// The deck's one host command: `agent-pane pick <name>` for a background row, by its absolute
2// path and an argument vector (no shell): the agent screen's top pane then shows that abduco
3// session. The name is checked here again (claude-dispatch's rule) before it reaches the argv;
4// agent-pane checks it once more. One run per name at a time: a second press while the first
5// runs does nothing.
6import type { EngineInterface } from 'claude-code'
7
8import { SESSION_NAME } from './background'
9import { redact } from './core'
10
11/** The names whose pick is under way. */
12const inFlight = new Set<string>()
13
14/** What the press came to, for the session log: `ok` when agent-pane exited 0. */
15export type PickOutcome = { ok: boolean; text: string }
16
17/** The first non-empty line of agent-pane's stderr, redacted, at most 120 characters. */
18const firstLine = (text: string): string => {
19  const line = text.split('\n').find(l => l.trim() !== '') ?? ''
20  const one = redact(line.replace(/\s+/g, ' ').trim())
21  return one.length > 120 ? `${one.slice(0, 119)}…` : one
22}
23
24/**
25 * Shows the session `name` in the agent screen's top pane; null when a pick of the same name is
26 * already under way (nothing to log).
27 */
28export async function pickSession($: EngineInterface, name: string): Promise<PickOutcome | null> {
29  if (!SESSION_NAME.test(name)) return { ok: false, text: 'nom invalide' }
30  if (inFlight.has(name)) return null
31  inFlight.add(name)
32  try {
33    const r = await $.process.run(['/etc/profiles/per-user/alx/bin/agent-pane', 'pick', name], { timeoutMs: 5000 })
34    if (r.exitCode === 0) return { ok: true, text: 'affichée en haut' }
35    const why = firstLine(r.stderr)
36    return { ok: false, text: why === '' ? `exit ${r.exitCode}` : `exit ${r.exitCode} · ${why}` }
37  } catch (e) {
38    // Could not start, or still running at 5 s: the pane may have switched all the same.
39    const why = e instanceof Error ? firstLine(e.message) : ''
40    const text = 'échec ou pas de retour en 5 s'
41    return { ok: false, text: why === '' ? text : `${text} · ${why}` }
42  } finally {
43    inFlight.delete(name)
44  }
45}
46
hooks/rail.tsx 75 lines
1// A connector drawn on the surface's own frame clock: packets travel along it while `active`,
2// and it rests as a plain dim line otherwise. Only this region redraws; the pane does not.
3import type { ClientModule } from 'claude-code'
4
5type Props = {
6  active: boolean
7  width: number
8  color: string
9  dim: string
10  /** Cells where a branch drops (┬); the rest of the line is ─. */
11  marks: number[]
12  /** Draw ┴ instead of ┬ at the marks: a merge into what is below. */
13  isMerge: boolean
14}
15
16type Ref = { phase: number; active: boolean }
17type State = { ref: Ref }
18
19const STEP_MS = 110
20
21const Rail: ClientModule<Props, State> = (props, surface) => {
22  const { Box, Text } = surface.elements
23  const ref = surface.state?.ref ?? { phase: 0, active: props.active }
24  ref.active = props.active
25  if (surface.state === undefined) {
26    surface.setState({ ref })
27    surface.every(STEP_MS, () => {
28      if (ref.active) {
29        ref.phase += 1
30        surface.setState({ ref })
31      }
32    })
33  }
34
35  const width = Math.max(1, surface.columns || props.width)
36  const cells = Array.from({ length: width }, () => '─')
37  for (const m of props.marks) if (m >= 0 && m < width) cells[m] = props.isMerge ? '┴' : '┬'
38
39  if (!props.active) {
40    return (
41      <Box>
42        <Text color={props.dim}>{cells.join('')}</Text>
43      </Box>
44    )
45  }
46
47  // Two packets per 24 cells, a bright head and a trailing dot, moving left to right.
48  const lit = new Map<number, string>()
49  for (let base = 0; base < width + 24; base += 24) {
50    const head = (base + ref.phase) % (width + 24)
51    if (head < width) lit.set(head, '●')
52    if (head - 1 >= 0 && head - 1 < width) lit.set(head - 1, '•')
53  }
54  // Runs, not cells: consecutive cells of one kind share a Text, a handful of nodes per frame.
55  const runs: { text: string; isLit: boolean }[] = []
56  cells.forEach((ch, i) => {
57    const isLit = lit.has(i)
58    const last = runs[runs.length - 1]
59    const glyph = lit.get(i) ?? ch
60    if (last && last.isLit === isLit) last.text += glyph
61    else runs.push({ text: glyph, isLit })
62  })
63  return (
64    <Box>
65      {runs.map(r => (
66        <Text color={r.isLit ? props.color : props.dim} bold={r.isLit}>
67          {r.text}
68        </Text>
69      ))}
70    </Box>
71  )
72}
73
74export default Rail
75
hooks/elapsed.tsx 38 lines
1// A running agent's clock, ticking on the surface's frame clock so the pane need not redraw.
2// `since` and `now` come from the hooks module's $.clock; between redraws it adds its own ticks.
3import type { ClientModule } from 'claude-code'
4
5type Props = { since: number; now: number; endAt: number | null; color: string }
6type Ref = { base: number; ticks: number; lastNow: number; isRunning: boolean }
7type State = { ref: Ref }
8
9const fmt = (ms: number) => {
10  const s = Math.max(0, Math.floor(ms / 1000))
11  const m = Math.floor(s / 60)
12  return m < 60 ? `${m}:${String(s % 60).padStart(2, '0')}` : `${Math.floor(m / 60)}h${String(m % 60).padStart(2, '0')}`
13}
14
15const Elapsed: ClientModule<Props, State> = (props, surface) => {
16  const { Text } = surface.elements
17  const ref = surface.state?.ref ?? { base: 0, ticks: 0, lastNow: -1, isRunning: true }
18  if (props.now !== ref.lastNow) {
19    // A fresh reading from the hooks module: restart the local count from it.
20    ref.lastNow = props.now
21    ref.base = (props.endAt ?? props.now) - props.since
22    ref.ticks = 0
23  }
24  ref.isRunning = props.endAt === null
25  if (surface.state === undefined) {
26    surface.setState({ ref })
27    surface.every(1000, () => {
28      if (ref.isRunning) {
29        ref.ticks += 1
30        surface.setState({ ref })
31      }
32    })
33  }
34  return <Text color={props.color}>{fmt(ref.base + ref.ticks * 1000)}</Text>
35}
36
37export default Elapsed
38
types/index.d.ts 219 lines
1// deck state contract: Flightdeck's panels (main, architect, agents, receipt,
2// log), the background agents panel and the APEX block (the live run, its live steps, alerts and background
3// shells). Self-contained (no import), as the plugin-authoring reference asks.
4
5export type DeckMoment = 'before a plan' | 'error repeats' | 'before done'
6
7export type DeckMain = { model: string; effort: string; mode: string; steps: number; isRunning: boolean }
8
9export type DeckUsage = {
10  pct: number | null
11  tokens: number | null
12  window: number
13  costUsd: number | null
14  limits: { kind: string; pct: number }[]
15  compactions: number
16  lastCompactAt: number | null
17}
18
19export type DeckConsult = { id: string; at: number; endAt: number | null; moment: DeckMoment; via: string }
20
21export type DeckArchitect = { consults: DeckConsult[]; ids: string[]; seen: string[]; lastAdvice: string }
22
23export type DeckToolNote = { tool: string; text: string; isError: boolean }
24
25export type DeckAgentCard = {
26  id: string
27  type: string
28  model: string
29  description: string
30  status: string
31  spawnedAt: number
32  endedAt: number | null
33  /** The agent's context now: input + cache read + cache write of its latest step. */
34  ctx: number
35  /** Output tokens summed over its steps. */
36  out: number
37  steps: number
38  lastStop: string | null
39  tools: DeckToolNote[]
40  answer: string
41}
42
43export type DeckLogLine = {
44  at: number
45  who: string
46  text: string
47  agentId: string | null
48  kind: 'info' | 'error' | 'consult' | 'done'
49}
50
51export type DeckTurn = {
52  edits: number
53  errorStreak: number
54  errors: number
55  isReviewing: boolean
56  startedAt: number
57  costAtStart: number | null
58}
59
60export type DeckReceipt = {
61  durationMs: number
62  agents: number
63  edits: number
64  errors: number
65  costDelta: number | null
66  reason: string
67}
68
69export type DeckLayout = 'auto' | 'compact' | 'wide' | 'mini'
70
71export type DeckView = { expanded: string | null; layout: DeckLayout | null }
72
73export type DeckRoster = { architectTypes: string[] }
74
75// ---------------------------------------------------------------- APEX
76
77export type DeckApexStepKind = 'done' | 'pending' | 'running' | 'skipped' | 'failed' | 'other'
78
79export type DeckApexStep = { step: string; status: string; kind: DeckApexStepKind }
80
81/** A live APEX run, read from <cwd>/.claude/output/apex/<dir>/00-context.md. */
82export type DeckApexRun = {
83  title: string
84  /** `Tier:` of the context file (first word), else its older `Mode:`. */
85  tier?: string
86  branch?: string
87  steps: DeckApexStep[]
88  currentStep?: string
89  /** The run's directory under .claude/output/apex, set by the poll. */
90  dir?: string
91}
92
93/** A live step of an APEX run, read from the run's tool calls. */
94export type DeckApexStepName = 'plan' | 'edit' | 'implement' | 'tests' | 'gate' | 'Codex' | 'review' | 'ship'
95
96export type DeckApexLiveStep = {
97  name: DeckApexStepName
98  status: 'seen'
99  /** When it was last seen. */
100  at: number
101  /** An agent step's description and model family. */
102  detail?: string
103  /** Codex's PASS/FAIL/BLOCKED or a reviewer's APPROVED/NEEDS_FIXES/BLOCKED. */
104  verdict?: string
105  findings?: number
106  /** The agent this step started, and when it ended. */
107  agentId?: string
108  endedAt?: number
109  /** plan / edit: the distinct path tails touched (bounded). */
110  files?: string[]
111  /** gate / ship: the last call's command, shortened. */
112  command?: string
113  /** gate: the exit code its output names, its error flag, its last non-empty output line. */
114  exitCode?: number
115  isError?: boolean
116  lastLine?: string
117  /** ship: the commit subject and the PR URL, kept across its calls. */
118  subject?: string
119  url?: string
120  /** An agent step: the first lines of its final answer (a reviewer's: those after its verdict). */
121  lines?: string[]
122  /** An agent step whose turn ended otherwise than with an answer. */
123  isFailed?: boolean
124}
125
126/** The live steps of the run `runKey` (a session key, else the run dir); `current` was seen last. */
127export type DeckApexSteps = { runKey: string | null; steps: DeckApexLiveStep[]; current: DeckApexStepName | null }
128
129/** `killed` is its own word (stopped, drawn ■), not a failure. */
130export type DeckApexShellStatus = 'running' | 'completed' | 'failed' | 'killed'
131
132/** One background shell of this session (its backgroundTaskId). */
133export type DeckApexShell = {
134  id: string
135  label: string
136  startedAt: number
137  endedAt?: number
138  status: DeckApexShellStatus
139  toolUseId?: string
140  /** The subagent whose loop started it (absent on the main loop). */
141  ownerAgentId?: string
142}
143
144/** The run's correction rounds used and granted (~/.claude/apex-correction-budget). */
145export type DeckApexBudget = { dir: string; rounds: number; grants: number }
146
147/** What the user must act on, most urgent kind first. */
148export type DeckApexAlert =
149  | { kind: 'step'; step: string }
150  | { kind: 'verify'; verdict: 'FAIL' | 'BLOCKED' | 'ERROR'; findings: number }
151  | { kind: 'budget'; rounds: number; cap: number }
152
153/** The session's last main-loop Skill(apex) call: a run without a folder (yet). */
154export type DeckApexSessionRun = {
155  startedAt: number
156  lastAt: number
157  args: string
158  /** When the main turn last completed; cleared by any new activity (null: the run is busy). */
159  turnEndAt?: number | null
160  /** A `gh pr merge` ship call was seen: at rest once the turn completes. */
161  merged?: boolean
162}
163
164/** The run's external verification file, as far as the block shows it. */
165export type DeckApexVerdict = { dir: string; verdict: string; findings: number; mtimeMs: number }
166
167// ---------------------------------------------------------------- background agents
168
169/**
170 * A background session's state as the panel groups it: the five words session-state.js writes,
171 * any other word `other`.
172 */
173export type DeckBgKind = 'needs-you' | 'waiting' | 'working' | 'idle' | 'other' | 'done'
174
175/** One background session, read from ~/.claude/session-state/<name>.json. */
176export type DeckBgAgent = {
177  /** Its abduco session name (the file stem). */
178  id: string
179  name: string
180  cwd: string
181  /** The repo folder's name (a worktree reads as its repo). */
182  project: string
183  /** The raw `state` word. */
184  state: string
185  kind: DeckBgKind
186  /** Its last notice (one line, redacted), or empty. */
187  detail: string
188  /** Its first prompt (one line, redacted), or empty. */
189  intent: string
190  /** Its last update (ms), else its file's mtime. */
191  updatedAt: number
192}
193
194declare module 'claude-code' {
195  interface PluginState {
196    'deck': {
197      main: DeckMain
198      usage: DeckUsage
199      architect: DeckArchitect
200      agents: DeckAgentCard[]
201      log: DeckLogLine[]
202      turn: DeckTurn
203      receipt: DeckReceipt | null
204      view: DeckView
205      roster: DeckRoster
206      run: DeckApexRun | null
207      apexSteps: DeckApexSteps
208      verdict: DeckApexVerdict | null
209      budget: DeckApexBudget | null
210      shells: DeckApexShell[]
211      sessionRun: DeckApexSessionRun | null
212      /** The step whose explanation box is open under the step row. */
213      openStep: DeckApexStepName | null
214      /** Background sessions of the current project, polled while the pane is open. */
215      background: DeckBgAgent[]
216    }
217  }
218}
219