High-performance statusline and above-the-prompt alert band for Claude Code, with setup commands and diagnostics

A multi-line statusline for Claude Code that shows context usage, cost tracking, active tools, running agents, and todo progress — updated live as you work.

Four things at a glance, re-colored live as you work:
CTX% · tokens · cost) are always visible. Config counts (CLAUDE.md / rules / MCPs / skills …) are an opt-in L2 row.none) to framed (console) to grouped Powerline/capsule rows (rail / anchor), plus built-in themes and composable per-segment widgets. See docs/layouts.md.none) to framed (console) to grouped Powerline/capsule rows (rail / anchor, … — see docs/layouts.md for the catalog)--preview (see src/themes/ for the full set)# npm (recommended — works on macOS, Linux, Windows)
npm install -g @cc-pulseline/cc-pulseline
# From source
cargo install cc-pulseline
# Or clone and build
git clone https://github.com/GregoryHo/cc-pulseline.git
cd cc-pulseline && ./scripts/install.sh
Add to ~/.claude/settings.json:
{
"statusLine": {
"type": "command",
"command": "~/.claude/pulseline/cc-pulseline"
}
}
Start a Claude Code session — the statusline appears automatically.
| Method | Command | Best For |
|---|---|---|
| npm | npm i -g @cc-pulseline/cc-pulseline | Claude Code users |
| cargo-binstall | cargo binstall cc-pulseline | Rust devs (prebuilt) |
| cargo install | cargo install cc-pulseline | Rust devs (from source) |
| install.sh | ./scripts/install.sh | Local clone |
The same binary also draws above the prompt, fed by Claude Code's function hooks rather than the statusline hook. It is the other half of this repository's plugin, so one install gets both it and the setup commands:
/plugin install pulseline --marketplace GregoryHo/cc-pulseline
The band draws only what needs you and the statusline cannot know — the same tool failing three times in a row, a call running past a minute, how many turns are left before autocompact (with a /compact button) — and nothing otherwise; the rail statusline's 5H / 7D cells carry each window's pace; /pulseline opens a pane with the full ledger. The two surfaces are a division of labour rather than a replacement: the band draws no identity, context or cost row, so keep your statusLine setting, which stays the steady-state summary. In the Claude Code desktop app, which runs no statusline, the band carries the identity and budget row itself — see the desktop app.
Requires cc-pulseline 1.7.0 or newer on the machine. The plugin finds the binary on its own — a path you configure, ~/.claude/pulseline/, PATH, or a local build — and says what is missing when none of them answers. See the band for the full picture.
cc-pulseline uses TOML configuration with two scopes:
~/.claude/pulseline/config.toml{project}/.claude/pulseline.toml (overrides user)cc-pulseline --init # Create user config
cc-pulseline --init --project # Create project config
cc-pulseline --check # Validate configs
cc-pulseline --print # Show effective merged config
[display]
theme = "tokyo-night" # tokyo-night | echo-sub-zero | titanium-precision | ...
# variant = "dark" # dark | light (overrides theme default)
icons = true # nerd font icons vs ascii
[segments.identity] # Line 1 — model, style, version, project, git
show_model = true
show_style = true
show_version = true
show_project = true
show_git = true
show_git_stats = false # !3 +1 ✘2 ?4 file stats after branch
show_agent = true # AG:agent-name when --agent is active
show_worktree = true # (WT) indicator when in a worktree session
show_effort = true # effort level pill (low/medium/high/xhigh/max, CC 2.1.119+)
show_thinking = true # thinking mode indicator (CC 2.1.119+)
[segments.config] # Line 2 — CLAUDE.md, rules, memories, hooks, MCPs, skills, plugins, duration
enabled = true # L2 row is opt-in (off by default)
show_claude_md = true
show_rules = true
show_memory = true
show_hooks = true
show_mcp = true
show_skills = true
show_plugins = true
show_duration = true
[segments.budget] # Line 3 — context, tokens, cost
show_context = true
show_tokens = true
show_cost = true
show_speed = false # output tok/s rate
show_cache_trend = false # cache trend: compact C-cell sparkline + ledger CACHE row (opt-in)
[segments.quota] # Usage/quota tracking (subscription plans)
enabled = false # opt-in: driven by CC's native rate_limits stdin field
show_five_hour = true
show_seven_day = false
[segments.tools]
enabled = true
max_lines = 2 # max running tools shown
max_completed = 4 # max completed tool counts
max_completed_lines = 1 # max rows of completed tools (overflow folds into a ` +N` tail)
[segments.agents]
enabled = true
max_lines = 1
[segments.todo]
enabled = true
max_lines = 1
[layout].name picks how rows are arranged and decorated. Layouts range from flat (none) to framed (console) to grouped Powerline/capsule rows (rail / anchor) — see docs/layouts.md for the catalog (pane::LayoutStyle is the source of truth).

Each layout asserts a tasteful default for every widget-bearing segment — see docs/layouts.md for the per-segment reference. The user can override per segment via *_visual strings — same widget, any layout:
# Console layout, but with a CTX gauge added (default is text-only).
[layout]
name = "console"
[segments.budget]
context_visual = "gauge"
# Console without quota gauge — text quota only.
[layout]
name = "console"
[segments.quota]
visual = "text"
Recognized context/quota widgets: gauge, sparkline, plot, text (context); gauge, text (quota). Combine with + (e.g. "gauge+sparkline"). Other segments compose too — [segments.tools] visual (counts/targets/ticker), [segments.todo] visual (text/bar), [segments.identity] effort_visual (word/ramp), [segments.agents] visual (name/description/model). Empty string defers to the layout default. Full reference: docs/layouts.md.
cc-pulseline # render statusline from stdin JSON (empty stdin = {})
cc-pulseline --init # create user config (--init --project for project config)
cc-pulseline --check # validate config files
cc-pulseline --print # show effective merged config
cc-pulseline --preview # preview themes (optional theme names)
cc-pulseline --preview-layouts # preview every layout (optional widths)
cc-pulseline --select-theme # interactively select and apply a theme (--project for project config)
cc-pulseline --palette-map # show palette field → UI element mapping (optional theme)
cc-pulseline --layout rail --columns 120 --rows 3 --no-icons # one-off overrides, handy for previewing
Run cc-pulseline --help for the full option reference and the built-in theme list.
| Variable | Effect |
|---|---|
NO_COLOR | Disable all color output |
COLUMNS | Terminal width for layout degradation |
| Requirement | Minimum |
|---|---|
| Terminal | 256-color ANSI |
| Rust (build) | 1.85+ |
| Node.js (npm) | 14+ |
| Platform | npm | cargo install | cargo-binstall |
|---|---|---|---|
| macOS ARM64 | Yes | Yes | Yes |
| macOS x64 | Yes | Yes | Yes |
| Linux x64 | Yes | Yes | Yes |
| Linux x64 (musl) | Yes | Yes | Yes |
| Linux ARM64 | Yes | Yes | Yes |
| Linux ARM64 (musl) | Yes | Yes | Yes |
| Windows x64 | Yes | Yes | Yes |
Designed for repeated invocation by Claude Code's statusline hook:
| Scenario | Target (p95) |
|---|---|
| Baseline (no activity) | < 10ms |
| Active session (10 tools + 5 agents) | < 20ms |
| Large transcript (2500 events) | < 50ms |
Benchmarks use Criterion.rs. Run with:
cargo bench
See docs/benchmarks.md for methodology and detailed results.
No color output? Check that the NO_COLOR environment variable is not set. Ensure your terminal supports 256-color ANSI. In tmux, verify TERM is set to xterm-256color or similar.
Icons look broken? Set icons = false in your config file, or install a Nerd Font.
Statusline not appearing? Verify the statusLine entry in ~/.claude/settings.json points to the correct binary path. Test directly with:
echo '{}' | cc-pulseline
Config changes not taking effect? Run cc-pulseline --check to validate your config files and cc-pulseline --print to see the effective merged config.
| Guide | Description |
|---|---|
| Architecture | Pipeline design, module responsibilities, transcript two-path event dispatcher |
| Layouts | Layout catalog and per-segment visual (gauge/sparkline/plot/text) reference |
| Metrics Reference | Per-metric data sources, parsing methods, cache strategies, and output examples |
| Theme & Palette | 256-color system specification, emphasis tiers, and color-annotated rendering examples |
| Activity Band | The above-the-prompt band and pane: what they draw, the binary ladder, the test kit |
| Benchmarks | Performance methodology and Criterion benchmark results |
| Changelog | Release history and version notes |
See CONTRIBUTING.md for development setup, testing, and pull request guidelines.
cc-pulseline draws inspiration from these excellent projects:
MIT License. See LICENSE for details.
hooks/register.tsx 2310 lines1import { atom, read, update } from 'claude-code'
2import type {
3 AgentInfo,
4 EngineInterface,
5 PluginOptions,
6 Register,
7 SessionContextUsage,
8 SessionUsage,
9 Timer,
10} from 'claude-code'
11
12import {
13 PROBE_TIMEOUT_MS,
14 candidates,
15 formatVersion,
16 isNewEnough,
17 missingMessage,
18 parseVersion,
19 tooOldMessage,
20} from './binary'
21import type { Version } from './binary'
22import {
23 COMPACT_KEY,
24 LONG_TURN_MS,
25 QUIET,
26 SPEND_EXPIRE_MS,
27 SPEND_PREFIX,
28 alertRow,
29 alertsOf,
30 longTurnNotice,
31 nextDeltas,
32 nextLongCheck,
33 nextStreak,
34 onDesktopBand,
35 onTerminalBand,
36 quotaKey,
37 quotaNotice,
38 quotaPast,
39 runwayOf,
40 shareLine,
41 shareOf,
42 shouldWriteSpend,
43 spendOf,
44 stripCells,
45 stripOf,
46 stripRows,
47 terminalRow,
48} from './desktop'
49import type { SessionSpend, StripCell } from './desktop'
50import { buildPayload } from './payload'
51import type { ActiveTool } from './payload'
52import { shouldRefresh } from './throttle'
53import type {
54 Alert,
55 BandRun,
56 BinaryChoice,
57 DrawnOutput,
58 Span,
59 SpanStyle,
60 TaskItem,
61 Tasks,
62 Todo,
63} from '../types'
64
65/**
66 * cc-pulseline as a mod, stage 0c.
67 *
68 * What the first two runs established:
69 * - a user-tier hooks module loads, and `$.process.run` with stdin is
70 * allowed there, so the Rust binary can stay the renderer;
71 * - the `AbovePrompt` band refuses a whole tree if any text child holds a
72 * control character, so the binary's ANSI has to be parsed into Text
73 * props (see `spansOf`), never passed through;
74 * - the band is small outside fullscreen: `maxRows` came back as 2, and a
75 * taller tree scrolls behind a `n more` row.
76 *
77 * So this revision draws the statusline rows and nothing else, clipped to
78 * `maxRows`, and refreshes them when a turn ends rather than only at
79 * session start.
80 *
81 * Every `$` call is written literally: the loader statically scans this
82 * source for them, so aliasing one would make it invisible to the scan.
83 *
84 * Every gating hook carries `.catch(($, e, next) => next(e))`. This mod
85 * only observes — it never denies and never rewrites what it is handed — so
86 * the right answer when one of its hooks throws or outruns its budget is
87 * whatever the chain beneath says. `next` is replay-safe inside a handler:
88 * where the hook had already called it, `next(e)` resolves to what that call
89 * settled to and nothing beneath runs twice, so a `tool.call` that failed
90 * after the tool ran still answers with the tool's real result and never a
91 * fabricated one.
92 *
93 * The budget those handlers guard is the hook's own code: 10s
94 * (`HookBudget.ms`), with waits on `next` and on `$` not counted. So the
95 * binary's `timeoutMs: 5000` sits outside it — it is a `$.process.run` wait
96 * — and only the work around the spawn, chiefly `spansOf` over a few
97 * hundred bytes, is ever on the clock.
98 */
99
100const PANE_ID = 'pulseline'
101
102/**
103 * The layouts the pane's switcher row offers, in order.
104 *
105 * `console` is left out on purpose: inside a pane it reads as `ledger` with
106 * a label column, and four visibly different views are worth more than five
107 * where two look alike.
108 */
109/**
110 * Calls that are not tool activity, mirrored from `providers/transcript.rs`.
111 *
112 * Two groups, excluded there in two different ways. `Agent`, `TaskCreate`,
113 * `TaskUpdate` and `TodoWrite` are dispatched and then returned from before
114 * the tool tracking, because each belongs somewhere else — the agent list, or
115 * the todo row. The rest are that file's `NOISE_TOOLS`, Claude Code's own
116 * control calls.
117 *
118 * Without this the band inflated its completed totals with its own
119 * bookkeeping, and an `Agent` call was drawn twice: once as a running tool
120 * and once as an agent.
121 */
122const NOT_TOOL_ACTIVITY = new Set([
123 'Agent',
124 'TaskCreate',
125 'TaskUpdate',
126 'TodoWrite',
127 'EnterPlanMode',
128 'ExitPlanMode',
129 'EnterWorktree',
130 'ExitWorktree',
131 'TaskGet',
132 'TaskList',
133 'TaskOutput',
134 'TaskStop',
135 'ToolSearch',
136])
137
138const LAYOUTS = ['ledger', 'budgets', 'compact', 'rail']
139
140/**
141 * The layouts the desktop band may draw, the first the default.
142 *
143 * `quiet`, the default, runs no binary for the band: the Code tab already
144 * shows the model, the effort, a context ring and every tool, so the band
145 * draws only what passes a limit — context, quota, a cold cache — as an
146 * `Svg` gauge and a line (see `hooks/desktop.ts`). Empty otherwise.
147 *
148 * The others are the binary's rows. The desktop's Code tab does not run the
149 * `statusLine` command, which carries identity and budget on the terminal,
150 * so without them the desktop has no context, cost or quota anywhere. Each of these carries
151 * all of them in a few rows:
152 * `compact` fuses identity and budget into one head row over the activity;
153 * `rail` and `anchor` draw them as a powerline bar, on half-block seams since
154 * the desktop has no Nerd Font (`--no-icons`), with `activity` stacked under
155 * (see `runDesktopBand`). Mirrored by the `desktopLayout` field's `options`
156 * in `plugin.json`.
157 */
158const DESKTOP_LAYOUTS = [QUIET, 'compact', 'rail', 'anchor']
159
160/**
161 * The desktop band's layout from the `desktopLayout` setting.
162 *
163 * The engine already treats a stored value outside the field's `options` as
164 * unset, so this check only matters to a manifest and a module that have
165 * drifted apart — and there the default is the safe answer.
166 */
167export function desktopLayoutOf(options: PluginOptions): string {
168 const chosen = options.desktopLayout
169 return typeof chosen === 'string' && DESKTOP_LAYOUTS.includes(chosen)
170 ? chosen
171 : (DESKTOP_LAYOUTS[0] ?? QUIET)
172}
173
174/**
175 * Asks the binary for no Nerd Font glyphs. The desktop app draws text in its
176 * own face, which has none of the Private Use Area icons or powerline seams;
177 * braille, gauge marks and half blocks it draws fine, and the binary keeps
178 * them.
179 */
180const NO_ICONS = '--no-icons'
181
182/** Button key prefix, so a press can name the layout it asks for. */
183const LAYOUT_KEY = 'layout:'
184
185/** Set true to draw the band/run diagnostics above the statusline rows. */
186const DEBUG = false
187
188/**
189 * The session's values, held by the host so a hot reload does not zero them.
190 *
191 * `plugin` and `key` are source literals on purpose: `claude plugin validate`
192 * lists every `$.state` key and holds it to the contract in `../types`, and
193 * only a family member's `id` may be computed.
194 */
195const sessionFacts = atom({ plugin: 'pulseline', key: 'session' } as const, {
196 cwd: '',
197 version: null,
198 effort: null,
199 tokens: null,
200 compactCount: 0,
201 outputStyle: null,
202 lastApiErrorMs: null,
203 cacheReadTotal: 0,
204 ctxTokens: null,
205 ctxDeltas: [],
206 autoCompact: null,
207})
208
209const toolTotals = atom({ plugin: 'pulseline', key: 'tools' } as const, {
210 counts: {},
211 completedTotal: 0,
212 failedTotal: 0,
213 failStreak: null,
214})
215
216const agentTimings = atom({ plugin: 'pulseline', key: 'agents' } as const, {
217 startedAt: {},
218 finishedAt: {},
219 agentType: {},
220})
221
222const instructions = atom({ plugin: 'pulseline', key: 'instructions' } as const, {
223 claudeMd: [],
224 agentsMd: [],
225 rules: [],
226 memories: [],
227})
228
229const todoList = atom({ plugin: 'pulseline', key: 'todo' } as const, null)
230
231/**
232 * The Task API's items, which the todo row is rebuilt from.
233 *
234 * An atom rather than a closure field for the same reason as the rest: an
235 * edit to this module reloads it, and a `TaskUpdate` naming an item created
236 * before the reload has to find it.
237 */
238const taskItems = atom({ plugin: 'pulseline', key: 'tasks' } as const, {
239 items: {} as Record<string, TaskItem>,
240})
241
242/** The person's own pane choices: a reload must not close it or reset it. */
243const paneWanted = atom({ plugin: 'pulseline', key: 'pane' } as const, {
244 open: false,
245 layout: 'ledger',
246})
247
248/**
249 * The binary's last output.
250 *
251 * Held rather than rebuilt for two reasons: a reload redraws the rows it
252 * already had instead of flashing the not-run-yet note, and a render hook
253 * that reads this subscribes its drawing, so writing it here draws the band
254 * again with nobody calling `$.ui.invalidate`.
255 */
256/**
257 * Which binary was resolved, `null` until the ladder has been walked.
258 *
259 * Cleared on `classic.ConfigChange`, so configuring the path or installing
260 * the binary mid-session takes effect without restarting.
261 */
262const binaryChoice = atom({ plugin: 'pulseline', key: 'binary' } as const, null)
263
264const drawnOutput = atom({ plugin: 'pulseline', key: 'output' } as const, {
265 desktopRows: [],
266 paneRows: [],
267 // Not `'failed'`: nothing has gone wrong yet, and the band draws the note
268 // only for `'failed'`. See `BandRun` in `../types`.
269 bandRun: 'never',
270 runNote: 'binary: not run yet',
271 paneNote: 'pane: not run yet',
272})
273
274// Built from a char code on purpose: a literal escape in this source
275// does not survive every editor round-trip.
276const ESC = String.fromCharCode(27)
277const ANSI_PATTERN = new RegExp(ESC + '\\[([0-9;]*)m', 'g')
278
279/** xterm-256 index to `#rrggbb`: 16 base colours, a 6^3 cube, a 24-step ramp. */
280export function ansi256Hex(index: number): string {
281 const base = [
282 0x000000, 0x800000, 0x008000, 0x808000, 0x000080, 0x800080, 0x008080, 0xc0c0c0, 0x808080,
283 0xff0000, 0x00ff00, 0xffff00, 0x0000ff, 0xff00ff, 0x00ffff, 0xffffff,
284 ]
285 const hex = (value: number) => `#${value.toString(16).padStart(6, '0')}`
286 if (index < 16) return hex(base[index] ?? 0)
287 if (index < 232) {
288 const step = [0, 95, 135, 175, 215, 255]
289 const offset = index - 16
290 const r = step[Math.floor(offset / 36)] ?? 0
291 const g = step[Math.floor((offset % 36) / 6)] ?? 0
292 const b = step[offset % 6] ?? 0
293 return hex((r << 16) | (g << 8) | b)
294 }
295 const level = 8 + (index - 232) * 10
296 return hex((level << 16) | (level << 8) | level)
297}
298
299/**
300 * Flattens text from outside the module before it goes on the band: a
301 * stderr dump, a caught error.
302 *
303 * The band refuses the *whole tree* over one control character — the engine
304 * says `ui.render (AbovePrompt) refused: a text child holds a control
305 * character (an escape sequence); the engine drew its own` — so an
306 * unflattened panic takes down the note that was meant to explain it, and the
307 * band goes blank with nothing to read. Runs become one space rather than
308 * nothing, where `stripControls` below drops them: a panic's first line is
309 * the useful one, and `at src/main.rs:1:1` must not be glued to the end of
310 * it. Flatten before slicing, or a cut can land inside an escape sequence.
311 */
312function noteText(text: string): string {
313 // SGR codes first, whole. Dropping the escape alone and keeping the rest
314 // left `[31mthread 'main' panicked [0m` on the band: accepted by the
315 // engine, and unreadable.
316 let flat = ''
317 let spaced = false
318 for (const char of text.replace(ANSI_PATTERN, '')) {
319 const code = char.codePointAt(0) ?? 32
320 if (code >= 32 && code !== 127) {
321 flat += char
322 spaced = false
323 continue
324 }
325 if (!spaced && flat.length > 0) {
326 flat += ' '
327 spaced = true
328 }
329 }
330 return flat.trimEnd()
331}
332
333/** Drops the control characters the band refuses to draw. */
334function stripControls(text: string): string {
335 let clean = ''
336 for (const char of text) {
337 const code = char.codePointAt(0) ?? 32
338 if (code >= 32 && code !== 127) clean += char
339 }
340 return clean
341}
342
343/** Splits one line of the binary's output into styled spans. */
344export function spansOf(line: string): Span[] {
345 const spans: Span[] = []
346 let style: SpanStyle = {}
347 let cursor = 0
348
349 const push = (text: string) => {
350 const clean = stripControls(text)
351 if (clean.length > 0) spans.push({ ...style, children: clean })
352 }
353
354 for (const match of line.matchAll(ANSI_PATTERN)) {
355 push(line.slice(cursor, match.index))
356 cursor = match.index + match[0].length
357
358 const codes = (match[1] ?? '').split(';').filter(code => code.length > 0)
359 for (let at = 0; at < codes.length; at += 1) {
360 const code = Number(codes[at])
361 if (code === 0) style = {}
362 else if (code === 1) style = { ...style, bold: true }
363 else if (code === 2) style = { ...style, dimColor: true }
364 else if (code === 7) style = { ...style, inverse: true }
365 else if (code === 49) {
366 // The one reset code the renderer emits besides 0: `powerline.rs`'s
367 // DEFAULT_BG, written at the pointed outer edge of a rail or anchor
368 // cluster to hand the terminal's own background back. Dropping the
369 // property is the whole fix — carried over, the previous segment's
370 // background stays on the seam span and the point paints as a filled
371 // rectangle. 39 is not handled because nothing emits it.
372 const cleared = { ...style }
373 delete cleared.backgroundColor
374 style = cleared
375 } else if ((code === 38 || code === 48) && codes[at + 1] === '5') {
376 const hex = ansi256Hex(Number(codes[at + 2]))
377 style = code === 38 ? { ...style, color: hex } : { ...style, backgroundColor: hex }
378 at += 2
379 }
380 }
381 }
382 push(line.slice(cursor))
383 return spans
384}
385
386/** What one refresh's engine calls answered, kept so a failed one can reuse it. */
387type Collected = {
388 usage: SessionUsage
389 modelId: string
390 sessionId: string
391 agents: readonly AgentInfo[]
392 now: number
393 /** Where the session draws, which decides which band runs are made. */
394 surfaces: readonly string[]
395}
396
397/**
398 * What stays in the module's closure, and so starts over on a hot reload.
399 *
400 * Everything the person would notice losing is in `$.state` instead (see
401 * `../types`). What is left is of two kinds:
402 *
403 * - geometry, which a render hook writes as it measures the box it is
404 * given. It cannot be an atom: the host refuses a state write while a
405 * `ui.render` hook draws. It is re-measured on the next draw anyway.
406 * - values a reload cannot be caught in the middle of: `active` is the
407 * tools in flight, and nothing is in flight at the instant the module
408 * is rebuilt; `lastRunMs` only gates the next 400ms; `lastCollected`
409 * is a cache of the engine's own answers, re-asked on the next refresh.
410 */
411type State = {
412 active: Map<string, ActiveTool>
413 lastRunMs: number
414 /**
415 * The refresh that moves a long tool call's alert: armed while a tool runs
416 * on the terminal, since no event marks the minute it crosses, cancelled
417 * once none does. See `armLongCheck`.
418 */
419 longTimer: Timer | null
420 /** The desktop band's box, measured apart: it is not the terminal's. */
421 desktopBandRows: number
422 desktopBandCols: number
423 /**
424 * Whether a desktop band has been measured yet. Until then its box is the
425 * 3x120 guess above, so the first measurement is a change by definition.
426 */
427 desktopBandMeasured: boolean
428 paneHeight: number
429 paneCols: number
430 /** MCP servers that are serving tools right now, by `$.tool.list()`. */
431 mcpServers: Set<string>
432 /** The last reading that came back whole, drawn again when one fails. */
433 lastCollected: Collected | null
434 /** Which refresh is newest; only that one may publish. See `refresh`. */
435 runSeq: number
436 /**
437 * The project root `syncRoot` last read, so a move can be told from the
438 * first read of a session. A closure field on purpose: a reload is not a
439 * move, and this starting over is what says so.
440 */
441 rootRead: string | null
442 /**
443 * Whether `$.session.version()` has answered in this load of the module.
444 * Until it has, every refresh asks again and its answer replaces the held
445 * version, which may be a CLI fallback. See `syncVersion`.
446 */
447 versionFromEngine: boolean
448 /**
449 * The manifest's `userConfig` values, as `register`'s second parameter
450 * handed them over. Fixed for this activation: a change to them reloads
451 * the module, so a closure is the right place for them.
452 */
453 options: PluginOptions
454 /**
455 * The quota windows already notified, by `quotaKey`. Seeded from the atom
456 * on the first refresh after a load, then checked and marked with no
457 * `await` between, so two refreshes in flight cannot both notify.
458 */
459 notified: Set<string> | null
460}
461
462/**
463 * The argument a tool row shows beside the tool name.
464 *
465 * `tool.call` carries the tool's own arguments on `e`, so this is a lookup,
466 * not the guess-by-shape that the transcript parser has to make.
467 */
468/**
469 * Which key each tool's useful argument is under, mirrored from
470 * `providers/transcript.rs`'s `extract_target`.
471 *
472 * A generic key sweep is not enough and was quietly wrong: `Grep` carries
473 * both `path` and `pattern`, and reading `path` first showed the directory
474 * being searched instead of what was being looked for. Tools whose argument
475 * is under none of the generic keys — `WebSearch`, `Skill`, `SendMessage`,
476 * `Monitor`, `PushNotification` — showed no target at all.
477 */
478const TARGET_KEYS: Record<string, readonly string[]> = {
479 Read: ['file_path'],
480 Write: ['file_path'],
481 Edit: ['file_path'],
482 NotebookEdit: ['file_path'],
483 Bash: ['command'],
484 PowerShell: ['command'],
485 Monitor: ['script_id', 'pattern'],
486 PushNotification: ['title'],
487 Advisor: ['query'],
488 MCPSearch: ['query'],
489 Glob: ['pattern'],
490 Grep: ['pattern'],
491 WebFetch: ['url'],
492 WebSearch: ['query'],
493 Skill: ['skill'],
494 SendMessage: ['to'],
495 LSP: ['command'],
496}
497
498/** The generic sweep, for a tool with no entry above. */
499const FALLBACK_TARGET_KEYS = ['file_path', 'command', 'pattern'] as const
500
501/**
502 * The argument a tool call shows in the band.
503 *
504 * Returned whole, only flattened to one line: the renderer truncates per tool
505 * kind and per available width (`render/activity/cells/recent_tool.rs` keeps
506 * the *tail* of a Read or Edit path, so cutting the head off here lost the
507 * filename and showed the wrong end).
508 */
509export function targetOf(event: Record<string, unknown>): string | undefined {
510 const name = typeof event.tool === 'string' ? event.tool : ''
511 const read = (key: string): string | undefined => {
512 const value = event[key]
513 return typeof value === 'string' && value.length > 0 ? value : undefined
514 }
515
516 // `AskUserQuestion` keeps its text one level down, in the first question.
517 if (name === 'AskUserQuestion') {
518 const first = Array.isArray(event.questions) ? event.questions[0] : undefined
519 const asked = (first as { question?: unknown } | undefined)?.question
520 return typeof asked === 'string' && asked.length > 0 ? singleLine(asked) : undefined
521 }
522
523 for (const key of TARGET_KEYS[name] ?? FALLBACK_TARGET_KEYS) {
524 const value = read(key)
525 if (value !== undefined) return singleLine(value)
526 }
527 return undefined
528}
529
530/** `fmt::sanitize_single_line`: a row is one line, so these become spaces. */
531function singleLine(text: string): string {
532 return text.replace(/[\n\r\t]/g, ' ')
533}
534
535/**
536 * Folds the Task API's items into the todo row's shape.
537 *
538 * A mirror of `state/mod.rs`'s `build_todo_from_tasks`, down to the summary
539 * wording and the sort, so the band draws the same row whichever path fed it.
540 * Note `pending` is everything not completed, the in-progress items included —
541 * that is the transcript path's arithmetic, not an oversight.
542 */
543export function todoFromTasks(items: Record<string, TaskItem>): Todo | null {
544 const all = Object.values(items)
545 if (all.length === 0) return null
546
547 const total = all.length
548 const completed = all.filter(item => item.status === 'completed').length
549 const pending = total - completed
550 const running = all
551 .filter(item => item.status === 'in_progress')
552 .map(item => ({ text: item.activeForm ?? item.subject, started_at: item.startedAt }))
553 .sort((a, b) => (a.started_at ?? Infinity) - (b.started_at ?? Infinity))
554
555 return {
556 text: `${completed}/${total} done, ${pending} pending`,
557 pending,
558 completed,
559 total,
560 in_progress_items: running,
561 all_done: pending === 0 && completed > 0,
562 is_task_api: true,
563 }
564}
565
566/**
567 * Folds one answered `TodoWrite`, `TaskCreate` or `TaskUpdate` into the todo
568 * row.
569 *
570 * All three run after `next(e)` and only when the call did not fail, because
571 * a list or a task the engine refused must not be drawn as current. Both ids
572 * come from the engine: the created task's from the call's own result, an
573 * update's from the event. Nothing is counted here, so a refused create
574 * cannot leave a phantom that a later update would move instead of the real
575 * task.
576 */
577async function rememberTodoCall(
578 $: EngineInterface,
579 name: string,
580 seen: Record<string, unknown>,
581 result: { result?: unknown },
582): Promise<void> {
583 if (name === 'TodoWrite' && Array.isArray(seen.todos)) {
584 const todo = todoOf(seen.todos as { content?: string; status?: string }[])
585 await update($, todoList, () => todo)
586 return
587 }
588
589 if (name === 'TaskCreate' && typeof seen.subject === 'string') {
590 const subject = seen.subject
591 const answered = (result.result as { task?: { id?: unknown } } | undefined)?.task?.id
592 if (typeof answered !== 'string' || answered.length === 0) return
593 const item: TaskItem = {
594 subject,
595 status: 'pending',
596 ...(typeof seen.activeForm === 'string' ? { activeForm: seen.activeForm } : {}),
597 }
598 await rebuildTodo($, held => ({ items: { ...held.items, [answered]: item } }))
599 return
600 }
601
602 if (name === 'TaskUpdate' && typeof seen.taskId === 'string') {
603 const taskId = seen.taskId
604 // `TaskUpdate` answers `{ success }`; a call that reported failure moved
605 // nothing, so neither does this.
606 const answered = result.result as { success?: unknown } | undefined
607 if (answered !== undefined && answered.success === false) return
608 const asked = typeof seen.status === 'string' ? seen.status : undefined
609 const subject = typeof seen.subject === 'string' ? seen.subject : undefined
610 const activeForm = typeof seen.activeForm === 'string' ? seen.activeForm : undefined
611 const at = await $.clock.now()
612 await rebuildTodo($, held => {
613 if (asked === 'deleted') {
614 const items = { ...held.items }
615 delete items[taskId]
616 return { items }
617 }
618 const was = held.items[taskId]
619 if (was === undefined) return held
620 // `status` is optional on `TaskUpdate`: the call also carries a new
621 // subject, active form or dependency set on its own. Defaulting it to
622 // `pending` reopened a completed task whenever the model only renamed
623 // one.
624 const status = asked ?? was.status
625 // The start is stamped once, so the row's elapsed time does not restart
626 // every time the same task is touched again.
627 const startedAt =
628 status === 'in_progress' && was.status !== 'in_progress' ? at : was.startedAt
629 return {
630 items: {
631 ...held.items,
632 [taskId]: {
633 ...was,
634 status,
635 startedAt,
636 ...(subject !== undefined ? { subject } : {}),
637 ...(activeForm !== undefined ? { activeForm } : {}),
638 },
639 },
640 }
641 })
642 }
643}
644
645/**
646 * Applies one change to the task items. One write, and the only one.
647 *
648 * It used to fold the result into the `todo` atom as a second write, and two
649 * task calls in flight together could interleave: both commit their items
650 * correctly, then the one that committed the *older* snapshot writes its fold
651 * last and the row drops or reopens a task until some later task event
652 * rebuilt it. The row is a fold over every item, so it is derived where it is
653 * drawn instead — `refresh` folds whatever the items atom holds at that
654 * moment, which is always the committed state.
655 */
656async function rebuildTodo($: EngineInterface, change: (held: Tasks) => Tasks): Promise<void> {
657 await update($, taskItems, change)
658}
659
660/** Folds one TodoWrite call's arguments into the todo row's shape. */
661function todoOf(
662 items: { content?: string; status?: string; activeForm?: string }[],
663): Todo | null {
664 // A cleared list is no list, not a list of nothing. The renderer reads any
665 // non-null todo as present and drew `0/0 done · 0 pending` in the ledger
666 // the pane shows; both siblings already answer this way —
667 // `extract_todo_summary` with `None`, `todoFromTasks` with `null` — and the
668 // transcript path's `dispatch_todo_write` passes that `None` straight to
669 // `set_todo`, so clearing is what the other path does too.
670 if (items.length === 0) return null
671
672 const running = items.filter(item => item.status === 'in_progress')
673 const completed = items.filter(item => item.status === 'completed').length
674 // Everything not completed, the running item included — which is what the
675 // transcript path's `extract_todo_summary` does and what `todoFromTasks`
676 // above does. Counting only `pending` left the ledger's
677 // `done = completed.max(total - pending)` reading a running item as done,
678 // so a lone running task drew `1/1 done · 0 pending`.
679 const pending = items.length - completed
680 const first = running[0]
681 return {
682 text: first?.activeForm ?? first?.content ?? '',
683 pending,
684 completed,
685 total: items.length,
686 in_progress_items: running.map(item => ({ text: item.activeForm ?? item.content ?? '' })),
687 all_done: items.length > 0 && completed === items.length,
688 is_task_api: true,
689 }
690}
691
692/**
693 * Writes the engine's own version, until the engine has answered once in
694 * this load of the module. True once it has.
695 *
696 * The engine's answer wins over whatever is held, because what is held may
697 * be a fallback: the CLI's version from `probeVersion`, or one an older
698 * revision of this module wrote — `$.state` survives the reload that
699 * upgrades the plugin, and 1.7.0 stored the `claude` on PATH. So the held
700 * value is not a reason to stop asking; only the engine's answer is, and the
701 * closure flag that records it starts over with the module, as it should.
702 *
703 * Cheap enough for every refresh — one engine call until it answers, none
704 * after — so `refresh` calls it as well as `session.start`: the version is
705 * right from the first draw even where `session.start` raced it, and the one
706 * place a test can reach it is the tool path. Never rejects.
707 */
708async function syncVersion(engine: EngineInterface, state: State): Promise<boolean> {
709 if (state.versionFromEngine) return true
710 try {
711 const { version } = await engine.session.version()
712 if (version.length === 0) return false
713 const held = await read(engine, sessionFacts)
714 if (held.version !== version) {
715 await update(engine, sessionFacts, facts => ({ ...facts, version }))
716 }
717 state.versionFromEngine = true
718 return true
719 } catch {
720 // An engine that does not answer, or an atom it would not read. The
721 // next refresh asks again; `probeVersion` falls back to the CLI.
722 return false
723 }
724}
725
726/**
727 * Resolves Claude Code's own version, once per session.
728 *
729 * `$.session.version()` first: the engine the session runs on, which is not
730 * always the `claude` on PATH. The desktop app runs a Claude Code of its own,
731 * and asking the CLI there reported the person's terminal install instead —
732 * `2.1.304` over a session running `2.1.299`.
733 *
734 * The CLI is the fallback for an engine that refuses the call.
735 * `CLAUDE_CODE_EXECPATH` is set on the children Claude Code spawns rather
736 * than on its own environment, so it is tried and is rarely there. Left null
737 * when every way fails: the statusline then draws its unknown marker, which
738 * is the truth.
739 */
740async function probeVersion(engine: EngineInterface, state: State): Promise<void> {
741 if (await syncVersion(engine, state)) return
742 const held = await read(engine, sessionFacts)
743 if (held.version !== null) return
744 const fromEnv = await engine.env.get('CLAUDE_CODE_EXECPATH')
745 const guess = fromEnv?.split('/').pop()
746 if (guess && /^\d+\.\d+\.\d+$/.test(guess)) {
747 await update(engine, sessionFacts, facts => ({ ...facts, version: guess }))
748 return
749 }
750 try {
751 const run = await engine.process.run(['claude', '--version'], { timeoutMs: 10000 })
752 const found = run.stdout.match(/\d+\.\d+\.\d+/)
753 if (found) {
754 const version = found[0]
755 await update(engine, sessionFacts, facts => ({ ...facts, version }))
756 }
757 } catch {
758 // Left as it was: the statusline draws its unknown marker, which is true.
759 }
760}
761
762/**
763 * Asks the engine everything one draw needs, in one round trip.
764 *
765 * These used to be six sequential awaits in `refresh`, outside any `try`, so
766 * a single engine call failing took the whole draw down to a note. They run
767 * together now and the caller owns the failure.
768 *
769 * It also stamps `lastRunMs` first thing, before anything is awaited on the
770 * engine: the stamp used to come after all six, so two callers could both
771 * clear the refresh gate and spawn the binary twice. Only
772 * `classic.ConfigChange` is still gated, and that is the stamp it reads.
773 */
774async function collect(engine: EngineInterface, state: State): Promise<Collected> {
775 const now = await engine.clock.now()
776 state.lastRunMs = now
777
778 const [usage, modelId, sessionId, agents, tools, surfaces] = await Promise.all([
779 engine.session.usage(),
780 engine.session.model(),
781 engine.session.id(),
782 engine.agent.list(),
783 engine.tool.list(),
784 engine.session.surfaces(),
785 ])
786
787 // Which MCP servers are actually serving tools, as against how many are
788 // written down in the settings files.
789 state.mcpServers = new Set(
790 tools
791 .filter(tool => tool.mcp)
792 .map(tool => tool.name.split('__')[1])
793 .filter((server): server is string => server !== undefined && server.length > 0),
794 )
795
796 // An agent the engine lists that no SubagentStart announced starts now,
797 // and stays started then: the stamp has to outlive this draw, or the
798 // agent's age would reset to zero on every row the band draws. It is a
799 // write, not a default, which is why it cannot live in `buildPayload`.
800 await update(engine, agentTimings, timings => {
801 const startedAt = { ...timings.startedAt }
802 const finishedAt = { ...timings.finishedAt }
803 let added = false
804 for (const agent of agents) {
805 if (startedAt[agent.id] === undefined) {
806 startedAt[agent.id] = now
807 added = true
808 }
809 // The same write at the other end. An agent the engine no longer lists
810 // as running that no `SubagentStop` stamped finished *now*, and stays
811 // finished: the renderer shows `completed_at - started_at`, so without
812 // the stamp a completed agent's elapsed time grows by one refresh
813 // interval on every draw instead of standing still.
814 if (agent.status !== 'running' && finishedAt[agent.id] === undefined) {
815 finishedAt[agent.id] = now
816 added = true
817 }
818 }
819 return added ? { ...timings, startedAt, finishedAt } : timings
820 })
821
822 return { usage, modelId, sessionId, agents, now, surfaces }
823}
824
825/**
826 * Walks the ladder until something answers `--version` and is new enough.
827 *
828 * Each rung is probed by running it, never by `$.fs.stat`: on a machine
829 * that has used the statusline, `~/.claude/pulseline/` exists and holds
830 * `config.toml` and no binary, and a stat of that directory answers yes.
831 * Running the candidate tells a binary from a folder and checks the version
832 * in the same call.
833 *
834 * `stdin: ''` is passed on purpose. `ProcessRunInit.stdin` is documented as
835 * "written to the child's standard input, then closed"; what an *absent*
836 * `stdin` does is not stated for `$.process.run` (its sibling
837 * `ProcessSpawnRequest.input` does say "absent, standard input is closed
838 * from the start", but `run` does not repeat it). Passing the empty string
839 * puts it on the documented path, so a same-named executable on PATH that
840 * reads standard input cannot sit there until the timeout. The timeout is
841 * the second guard, at 400ms a rung.
842 *
843 * The answer is cached in `$.state`, so this runs once a session rather
844 * than once a refresh.
845 */
846/**
847 * How long a failed walk is kept before the ladder is tried again.
848 *
849 * Long enough that a session with nothing installed does not re-probe five
850 * rungs on every refresh, short enough that following the band's own
851 * `npm install -g` line is seen without restarting.
852 */
853const NEGATIVE_TTL_MS = 10_000
854
855async function resolveBinary(engine: EngineInterface, state: State): Promise<BinaryChoice> {
856 const held = await read(engine, binaryChoice)
857 const now = await engine.clock.now()
858 if (held !== null && (held.kind === 'ok' || now - held.at < NEGATIVE_TTL_MS)) return held
859
860 const configured = state.options.binaryPath
861 const home = (await engine.env.get('HOME')) ?? (await engine.env.get('USERPROFILE')) ?? ''
862 const facts = await read(engine, sessionFacts)
863
864 const ladder = candidates({
865 configured: typeof configured === 'string' ? configured : '',
866 pluginRoot: engine.plugin.root,
867 home,
868 cwd: facts.cwd,
869 })
870
871 // The *newest* thing that answered but was too old, so the note names the
872 // version the person actually has. Keeping the first one found would name
873 // an older copy further up the ladder and send them updating to a version
874 // they are already past.
875 let outdated: { path: string; version: Version; rung: string } | null = null
876
877 for (const candidate of ladder) {
878 try {
879 const run = await engine.process.run([candidate.path, '--version'], {
880 stdin: '',
881 timeoutMs: PROBE_TIMEOUT_MS,
882 })
883 if (run.exitCode !== 0) continue
884 const version = parseVersion(run.stdout)
885 if (version === null) continue
886 if (isNewEnough(version)) {
887 const choice: BinaryChoice = {
888 kind: 'ok',
889 path: candidate.path,
890 version: formatVersion(version),
891 rung: candidate.rung,
892 }
893 await update(engine, binaryChoice, () => choice)
894 return choice
895 }
896 if (outdated === null || isNewEnough(version, outdated.version)) {
897 outdated = { path: candidate.path, version, rung: candidate.rung }
898 }
899 } catch {
900 // Not there, not runnable, or it outran the probe. Next rung.
901 }
902 }
903
904 const choice: BinaryChoice =
905 outdated === null
906 ? { kind: 'missing', at: now }
907 : {
908 kind: 'too-old',
909 path: outdated.path,
910 version: formatVersion(outdated.version),
911 rung: outdated.rung,
912 at: now,
913 }
914 await update(engine, binaryChoice, () => choice)
915 return choice
916}
917
918/** Whether a path sits inside a directory, native separators included. */
919function under(dir: string, path: string): boolean {
920 if (dir.length === 0) return false
921 const slashed = (text: string) => text.replace(/\\/g, '/').replace(/\/+$/, '')
922 return `${slashed(path)}/`.startsWith(`${slashed(dir)}/`)
923}
924
925/**
926 * Puts the session's own project root in the atom, and forgets a binary that
927 * was found under the old one.
928 *
929 * `session.start`'s `e.cwd` is where the session began, not where it is.
930 * `$.session.root()` is the one that moves: its contract names `/cd`, a
931 * host's directory change and a worktree move, and says nested instruction
932 * files are read only beneath it — which is exactly what the binary scans
933 * for the config row, and what its git shell-out runs in. Held from the
934 * start, every later payload described the directory the person left.
935 *
936 * Read before the ladder rather than inside `collect`, which runs after it:
937 * the dev rung is `<root>/target/release/cc-pulseline`, so a choice made
938 * under the old root points into the old checkout.
939 */
940async function syncRoot(engine: EngineInterface, state: State): Promise<void> {
941 const root = await engine.session.root()
942 const facts = await read(engine, sessionFacts)
943 if (facts.cwd !== root) {
944 await update(engine, sessionFacts, held => ({ ...held, cwd: root }))
945 // Dropped rather than re-walked here: the ladder does that once, on the
946 // root just written.
947 await update(engine, binaryChoice, () => null)
948 }
949
950 // Only a root this function read before and now finds changed is a move.
951 // The first read is not one: `cwd` is empty until then, or holds
952 // `session.start`'s `e.cwd`, which is where the session began rather than
953 // where its root is — and the instructions loaded before this point were
954 // loaded for the root either way. Nor is a reload a move, which is why this
955 // sits in the closure: it starts over with the module, as it should.
956 const left = state.rootRead
957 state.rootRead = root
958 if (left === null || left === root) return
959 // The instruction counts are the other thing the root owns. Left standing,
960 // the ENV row reported the project the person had left — and then kept
961 // adding the new one's files to it, so the counts were two projects deep
962 // for the rest of the session. Reading the root live without this made that
963 // worse than leaving both stale: the path was right and the counts were not.
964 await update(engine, instructions, loaded => ({
965 // Kept: the files that are nobody's project — `~/.claude/CLAUDE.md`,
966 // `~/.claude/rules/`. Those were loaded for the session, not for the root.
967 claudeMd: loaded.claudeMd.filter(path => !under(left, path)),
968 agentsMd: loaded.agentsMd.filter(path => !under(left, path)),
969 rules: loaded.rules.filter(path => !under(left, path)),
970 // Cleared outright, where the others are filtered: every memory file is
971 // keyed by the project it belongs to — the binary reads them from
972 // `~/.claude/projects/<encoded-root>/memory/` — so none of the old root's
973 // are the new root's. The prefix test cannot see that, because they live
974 // under HOME rather than under the root.
975 memories: [],
976 }))
977 // A count of zero is sent as no field at all, so until the engine names the
978 // new root's files the binary's own scan stands. That is the right way to
979 // be wrong here: the scan reads the directory the session is actually in.
980}
981
982/**
983 * One band run: spawns the binary on the payload and parses its rows.
984 *
985 * Never rejects. `fault` is the note for a run that did not answer cleanly —
986 * a non-zero exit with its stderr, or a refused spawn — and `null` for one
987 * that did, zero rows included.
988 */
989async function runRows(
990 engine: EngineInterface,
991 payload: string,
992 argv: string[],
993): Promise<{ rows: Span[][]; fault: string | null }> {
994 try {
995 const run = await engine.process.run(argv, { stdin: payload, timeoutMs: 5000 })
996 const rows = run.stdout
997 .split('\n')
998 .filter(line => line.length > 0)
999 .map(spansOf)
1000 return run.exitCode === 0
1001 ? { rows, fault: null }
1002 : { rows, fault: `exit ${run.exitCode} — ${noteText(run.stderr).slice(0, 120)}` }
1003 } catch (error) {
1004 return { rows: [], fault: `run refused — ${noteText(String(error)).slice(0, 160)}` }
1005 }
1006}
1007
1008/**
1009 * The desktop band's run: the `desktopLayout` setting, without Nerd Font
1010 * glyphs.
1011 *
1012 * `compact` carries the activity row itself. `rail` and `anchor` do not —
1013 * they draw identity, context and quota as a powerline bar and stop there,
1014 * whatever `--rows` allows — and the desktop has no statusline to leave the
1015 * turn in flight to. So those two are a head, and `activity` is run under it
1016 * with the rows the head left: the bar on top, the running tools below.
1017 *
1018 * The head gets every row but one, so a band with room for two still shows
1019 * the tool that is running. A fault in either run is the band's fault.
1020 */
1021async function runDesktopBand(
1022 engine: EngineInterface,
1023 payload: string,
1024 binaryPath: string,
1025 state: State,
1026): Promise<{ rows: Span[][]; fault: string | null }> {
1027 const layout = desktopLayoutOf(state.options)
1028 const box = (rows: number) => [
1029 binaryPath,
1030 '--rows',
1031 String(rows),
1032 '--columns',
1033 String(state.desktopBandCols),
1034 ]
1035 if (layout === 'compact') {
1036 return runRows(engine, payload, [...box(state.desktopBandRows), '--layout', layout, NO_ICONS])
1037 }
1038
1039 const total = Math.max(1, state.desktopBandRows)
1040 const headRows = Math.max(1, total - 1)
1041 const ran = await runRows(engine, payload, [...box(headRows), '--layout', layout, NO_ICONS])
1042 // Clipped here as well as asked for: a head that drew past `--rows` would
1043 // push the running tool out of the band, which is the row this is for.
1044 const head = { ...ran, rows: ran.rows.slice(0, headRows) }
1045 const left = total - head.rows.length
1046 if (head.fault !== null || left <= 0) return head
1047 const activity = await runRows(engine, payload, [
1048 ...box(left),
1049 '--layout',
1050 'activity',
1051 NO_ICONS,
1052 ])
1053 return { rows: [...head.rows, ...activity.rows], fault: activity.fault }
1054}
1055
1056/**
1057 * Builds the payload from the engine, runs the binary, parses its rows.
1058 *
1059 * **Call it through `drawSoon`, never directly.** It guards its own writes
1060 * with `runSeq`, but a throw that gets past its internal handlers — an atom
1061 * read, the write at the end — leaves the atom untouched, and the band's note
1062 * is keyed on `bandRun` rather than on the row count: a direct caller that
1063 * lets the rejection go therefore makes the band go quiet about it. `drawSoon`
1064 * is where that rejection is recorded, under this run's own sequence number.
1065 *
1066 * Declared at the top of the file on purpose: the loader only lets `$` be
1067 * passed to a function declared here, never to a closure inside `register`.
1068 */
1069/**
1070 * A native notification, or a toast where no channel sends one.
1071 *
1072 * A session the desktop hosts alone has no terminal, so only the person's
1073 * Notification hooks run and `isSent` can be false; a hook's `{ deny }` makes
1074 * the call reject. Either way the toast still says it, so nothing is lost.
1075 * Never rejects: its callers float it.
1076 */
1077async function notifyOrToast(engine: EngineInterface, text: string): Promise<void> {
1078 try {
1079 const sent = await engine.ui.notify(text, { title: 'pulseline' })
1080 if (!sent.isSent) engine.ui.toast(text)
1081 } catch {
1082 engine.ui.toast(text)
1083 }
1084}
1085
1086/**
1087 * Writes this desktop session's spend to `$.store` and reads every other's,
1088 * deleting what has expired. Each session owns its key, so nothing here is a
1089 * read-then-write of a value another process writes too.
1090 *
1091 * Returns the other sessions' spends, or `null` when this one has no cost to
1092 * say.
1093 */
1094async function syncSpend(
1095 engine: EngineInterface,
1096 sessionId: string,
1097 usd: number | undefined,
1098 now: number,
1099): Promise<SessionSpend[] | null> {
1100 if (usd === undefined) return null
1101 const own = `${SPEND_PREFIX}${sessionId}`
1102 // Throttled against what the store holds, not a remembered write: another
1103 // process's cleanup can read this key stale, and delete it after a fresh
1104 // write lands. Read back, a deleted key is written again on the next refresh.
1105 if (shouldWriteSpend(spendOf(await engine.store.get(own)), usd, now)) {
1106 await engine.store.set(own, { usd, at: now })
1107 }
1108 const keys = (await engine.store.keys()).filter(key => key.startsWith(SPEND_PREFIX) && key !== own)
1109 const others: SessionSpend[] = []
1110 for (const key of keys) {
1111 const spend = spendOf(await engine.store.get(key))
1112 // Malformed is deleted too: nothing this module writes looks like that.
1113 if (spend === null || now - spend.at > SPEND_EXPIRE_MS) await engine.store.delete(key)
1114 else others.push(spend)
1115 }
1116 return others
1117}
1118
1119/**
1120 * Keeps one refresh pending while a tool runs on the terminal: at the moment
1121 * the oldest crosses `LONG_TOOL_MS`, then every `LONG_TICK_MS` so its time
1122 * moves. No event marks either moment, and the band draws only what a
1123 * refresh published. Each refresh re-arms it from its own reading, and one
1124 * with nothing running cancels it.
1125 */
1126function armLongCheck(engine: EngineInterface, state: State, running: readonly ActiveTool[], now: number): void {
1127 state.longTimer?.cancel()
1128 const due = nextLongCheck(running, now)
1129 state.longTimer = due === null ? null : engine.clock.after(due, () => void drawSoon(engine, state))
1130}
1131
1132async function refresh(engine: EngineInterface, state: State): Promise<void> {
1133 // Each refresh claims a number and only the newest may publish. Several can
1134 // be in flight at once — parallel tool calls, a turn event landing beside
1135 // them — each with its own reading and its own spawn, and the write is a
1136 // plain overwrite. Without this the slowest finisher wins, so an older
1137 // reading can replace a newer one and leave a finished tool drawn as
1138 // running until the next event.
1139 const seq = (state.runSeq += 1)
1140 // The running list as it is *now*, not as it will be when the payload is
1141 // built: between here and there are a binary probe, a root read and seven
1142 // engine calls, and a tool that finishes in that window is deleted from
1143 // `state.active` by its own hook. Read late, this refresh would either
1144 // lose the tool it was started to draw, or — from another event's refresh
1145 // — serialise a tool that had already finished as still running.
1146 const running = [...state.active.values()]
1147 const publish = async (change: (out: DrawnOutput) => DrawnOutput): Promise<void> => {
1148 if (seq !== state.runSeq) return
1149 // Checked again *inside* the change, because `update` is a read-apply-write
1150 // with retries: it yields, and a newer refresh can claim the number and
1151 // publish in that window, which the outer check above has already passed.
1152 // The change runs inside the transaction and on each retry, so this is the
1153 // one that decides. Returning the value unchanged is the no-op.
1154 await update(engine, drawnOutput, out => (seq === state.runSeq ? change(out) : out))
1155 }
1156
1157 // Before the ladder, because the dev rung is built from the root.
1158 // Its own statement: `syncVersion` never rejects, and a refused root read
1159 // must not cost the version its sync.
1160 await syncVersion(engine, state)
1161 try {
1162 await syncRoot(engine, state)
1163 } catch {
1164 // Not worth blanking the band for: the root already held is the one the
1165 // session started in, and `collect` below reports an engine refusing
1166 // calls through `stale`.
1167 }
1168
1169 // Nothing to run means nothing to draw but the reason. The band draws
1170 // `runNote` when `bandRun` is `'failed'`, so this is what reaches it.
1171 const binary = await resolveBinary(engine, state)
1172 if (binary.kind !== 'ok') {
1173 const note = binary.kind === 'missing' ? missingMessage() : tooOldMessage(binary.version)
1174 // `'failed'`, not `'never'`: the ladder walked and came back empty-handed,
1175 // and this message is the only place an install line can reach the person.
1176 await publish(out => ({
1177 ...out,
1178 desktopRows: [],
1179 paneRows: [],
1180 bandRun: 'failed',
1181 runNote: note,
1182 }))
1183 return
1184 }
1185
1186 let collected: Collected
1187 let stale: string | null = null
1188 try {
1189 collected = await collect(engine, state)
1190 // Only the newest refresh may leave the fallback behind it. Unguarded, an
1191 // older refresh finishing its collection late replaced a newer reading —
1192 // and the next refresh whose own collection fails draws that older one,
1193 // with its stale usage and agent list, under the `stale:` note.
1194 if (seq === state.runSeq) state.lastCollected = collected
1195 } catch (error) {
1196 // Nothing has ever come back whole: there is no reading to draw, and
1197 // spawning the binary with fabricated zeros would draw a lie.
1198 if (state.lastCollected === null) {
1199 await publish(out => ({
1200 ...out,hooks/binary.ts 153 lines1/**
2 * Where the cc-pulseline binary is, and whether it is new enough.
3 *
4 * Everything here is pure: the ladder is a list of paths built from four
5 * strings, and the version gate is string parsing. The probing itself lives
6 * in register.tsx, because a function handed `$` has to be declared in the
7 * module the loader scans for `$` calls — the host refuses a call its scan
8 * did not list.
9 *
10 * No binary is bundled and none is downloaded. `$.fs.write` is text-only,
11 * `FsStat` carries no mode bit and there is no chmod, so a downloaded file
12 * could never be made executable; and the npm package already ships seven
13 * platforms with musl detection, so there is nothing here to rebuild.
14 */
15
16/**
17 * The oldest binary whose CLI this mod can drive.
18 *
19 * A rung that answers but is older is passed over, not accepted and not
20 * fatal: the walk goes on and a later rung may be new enough. That is the
21 * real shape of the machine this was written on — `cargo install` left an
22 * older copy on PATH while the dev build was current — and a ladder that
23 * stopped at the first thing to answer would have taken the old one. The
24 * too-old message is only reached when no rung at all is new enough.
25 *
26 * It tracks the release, because each release so far has added the CLI the
27 * band of that release drives. 1.6.0 added `--layout activity`, which the
28 * band now always asks for, and an unknown layout name is not an error to
29 * the binary: it warns on stderr, falls back to `none` and exits 0. So a
30 * 1.5.x binary would answer a band spawn with the identity and budget rows
31 * — the statusline, drawn a second time above the prompt and now resident —
32 * and `bandRun` would read `'ok'`. Refusing it outright is the only way that
33 * failure gets said out loud.
34 *
35 * 1.7.0 added `--no-icons`, which every spawn for the desktop app carries.
36 * An older binary ignores an unknown flag the same way, so on the desktop it
37 * would draw Nerd Font glyphs the app's face does not have — a row of boxes,
38 * recorded as `'ok'`.
39 */
40export const MIN_VERSION: Version = [1, 7, 0]
41
42/** How long one probe may take. Five rungs, so this bounds the whole ladder. */
43export const PROBE_TIMEOUT_MS = 400
44
45export type Version = [number, number, number]
46
47/** Which rung a candidate came from, for the note and for the tests. */
48export type Rung = 'configured' | 'bundled' | 'installed' | 'path' | 'dev'
49
50export type Candidate = { path: string; rung: Rung }
51
52export type Where = {
53 /** The `binaryPath` userConfig field; empty when the person left it unset. */
54 configured?: string | undefined
55 /** `$.plugin.root`: the folder holding plugin.json. */
56 pluginRoot: string
57 /** The person's home directory, for the installed path. */
58 home: string
59 /** The session's working directory, for the dev rung. */
60 cwd: string
61}
62
63export const BINARY_NAME = 'cc-pulseline'
64
65/**
66 * The ladder, in the order it is tried.
67 *
68 * Each rung is only a path; whether anything is there is settled by running
69 * it, never by `$.fs.stat`. That is not caution — on a machine that has used
70 * the statusline, `~/.claude/pulseline/` exists and holds `config.toml` and
71 * no binary, and a stat of the *directory* answers yes. Running the
72 * candidate is the only thing that tells a binary from a folder, and it
73 * doubles as the version check.
74 */
75export function candidates(where: Where): Candidate[] {
76 const found: Candidate[] = []
77 const add = (path: string, rung: Rung) => {
78 if (path.length > 0 && !found.some(one => one.path === path)) found.push({ path, rung })
79 }
80
81 // 1. What the person named, which always wins.
82 add((where.configured ?? '').trim(), 'configured')
83
84 // 2. Shipped beside the mod. Reserved for a bundling decision that has not
85 // been taken, so this is expected to miss. No engine call answers the
86 // platform, so there is no `<platform>` segment to build: whoever
87 // bundles picks the layout and this rung follows it.
88 if (where.pluginRoot.length > 0) add(`${where.pluginRoot}/bin/${BINARY_NAME}`, 'bundled')
89
90 // 3. Where scripts/install.sh puts it on its download path.
91 if (where.home.length > 0) add(`${where.home}/.claude/pulseline/${BINARY_NAME}`, 'installed')
92
93 // 4. On PATH — the npm package, or `cargo install` landing in ~/.cargo/bin,
94 // which is what install.sh does when it is run inside the repo.
95 add(BINARY_NAME, 'path')
96
97 // 5. The dev rung, and labelled as such. It cannot be dropped: this
98 // repository's own session draws from its own build, and install.sh run
99 // inside the repo never writes to the installed path. It is the session's
100 // working directory rather than anyone's absolute path, so it works in
101 // any checkout.
102 if (where.cwd.length > 0) add(`${where.cwd}/target/release/${BINARY_NAME}`, 'dev')
103
104 return found
105}
106
107/** Reads `cc-pulseline 1.5.0` — or any line carrying a three-part version. */
108export function parseVersion(stdout: string): Version | null {
109 const found = stdout.match(/(\d+)\.(\d+)\.(\d+)/)
110 if (found === null) return null
111 const [major, minor, patch] = [Number(found[1]), Number(found[2]), Number(found[3])]
112 if (!Number.isFinite(major) || !Number.isFinite(minor) || !Number.isFinite(patch)) return null
113 return [major, minor, patch]
114}
115
116export function formatVersion(version: Version): string {
117 return version.join('.')
118}
119
120/** True when `version` is at least `MIN_VERSION`. */
121export function isNewEnough(version: Version, minimum: Version = MIN_VERSION): boolean {
122 for (let at = 0; at < 3; at += 1) {
123 const have = version[at] ?? 0
124 const need = minimum[at] ?? 0
125 if (have !== need) return have > need
126 }
127 return true
128}
129
130const INSTALL = 'npm install -g @cc-pulseline/cc-pulseline'
131
132/** What the band says when no rung answered. */
133export function missingMessage(): string {
134 return `cc-pulseline not found — install it with: ${INSTALL}`
135}
136
137/**
138 * What the band says when a binary answered but is too old.
139 *
140 * It names the statusline on purpose. Every version below the floor draws
141 * the statusline perfectly well; what they lack is a band flag — `--rows`
142 * and `--columns` before 1.5.0, `--layout activity` before 1.6.0, `--no-icons` before 1.7.0 — and none
143 * of them refuses. They draw the classic layout into the band at the wrong
144 * width, row count or both. Someone reading "too old" would otherwise go
145 * looking for a broken statusline that is not broken.
146 */
147export function tooOldMessage(version: string): string {
148 return (
149 `cc-pulseline ${version} is too old — the band needs ${formatVersion(MIN_VERSION)} ` +
150 `or newer; your statusline is unaffected. Update with: ${INSTALL}`
151 )
152}
153hooks/desktop.ts 558 lines1import type { SessionUsage } from 'claude-code'
2
3import type { ActiveTool } from './payload'
4import type { Alert, FailStreak, Strip, Tokens } from '../types'
5
6/**
7 * The quiet desktop band: what it draws, worked out from figures the module
8 * already holds. Pure, so the tests reach it without the engine.
9 *
10 * The Code tab already shows the model, the effort, the permission mode, the
11 * branch and a context ring, and its transcript lists every tool. What it
12 * does not show is where quota is heading, cost, and the cache. So the quiet
13 * band keeps one thin strip of quota and cost, and adds a row only when the
14 * context or the cache passes its limit.
15 *
16 * The terminal band is quieter still. Its statusline carries the quota and
17 * its pace, the cost, the context and the cache, and Claude Code's own
18 * transcript every tool, so it draws nothing at all until something needs
19 * the person: the same tool failing again and again, a tool running long,
20 * the turns left before autocompact.
21 */
22
23/**
24 * When an alert opens: the binary's own marks, so the band and the pane
25 * agree. CTX's critical mark is 70 (`ThemePalette::ctx_marks()`), quota's 85.
26 */
27export const LIMITS = { ctx: 70, quota: 85 } as const
28
29/** The gauge's threshold marks, drawn as ticks: the binary's `[55, 70]` and `[50, 85]`. */
30const CTX_MARKS = [55, 70]
31const QUOTA_MARKS = [50, 85]
32
33/**
34 * The cold-cache ladder of the binary's `C:%` colour: under 40% of the input
35 * read from cache, with half or more written to it, is a cache rebuilding.
36 */
37const CACHE_READ_UNDER = 0.4
38const CACHE_CREATION_AT = 0.5
39
40/**
41 * How near autocompact opens the context alert early, in turns: enough to
42 * finish the task at hand and compact at its end rather than mid-task.
43 */
44export const RUNWAY_TURNS = 5
45
46/** How many turns' growth the runway averages over. */
47const RUNWAY_SAMPLES = 5
48
49/** How many failures in a row of one tool open the terminal band's alert. */
50export const FAIL_STREAK = 3
51
52/** How long one tool call runs before the terminal band says so. */
53export const LONG_TOOL_MS = 60_000
54
55/** How often a long call's row is redrawn, so its time moves. */
56export const LONG_TICK_MS = 15_000
57
58/** How long a turn runs before its end is worth a notification. */
59export const LONG_TURN_MS = 3 * 60_000
60
61/** The `desktopLayout` value that draws this band rather than the binary's rows. */
62export const QUIET = 'quiet'
63
64/** The `/compact` button's key: its address at `ui.press`. */
65export const COMPACT_KEY = 'pulseline:compact'
66
67const AMBER = '#d7875f'
68const RED = '#d75f5f'
69const BLUE = '#7a9cc6'
70
71/** The last turn's input, split into cache read, cache written, and the rest. */
72export function hitRate(tokens: Tokens | null): { read: number; creation: number } | null {
73 if (tokens === null) return null
74 const read = tokens.cache_read_input_tokens
75 const made = tokens.cache_creation_input_tokens
76 const all = read + made + tokens.input_tokens
77 if (all === 0) return null
78 return { read: read / all, creation: made / all }
79}
80
81/**
82 * The growth series after a main turn ends with the context at `tokens`: its
83 * growth appended, the oldest dropped past `RUNWAY_SAMPLES`. A context that
84 * shrank was compacted (or cleared), so the series starts over from it.
85 */
86export function nextDeltas(last: number | null, deltas: readonly number[], tokens: number): number[] {
87 if (last === null || tokens < last) return []
88 return [...deltas, tokens - last].slice(-RUNWAY_SAMPLES)
89}
90
91/**
92 * Whole turns left before autocompact runs at `threshold`, at the recent
93 * turns' average growth; `null` with fewer than two turns' growth, growth
94 * that is flat or falling, or no threshold (autocompact off).
95 */
96export function runwayOf(current: number, deltas: readonly number[], threshold: number | null): number | null {
97 if (threshold === null || deltas.length < 2) return null
98 const average = deltas.reduce((sum, delta) => sum + delta, 0) / deltas.length
99 if (average <= 0) return null
100 return Math.max(0, Math.floor((threshold - current) / average))
101}
102
103/**
104 * The alert rows for one reading, context first: it is the one with a button.
105 * Quota has no row of its own; the strip draws it, and `quotaPast` notifies.
106 *
107 * The context's opens at its limit, or earlier once autocompact is
108 * `RUNWAY_TURNS` turns off.
109 */
110export function desktopAlerts(usage: SessionUsage, tokens: Tokens | null, runway: number | null = null): Alert[] {
111 const alerts: Alert[] = []
112
113 const ctx = usage.context.percent
114 const near = runway !== null && runway <= RUNWAY_TURNS
115 if (ctx !== undefined && (ctx >= LIMITS.ctx || near)) {
116 alerts.push({
117 kind: 'ctx',
118 percent: ctx,
119 used: usage.context.tokens ?? Math.round((usage.context.window * ctx) / 100),
120 window: usage.context.window,
121 ...(runway !== null ? { runway } : {}),
122 })
123 }
124
125 const hit = hitRate(tokens)
126 if (hit !== null && hit.read < CACHE_READ_UNDER && hit.creation >= CACHE_CREATION_AT) {
127 alerts.push({ kind: 'cache', ...hit })
128 }
129
130 return alerts
131}
132
133/** Whether the desktop's quiet band draws an alert: its strip and transcript carry the rest. */
134export function onDesktopBand(alert: Alert): boolean {
135 return alert.kind === 'ctx' || alert.kind === 'cache'
136}
137
138/**
139 * The failure run after one main-loop tool call ends: a failure of the same
140 * tool adds to it, of another starts a new one; a success of the same tool
141 * ends it, and of another leaves it be.
142 */
143export function nextStreak(
144 streak: FailStreak | null,
145 tool: string,
146 failed: boolean,
147 target: string | undefined,
148): FailStreak | null {
149 const same = streak !== null && streak.tool === tool
150 if (!failed) return same ? null : streak
151 return { tool, count: same ? streak.count + 1 : 1, ...(target !== undefined ? { target } : {}) }
152}
153
154/**
155 * Every alert for one reading, most pressing first: what failed, what is
156 * running long, the context, the cache. The tools first, because they are
157 * this turn's and the rest can wait for its end. Each band filters the list
158 * (`onTerminalBand`, `onDesktopBand`). `now` is `$.clock.now()`.
159 */
160export function alertsOf(
161 usage: SessionUsage,
162 tokens: Tokens | null,
163 runway: number | null,
164 streak: FailStreak | null,
165 active: readonly ActiveTool[],
166 now: number,
167): Alert[] {
168 const alerts: Alert[] = []
169 if (streak !== null && streak.count >= FAIL_STREAK) alerts.push({ kind: 'fails', ...streak })
170 for (const tool of active) {
171 if (now - tool.startedAt < LONG_TOOL_MS) continue
172 const { name, target, startedAt } = tool
173 alerts.push({ kind: 'long', tool: name, startedAt, ...(target !== undefined ? { target } : {}) })
174 }
175 alerts.push(...desktopAlerts(usage, tokens, runway))
176 return alerts
177}
178
179/**
180 * Whether the terminal band draws an alert. Its statusline carries the
181 * quota pace, the context percent and the cache, so what is left is what
182 * only the mod knows: a failure run, a long call, and how many turns are
183 * left before autocompact.
184 */
185export function onTerminalBand(alert: Alert): boolean {
186 // The desktop also opens it at 70%; the terminal's statusline has that.
187 if (alert.kind === 'ctx') return alert.runway !== undefined && alert.runway <= RUNWAY_TURNS
188 return alert.kind === 'fails' || alert.kind === 'long'
189}
190
191/** One alert as the terminal band draws it: the context row is its runway alone. */
192export function terminalRow(alert: Alert, now: number): AlertRow {
193 const row = alertRow(alert, now)
194 return alert.kind === 'ctx' ? { ...row, gauge: null, label: row.detail, detail: '' } : row
195}
196
197/**
198 * How long until the terminal band must refresh for a long call: when the
199 * oldest running one crosses `LONG_TOOL_MS`, then every `LONG_TICK_MS` so its
200 * time moves; `null` with nothing running. No event marks either moment.
201 */
202export function nextLongCheck(active: readonly ActiveTool[], now: number): number | null {
203 if (active.length === 0) return null
204 const oldest = Math.min(...active.map(tool => tool.startedAt))
205 const left = LONG_TOOL_MS - (now - oldest)
206 return left > 0 ? Math.max(1000, left) : LONG_TICK_MS
207}
208
209/** One quota window as the strip holds it. */
210export type QuotaWindow = Strip['quota'][number]
211
212/** The engine's rate-limit windows, their resets as epoch seconds. */
213function quotaWindows(usage: SessionUsage): QuotaWindow[] {
214 return usage.rateLimits.map(limit => {
215 const resetsMs = limit.resetsAt === undefined ? NaN : Date.parse(limit.resetsAt)
216 return {
217 window: limit.kind,
218 percent: limit.percentUsed,
219 ...(Number.isFinite(resetsMs) ? { resetsAt: Math.floor(resetsMs / 1000) } : {}),
220 }
221 })
222}
223
224/** The quota windows at or past their limit: each is notified once per reset. */
225export function quotaPast(usage: SessionUsage): QuotaWindow[] {
226 return quotaWindows(usage).filter(quota => quota.percent >= LIMITS.quota)
227}
228
229/** What a quota window is notified under: the window and its reset. */
230export function quotaKey(quota: QuotaWindow): string {
231 return `${quota.window}@${quota.resetsAt ?? 'unknown'}`
232}
233
234/**
235 * The strip the quiet band keeps on screen: every quota window, the session
236 * cost and its rate. `now` is `$.clock.now()`, the clock
237 * `usage.startedAt` is on.
238 */
239export function stripOf(usage: SessionUsage, now: number): Strip {
240 const usd = usage.cost?.usd
241 const hours = (now - usage.startedAt) / 3_600_000
242 // A rate over the first minute is noise: one turn's cost read as an hour's.
243 const usdPerHour = usd !== undefined && hours >= 1 / 60 ? usd / hours : undefined
244 return {
245 quota: quotaWindows(usage),
246 ...(usd !== undefined ? { usd } : {}),
247 ...(usdPerHour !== undefined ? { usdPerHour } : {}),
248 }
249}
250
251/**
252 * What one desktop session keeps in `$.store` so the others can see it: its
253 * cost so far, and when it last said so. Quota is the account's, shared by
254 * every session, so only the sessions' own costs can say which one burns it.
255 *
256 * One key per session, never a shared total: the store is one file across
257 * processes, and a read-then-write of a shared value loses updates.
258 */
259export type SessionSpend = { usd: number; at: number }
260
261/** The store key a session's spend is kept under. */
262export const SPEND_PREFIX = 'session.'
263
264/** A session that has not said anything for this long is not active. */
265export const SPEND_ACTIVE_MS = 10 * 60_000
266
267/** A key this old is deleted, so the store (4 MiB in all) cannot grow forever. */
268export const SPEND_EXPIRE_MS = 24 * 3_600_000
269
270/** How often an unchanged spend is written again, to stay active. */
271export const SPEND_WRITE_MS = 30_000
272
273/** A store value as a spend, or `null` for anything else: never cast. */
274export function spendOf(value: unknown): SessionSpend | null {
275 if (typeof value !== 'object' || value === null) return null
276 const { usd, at } = value as Record<string, unknown>
277 return typeof usd === 'number' && typeof at === 'number' ? { usd, at } : null
278}
279
280/**
281 * Whether to write the spend again: it moved, or the last write is going
282 * stale. Never over a newer one: refreshes overlap, and the one that read
283 * the clock first can reach the store last.
284 */
285export function shouldWriteSpend(last: SessionSpend | null, usd: number, now: number): boolean {
286 if (last === null) return true
287 if (last.at > now) return false
288 return last.usd !== usd || now - last.at >= SPEND_WRITE_MS
289}
290
291/**
292 * This session's share of what the active sessions have spent, with how many
293 * others are active; `null` with none, or nothing spent, since a lone
294 * session's 100% says nothing. `others` are the other sessions' spends.
295 */
296export function shareOf(
297 usd: number,
298 others: readonly SessionSpend[],
299 now: number,
300): NonNullable<Strip['share']> | null {
301 const active = others.filter(other => now - other.at <= SPEND_ACTIVE_MS)
302 const total = active.reduce((sum, other) => sum + other.usd, usd)
303 if (active.length === 0 || total <= 0) return null
304 return { share: usd / total, others: active.length }
305}
306
307/** `this session ~40% of spend · 2 others active` */
308export function shareLine(share: NonNullable<Strip['share']>): string {
309 const others = share.others === 1 ? '1 other' : `${share.others} others`
310 return `this session ~${Math.round(share.share * 100)}% of spend · ${others} active`
311}
312
313/** `five_hour` → `5h`, `seven_day` → `7d`; any other window as the engine names it. */
314export function windowLabel(window: string): string {
315 if (window === 'five_hour') return '5h'
316 if (window === 'seven_day') return '7d'
317 return window
318}
319
320/** `6m 12s`, `2h 5m`, `6d 10h`: the two largest units, a trailing zero dropped. */
321export function formatSpan(ms: number): string {
322 const total = Math.max(0, Math.round(ms / 1000))
323 const parts: [number, string][] = [
324 [Math.floor(total / 86_400), 'd'],
325 [Math.floor((total % 86_400) / 3600), 'h'],
326 [Math.floor((total % 3600) / 60), 'm'],
327 [total % 60, 's'],
328 ]
329 const from = parts.findIndex(([value]) => value > 0)
330 if (from < 0) return '0s'
331 return parts
332 .slice(from, from + 2)
333 .filter(([value], index) => index === 0 || value > 0)
334 .map(([value, unit]) => `${value}${unit}`)
335 .join(' ')
336}
337
338/** `146.0k`, `1.2M`: the binary's own token format. */
339function formatTokens(count: number): string {
340 if (count >= 1_000_000) return `${(count / 1_000_000).toFixed(1)}M`
341 if (count >= 1_000) return `${(count / 1_000).toFixed(1)}k`
342 return String(count)
343}
344
345/** How long until a reset, rounded to the minute; `null` when none was named. */
346function resetsIn(resetsAt: number | undefined, now: number): string | null {
347 if (resetsAt === undefined) return null
348 return formatSpan(Math.round((resetsAt * 1000 - now) / 60_000) * 60_000)
349}
350
351/** How long each rate-limit window runs, so a reset says how far in it is. */
352const WINDOW_MS: Record<string, number> = { five_hour: 5 * 3_600_000, seven_day: 7 * 86_400_000 }
353
354/**
355 * How far into a window a projection waits: before it, one burst reads as a
356 * whole window's pace. 15 minutes of five hours, 8.4 hours of seven days.
357 */
358const PACE_FROM = 0.05
359
360/** A window's average pace so far, carried to its reset. */
361type Pace = {
362 /** The share of the window gone, 0 to 1. */
363 elapsed: number
364 /** The percent used by the reset at this pace; 100 or more runs out first. */
365 projected: number
366 /** At or past 100: how long until the window runs out. */
367 fullInMs?: number
368}
369
370/** `null` for a window of unknown length, with no reset, too early in, or unused. */
371function paceOf(quota: QuotaWindow, now: number): Pace | null {
372 const length = WINDOW_MS[quota.window]
373 if (length === undefined || quota.resetsAt === undefined || quota.percent <= 0) return null
374 const gone = length - (quota.resetsAt * 1000 - now)
375 const elapsed = gone / length
376 if (elapsed < PACE_FROM || elapsed > 1) return null
377 const projected = quota.percent / elapsed
378 if (projected < 100) return { elapsed, projected }
379 return { elapsed, projected, fullInMs: ((100 - quota.percent) * gone) / quota.percent }
380}
381
382/** A pace as the strip's line under the label: tight, as the reset is. */
383function paceLine(pace: Pace): { text: string; color?: string } {
384 if (pace.fullInMs === undefined) return { text: `→ ~${Math.round(pace.projected)}% at reset` }
385 const span = formatSpan(Math.round(pace.fullInMs / 60_000) * 60_000).replace(' ', '')
386 return { text: `full in ~${span}`, color: AMBER }
387}
388
389/** One alert as the band draws it: an optional gauge, a label, the detail. */
390export type AlertRow = {
391 /** The `Svg` gauge's markup, and what it says for a reader that cannot see it. */
392 gauge: { source: string; alt: string } | null
393 label: string
394 /** The label's colour: amber for a warning. */
395 color: string
396 detail: string
397 /** Whether the row carries the `/compact` button. */
398 compact: boolean
399}
400
401/**
402 * `now` moves a long call's time on: the render passes the last refresh's
403 * clock, and the refresh timer keeps that within `LONG_TICK_MS`.
404 */
405export function alertRow(alert: Alert, now: number): AlertRow {
406 switch (alert.kind) {
407 case 'fails':
408 return {
409 gauge: null,
410 label: `✘ ${alert.tool} failed ${alert.count}× in a row`,
411 color: RED,
412 detail: alert.target ?? '',
413 compact: false,
414 }
415 case 'long':
416 return {
417 gauge: null,
418 label: `◷ ${alert.tool} running ${formatSpan(Math.max(0, now - alert.startedAt))}`,
419 color: AMBER,
420 detail: alert.target ?? '',
421 compact: false,
422 }
423 case 'ctx': {
424 const label = `CTX ${Math.round(alert.percent)}%`
425 return {
426 gauge: { source: gaugeSvg(alert.percent, CTX_MARKS, AMBER), alt: `Context ${label}` },
427 label,
428 color: AMBER,
429 detail:
430 alert.runway === undefined
431 ? `${formatTokens(alert.used)} / ${formatTokens(alert.window)}`
432 : runwayText(alert.runway),
433 compact: true,
434 }
435 }
436 case 'cache':
437 return {
438 gauge: null,
439 label: `cache ${Math.round(alert.read * 100)}%`,
440 color: AMBER,
441 detail: `rebuilding · ${Math.round(alert.creation * 100)}% of input is new cache`,
442 compact: false,
443 }
444 }
445}
446
447/** `~4 turns to autocompact`; under one turn's growth left, the next turn. */
448function runwayText(turns: number): string {
449 if (turns === 0) return 'autocompact next turn'
450 return `~${turns} turn${turns === 1 ? '' : 's'} to autocompact`
451}
452
453/** The notification a quota window raises once per reset. */
454export function quotaNotice(quota: QuotaWindow, now: number): string {
455 const reset = resetsIn(quota.resetsAt, now)
456 const head = `${windowLabel(quota.window)} quota at ${Math.round(quota.percent)}%.`
457 return reset === null ? head : `${head} It resets in ${reset}.`
458}
459
460/** One cell of the strip: an optional small gauge, a label, a dim detail. */
461export type StripCell = {
462 /** `height` is the image's: a paced gauge's tick stands above and below its bar. */
463 gauge: { source: string; alt: string; height: number } | null
464 label: string
465 /** The label's colour; absent, the surface's own text colour. */
466 color?: string
467 /** Where the window's pace lands it, over the detail; amber when it runs out first. */
468 pace: { text: string; color?: string } | null
469 detail: string | null
470}
471
472/** The strip as cells, in the order drawn; empty when it has nothing to say. */
473export function stripCells(strip: Strip, now: number): StripCell[] {
474 const cells: StripCell[] = strip.quota.map(quota => {
475 const label = `${windowLabel(quota.window)} ${Math.round(quota.percent)}%`
476 const pace = paceOf(quota, now)
477 const runsOut = pace?.fullInMs !== undefined
478 const fill =
479 quota.percent >= QUOTA_MARKS[1]! ? RED : quota.percent >= QUOTA_MARKS[0]! || runsOut ? AMBER : BLUE
480 const color = quota.percent >= QUOTA_MARKS[1]! ? RED : runsOut ? AMBER : undefined
481 const reset = resetsIn(quota.resetsAt, now)
482 const tick = pace === null ? undefined : pace.elapsed * 100
483 const source = gaugeSvg(quota.percent, QUOTA_MARKS, fill, 64, 8, tick)
484 return {
485 gauge: { source, alt: `Quota ${label}`, height: pace === null ? 8 : 12 },
486 label,
487 ...(color !== undefined ? { color } : {}),
488 pace: pace === null ? null : paceLine(pace),
489 // No space inside the span: the column is narrow, and `4h22m` stays on one line.
490 detail: reset === null ? null : `resets ${reset.replace(' ', '')}`,
491 }
492 })
493 if (strip.usd !== undefined) {
494 cells.push({
495 gauge: null,
496 pace: null,
497 label: `$${strip.usd.toFixed(2)}`,
498 detail: strip.usdPerHour !== undefined ? `$${strip.usdPerHour.toFixed(2)}/h` : null,
499 })
500 }
501 return cells
502}
503
504/**
505 * How many rows the strip stands: its tallest cell (a label, then a pace and
506 * a reset under it), and the share line under them all.
507 */
508export function stripRows(cells: readonly StripCell[], share: boolean): number {
509 if (cells.length === 0) return 0
510 const tallest = Math.max(
511 ...cells.map(cell => 1 + (cell.pace !== null ? 1 : 0) + (cell.detail !== null ? 1 : 0)),
512 )
513 return tallest + (share ? 1 : 0)
514}
515
516/** The notification a long turn raises when it ends. */
517export function longTurnNotice(durationMs: number): string {
518 return `The turn ended after ${formatSpan(durationMs)}.`
519}
520
521/**
522 * A bar gauge as an SVG document: a track, the filled share, and a tick at
523 * each threshold mark. Drawn as an image on the desktop, so its colours hold
524 * on a light and a dark theme alike: the track is translucent.
525 *
526 * With `pace`, the share of the window gone, the image grows 2px above and
527 * below the bar for a tick there: a fill past it is a window used faster
528 * than it runs.
529 */
530export function gaugeSvg(
531 percent: number,
532 marks: readonly number[],
533 fill: string,
534 width = 120,
535 height = 10,
536 pace?: number,
537): string {
538 const at = (share: number) => Math.round((width * Math.min(100, Math.max(0, share))) / 100)
539 const inset = pace === undefined ? 0 : 2
540 const tall = height + 2 * inset
541 const y = inset === 0 ? '' : `y="${inset}" `
542 const ticks = marks
543 .map(mark => `<rect x="${at(mark)}" ${y}width="1" height="${height}" fill="#ffffff" fill-opacity="0.7"/>`)
544 .join('')
545 const paceTick =
546 pace === undefined
547 ? ''
548 : `<rect x="${Math.min(width - 2, at(pace))}" width="2" height="${tall}" fill="#8a8578"/>`
549 return (
550 `<svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="${tall}" viewBox="0 0 ${width} ${tall}">` +
551 `<rect ${y}width="${width}" height="${height}" rx="3" fill="#8a8578" fill-opacity="0.3"/>` +
552 `<rect ${y}width="${at(percent)}" height="${height}" rx="3" fill="${fill}"/>` +
553 ticks +
554 paceTick +
555 `</svg>`
556 )
557}
558hooks/payload.ts 192 lines1import type { AgentInfo, SessionUsage } from 'claude-code'
2
3import type { Todo, Tokens, ToolCount } from '../types'
4
5/**
6 * The stdin contract between the mod and the cc-pulseline binary.
7 *
8 * The binary reads the same JSON Claude Code's own statusline hook writes,
9 * so this file is the one place that knows that schema: everything else in
10 * the mod collects facts, and `buildPayload` is the only thing that names a
11 * payload field. It touches no `$` and mutates nothing — hand it the same
12 * snapshot twice and it returns the same bytes.
13 */
14
15/**
16 * One running tool call, keyed by its `tool_use_id`.
17 *
18 * Not in the `$.state` contract: running tools live in the module's closure,
19 * since nothing is mid-flight at the moment a reload happens. `startedAt` is
20 * the call's start, in epoch milliseconds, for the terminal band's alert.
21 */
22export type ActiveTool = { id: string; name: string; target?: string; startedAt: number }
23
24/**
25 * Everything one payload is built from: what the engine answered for this
26 * refresh, and what the hooks have accumulated since the session began.
27 *
28 * The maps are read-only here on purpose. An agent with no `startedAt`
29 * record must be stamped *before* this is built, or its start time would be
30 * the moment of each draw rather than the moment it was first seen; the
31 * caller owns that stamping, which is why this stays pure.
32 */
33export type PayloadSnapshot = {
34 /** What the engine answered this refresh. */
35 sessionId: string
36 modelId: string
37 usage: SessionUsage
38 agents: readonly AgentInfo[]
39 now: number
40
41 /**
42 * Session facts the hooks resolved once.
43 *
44 * `outputStyle` and `lastApiErrorMs` may arrive `undefined` rather than
45 * `null` from a session whose `session` atom the host wrote before these
46 * two existed, so both are read defensively below.
47 */
48 cwd: string
49 version: string | null
50 effort: string | null
51 outputStyle: string | null
52 lastApiErrorMs: number | null
53 cacheReadTotal: number
54 tokens: Tokens | null
55
56 /**
57 * Counts the engine answered for. A zero means "nothing seen", and the
58 * field is then left out so the binary's own filesystem scan stands.
59 */
60 mcpCount: number
61 claudeMdCount: number
62 agentsMdCount: number
63 rulesCount: number
64 memoryCount: number
65
66 /**
67 * Activity the hooks accumulated.
68 *
69 * Plain records rather than `Map`s: every one of these but `active` is an
70 * atom value now, and an atom value crosses to the host as JSON. Key order
71 * is insertion order either way, so the rows come out as they did — tool
72 * names are never integer-like, which is the one case where an object
73 * would reorder them.
74 *
75 * `active` is a list, and a copy: `refresh` takes it when it starts, so a
76 * tool that finishes while the draw is still gathering cannot be drawn as
77 * running by it, nor lost from the draw it was started for.
78 */
79 active: readonly ActiveTool[]
80 counts: Readonly<Record<string, ToolCount>>
81 completedTotal: number
82 failedTotal: number
83 startedAt: Readonly<Record<string, number>>
84 finishedAt: Readonly<Record<string, number>>
85 agentType: Readonly<Record<string, string>>
86 compactCount: number
87 todo: Todo | null
88}
89
90/**
91 * Turns a model id into the name the statusline shows.
92 *
93 * The engine hands out ids (`claude-opus-5[1m]`); the statusline payload
94 * that Claude Code itself writes carries a display name, and there is no
95 * call for that one, so this rebuilds it.
96 */
97export function modelName(id: string): string {
98 const isMillion = id.includes('[1m]')
99 const base = id
100 .replace('[1m]', '')
101 .replace(/^claude-/, '')
102 .replace(/-\d{8}$/, '')
103 const words = base
104 .split('-')
105 .map(word => word.charAt(0).toUpperCase() + word.slice(1))
106 .join(' ')
107 return isMillion ? `${words} (1M context)` : words
108}
109
110/** The JSON the binary reads on stdin. */
111export function buildPayload(snapshot: PayloadSnapshot): string {
112 const { usage, now } = snapshot
113
114 const limits: Record<string, { used_percentage: number; resets_at?: number }> = {}
115 for (const limit of usage.rateLimits) {
116 // Left out when the engine named no reset, and when it named one that
117 // does not parse. `resets_at: 0` is not "unknown" to the binary — it is
118 // the epoch, and the quota cell then reads `resets <1m` on every refresh
119 // for the rest of the session. An absent key is `None` there, which draws
120 // the percentage and no reset at all.
121 const resetsAt = limit.resetsAt === undefined ? NaN : Date.parse(limit.resetsAt) / 1000
122 limits[limit.kind] = {
123 used_percentage: limit.percentUsed,
124 ...(Number.isFinite(resetsAt) ? { resets_at: Math.floor(resetsAt) } : {}),
125 }
126 }
127
128 return JSON.stringify({
129 session_id: snapshot.sessionId,
130 model: { display_name: modelName(snapshot.modelId) },
131 output_style: snapshot.outputStyle ? { name: snapshot.outputStyle } : undefined,
132 version: snapshot.version ?? undefined,
133 effort: snapshot.effort ? { level: snapshot.effort } : undefined,
134 cwd: snapshot.cwd,
135 workspace: { current_dir: snapshot.cwd },
136 context_window: {
137 context_window_size: usage.context.window,
138 used_percentage: usage.context.percent,
139 current_usage: snapshot.tokens ?? undefined,
140 },
141 cost: usage.cost ? { total_cost_usd: usage.cost.usd } : undefined,
142 rate_limits: limits,
143 // Only the counts the engine answered for; the rest stay as the
144 // binary's own filesystem scan found them.
145 env: {
146 mcp_count: snapshot.mcpCount,
147 claude_md_count: snapshot.claudeMdCount > 0 ? snapshot.claudeMdCount : undefined,
148 agents_md_count: snapshot.agentsMdCount > 0 ? snapshot.agentsMdCount : undefined,
149 rules_count: snapshot.rulesCount > 0 ? snapshot.rulesCount : undefined,
150 memory_count: snapshot.memoryCount > 0 ? snapshot.memoryCount : undefined,
151 },
152 activity: {
153 tools: snapshot.active.map(tool => ({
154 id: tool.id,
155 name: tool.name,
156 target: tool.target ?? null,
157 })),
158 completed_counts: Object.entries(snapshot.counts).map(([name, count]) => ({
159 name,
160 count: count.count,
161 failed: count.failed,
162 // What the binary ranks on, beside the count. Left out when a kind
163 // has no stamp — a session whose atom the host wrote before this
164 // field existed — where the binary then scores it on its count alone.
165 last_completed_at: count.lastAt > 0 ? count.lastAt : undefined,
166 })),
167 completed_total: snapshot.completedTotal,
168 failed_total: snapshot.failedTotal,
169 agents: snapshot.agents.map(agent => ({
170 id: agent.id,
171 description: agent.description,
172 agent_type: snapshot.agentType[agent.id] ?? agent.type,
173 started_at: snapshot.startedAt[agent.id] ?? now,
174 // A stamp from `SubagentStop`, or the one `collect` wrote the first
175 // time the engine stopped listing the agent as running. The `now`
176 // below is only reached by a snapshot built without that write — a
177 // live refresh always has the stamp, which is what keeps a completed
178 // agent's elapsed time still.
179 completed_at:
180 snapshot.finishedAt[agent.id] ?? (agent.status === 'running' ? null : now),
181 })),
182 compact_count: snapshot.compactCount,
183 last_api_error_ms: snapshot.lastApiErrorMs ?? undefined,
184 // Already totalled, because only this side can total it. Left out
185 // while nothing has been read, so the binary keeps its own figure
186 // rather than being told the session read zero.
187 cache_read_total: snapshot.cacheReadTotal > 0 ? snapshot.cacheReadTotal : undefined,
188 todo: snapshot.todo,
189 },
190 })
191}
192hooks/throttle.ts 26 lines1/**
2 * The refresh gate, as a function of three numbers.
3 *
4 * Pulled out for the same reason `buildPayload` was: the decision is
5 * arithmetic, and arithmetic can be tested without a clock, a spawn or a
6 * mounted drawing. `maybeRefresh` keeps the part that is genuinely about
7 * timing — reading the clock and claiming the window — and asks this.
8 *
9 * Several sites can trigger a refresh. The gate guards the ones that fire
10 * without a tool call of their own to account for — a run of
11 * `classic.ConfigChange` writes, say — so a burst of them does not spawn the
12 * binary once each.
13 *
14 * It does not guard the tool-call path any more, at either end. A gated start
15 * is not drawn late but never drawn at all, since the window is closed by the
16 * previous call's completion and the next refresh is this call's own, after
17 * its entry is gone; and a gated completion leaves a finished tool drawn as
18 * running. Both ends of a tool call therefore refresh unconditionally and pay
19 * a spawn each, against a floor under 3ms.
20 */
21export function shouldRefresh(lastRunMs: number, nowMs: number, gapMs: number): boolean {
22 // `>=`, so a gap of 0 always refreshes — a test that wants every call to
23 // go through asks for 0 rather than having to move a clock.
24 return nowMs - lastRunMs >= gapMs
25}
26types/index.d.ts 352 lines1/**
2 * The mod's `$.state` contract: what the host holds for the session, and so
3 * what survives a hot reload of this code.
4 *
5 * The test for a field belonging here is not "does it accumulate" but "would
6 * the person notice it being lost", because a reload happens every time the
7 * mod is edited. That covers three kinds of value: what the hooks have added
8 * up over the session, what the person has asked for (their pane, their
9 * layout), and the binary's last output, so a reload redraws the rows it
10 * already had instead of flashing a not-run-yet note.
11 *
12 * Geometry (`bandRows`, `bandCols`, `paneCols`, `paneHeight`) is deliberately
13 * NOT here: it is written from inside `ui.render`, and the host refuses a
14 * state write while a render hook draws.
15 *
16 * Values are grouped by concern rather than one atom per field: `update` is a
17 * read-modify-write with `ifVersion` and a retry, so a group is safe against
18 * concurrent writers, and `refresh` sits in the tool-call path where seven
19 * round trips beat twenty-one.
20 */
21
22/**
23 * The styles `spansOf` sets from the binary's SGR codes.
24 *
25 * Spelled out rather than taken from `TextProps`, because a contract has to
26 * be self-contained — `claude plugin validate` refuses one that imports. It
27 * is the subset the ANSI parser actually produces, and every member is a
28 * `TextProps` member, so a span still spreads onto a `Text`.
29 */
30export type SpanStyle = {
31 color?: string
32 backgroundColor?: string
33 bold?: boolean
34 dimColor?: boolean
35 inverse?: boolean
36}
37
38/** One run of text carrying the style the SGR codes before it set. */
39export type Span = SpanStyle & { children: string }
40
41/** Turn token counts, kept from the last `turn.complete`. */
42export type Tokens = {
43 input_tokens: number
44 output_tokens: number
45 cache_read_input_tokens: number
46 cache_creation_input_tokens: number
47}
48
49/** Session totals per tool name, as the completed-counts row shows them. */
50/**
51 * One tool kind's tally.
52 *
53 * `lastAt` is when it last finished, in epoch milliseconds. The binary ranks
54 * the kinds by count plus a recency bonus and keeps only
55 * `max_completed_tools` of them — four by default — so without a stamp the
56 * four a session opened with would outrank the ones it actually leans on.
57 */
58export type ToolCount = { count: number; failed: number; lastAt: number }
59
60/** The todo list as the last TodoWrite call left it. */
61export type Todo = {
62 text: string
63 pending: number
64 completed: number
65 total: number
66 in_progress_items: { text: string; started_at?: number }[]
67 all_done: boolean
68 is_task_api: boolean
69}
70
71/**
72 * One Task API item: `TaskCreate` opens it, `TaskUpdate` moves its status.
73 *
74 * The transcript path keeps the same four fields (`state/mod.rs`'s `TaskItem`)
75 * because the todo row is rebuilt from the whole set on every change — a
76 * status arrives with an id and nothing else, so the rest has to be held.
77 */
78export type TaskItem = {
79 subject: string
80 status: string
81 activeForm?: string
82 startedAt?: number
83}
84
85/**
86 * The Task API's items, by the id the engine gave each one.
87 *
88 * `TaskCreate`'s *result* carries that id (`{ task: { id } }`), which is the
89 * id a later `TaskUpdate` names — so nothing here is counted or guessed, and
90 * a refused create leaves no entry behind.
91 */
92export type Tasks = {
93 items: Record<string, TaskItem>
94}
95
96/**
97 * Facts about the session the hooks resolve as the engine reports them.
98 *
99 * `cwd` holds the session's project root, which `$.session.root()` answers
100 * before every ladder walk: it moves under the mod — `/cd`, a host's
101 * directory change, a worktree move — and it is both what the binary scans
102 * for the config row and where its git shell-out runs, so a held one reports
103 * the project the person left. `session.start`'s `e.cwd` still seeds it, as
104 * the value the read falls back to: the window between `register` running
105 * and that event arriving draws the project it already knew rather than an
106 * empty path, and a payload with no `cwd` resolves to an unknown project
107 * where the binary has no env, no git and no project config.
108 */
109export type SessionFacts = {
110 cwd: string
111 version: string | null
112 effort: string | null
113 tokens: Tokens | null
114 compactCount: number
115 /** What the person chose in place of the default way of answering. */
116 outputStyle: string | null
117 /**
118 * When the last turn ended in an API error, in epoch milliseconds.
119 *
120 * Never cleared: the binary already drops a reading older than 30s, so a
121 * stale one cannot light the badge.
122 */
123 lastApiErrorMs: number | null
124 /**
125 * Cache-read tokens summed over the session, for the ledger's CACHE row.
126 *
127 * The mod has to total this itself. The binary cannot: only the transcript
128 * path can dedupe per-API-call usage by `message.id`, and every refresh
129 * re-sends the same last-turn usage as `current_usage` — twice over when
130 * the pane is open — so accumulating there would multiply-count.
131 *
132 * Not reset on compaction, deliberately. The transcript path keeps it
133 * across `compact_boundary` and clears only the trend window
134 * (`providers/transcript.rs`), and the row claims a session total, so
135 * resetting here would make the two paths disagree.
136 */
137 cacheReadTotal: number
138 /**
139 * The context's tokens at the end of the last main turn, as the engine's
140 * `/context` breakdown totals them, for the quiet desktop band's
141 * autocompact runway. Absent from an atom an older
142 * version wrote, so read it as `?? null`.
143 */
144 ctxTokens?: number | null
145 /**
146 * How much each of the last few main turns grew the context, oldest
147 * first; cleared when the context shrinks, as a compaction makes it. Read
148 * as `?? []`.
149 */
150 ctxDeltas?: number[]
151 /**
152 * Where autocompact runs, as the engine's `/context` breakdown last said:
153 * `threshold` in tokens, `null` when it named none. Read as `?? null`.
154 */
155 autoCompact?: { threshold: number | null; enabled: boolean } | null
156}
157
158/** What the tool-call hook has counted this session. */
159export type ToolTotals = {
160 counts: Record<string, ToolCount>
161 completedTotal: number
162 failedTotal: number
163 /**
164 * The main loop's run of failures of one tool, for the terminal band's
165 * alert: `count` failures in a row, the last one's target. A failure of
166 * another tool starts a new run; a success of this one ends it. Absent
167 * from an atom an older version wrote, so read it as `?? null`.
168 */
169 failStreak?: FailStreak | null
170}
171
172/** One tool failing again and again, as `ToolTotals.failStreak` holds it. */
173export type FailStreak = { tool: string; count: number; target?: string }
174
175/** Agent timings and resolved types, by agent id. */
176export type AgentTimings = {
177 startedAt: Record<string, number>
178 finishedAt: Record<string, number>
179 agentType: Record<string, string>
180}
181
182/** The instruction files the engine said it loaded, by kind. */
183export type Instructions = {
184 claudeMd: string[]
185 /**
186 * Kept apart from `claudeMd` because the binary counts the two separately:
187 * `env.rs`'s `count_agents_md` has its own column on the ENV row, so an
188 * AGENTS.md folded into the CLAUDE.md count is drawn twice.
189 */
190 agentsMd: string[]
191 rules: string[]
192 memories: string[]
193}
194
195/** What the person asked of the pane, which a reload must not undo. */
196export type PaneWanted = {
197 open: boolean
198 layout: string
199}
200
201/**
202 * Which binary the mod resolved, and whether it can be used.
203 *
204 * Held rather than recomputed because resolving it means running up to five
205 * candidates: a closure would re-probe the whole ladder on every hot reload.
206 * It is set back to `null` on `classic.ConfigChange`, so a binary installed
207 * or a path configured mid-session is picked up — without that an atom would
208 * keep one bad answer for the life of the session.
209 */
210/**
211 * Where the binary is, as the ladder last answered.
212 *
213 * The two negative answers carry `at`, the moment the walk was made, because
214 * they expire: the band's own message is `npm install -g …`, and an install
215 * raises no event at all — so a cached failure that never expired would
216 * outlive the fix it asked for and the band could not recover inside the
217 * session. A successful answer has no `at`; it is kept until a settings
218 * write clears it.
219 */
220export type BinaryChoice =
221 | { kind: 'ok'; path: string; version: string; rung: string }
222 | { kind: 'too-old'; path: string; version: string; rung: string; at: number }
223 | { kind: 'missing'; at: number }
224
225/**
226 * How the last band run ended, which is not the same question as whether
227 * there are rows.
228 *
229 * A quiet band draws nothing until something passes a limit, and the
230 * binary-drawn layouts can draw nothing too — so zero rows is the ordinary
231 * state, not a fault. Only `'failed'` is worth saying out loud, and it has
232 * to be said whether or not a turn is running: a missing binary raises no
233 * event, and an install line nobody sees fixes nothing.
234 *
235 * `'never'` is the value before the first walk finishes. It draws nothing,
236 * so the band does not flash a not-run-yet note over an idle prompt while
237 * `session.start` is still probing.
238 */
239export type BandRun = 'never' | 'ok' | 'failed'
240
241/**
242 * One alert row a quiet band draws: something past its limit.
243 *
244 * Worked out in `refresh` from `$.session.usage()`, the last turn's tokens,
245 * the running tools and the failure run (`hooks/desktop.ts`), and published
246 * with the rows, because the render hook may read state but never write it.
247 * The terminal band draws every kind. The desktop's draws `ctx` and `cache`
248 * only: its strip carries the quota pace, and its transcript every tool.
249 */
250export type Alert =
251 | {
252 kind: 'fails'
253 tool: string
254 /** Failures in a row, `FAIL_STREAK` or more. */
255 count: number
256 target?: string
257 }
258 | {
259 kind: 'long'
260 tool: string
261 target?: string
262 /** When the call started, in epoch milliseconds. */
263 startedAt: number
264 }
265 | {
266 kind: 'ctx'
267 percent: number
268 used: number
269 window: number
270 /**
271 * Whole turns left before autocompact runs, at the recent turns'
272 * growth; absent when there is no reading for it, or from an alert an
273 * older version wrote.
274 */
275 runway?: number
276 }
277 | {
278 kind: 'cache'
279 /** Shares of the last turn's input: read from cache, written to it. */
280 read: number
281 creation: number
282 }
283
284/**
285 * The thin strip the quiet desktop band keeps on screen: what the Code tab
286 * does not show. Each part is left out when there is no reading for it.
287 */
288export type Strip = {
289 quota: {
290 /** The rate-limit window as the engine names it: `five_hour`, `seven_day`. */
291 window: string
292 percent: number
293 /** Epoch seconds; absent when the engine named no reset. */
294 resetsAt?: number
295 }[]
296 /** Session cost so far, and per hour since the session began. */
297 usd?: number
298 usdPerHour?: number
299 /**
300 * This session's share of what every active session has spent,
301 * 0 to 1, and how many others are active. Absent with no other session
302 * active, and from an atom an older version wrote, so read it as `?? null`.
303 */
304 share?: { share: number; others: number }
305}
306
307/**
308 * The binary's last output, kept so a reload redraws rather than blanks.
309 *
310 * `desktopRows` is the desktop app's band, when its layout is one the binary
311 * draws; the terminal band draws `alerts` alone and runs no binary. `bandRun`
312 * and `runNote` are shared — a failing run on either surface is said on both.
313 */
314export type DrawnOutput = {
315 desktopRows: Span[][]
316 /**
317 * The quiet bands' alerts, every kind; each surface picks its own. Absent
318 * from an atom an older version wrote, so read it as `?? []`.
319 */
320 alerts?: Alert[]
321 /**
322 * The quiet desktop band's strip; `null` when no desktop shows it. Absent
323 * from an atom an older version wrote, so read it as `?? null`.
324 */
325 strip?: Strip | null
326 /**
327 * The quota windows already notified, one `quotaKey` each, so a window is
328 * notified once per reset and not again after a reload. Read as `?? []`.
329 */
330 notified?: string[]
331 paneRows: Span[][]
332 bandRun: BandRun
333 runNote: string
334 paneNote: string
335}
336
337declare module 'claude-code' {
338 interface PluginState {
339 'pulseline': {
340 session: SessionFacts
341 tools: ToolTotals
342 agents: AgentTimings
343 instructions: Instructions
344 todo: Todo | null
345 tasks: Tasks
346 pane: PaneWanted
347 output: DrawnOutput
348 binary: BinaryChoice | null
349 }
350 }
351}
352