Context window details like the Desktop app's panel: /ctx opens a pane that docks beside the transcript, and a 📊 button above the prompt toggles it.

Context window details for Claude Code, in a pane and a band: how full the window is, how fast it is filling, what filled it, how to compact on your terms, and what each of those costs.
It mirrors the Desktop app's context panel, so the same information is one keypress away in the terminal. It only observes. It never compacts, rewrites or turns anything off unless you ask.
ctx in Claude's orange (it breathes near auto-compact), a small bar, the fill, a trend sparkline, the last turn's cost, the plan's pace (or an API account's session total) at the right, and a 📊 button that opens the pane. Each category in use gets at least one whole cell of the bar, so the split reads even on a nearly empty 1M window, and the free space is water (████≈~~~~~~~~~~░). The bar is 16 cells, 24 from 130 columns, 48 from 160, 64 from 200 and 96 from 240 (8 under 70), so the minimum cells overstate a near-empty window less; while an auto-compact warning stands it stays at 16 until 240 columns.Why each feature exists and how it is built: DESIGN.md.
claude plugin marketplace add afterever/claude-mods
claude plugin install ctx@afterever-mods
Restart Claude Code afterwards: an installed plugin is not hot-reloaded. Pick up new versions with claude plugin marketplace update afterever-mods and then claude plugin update ctx@afterever-mods.
The pane docks to the right of the transcript only in Claude Code's fullscreen (alternate-screen) layout, and only from 110 columns. In the main-screen layout the engine seats it above the prompt, inside the conversation. The layout belongs to Claude Code, is fixed for the session, and a mod cannot change where a pane is seated.
Turn fullscreen on with either of these:
/tui fullscreen. It saves the setting and relaunches into fullscreen with the conversation intact. /tui on its own prints the renderer in use, and /tui default goes back.~/.claude/settings.json, then restart Claude Code: "tui": "fullscreen"
Check these in order:
/tui says default. Run /tui fullscreen.CLAUDE_CODE_NO_FLICKER=0 and CLAUDE_CODE_DISABLE_ALTERNATE_SCREEN=1 both beat the tui setting. Unset them.tui setting is meant to override that default; if /tui still reports default, start Claude Code with CLAUDE_CODE_NO_FLICKER=1, which forces fullscreen for that session.The band is always above the prompt, in both layouts. Only the pane moves.
The pane also tells you where it is: in the main-screen layout it ends with a dim line, "Shown above the prompt. In the fullscreen layout (110+ columns) this docks beside the transcript."
| Command or key | Does |
|---|---|
/ctx, or 📊 / x on the band | Open the pane, or close it |
/ctx show, /ctx hide, /ctx toggle | Open, close or flip the pane |
/ctx exact, /ctx quick (e in the pane) | Count with the token API, or estimate locally (the default) |
/ctx compact [focus] (c) | Compact now, telling the summary your focus, the files you edited and your latest requests |
/ctx autokeep on or off (k) | Give every compaction the same keep list, auto-compact included. Off by default |
/ctx cost on or off (p) | Show or hide the dollar figures. On by default |
/ctx footer on or off | Show ctx N% in the footer of Claude Desktop, beside the band's own fill. Off by default; the terminal never shows it |
m f s a h d in the pane | Open MCP tools, memory files, skills, agents, heaviest results, unused so far |
r in the pane | Count again |
Esc | Close the pane when it has focus |
Whether the pane was open, autokeep and cost are remembered between sessions. Exact mode is not: an exact count costs a token-count call per change, so each session starts on the estimate.
ctx shares its look with Agent-Pulse, Waypoints and subagent-progress. Two settings, in /config → ctx:
| Setting | Values | Default |
|---|---|---|
palette | follow, ember, claude, neon, mono | follow |
animation | follow, off, subtle, full | follow |
follow takes Agent-Pulse's own setting (ember and subtle when it is not installed). In ember and neon each category has a colour of its own that shades along its cells, and the free space is water. claude and mono keep the engine's category colours and dotted free space, as before 0.8.
Every effect means something:
| Effect | Means | Levels |
|---|---|---|
The foam at the water's edge laps; at full the water drifts | the room left | subtle, full |
| The cells a turn added shimmer for a moment | what that turn ate | subtle, full |
The ctx word and the foam breathe amber, then red | auto-compact is near | subtle, full (off: still, in the hot colour) |
| A wave runs back over the freed cells | a compaction gave room back | full |
| The trend's newest point pulses | a turn is running | subtle, full |
On Claude Desktop the band's bar is a small SVG pill with the same meaning, and so is the pane's, drawn at the pane's own width with the ▲ auto-compact marker beneath it (0.8.0 drew the pane's bar as text, which overran the pane and wrapped). Pointing at a category lights its row on the terminal only. The band's trend takes the pane's colours.
81.9k/1M·8%): how full the window is. Green below 50%, amber to 80%, red above. The ▲ under the bar is where auto-compact starts.trend and ~N turns to auto-compact: the pace over the last six turns, so you can compact on your terms before the engine does it for you.Heaviest results: the tool results that took the most room, with the turn they landed in. Any single result over about 15k tokens gets a toast as it lands.Unused so far: MCP servers, skills and agents loaded and never called. A server idle for five sessions in a project is a suggestion to turn it off in /mcp. ctx never does it for you.last turn +$1.84: what the last turn cost, from the engine's own ledger. Figures with a ~ are estimates, priced from the last clean turns of the model in use.🐾 25% (3h 40m/-2%) · 22% (4d 16h/-11%), at the right of the band on a subscription: the share of the 5-hour and 7-day limits used, the time left in each window, and how far ahead of (+) or behind (-) an even spend you are. The figures and colors are claude-hud's pace. It narrows with the band (no countdown, then the deltas alone, then nothing); on the Desktop it is always whole. An API account sees session $14.2 there instead, which /ctx cost off hides, and the pace stays.hooks).Load it from disk, which hot-reloads on save:
claude --plugin-dir <path to claude-mods>/ctx
Check it before committing, from the repository root:
claude plugin validate .
claude plugin test ctx
Bump version in .claude-plugin/plugin.json and VERSION in hooks/version.ts together. The host gives a module no way to read its own manifest, so no test can compare them.
hooks/register.tsx 1476 lines1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, Register, RenderElement, SessionContextBreakdown, Timer } from 'claude-code'
3
4import type { CtxDetail, CtxFx, CtxLimit, CtxProjectLog, CtxSample, CtxServer, CtxSnapshot, CtxSpend, CtxWarn } from '../types'
5import type { BarRun, Cell } from './fmt'
6import type { ApiUsage, Piece, Rates } from './cost'
7import { addRecent, clipAsk, keepInstructions, mergeInstructions, shouldWarn, warnBadge, warnLevel, warnText } from './compact'
8import { addEater, addUsage, calibrate, DEFAULT_CPT, EMPTY_USAGE, estimateTokens, idleSessions, logSession, toolLabel, usageOf } from './usage'
9import { bandPace, paceStep, type PacePiece } from './pace'
10import { VERSION } from './version'
11import { breath, categoryTints, heatKeys, hexHeat, paletteOf, resolveLook, sparkColors, svgTints, waterOf, type Look, type Tint } from './palette'
12import { bandSvg, breathSvg } from './svg'
13import { frameAt, type TideProps } from './tide'
14import {
15 bandSuffix,
16 carry,
17 carryLine,
18 compacted as noteCompacted,
19 compactPlan,
20 EMPTY_SPEND,
21 fitRates,
22 fmtIdle,
23 fmtUsd,
24 idleCost,
25 ledgerAt,
26 median,
27 missLine,
28 rewrite,
29 sessionParts,
30 shownTurn,
31 startTurn,
32 stepDone,
33 subUsd,
34 ttlMs,
35 turnDone,
36 turnLine,
37} from './cost'
38import {
39 ago,
40 bandBarWidth,
41 bandCells,
42 barRuns,
43 breatheAt,
44 BUFFER_GLYPH,
45 compactMarker,
46 edgeOf,
47 fillColor,
48 FREE_GLYPH,
49 fmtCount,
50 fmtDelta,
51 fmtShare,
52 fmtTokens,
53 growthSpan,
54 openerFor,
55 paneRows,
56 shareBar,
57 shortPath,
58 sparkline,
59 sweepSpan,
60 trend,
61 trendLabel,
62} from './fmt'
63
64const PANE = 'ctx'
65// How often an open pane redraws its "updated 12s ago"; no count runs on it
66const TICK_MS = 15000
67const SKILL_LIMIT = 12
68const GAUGE = 6
69// Claude's own orange (the palettes' `tool`), for the band's calm `ctx` word
70const CLAUDE_ORANGE = '#d97757'
71// Bar runs and category rows share a hover group per category
72const SCOPE = 'ctx:'
73
74// What the drawings read lives in $.state, so a hot reload keeps it
75const snap = atom({ plugin: 'ctx', key: 'snap' } as const, null)
76const isVisible = atom({ plugin: 'ctx', key: 'isVisible' } as const, false)
77const opened = atom({ plugin: 'ctx', key: 'opened' } as const, [])
78const mode = atom({ plugin: 'ctx', key: 'mode' } as const, 'summary')
79const stale = atom({ plugin: 'ctx', key: 'stale' } as const, false)
80const tick = atom({ plugin: 'ctx', key: 'tick' } as const, 0)
81// The window's fill after each turn, oldest first, as the API reported it
82const history = atom({ plugin: 'ctx', key: 'history' } as const, [])
83const HISTORY_LIMIT = 48
84const eaters = atom({ plugin: 'ctx', key: 'eaters' } as const, [])
85const cptAtom = atom({ plugin: 'ctx', key: 'cpt' } as const, DEFAULT_CPT)
86const usage = atom({ plugin: 'ctx', key: 'usage' } as const, EMPTY_USAGE)
87const project = atom({ plugin: 'ctx', key: 'project' } as const, null)
88// A single result past this many tokens gets a toast as it lands
89const TOAST_TOKENS = 15000
90// Results smaller than this never make the heaviest list
91const EATER_MIN_CHARS = 2000
92// A fall this steep between turns is a compaction or a /clear: what was eaten is gone
93const DROP_RATIO = 0.7
94
95// The `palette` and `animation` options (register sets them) and the look they resolve to: 'follow'
96// takes Agent-Pulse's /config rows. Module state, so a reload with new options starts over from them
97let configured: { palette?: unknown; animation?: unknown } = {}
98let look: Look = resolveLook({}, [])
99
100// Reads Agent-Pulse's rows again; a change redraws everything ctx draws
101async function refreshLook($: EngineInterface) {
102 let rows: unknown = []
103 try {
104 rows = await $.config.list()
105 } catch {
106 // no rows: follow falls back to ember / subtle
107 }
108 const next = resolveLook(configured, rows)
109 if (next.palette === look.palette && next.level === look.level) return
110 look = next
111 $.ui.invalidate('ui.render')
112}
113
114// Characters of tool results the main conversation took in since the last measurement
115let turnChars = 0
116
117const projectKey = async ($: EngineInterface) => 'project:' + (await $.session.cwd())
118
119// Writes this session's line in the project's log: the servers it has loaded, the ones it called
120async function logProject($: EngineInterface) {
121 try {
122 const s = await read($, snap)
123 if (!s) return
124 const loaded: Record<string, number> = {}
125 for (const v of s.servers) if (v.tokens > 0) loaded[v.key] = v.tokens
126 const used = Object.keys((await read($, usage)).mcp)
127 const { requests, misses } = await read($, spend)
128 const key = await projectKey($)
129 const log = (await $.store.get(key)) as CtxProjectLog | undefined
130 await $.store.set(key, logSession(log, await $.session.id(), loaded, used, { requests, misses }))
131 } catch {
132 // the log is a convenience: the pane still counts this session
133 }
134}
135
136const compacted = atom({ plugin: 'ctx', key: 'compacted' } as const, [])
137const edited = atom({ plugin: 'ctx', key: 'edited' } as const, [])
138const asks = atom({ plugin: 'ctx', key: 'asks' } as const, [])
139const autokeep = atom({ plugin: 'ctx', key: 'autokeep' } as const, false)
140const warned = atom({ plugin: 'ctx', key: 'warned' } as const, 'none')
141const EDIT_LIMIT = 12
142const ASK_LIMIT = 3
143// What the session spent, per turn, from the engine's cost ledger
144const spend = atom({ plugin: 'ctx', key: 'spend' } as const, EMPTY_SPEND)
145const costOn = atom({ plugin: 'ctx', key: 'costOn' } as const, true)
146// The Desktop footer's `ctx N%`, a second reading beside the band's own fill
147const footerOn = atom({ plugin: 'ctx', key: 'footerOn' } as const, false)
148// The plan's rate-limit windows as the last response reported them, and a
149// minute tick that moves the band's countdown between responses
150const limits = atom({ plugin: 'ctx', key: 'limits' } as const, [])
151const paceTick = atom({ plugin: 'ctx', key: 'paceTick' } as const, 0)
152const PACE_TICK_MS = 60000
153// The look's effect events (growth, sweep), and how long a one-shot is handed
154// to the bar after it landed: past that a redraw, a reload or a resume never replays it
155const fx = atom({ plugin: 'ctx', key: 'fx' } as const, {})
156const GROWTH_LIVE_MS = 1800
157const SWEEP_LIVE_MS = 1500
158// A compaction is heard twice (the drop on session.measure, then afterCompaction): one sweep
159const SWEEP_GUARD_MS = 2000
160const turnRunning = atom({ plugin: 'ctx', key: 'turnRunning' } as const, false)
161const fxTick = atom({ plugin: 'ctx', key: 'fxTick' } as const, 0)
162
163async function noteFx($: EngineInterface, kind: keyof CtxFx, delta: number) {
164 if (delta <= 0) return
165 try {
166 const now = await $.clock.now()
167 await update($, fx, f => {
168 const last = f[kind]
169 if (kind === 'sweep' && last && now - last.at < SWEEP_GUARD_MS) return f
170 return { ...f, [kind]: { id: (last?.id ?? 0) + 1, at: now, delta } }
171 })
172 playFx($, now)
173 } catch {
174 // a missed effect is only a missed glow
175 }
176}
177
178// Desktop has no Client, so its pane plays a one-shot by redraws: a tick while one is live, then none
179const FX_FRAME_MS = 80
180let fxTimer: Timer | undefined
181let fxUntil = 0
182
183function playFx($: EngineInterface, at: number) {
184 fxUntil = Math.max(fxUntil, at + GROWTH_LIVE_MS + 100)
185 fxTimer ??= $.clock.every(FX_FRAME_MS, () => {
186 void $.clock.now().then(now => {
187 if (now > fxUntil) {
188 fxTimer?.cancel()
189 fxTimer = undefined
190 }
191 return update($, fxTick, n => n + 1)
192 })
193 })
194}
195
196// The bar's motion for the look in force: the foam laps and the water drifts,
197// the cells breathe near auto-compact, and a one-shot plays while it is live
198function tideOf(cells: Cell[], max: number, f: CtxFx, now: number, warn: CtxWarn): TideProps {
199 const edge = edgeOf(cells)
200 const props: TideProps = { cells, level: look.level === 'full' ? 'full' : 'subtle', edge }
201 if (look.level === 'off') return props
202 const p = paletteOf(look.palette)
203 const water = waterOf(look)
204 if (water && edge >= 0) props.lap = [water.foam, water.water]
205 if (water && look.level === 'full') props.drift = water.foam
206 if (warn !== 'none') props.breathe = { at: breatheAt(cells), colors: breath(p.heat[warn === 'imminent' ? 2 : 0]) }
207 if (f.growth && now - f.growth.at < GROWTH_LIVE_MS) props.growth = { id: f.growth.id, ...growthSpan(cells, f.growth.delta, max), colors: [...p.sparkle] }
208 if (look.level === 'full' && f.sweep && now - f.sweep.at < SWEEP_LIVE_MS) {
209 const span = sweepSpan(cells, f.sweep.delta, max)
210 const shore = cells[Math.max(0, edge - 1)]?.color ?? p.hex.tool
211 if (span.to > span.from) props.sweep = { id: f.sweep.id, ...span, shore, water: water?.water ?? shore, foam: water?.foam ?? shore }
212 }
213 return props
214}
215
216// The band's bar for Desktop: the same cells and one-shots as the terminal's, drawn by bandSvg
217function pill(s: CtxSnapshot, width: number, f: CtxFx, now: number, warn: CtxWarn, fine?: { cellPx: number; label?: string }) {
218 // an SVG takes no theme keys: the dots and the buffer of claude and mono draw in the palette's idle grey
219 const idle = paletteOf(look.palette).hex.idle
220 const cells = bandCells(s, width, svgTints(look, s.rows), waterOf(look)).map(c => (/^#/.test(c.color) ? c : { ...c, color: idle }))
221 const t = tideOf(cells, s.max, f, now, warn)
222 const tick = s.compactAt && s.max ? Math.min(width - 1, Math.floor((s.compactAt / s.max) * width)) : undefined
223 return bandSvg({
224 cells,
225 level: look.level,
226 edge: t.edge,
227 ...(fine ? { cellPx: fine.cellPx, ...(fine.label ? { label: fine.label } : {}) } : {}),
228 ...(tick !== undefined ? { tick } : {}),
229 ...(warn !== 'none' && look.level !== 'off' ? { warn: hexHeat(look, warn === 'imminent' ? 2 : 0) } : {}),
230 ...(t.growth ? { growth: t.growth } : {}),
231 ...(t.sweep ? { sweep: { id: t.sweep.id, from: t.sweep.from, to: t.sweep.to } } : {}),
232 })
233}
234
235const moves = (t: TideProps) => Boolean(t.lap || t.breathe || t.growth || t.sweep || (t.level === 'full' && t.drift))
236
237// A compaction's summary when none has been seen yet, in tokens
238const SUMMARY_TOKENS = 8000
239
240// The prices of the model the main loop answers with, once the ledger has taught them
241function ratesOf(s: CtxSpend): Rates | undefined {
242 const model = shownTurn(s)?.model || s.cur?.model
243 return model ? fitRates(s.samples, model) : undefined
244}
245
246// What the window will be after a compaction: what the last one left, else
247// everything but the messages plus a summary
248function afterCompact(s: CtxSpend, snapshot: CtxSnapshot | null): number | undefined {
249 if (s.compact?.after) return s.compact.after
250 const messages = snapshot?.rows.find(r => r.name === 'Messages')
251 if (!snapshot || !messages) return undefined
252 const fixed = snapshot.rows.filter(r => r.kind === 'used' && r !== messages).reduce((a, r) => a + r.tokens, 0)
253 return fixed + (s.compact?.summary ?? SUMMARY_TOKENS)
254}
255
256// Main-loop requests per finished turn
257function perTurn(s: CtxSpend): number | undefined {
258 return s.turns > 0 ? s.requests / s.turns : undefined
259}
260
261// After a compaction the ledger says what it cost, and the result how big the window is now
262async function priceCompaction($: EngineInterface, r: { tokensAfter?: number; usage?: ApiUsage }, ledger: number | undefined) {
263 try {
264 const now = (await $.session.usage()).cost?.usd
265 const usd = now !== undefined && ledger !== undefined && now > ledger ? now - ledger : undefined
266 await update($, spend, s => noteCompacted(now !== undefined ? ledgerAt(s, now) : s, { after: r.tokensAfter, usd, summary: r.usage?.output_tokens }))
267 } catch {
268 // the toast goes out without the price
269 }
270}
271
272// A compaction happened since the last reading: the next one carries the mark
273let pendingMark = false
274// The mod's own compaction is under way: compactNow follows it up, so the
275// session.compact hook must not do it a second time should it hear it
276let selfCompact = false
277
278// The last `n` flags, padded in front: readings from before marks existed read as unmarked
279function alignFlags(flags: readonly boolean[], n: number): boolean[] {
280 return [...Array<boolean>(Math.max(0, n - flags.length)).fill(false), ...flags.slice(-n)]
281}
282
283async function record($: EngineInterface, tokens: number) {
284 const past = await read($, history)
285 if (past[past.length - 1] === tokens) return
286 const mark = pendingMark
287 pendingMark = false
288 await update($, compacted, flags => [...alignFlags(flags, past.length), mark].slice(-HISTORY_LIMIT))
289 await update($, history, list => [...list, tokens].slice(-HISTORY_LIMIT))
290}
291
292// The newest reading of the window, the API's when there is one
293async function latestTokens($: EngineInterface): Promise<number | undefined> {
294 const past = await read($, history)
295 return past[past.length - 1] ?? (await read($, snap))?.total
296}
297
298// How close auto-compaction is right now, with the turns left at this pace
299async function warning($: EngineInterface): Promise<{ level: CtxWarn; tokens: number; compactAt?: number; turnsLeft?: number }> {
300 const s = await read($, snap)
301 const tokens = (await latestTokens($)) ?? 0
302 const compactAt = s?.compactAt
303 const turnsLeft = trend(await read($, history), compactAt).turnsLeft
304 return { level: warnLevel(tokens, compactAt, turnsLeft), tokens, compactAt, turnsLeft }
305}
306
307async function keepText($: EngineInterface, focus?: string): Promise<string> {
308 return keepInstructions({ focus, edited: await read($, edited), asks: await read($, asks) })
309}
310
311// Once a compaction stands: the next reading is marked, what was eaten and
312// warned of starts over, and the drop is toasted when the new count lands
313async function afterCompaction($: EngineInterface, before: number | undefined) {
314 pendingMark = true
315 await update($, eaters, () => [])
316 await update($, warned, () => 'none')
317 await refresh($)
318 const s = await read($, snap)
319 if (before === undefined || !s) return
320 await noteFx($, 'sweep', before - s.total)
321 let text = `Compacted ${fmtTokens(before)} → ~${fmtTokens(s.total)} (${fmtDelta(s.total - before)})`
322 if (await read($, costOn)) {
323 const sp = await read($, spend)
324 const r = ratesOf(sp)
325 if (sp.compact?.usd) text += ` · summary ${fmtUsd(sp.compact.usd)}`
326 if (r) text += ` · now ~${fmtUsd(carry(s.total, r))}/request (was ~${fmtUsd(carry(before, r))})`
327 }
328 $.ui.toast(text)
329}
330
331// Compacts now, the summary told what this session is in the middle of. The
332// mod's own session.compact hook does not hear its own call, so this follows up itself
333async function compactNow($: EngineInterface, focus?: string) {
334 $.ui.toast('Compacting…')
335 try {
336 const before = await latestTokens($)
337 const ledger = (await read($, spend)).ledger
338 selfCompact = true
339 const r = await $.session.compact({ instructions: await keepText($, focus) }).finally(() => {
340 selfCompact = false
341 })
342 if ('skip' in r && r.skip) $.ui.toast(`Compaction skipped: ${r.skip}`)
343 else if (r.messages) {
344 await priceCompaction($, r, ledger)
345 await afterCompaction($, before)
346 }
347 } catch {
348 $.ui.toast('Could not compact right now')
349 }
350}
351
352async function setAutokeep($: EngineInterface, value: boolean) {
353 await update($, autokeep, () => value)
354 try {
355 await $.store.set('autokeep', value)
356 } catch {
357 // on for this session still
358 }
359 $.ui.toast(value ? 'Autokeep on: every compaction keeps your files and latest requests' : 'Autokeep off')
360}
361
362async function setCost($: EngineInterface, value: boolean) {
363 await update($, costOn, () => value)
364 try {
365 await $.store.set('cost', value)
366 } catch {
367 // for this session still
368 }
369 $.ui.toast(value ? 'Cost on: dollar figures beside the tokens' : 'Cost off: tokens only')
370}
371
372async function setFooter($: EngineInterface, value: boolean) {
373 await update($, footerOn, () => value)
374 try {
375 await $.store.set('footer', value)
376 } catch {
377 // for this session still
378 }
379 $.ui.toast(value ? 'Footer on: ctx N% in the Desktop footer' : 'Footer off')
380}
381
382// Opens a memory file with the host's default app for it
383async function openFile($: EngineInterface, path: string) {
384 const name = shortPath(path)
385 try {
386 const home = (await $.env.get('HOME')) ?? ''
387 const os =
388 (await $.env.get('OS')) === 'Windows_NT' || /^[A-Za-z]:[\\/]/.test(path)
389 ? 'windows'
390 : path.startsWith('/Users/') || home.startsWith('/Users/')
391 ? 'mac'
392 : 'linux'
393 const { exitCode, stderr } = await $.process.run(openerFor(path, os), { timeoutMs: 15000 })
394 await $.ui.toast(exitCode === 0 ? `Opened ${name}` : `Couldn't open ${name}: ${stderr.trim().split('\n')[0] || `exit ${exitCode}`}`)
395 } catch {
396 // no host to run on (the Desktop app), or the opener is missing
397 await $.ui.toast(`Couldn't open ${name}`)
398 }
399}
400
401function toSnapshot(b: SessionContextBreakdown, detail: CtxDetail, at: number): CtxSnapshot {
402 const byServer = new Map<string, CtxServer>()
403 for (const t of b.mcpTools) {
404 const key = /^mcp__(.+?)__/.exec(t.name)?.[1] ?? t.serverName
405 const s = byServer.get(t.serverName) ?? { name: t.serverName, key, tokens: 0, count: 0, deferredTokens: 0, deferredCount: 0 }
406 if (t.isLoaded) {
407 s.tokens += t.tokens
408 s.count += 1
409 } else {
410 s.deferredTokens += t.tokens
411 s.deferredCount += 1
412 }
413 byServer.set(t.serverName, s)
414 }
415 const servers = [...byServer.values()].sort((x, y) => y.tokens - x.tokens || y.deferredTokens - x.deferredTokens)
416 const sum = (xs: { tokens: number }[]) => xs.reduce((a, x) => a + x.tokens, 0)
417 return {
418 rows: b.categories.map(c => ({ name: c.name, tokens: c.tokens, color: c.color, kind: c.kind })),
419 total: b.totalTokens,
420 max: b.rawMaxTokens,
421 percent: b.percentage,
422 detail,
423 at,
424 model: b.model,
425 compactAt: b.isAutoCompactEnabled ? b.autoCompactThreshold : undefined,
426 mcpTokens: sum(servers),
427 mcpCount: servers.reduce((a, s) => a + s.count, 0),
428 mcpDeferredTokens: servers.reduce((a, s) => a + s.deferredTokens, 0),
429 mcpDeferredCount: servers.reduce((a, s) => a + s.deferredCount, 0),
430 servers,
431 memory: b.memoryFiles.map(f => ({ path: f.path, type: f.type, tokens: f.tokens })),
432 skillCount: b.skills?.totalSkills ?? 0,
433 skillIncluded: b.skills?.includedSkills ?? 0,
434 skillTokens: b.skills?.tokens ?? 0,
435 skills: (b.skills?.skillFrontmatter ?? []).map(s => ({ name: s.name, tokens: s.tokens })).sort((x, y) => y.tokens - x.tokens),
436 agentTokens: sum(b.agents),
437 agents: b.agents.map(a => ({ name: a.agentType, tokens: a.tokens })).sort((x, y) => y.tokens - x.tokens),
438 commandCount: b.slashCommands?.totalCommands ?? 0,
439 commandIncluded: b.slashCommands?.includedCommands ?? 0,
440 commandTokens: b.slashCommands?.tokens ?? 0,
441 }
442}
443
444// Counts can overlap (a turn ends while an exact count is out): the one
445// started last wins, so a slow older count never overwrites a newer one
446let started = 0
447let landed = 0
448
449// Counts at the mode the person chose, so an exact count stays exact
450async function refresh($: EngineInterface) {
451 const detail = await read($, mode)
452 const id = ++started
453 try {
454 const { context } = await $.session.usage({ breakdown: detail })
455 const b = context.breakdown
456 if (!b || id < landed) return
457 landed = id
458 const at = await $.clock.now()
459 await update($, snap, () => toSnapshot(b, detail, at))
460 await update($, stale, () => false)
461 } catch {
462 // no session bound yet, or the count failed: the last snapshot stays, marked
463 if (await read($, snap)) await update($, stale, () => true)
464 }
465}
466
467// The pane docks beside the transcript in the fullscreen layout (from 110
468// columns), like /diff; on the main screen it sits above the prompt instead
469const PANE_ARGS = { id: PANE, title: 'Context', closeOnEscape: true, columns: 48, rows: 26 } as const
470
471// Desktop's pane bar is an Svg drawn at 2 px a cell, so it fills the pane to the pixel. A cell
472// of the surface's code font is taken as 8 px, as the band's pill is; the pane's width is the
473// narrower of the two measures the surface gives (either may be missing), less a margin
474const PANE_CELL_PX = 2
475function paneBarPx(viewportColumns?: number, bodyColumns?: number): number {
476 const known = [viewportColumns, bodyColumns].filter((c): c is number => typeof c === 'number' && c > 0)
477 const columns = known.length > 0 ? Math.min(...known) : PANE_ARGS.columns
478 return Math.max(120, Math.min(560, columns * 8 - 16))
479}
480
481// Redraws "updated 12s ago" while the pane is open
482let ticker: Timer | undefined
483
484function startTicker($: EngineInterface) {
485 // the look's fallback refresh rides on the tick, for a change that never reached config.set
486 ticker ??= $.clock.every(TICK_MS, () => void update($, tick, n => n + 1).then(() => refreshLook($)))
487}
488
489function stopTicker() {
490 ticker?.cancel()
491 ticker = undefined
492}
493
494// Redraws the band's countdown once a minute; it only runs while the plan has windows
495let paceTimer: Timer | undefined
496
497// The windows the engine reports now (none off a subscription)
498async function setLimits($: EngineInterface, list: readonly CtxLimit[] | undefined) {
499 const next = Array.isArray(list) ? list.map(l => ({ ...l })) : []
500 await update($, limits, () => next)
501 if (next.length > 0) paceTimer ??= $.clock.every(PACE_TICK_MS, () => void update($, paceTick, n => n + 1).then(() => refreshLook($)))
502}
503
504async function setVisible($: EngineInterface, value: boolean, focus = false) {
505 await update($, isVisible, () => value)
506 try {
507 await $.store.set('visible', value)
508 } catch {
509 // the toggle still works for this session
510 }
511 if (value) {
512 // open first: the count fills the pane in as it lands
513 await $.ui.open(focus ? { ...PANE_ARGS, focus: true } : PANE_ARGS)
514 startTicker($)
515 void refresh($)
516 } else {
517 stopTicker()
518 await $.ui.close({ id: PANE })
519 }
520}
521
522async function toggleVisible($: EngineInterface) {
523 await setVisible($, !(await read($, isVisible)))
524}
525
526async function setMode($: EngineInterface, value: CtxDetail) {
527 await update($, mode, () => value)
528 await refresh($)
529}
530
531async function toggleOpen($: EngineInterface, key: string) {
532 await update($, opened, list => (list.includes(key) ? list.filter(k => k !== key) : [...list, key]))
533}
534
535type El = ReturnType<EngineInterface['ui']['resolve']>
536
537// The segmented bar: one Text per run, each in its category's hover group
538function Bar({ el, runs }: { el: El; runs: BarRun[] }) {
539 const { Box, Text } = el
540 return (
541 <Box flexDirection="row" flexShrink={0}>
542 {runs.map(r => (
543 <Text
544 color={r.color}
545 {...(r.bg ? { backgroundColor: r.bg } : {})}
546 {...(r.dim ? { dimColor: true } : {})}
547 hover={{ scope: SCOPE + r.scope, inverse: true }}
548 >
549 {r.text}
550 </Text>
551 ))}
552 </Box>
553 )
554}
555
556// The band's bar held still: one Text per run of like cells, each in its category's hover group
557function Cells({ el, cells }: { el: El; cells: Cell[] }) {
558 const runs: BarRun[] = []
559 for (const c of cells) {
560 const last = runs[runs.length - 1]
561 if (last && last.color === c.color && last.bg === c.bg && Boolean(last.dim) === Boolean(c.dim) && last.scope === c.scope) last.text += c.ch
562 else runs.push({ text: c.ch, color: c.color, scope: c.scope, ...(c.bg ? { bg: c.bg } : {}), ...(c.dim ? { dim: true } : {}) })
563 }
564 return Bar({ el, runs })
565}
566
567// "81.9k/1M·" dim, then the percent bold in green, amber or red
568function Fill({ el, s }: { el: El; s: CtxSnapshot }) {
569 const { Box, Text } = el
570 return (
571 <Box flexDirection="row" flexShrink={0}>
572 <Text dimColor>{`${fmtTokens(s.total)}/${fmtTokens(s.max)}·`}</Text>
573 <Text bold color={fillColor(s.percent)}>{`${Math.round(s.percent)}%`}</Text>
574 </Box>
575 )
576}
577
578// The fill per turn: dim history, the latest reading lit in the fill's color
579// The fill per turn: dim history, compactions lit in blue, the latest
580// reading in the fill's color
581// With `shade` the past glyphs take the look's colours (Messages' core to glow), and `mark` is the
582// compactions' colour (the water's); `pulse` draws the newest point while a turn runs
583function Spark({
584 el,
585 values,
586 marks,
587 width,
588 percent,
589 shade,
590 mark = 'permission',
591 pulse,
592}: {
593 el: El
594 values: readonly number[]
595 marks: readonly boolean[]
596 width: number
597 percent: number
598 shade?: (n: number) => string[] | undefined
599 mark?: string
600 pulse?: (glyph: string) => RenderElement
601}) {
602 const { Box, Text } = el
603 const glyphs = [...sparkline(values, width)]
604 const flags = alignFlags(marks, values.length).slice(-glyphs.length)
605 const colors = shade?.(glyphs.length)
606 const runs: { text: string; kind: 'past' | 'mark' | 'last'; color?: string }[] = []
607 glyphs.forEach((g, i) => {
608 const kind = i === glyphs.length - 1 ? 'last' : flags[i] ? 'mark' : 'past'
609 const color = kind === 'past' ? colors?.[i] : undefined
610 const run = runs[runs.length - 1]
611 if (run && run.kind === kind && run.color === color) run.text += g
612 else runs.push({ text: g, kind, ...(color ? { color } : {}) })
613 })
614 return (
615 <Box flexDirection="row" flexShrink={0}>
616 {runs.map(r =>
617 r.kind === 'past' ? (
618 r.color ? <Text color={r.color}>{r.text}</Text> : <Text color="claude" dimColor>{r.text}</Text>
619 ) : r.kind === 'mark' ? (
620 <Text color={mark} bold>{r.text}</Text>
621 ) : pulse ? (
622 pulse(r.text)
623 ) : (
624 <Text color={fillColor(percent)} bold>{r.text}</Text>
625 ),
626 )}
627 </Box>
628 )
629}
630
631// Pieces of text, each in its tone: the band's last-turn suffix
632function Pieces({ el, pieces }: { el: El; pieces: Piece[] }) {
633 const { Box, Text } = el
634 return (
635 <Box flexDirection="row" flexShrink={0}>
636 {pieces.map(p =>
637 p.tone === 'plain' ? (
638 <Text>{p.text}</Text>
639 ) : p.tone === 'dim' ? (
640 <Text dimColor>{p.text}</Text>
641 ) : p.tone === 'sub' ? (
642 <Text color="permission">{p.text}</Text>
643 ) : (
644 <Text color={p.tone} bold>{p.text}</Text>
645 ),
646 )}
647 </Box>
648 )
649}
650
651// The pace: pieces of text, each in its tone; the HUD draws none of it bold
652function Pace({ el, pieces }: { el: El; pieces: PacePiece[] }) {
653 const { Box, Text } = el
654 return (
655 <Box key="ctx-pace" flexDirection="row" flexShrink={0}>
656 {pieces.map(p => (p.tone === 'dim' ? <Text dimColor>{p.text}</Text> : <Text color={p.tone}>{p.text}</Text>))}
657 </Box>
658 )
659}
660
661function Swatch({ el, kind, color, scope, water }: { el: El; kind: string; color: string; scope: string; water?: string }) {
662 const { Text } = el
663 const hover = { scope: SCOPE + scope, inverse: true }
664 if (kind === 'free')
665 return water ? (
666 <Text color={water} dimColor hover={hover}>
667 ~
668 </Text>
669 ) : (
670 <Text color="inactive" dimColor hover={hover}>
671 {FREE_GLYPH}
672 </Text>
673 )
674 if (kind === 'buffer') return <Text color={water ?? color} dimColor hover={hover}>{BUFFER_GLYPH}</Text>
675 return <Text color={color} dimColor={kind === 'deferred'} hover={hover}>■</Text>
676}
677
678// A detail row under an open section: name on the left, figures on the right
679function Item({ el, name, right, truncate = 'truncate-end' }: { el: El; name: string; right: string; truncate?: 'truncate-end' | 'truncate-start' }) {
680 const { Box, Text } = el
681 return (
682 <Box flexDirection="row" width="100%" columnGap={2}>
683 <Box flexGrow={1} flexShrink={1}>
684 <Text dimColor wrap={truncate}>{' ' + name}</Text>
685 </Box>
686 <Text dimColor>{right}</Text>
687 </Box>
688 )
689}
690
691export const register: Register = (on, options) => {
692 configured = options ?? {}
693 look = resolveLook(configured, [])
694
695 on('session.start', async ($, e, next) => {
696 await refreshLook($)
697 try {
698 await $.command.register({
699 name: 'ctx',
700 description: 'Context window details (/ctx opens the pane; /ctx show|hide|toggle|exact|quick|compact [focus]|autokeep [on|off]|cost [on|off]|footer [on|off])',
701 argumentHint: '[show|hide|toggle|exact|quick|compact [focus]|autokeep [on|off]|cost [on|off]|footer [on|off]]',
702 immediate: true,
703 })
704 } catch {
705 // the 📊 button still works without the command
706 }
707 await refresh($)
708 try {
709 // the project's log as it stood before this session (a hot reload
710 // runs this again: this session's own line is left out either way)
711 const log = (await $.store.get(await projectKey($))) as CtxProjectLog | undefined
712 const id = await $.session.id()
713 await update($, project, () => (log ? { sessions: log.sessions.filter(x => x.id !== id) } : null))
714 } catch {
715 // no history: every streak starts at this session
716 }
717 try {
718 await update($, autokeep, () => false)
719 if ((await $.store.get('autokeep')) === true) await update($, autokeep, () => true)
720 } catch {
721 // autokeep stays off
722 }
723 try {
724 await update($, footerOn, () => false)
725 if ((await $.store.get('footer')) === true) await update($, footerOn, () => true)
726 } catch {
727 // the footer stays off
728 }
729 try {
730 // the ledger as it stands, and the prices earlier sessions taught
731 await update($, costOn, () => true)
732 if ((await $.store.get('cost')) === false) await update($, costOn, () => false)
733 const saved = (await $.store.get('costSamples')) as CtxSample[] | undefined
734 if (Array.isArray(saved)) await update($, spend, s => (s.samples.length ? s : { ...s, samples: saved }))
735 const taken = await $.session.usage()
736 const usd = taken.cost?.usd
737 if (usd !== undefined) await update($, spend, s => ledgerAt(s, usd))
738 await setLimits($, taken.rateLimits)
739 } catch {
740 // no ledger: the dollar figures stay out
741 }
742 try {
743 // reopen where the person left it; unasked, it waits below 144 columns
744 const saved = await $.store.get('visible')
745 await update($, isVisible, () => saved === true)
746 if (saved === true) {
747 void $.ui.open(PANE_ARGS)
748 startTicker($)
749 }
750 } catch {
751 // start closed
752 }
753 return next(e)
754 })
755
756 // The engine pushes a measurement when the window's fill moves (after each
757 // main-thread turn, a compaction, a /clear): count again then, never on a timer
758 on('session.measure', async ($, e, next) => {
759 const r = await next(e)
760 // the cost ledger, real dollars: the running turn has spent what it grew by
761 const usd = e.cost?.usd
762 if (usd !== undefined) await update($, spend, s => ledgerAt(s, usd))
763 await setLimits($, e.rateLimits)
764 if (e.changed.includes('context')) {
765 // the API's own figure, so switching between exact and quick adds no jumps
766 const tokens = e.context.tokens
767 if (tokens !== undefined) {
768 const past = await read($, history)
769 const prev = past[past.length - 1]
770 if (prev !== undefined && tokens < prev * DROP_RATIO) {
771 await update($, eaters, () => [])
772 await update($, warned, () => 'none')
773 await noteFx($, 'sweep', prev - tokens)
774 } else if (prev !== undefined) {
775 if (tokens > prev) await noteFx($, 'growth', tokens - prev)
776 const chars = turnChars
777 await update($, cptAtom, cpt => calibrate(cpt, chars, tokens - prev))
778 }
779 turnChars = 0
780 await record($, tokens)
781 // warn once per step as auto-compaction nears
782 const w = await warning($)
783 const was = await read($, warned)
784 if (shouldWarn(was, w.level) && w.compactAt) {
785 await update($, warned, () => w.level)
786 $.ui.toast(warnText(w.level, w.tokens, w.compactAt, w.turnsLeft))
787 }
788 }
789 void refresh($).then(() => logProject($))
790 }
791 return r
792 })
793
794 // Every tool call: which server, skill or agent it used, and, in the main
795 // conversation, how much its result added to the window
796 on('tool.call', async ($, e, next) => {
797 const r = await next(e)
798 try {
799 const args = e as unknown as Record<string, unknown>
800 const hit = usageOf(e.tool, args)
801 if (hit) await update($, usage, u => addUsage(u, hit))
802 // the files the session changed, for what a compaction must keep
803 const path = typeof args.file_path === 'string' ? args.file_path : typeof args.notebook_path === 'string' ? args.notebook_path : ''
804 const ok = !('isError' in r && r.isError) && !('deny' in r && r.deny)
805 if (path && ok && (e.tool === 'Edit' || e.tool === 'Write' || e.tool === 'NotebookEdit')) {
806 await update($, edited, list => addRecent(list, path, EDIT_LIMIT))
807 }
808 // a subagent's results stay in its own window
809 const text = 'text' in r && typeof r.text === 'string' ? r.text : ''
810 if (!e.agentId && text.length > 0) {
811 turnChars += text.length
812 if (text.length >= EATER_MIN_CHARS) {
813 const label = toolLabel(e.tool, args)
814 const turn = (await $.session.turns()) + 1
815 await update($, eaters, list => addEater(list, { tool: e.tool, label, chars: text.length, turn }))
816 const tokens = estimateTokens(text.length, await read($, cptAtom))
817 if (tokens >= TOAST_TOKENS) $.ui.toast(`${label} added ~${fmtTokens(tokens)} tokens`)
818 }
819 }
820 } catch {
821 // counting never gets in the way of the call
822 }
823 return r
824 })
825
826 // A main-loop turn begins (subagents raise none): the one before is frozen,
827 // and a clean one is kept, here and for later sessions, to learn prices from
828 on('turn.start', async ($, e, next) => {
829 try {
830 await update($, turnRunning, () => true)
831 } catch {
832 // the pulse is decoration
833 }
834 try {
835 const was = (await read($, spend)).samples
836 const s = await update($, spend, startTurn)
837 // state hands back copies: a new sample shows in the length or the newest one
838 if (s.samples.length !== was.length || s.samples[s.samples.length - 1]?.usd !== was[was.length - 1]?.usd) {
839 await $.store.set('costSamples', s.samples)
840 }
841 } catch {
842 // the turn runs whatever the count does
843 }
844 return next(e)
845 })
846
847 // Every model request, main loop and subagents: its token counts as the API
848 // reported them. Observe only: the response streams through untouched
849 on('turn.step', async function* ($, e, next) {
850 let startedAt = 0
851 try {
852 startedAt = await $.clock.now()
853 } catch {
854 // timing is only evidence about the cache
855 }
856 const r = yield* next(e)
857 try {
858 const u = r.usage
859 if (u) {
860 const endedAt = await $.clock.now()
861 await update($, spend, s => stepDone(s, u, { ...(e.agentId ? { agentId: e.agentId } : {}), startedAt, endedAt }))
862 }
863 } catch {
864 // counting never gets in the way of the response
865 }
866 return r
867 })
868
869 on('turn.complete', async ($, e, next) => {
870 const r = await next(e)
871 try {
872 if (!e.agentId) await update($, turnRunning, () => false)
873 await update($, spend, s => turnDone(s, e.agentId))
874 } catch {
875 // the answer stands either way
876 }
877 return r
878 })
879
880 // The person's latest requests, for what a compaction must keep
881 on('prompt.submit', async ($, e, next) => {
882 const text = e.text.trim()
883 if (text && !text.startsWith('/')) await update($, asks, list => addRecent(list, clipAsk(text), ASK_LIMIT))
884 return next(e)
885 })
886
887 // Every compaction of the main conversation: with autokeep on, the summary is
888 // told what to keep; once it stands, the drop is marked and toasted
889 on('session.compact', async ($, e, next) => {
890 if (e.agentId) return next(e)
891 // only a compaction that carries its messages is rewritten (the engine's always do)
892 const keep =
893 (await read($, autokeep)) && Array.isArray(e.messages) ? { ...e, instructions: mergeInstructions(e.instructions, await keepText($)) } : e
894 const before = await latestTokens($)
895 const ledger = (await read($, spend)).ledger
896 const r = await next(keep)
897 if (e.trigger !== 'precompute' && r.messages && !selfCompact) void priceCompaction($, r, ledger).then(() => afterCompaction($, before))
898 return r
899 })
900
901 // Another plugin's /config change this mod follows: the new value is in the rows once it went through.
902 // Literals, so the engine can read the matcher off the source
903 on('config.set', { key: ['agent-pulse.palette', 'agent-pulse.animation'] }, async ($, e, next) => {
904 const r = await next(e)
905 if (r.deny === undefined) await refreshLook($)
906 return r
907 })
908
909 on('command.run', { command: 'ctx' }, async ($, e) => {
910 const [word = '', ...rest] = String(e.args || '').trim().split(/\s+/)
911 const arg = word.toLowerCase()
912 if (arg === 'compact') {
913 await compactNow($, rest.join(' '))
914 return {}
915 }
916 if (arg === 'autokeep') {
917 const v = rest[0]?.toLowerCase()
918 await setAutokeep($, v === 'on' ? true : v === 'off' ? false : !(await read($, autokeep)))
919 return {}
920 }
921 if (arg === 'cost') {
922 const v = rest[0]?.toLowerCase()
923 await setCost($, v === 'on' ? true : v === 'off' ? false : !(await read($, costOn)))
924 return {}
925 }
926 if (arg === 'footer') {
927 const v = rest[0]?.toLowerCase()
928 await setFooter($, v === 'on' ? true : v === 'off' ? false : !(await read($, footerOn)))
929 return {}
930 }
931 if (arg === 'hide') {
932 await setVisible($, false)
933 return {}
934 }
935 if (arg === 'toggle') {
936 await toggleVisible($)
937 return {}
938 }
939 if (arg === 'exact' || arg === 'full') await update($, mode, () => 'full')
940 if (arg === 'quick' || arg === 'summary') await update($, mode, () => 'summary')
941 await setVisible($, true, true)
942 return {}
943 })
944
945 // a close by the person (Esc, the pane's mark) turns the toggle off too
946 on('ui.close', async ($, e, next) => {
947 const r = await next(e)
948 // an unload (hot reload, exit) must not forget that the pane was wanted
949 if (e.id === PANE && e.origin.kind !== 'unload') {
950 stopTicker()
951 await update($, isVisible, () => false)
952 try {
953 await $.store.set('visible', false)
954 } catch {
955 // nothing to keep
956 }
957 }
958 return r
959 })
960
961 // The band: a small bar and the fill on one line, the 📊 toggle at its right
962 // edge. The toggle opens or closes the pane, which docks to the right like /diff
963 on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
964 const below = await next(e)
965 if (e.props.hasSurvey) return below
966 const el = $.ui.resolve(e)
967 const { Box, Button, Text } = el
968 const s = await read($, snap)
969 const show = await read($, isVisible)
970 const old = await read($, stale)
971 const past = await read($, history)
972 const wide = (e.props.bodyColumns ?? 80) >= 70
973 const step = trend(past).delta
974 const marks = await read($, compacted)
975 const w = await warning($)
976 // Desktop passes no bodyColumns, so its pill stays at the 80-column step
977 const barWidth = bandBarWidth(e.props.bodyColumns ?? 80, w.level !== 'none')
978 const hot = w.level === 'imminent' ? 'error' : 'warning'
979 // the bar: whole cells in the look's colours; a Tide client while anything moves
980 const nowMs = await $.clock.now()
981 const tints = s ? categoryTints(look, s.rows) : {}
982 const cells = s ? bandCells(s, barWidth, tints, waterOf(look)) : []
983 const tide = s ? tideOf(cells, s.max, await read($, fx), nowMs, w.level) : undefined
984 const live = Boolean(tide && e.surface === 'terminal' && 'Client' in el && moves(tide))
985 const Client = 'Client' in el ? (el as { Client: any }).Client : undefined
986 const heat = paletteOf(look.palette).heat[w.level === 'imminent' ? 2 : 0]
987 // Desktop: the bar is an SVG pill, its motion in CSS; its colours always hex
988 const Svg = e.surface !== 'terminal' && 'Svg' in el ? (el as { Svg: any }).Svg : undefined
989 const svgBar = s && Svg ? pill(s, barWidth, await read($, fx), nowMs, w.level) : undefined
990 // the warning badge takes the sparkline's place on a band under 100 columns
991 const cols = e.props.bodyColumns ?? 80
992 const roomy = wide && (w.level === 'none' || cols >= 100)
993 // the last turn's dollars, from the ledger; nothing where there is none
994 const sp = await read($, spend)
995 const money = (await read($, costOn)) && sp.ledger !== undefined
996 const lastTurn = money ? shownTurn(sp) : undefined
997 const rates = money ? ratesOf(sp) : undefined
998 // the plan's pace (or an API account's session total), right-aligned beside the toggle
999 await read($, paceTick)
1000 const pace = bandPace({
1001 limits: await read($, limits),
1002 usd: sp.ledger,
1003 costOn: await read($, costOn),
1004 step: paceStep(e.props.bodyColumns, e.surface),
1005 now: await $.clock.now(),
1006 })
1007 return (
1008 <Box flexDirection="column">
1009 <Box flexDirection="row" justifyContent="space-between" width="100%" columnGap={2}>
1010 {s ? (
1011 <Box flexDirection="row" columnGap={1} flexShrink={1}>
1012 <Text>🧠</Text>
1013 {w.level === 'none' ? (
1014 <Text color={CLAUDE_ORANGE}>ctx</Text>
1015 ) : live && Client ? (
1016 <Client
1017 key="ctx-word"
1018 module="./tide.tsx"
1019 props={{ cells: [...'ctx'].map(ch => ({ ch, color: heat, scope: 'word' })), level: 'subtle', edge: -1, breathe: { at: [0, 1, 2], colors: breath(heat) } }}
1020 width={3}
1021 height={1}
1022 />
1023 ) : (
1024 <Text color={hot} bold>ctx</Text>
1025 )}
1026 {svgBar ? (
1027 <Svg key="ctx-pill" source={svgBar.source} alt={`context ${Math.round(s.percent)}% full`} width={svgBar.width} height={svgBar.height} />
1028 ) : live && Client && tide ? (
1029 <Client key="ctx-tide" module="./tide.tsx" props={tide} width={barWidth} height={1} />
1030 ) : (
1031 Cells({ el, cells: tide ? frameAt(tide, 0, {}) : cells })
1032 )}
1033 {Fill({ el, s })}
1034 {roomy &&
1035 past.length >= 2 &&
1036 // the pane's colours: Messages' core to glow along the line, compactions in the water's
1037 Spark({
1038 el,
1039 values: past,
1040 marks,
1041 width: 10,
1042 percent: s.percent,
1043 shade: n => sparkColors(look, tints['Messages'], n),
1044 ...(waterOf(look) ? { mark: waterOf(look)!.water } : {}),
1045 })}
1046 {roomy && step !== undefined && step !== 0 && <Text dimColor>{fmtDelta(step)}</Text>}
1047 {wide &&
1048 lastTurn &&
1049 Pieces({ el, pieces: bandSuffix(lastTurn, cols, { median: sp.usds.length >= 3 ? median(sp.usds) : undefined, subUsd: subUsd(lastTurn, rates) }) })}
1050 {w.level !== 'none' && w.compactAt && (
1051 <Text color={hot} bold>
1052 {warnBadge(w.tokens, w.compactAt, w.turnsLeft)}
1053 </Text>
1054 )}
1055 {w.level !== 'none' && rates && cols >= 100 && <Text dimColor>{`· ~${fmtUsd(carry(w.tokens, rates))}/request`}</Text>}
1056 {old && <Text color="warning">⚠ stale</Text>}
1057 </Box>
1058 ) : (
1059 <Text dimColor>Context</Text>
1060 )}
1061 <Box flexDirection="row" columnGap={2} flexShrink={0}>
1062 {pace.length > 0 && Pace({ el, pieces: pace })}
1063 <Button
1064 key="ctx-toggle"
1065 label={show ? '📊▾' : '📊'}
1066 hotkey="x"
1067 plain
1068 dimColor={!show}
1069 onPress={() => toggleVisible($)}
1070 />
1071 </Box>
1072 </Box>
1073 {below}
1074 </Box>
1075 )
1076 })
1077
1078 // The footer, for the Desktop app, when `/ctx footer on` asks for it: the
1079 // band already shows the fill, and a hook cannot tell when the person has
1080 // collapsed the band. On the terminal the band is enough. Desktop does not
1081 // draw the labels in `modes` (this one and waypoints' plan never showed),
1082 // only a tree, so the engine's footer is wrapped, as arsenal's launcher
1083 // does, and the percent goes first
1084 on('ui.render', { component: 'SessionMode' }, async ($, e, next) => {
1085 if (e.surface !== 'desktop' || !(await read($, footerOn))) return next(e)
1086 const s = await read($, snap)
1087 if (!s) return next(e)
1088 const footer = await next(e)
1089 const { Box, Text } = $.ui.resolve(e)
1090 return (
1091 <Box key="ctx-footer">
1092 <Text color={fillColor(s.percent)}>{`ctx ${Math.round(s.percent)}%`}</Text>
1093 <Text> </Text>
1094 {footer}
1095 </Box>
1096 )
1097 })
1098
1099 on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
1100 const el = $.ui.resolve(e)
1101 const { Box, Button, Text } = el
1102 const s = await read($, snap)
1103 const open = await read($, opened)
1104 const want = await read($, mode)
1105 const old = await read($, stale)
1106 const past = await read($, history)
1107 const eaten = await read($, eaters)
1108 const cpt = await read($, cptAtom)
1109 const calls = await read($, usage)
1110 const log = await read($, project)
1111 const marks = await read($, compacted)
1112 const keepOn = await read($, autokeep)
1113 const w = await warning($)
1114 await read($, tick)
1115 const now = await $.clock.now()
1116 const paneFx = await read($, fx)
1117 // Desktop redraws its one-shots on this tick
1118 if (e.surface !== 'terminal') await read($, fxTick)
1119 const paneSvg = e.surface !== 'terminal' && 'Svg' in el
1120 const Svg = paneSvg ? (el as { Svg: any }).Svg : undefined
1121 const running = await read($, turnRunning)
1122 // the body as the surface measured it: the person may drag the dock narrower
1123 const width = Math.max(20, e.props.bodyColumns || PANE_ARGS.columns)
1124 if (!s) return <Text dimColor>No context data yet. It fills in after the first response.</Text>
1125
1126 const used = Math.max(1, s.total)
1127 // the look: the rows' tints, the water, the heat scale; claude and mono keep 0.7's colours
1128 const tints = categoryTints(look, s.rows)
1129 const water = waterOf(look)
1130 const pal = paletteOf(look.palette)
1131 const hk = heatKeys(look)
1132 const Client = 'Client' in el ? (el as { Client: any }).Client : undefined
1133 const moving = e.surface === 'terminal' && Client !== undefined && look.level !== 'off'
1134 // each section's gauge in its category's colour (slash commands share the skills')
1135 const GAUGE_ROW: Record<string, string> = { mcp: 'MCP tools', memory: 'Memory files', skills: 'Skills', agents: 'Custom agents', commands: 'Skills' }
1136 const gaugeColor = (key: string) =>
1137 !water ? 'claude' : key === 'eaters' ? pal.hex.tool : key === 'dead' ? pal.hex.idle : ((tints[GAUGE_ROW[key] ?? ''] as Tint | undefined)?.core ?? pal.hex.tool)
1138 const section = (key: string, hotkey: string, title: string, tokens: number, count: string) => {
1139 const g = shareBar(tokens, used, GAUGE)
1140 return (
1141 <Box flexDirection="row" width="100%" columnGap={1}>
1142 <Box flexGrow={1} flexShrink={1}>
1143 <Button key={'sec-' + key} label={`${open.includes(key) ? '▾' : '▸'} ${title}`} hotkey={hotkey} plain onPress={() => toggleOpen($, key)} />
1144 </Box>
1145 <Box flexDirection="row" flexShrink={0}>
1146 <Text color={gaugeColor(key)}>{g.fill}</Text>
1147 <Text color="inactive" dimColor>{g.rest}</Text>
1148 </Box>
1149 <Text dimColor>{fmtTokens(tokens).padStart(6)}</Text>
1150 <Text bold>{count.padStart(6)}</Text>
1151 </Box>
1152 )
1153 }
1154 const marker = compactMarker(s, width)
1155 // Desktop: block and wave glyphs fall back to fonts of their own widths, so a Text bar of
1156 // `width` cells overruns the pane and wraps. An Svg fills the measured width in pixels instead,
1157 // and carries the auto-compact marker with it
1158 const paneBar = Svg
1159 ? pill(s, Math.floor(paneBarPx(e.viewport?.columns, e.props.bodyColumns) / PANE_CELL_PX), paneFx, now, w.level, {
1160 cellPx: PANE_CELL_PX,
1161 ...(s.compactAt ? { label: `auto-compact ${fmtTokens(s.compactAt)}` } : {}),
1162 })
1163 : undefined
1164 const pace = trend(past, s.compactAt)
1165 // the engine's own count of finished turns; the sparkline can't be counted
1166 // by eye (it is capped and skips repeats). A failed call just hides it.
1167 let turnsDone: number | undefined
1168 try {
1169 turnsDone = await $.session.turns()
1170 } catch {
1171 turnsDone = undefined
1172 }
1173 const turnCount = turnsDone && turnsDone > 0 ? `· ${turnsDone} ${turnsDone === 1 ? 'turn' : 'turns'}` : undefined
1174
1175 // What this session has paid for and not used: loaded MCP servers it never
1176 // called, skills and agent types listed for the model and never invoked
1177 // Dollar figures: what the last turn spent (real, from the ledger), and what
1178 // the window costs to keep, rewrite and compact (at the learned prices)
1179 const sp = await read($, spend)
1180 const costShown = await read($, costOn)
1181 const money = costShown && sp.ledger !== undefined
1182 const rates = money ? ratesOf(sp) : undefined
1183 const lastTurn = money ? shownTurn(sp) : undefined
1184 // the ledger's total is the denominator for the turn's dollars below it
1185 const session = money && sp.ledger !== undefined ? sessionParts(sp.ledger, lastTurn?.usd) : undefined
1186 const winTokens = past[past.length - 1] ?? s.total
1187 const rpt = perTurn(sp)
1188 const after = afterCompact(sp, s)
1189 const plan = rates && after !== undefined && winTokens > 2 * after ? compactPlan(winTokens, after, rates, sp.compact?.summary ?? SUMMARY_TOKENS) : undefined
1190 const ttl = ttlMs(sp)
1191 const idleMs = sp.lastStepAt !== undefined ? now - sp.lastStepAt : 0
1192 const cold = money && ttl !== undefined && sp.lastStepAt !== undefined && idleMs >= ttl
1193 const muted = (text: string) => <Text color="inactive" dimColor wrap="wrap">{text}</Text>
1194
1195 const idleServers = s.servers
1196 .filter(v => v.tokens > 0 && !calls.mcp[v.key])
1197 .map(v => {
1198 const run = idleSessions(log ?? undefined, v.key)
1199 // this session counts too, with what it has spent so far
1200 const cost = rates ? idleCost(v.tokens, [...run, { requests: sp.requests, misses: sp.misses }], rates) : undefinedhooks/fmt.ts 354 lines1import type { CtxRow, CtxSnapshot } from '../types'
2import { mix, type Tint } from './palette'
3
4// 33400 -> "33.4k", 1000000 -> "1M", 584 -> "584"
5export function fmtTokens(n: number): string {
6 if (!Number.isFinite(n)) return '0'
7 if (n < 1000) return String(Math.round(n))
8 if (n < 1_000_000) return trim((n / 1000).toFixed(1)) + 'k'
9 return trim((n / 1_000_000).toFixed(1)) + 'M'
10}
11
12function trim(s: string): string {
13 return s.replace(/\.0$/, '')
14}
15
16// A row's share of the window; deferred schemas sit outside it
17export function fmtShare(row: CtxRow, max: number): string {
18 if (row.kind === 'deferred' || !max) return '—'
19 return ((row.tokens / max) * 100).toFixed(1) + '%'
20}
21
22// The pane's rows in three groups: what the window holds, largest first; the
23// buffer and the free space, which are headroom rather than something to trim;
24// then the deferred schemas, largest first, since they sit outside the window.
25// Sorting them in with the rest would put them at the top of a list of what the
26// window holds. Sizes that tie keep the order /context gave them
27export function paneRows(rows: readonly CtxRow[]): CtxRow[] {
28 const group = (r: CtxRow) => (r.kind === 'used' ? 0 : r.kind === 'deferred' ? 2 : 1)
29 const rank = (r: CtxRow) => (r.kind === 'free' ? 1 : 0)
30 return rows
31 .filter(r => r.tokens > 0 || r.kind === 'free')
32 .map((r, i) => ({ r, i }))
33 .sort((a, b) => group(a.r) - group(b.r) || (group(a.r) === 1 ? rank(a.r) - rank(b.r) : b.r.tokens - a.r.tokens) || a.i - b.i)
34 .map(x => x.r)
35}
36
37// "12/40" when the listing left some out, "40" when it holds them all
38export function fmtCount(included: number, total: number): string {
39 return included < total ? `${included}/${total}` : String(total)
40}
41
42export function headline(snap: CtxSnapshot): string {
43 return `${fmtTokens(snap.total)} / ${fmtTokens(snap.max)} (${Math.round(snap.percent)}%)`
44}
45
46// Theme keys, so the colors follow the person's light or dark theme
47export function fillColor(percent: number): 'success' | 'warning' | 'error' {
48 return percent < 50 ? 'success' : percent < 80 ? 'warning' : 'error'
49}
50
51export function ago(ms: number): string {
52 const s = Math.max(0, Math.round(ms / 1000))
53 if (s < 10) return 'just now'
54 if (s < 60) return `${s}s ago`
55 if (s < 3600) return `${Math.floor(s / 60)}m ago`
56 return `${Math.floor(s / 3600)}h ago`
57}
58
59export function shortPath(p: string): string {
60 const parts = p.replace(/\\/g, '/').split('/')
61 return parts.length > 2 ? '…/' + parts.slice(-2).join('/') : p
62}
63
64// Left-aligned partial blocks, indexed by eighths filled (1 to 7)
65const EIGHTHS = ['', '▏', '▎', '▍', '▌', '▋', '▊', '▉']
66// The least a category holding anything gets, so it never vanishes
67const MIN_EIGHTHS = 2
68export const FREE_GLYPH = '·'
69export const BUFFER_GLYPH = '░'
70
71type Seg = { name: string; color: string; style: 'solid' | 'free' | 'buffer'; start: number; end: number }
72
73// The window laid out in eighths of a cell, as /context orders it: the used
74// rows, the free space, the compaction buffer against the right edge
75export function barSegments(snap: CtxSnapshot, width: number): Seg[] {
76 const total = Math.max(1, width) * 8
77 const max = snap.max || 1
78 const eighths = (t: number) => Math.round((t / max) * total)
79 const segs: Seg[] = []
80 let pos = 0
81 for (const r of snap.rows) {
82 if (r.kind !== 'used' || r.tokens <= 0 || pos >= total) continue
83 const end = Math.min(total, pos + Math.max(MIN_EIGHTHS, eighths(r.tokens)))
84 segs.push({ name: r.name, color: r.color, style: 'solid', start: pos, end })
85 pos = end
86 }
87 const buffer = snap.rows.find(r => r.kind === 'buffer' && r.tokens > 0)
88 const bufStart = buffer ? Math.max(pos, total - eighths(buffer.tokens)) : total
89 if (bufStart > pos) {
90 const free = snap.rows.find(r => r.kind === 'free')
91 segs.push({ name: free?.name ?? 'Free space', color: 'inactive', style: 'free', start: pos, end: bufStart })
92 }
93 if (buffer && total > bufStart) segs.push({ name: buffer.name, color: buffer.color, style: 'buffer', start: bufStart, end: total })
94 return segs
95}
96
97/** A run of same-styled cells; `scope` is the category it draws, for hover. */
98export type BarRun = { text: string; color: string; bg?: string; dim?: boolean; scope: string }
99
100/** The free space drawn as water: `~` in `water`, the first free cell `≈` in `foam`. */
101export type Water = { water: string; foam: string }
102export const WATER_GLYPH = '~'
103export const FOAM_GLYPH = '≈'
104
105// The bar as runs of cells, `width` cells wide. A cell where one used row
106// ends draws that row's partial block over the next row's color, so the bar
107// is smooth to an eighth of a cell rather than a whole one. With `tints` the
108// rows take the palette's colors; with `water` the free space is water
109export function barRuns(snap: CtxSnapshot, width: number, tints?: Record<string, Tint>, water?: Water): BarRun[] {
110 const segs = barSegments(snap, width)
111 const tint = (s: Seg) => (s.style === 'solid' ? (tints?.[s.name]?.core ?? s.color) : s.color)
112 // never empty: whatever the rows hold, free space or a used row covers the width
113 const segAt = (e: number) => segs.find(s => s.start <= e && e < s.end) ?? segs[segs.length - 1]!
114 const runs: BarRun[] = []
115 let shore = true
116 for (let c = 0; c < Math.max(1, width); c++) {
117 let cell = cellOf(segAt(c * 8), segAt(c * 8 + 7), c * 8, tint)
118 if (water && cell.text === FREE_GLYPH) {
119 cell = shore ? { text: FOAM_GLYPH, color: water.foam, scope: cell.scope } : { text: WATER_GLYPH, color: water.water, dim: true, scope: cell.scope }
120 shore = false
121 } else if (water && cell.text === BUFFER_GLYPH) {
122 cell = { ...cell, color: water.water }
123 }
124 const last = runs[runs.length - 1]
125 if (last && last.color === cell.color && last.bg === cell.bg && last.dim === cell.dim && last.scope === cell.scope) {
126 last.text += cell.text
127 } else {
128 runs.push(cell)
129 }
130 }
131 return runs
132}
133
134function cellOf(a: Seg, b: Seg, start: number, tint: (s: Seg) => string): BarRun {
135 if (a.style === 'solid') {
136 if (a === b) return { text: '█', color: tint(a), scope: a.name }
137 return {
138 text: EIGHTHS[Math.min(7, a.end - start)] ?? '▏',
139 color: tint(a),
140 bg: b.style === 'solid' ? tint(b) : undefined,
141 scope: a.name,
142 }
143 }
144 const s = a.end - start >= 4 ? a : b
145 return s.style === 'free'
146 ? { text: FREE_GLYPH, color: 'inactive', dim: true, scope: s.name }
147 : { text: BUFFER_GLYPH, color: s.color, dim: true, scope: s.name }
148}
149
150// How many cells the band's bar takes. Every row in use gets a whole cell, so
151// a near-empty window draws as many cells as it has rows (six rows on a 1M window
152// at 5% fill 6 of 16, which reads as ~40%); a longer bar shrinks that overstatement,
153// where the band has the room. A standing warning keeps it at 16 until 240 columns: the badge
154// and the carrying cost need the width (about 143 columns beside the bar in the worst case)
155export function bandBarWidth(columns: number, warning: boolean): number {
156 if (columns < 70) return 8
157 if (columns < 130 || (warning && columns < 240)) return 16
158 if (columns < 160) return 24
159 if (columns < 200) return 48
160 return columns < 240 ? 64 : 96
161}
162
163/** One cell of the band's bar; `scope` is the category it draws, for hover. */
164export type Cell ={ ch: string; color: string; bg?: string; dim?: boolean; scope: string }
165
166const isHex = (c: string) => /^#[0-9a-f]{6}$/i.test(c)
167
168// The band's bar, `width` whole cells: every used row holding anything, and
169// the buffer, get at least one, so a split still reads on a nearly empty 1M
170// window. The cells those minimums need come off Messages (the largest used
171// row) before the free space, so the fill keeps its true length wherever it can
172export function bandCells(snap: CtxSnapshot, width: number, tints: Record<string, Tint>, water?: Water): Cell[] {
173 const w = Math.max(1, width)
174 const freeRow = snap.rows.find(r => r.kind === 'free')
175 const freeName = freeRow?.name ?? 'Free space'
176 const used = snap.rows.filter(r => r.kind === 'used' && r.tokens > 0)
177 const buffer = snap.rows.find(r => r.kind === 'buffer' && r.tokens > 0)
178 type Part = { name: string; color: string; kind: 'used' | 'free' | 'buffer'; tokens: number; n: number }
179 const free = (): Part => ({ name: freeName, color: 'inactive', kind: 'free', tokens: 0, n: w })
180 if (!snap.max) return paint([free()], tints, water)
181
182 // the smallest rows lose their minimum first when there are more rows than cells
183 let kept = used
184 while (kept.length + (buffer ? 1 : 0) > w && kept.length > 0) {
185 const smallest = kept.reduce((a, r) => (r.tokens < a.tokens ? r : a))
186 kept = kept.filter(r => r !== smallest)
187 }
188 const usedTokens = kept.reduce((a, r) => a + r.tokens, 0)
189 const parts: Part[] = [
190 ...kept.map(r => ({ name: r.name, color: r.color, kind: 'used' as const, tokens: r.tokens, n: 0 })),
191 { name: freeName, color: 'inactive', kind: 'free', tokens: Math.max(0, snap.max - usedTokens - (buffer?.tokens ?? 0)), n: 0 },
192 ...(buffer ? [{ name: buffer.name, color: buffer.color, kind: 'buffer' as const, tokens: buffer.tokens, n: 0 }] : []),
193 ]
194 // the ideal shares, rounded by largest remainder so they sum to the width
195 const sum = parts.reduce((a, p) => a + p.tokens, 0) || 1
196 const exact = parts.map(p => (p.tokens / sum) * w)
197 parts.forEach((p, i) => (p.n = Math.floor(exact[i]!)))
198 const order = parts.map((_, i) => i).sort((i, j) => exact[j]! - Math.floor(exact[j]!) - (exact[i]! - Math.floor(exact[i]!)))
199 for (let k = 0, left = w - parts.reduce((a, p) => a + p.n, 0); k < left; k++) parts[order[k % parts.length]!]!.n++
200 // each row in use, and the buffer, at least one cell: from the largest used row while it keeps one, else the water
201 for (const p of parts) {
202 if (p.kind === 'free' || p.n > 0) continue
203 const donors = parts.filter(d => d.kind === 'used' && d.n > 1).sort((a, b) => b.n - a.n)
204 const water = parts.find(d => d.kind === 'free' && d.n > 0)
205 const donor = donors[0] ?? water ?? parts.filter(d => d.n > 1).sort((a, b) => b.n - a.n)[0]
206 if (!donor) break
207 donor.n--
208 p.n++
209 }
210 return paint(parts, tints, water)
211}
212
213function paint(parts: { name: string; color: string; kind: 'used' | 'free' | 'buffer'; n: number }[], tints: Record<string, Tint>, water?: Water): Cell[] {
214 const cells: Cell[] = []
215 let shore = true
216 for (const p of parts) {
217 for (let i = 0; i < p.n; i++) {
218 if (p.kind === 'used') {
219 const t = tints[p.name] ?? { core: p.color, glow: p.color }
220 const color = isHex(t.core) && isHex(t.glow) && p.n > 1 ? mix(t.core, t.glow, i / (p.n - 1)) : t.core
221 cells.push({ ch: '█', color, scope: p.name })
222 } else if (p.kind === 'buffer') {
223 cells.push({ ch: BUFFER_GLYPH, color: water ? water.water : p.color, dim: true, scope: p.name })
224 } else if (!water) {
225 cells.push({ ch: FREE_GLYPH, color: 'inactive', dim: true, scope: p.name })
226 } else {
227 cells.push(shore ? { ch: FOAM_GLYPH, color: water.foam, scope: p.name } : { ch: WATER_GLYPH, color: water.water, dim: true, scope: p.name })
228 shore = false
229 }
230 }
231 }
232 return cells
233}
234
235// Where the used cells end: the water's edge, else the buffer, else the bar's end
236function shoreEnd(cells: readonly Cell[]): number {
237 const edge = edgeOf(cells)
238 if (edge >= 0) return edge
239 const buf = cells.findIndex(c => c.ch === BUFFER_GLYPH)
240 return buf >= 0 ? buf : cells.length
241}
242
243const spanCells = (cells: readonly Cell[], delta: number, max: number) => Math.max(1, Math.round((delta / (max || 1)) * cells.length))
244
245/** The cells a turn added: the last used ones before the edge, at least one. */
246export function growthSpan(cells: readonly Cell[], delta: number, max: number): { from: number; to: number } {
247 const to = shoreEnd(cells)
248 return { from: Math.max(0, to - spanCells(cells, delta, max)), to }
249}
250
251/** The cells a compaction freed: from the edge onward, never into the buffer; empty with no water. */
252export function sweepSpan(cells: readonly Cell[], delta: number, max: number): { from: number; to: number } {
253 const edge = edgeOf(cells)
254 if (edge < 0) return { from: cells.length, to: cells.length }
255 const buf = cells.findIndex((c, i) => i > edge && c.ch === BUFFER_GLYPH)
256 return { from: edge, to: Math.min(buf >= 0 ? buf : cells.length, edge + spanCells(cells, delta, max)) }
257}
258
259/** What breathes near auto-compact: the foam, or the last used cell when no water is left. */
260export function breatheAt(cells: readonly Cell[]): number[] {
261 const edge = edgeOf(cells)
262 if (edge >= 0) return [edge]
263 return [Math.max(0, shoreEnd(cells) - 1)]
264}
265
266/** The first free cell (the water's edge), or -1 on a window with none. */
267export function edgeOf(cells: readonly Cell[]): number {
268 return cells.findIndex(c => c.ch === FOAM_GLYPH || c.ch === FREE_GLYPH)
269}
270
271// The line beneath the bar: a caret under the auto-compact point, labelled on
272// whichever side has room, the label shortened (or left out) on a narrow bar
273export function compactMarker(snap: CtxSnapshot, width: number): string | undefined {
274 if (!snap.compactAt || !snap.max || width < 1) return undefined
275 const col = Math.min(width - 1, Math.max(0, Math.floor((snap.compactAt / snap.max) * width)))
276 for (const label of [`auto-compact ${fmtTokens(snap.compactAt)}`, fmtTokens(snap.compactAt)]) {
277 if (col + 2 + label.length <= width) return ' '.repeat(col) + '▲ ' + label
278 if (col >= label.length + 1) return ' '.repeat(col - label.length - 1) + label + ' ▲'
279 }
280 return ' '.repeat(col) + '▲'
281}
282
283// A small gauge for a section header: `part` of `whole` in `width` cells
284export function shareBar(part: number, whole: number, width: number): { fill: string; rest: string } {
285 const n = whole > 0 ? Math.min(width * 8, Math.round((part / whole) * width * 8)) : 0
286 const full = Math.floor(n / 8)
287 const fill = '█'.repeat(full) + EIGHTHS[n % 8]
288 return { fill, rest: FREE_GLYPH.repeat(width - full - (n % 8 ? 1 : 0)) }
289}
290
291const SPARK = '▁▂▃▄▅▆▇█'
292
293// The last `width` readings as one glyph each, scaled between their own low
294// and high so a slow climb still shows; a flat run sits mid-height
295export function sparkline(values: readonly number[], width: number): string {
296 const v = values.slice(-Math.max(1, width))
297 if (v.length === 0) return ''
298 const lo = Math.min(...v)
299 const hi = Math.max(...v)
300 if (hi === lo) return (SPARK[3] ?? '▄').repeat(v.length)
301 return v.map(x => SPARK[Math.round(((x - lo) / (hi - lo)) * 7)] ?? '▄').join('')
302}
303
304export type Trend = {
305 /** What the last turn added (negative after a compaction or /clear). */
306 delta?: number
307 /** Average growth per turn since the last drop, over the last few turns. */
308 perTurn?: number
309 /** Turns until auto-compaction at that pace. */
310 turnsLeft?: number
311}
312
313const PACE_TURNS = 6
314
315// How the window grows: the last step, the pace since the last drop (a
316// compaction resets the pace rather than dragging it negative), and how many
317// turns that pace leaves before auto-compaction
318export function trend(values: readonly number[], compactAt?: number): Trend {
319 const n = values.length
320 if (n < 2) return {}
321 const last = values[n - 1]!
322 const delta = last - values[n - 2]!
323 let from = n - 1
324 while (from > 0 && n - 1 - from < PACE_TURNS && values[from - 1]! <= values[from]!) from--
325 if (from === n - 1) return { delta }
326 const perTurn = (last - values[from]!) / (n - 1 - from)
327 if (perTurn <= 0) return { delta, perTurn: 0 }
328 const turnsLeft = compactAt && compactAt > last ? Math.ceil((compactAt - last) / perTurn) : undefined
329 return { delta, perTurn, ...(turnsLeft !== undefined ? { turnsLeft } : {}) }
330}
331
332// "+3.2k", "−41k", "±0"
333export function fmtDelta(n: number): string {
334 if (n === 0) return '±0'
335 return (n > 0 ? '+' : '−') + fmtTokens(Math.abs(n))
336}
337
338// The pane's trend caption, as long as the facts allow
339export function trendLabel(t: Trend): string {
340 const parts: string[] = []
341 if (t.delta !== undefined) parts.push(`${fmtDelta(t.delta)} last turn`)
342 if (t.perTurn) parts.push(`~${fmtTokens(t.perTurn)}/turn`)
343 if (t.turnsLeft !== undefined) parts.push(`~${t.turnsLeft} ${t.turnsLeft === 1 ? 'turn' : 'turns'} to auto-compact`)
344 return parts.join(' · ')
345}
346
347// The host command that opens `path` with its default app: Start-Process on
348// Windows (as Explorer would), `open` on macOS, `xdg-open` elsewhere. Never
349// $EDITOR: a terminal editor has no terminal to draw in from here
350export function openerFor(path: string, os: 'windows' | 'mac' | 'linux'): string[] {
351 if (os === 'windows') return ['powershell', '-NoProfile', '-NonInteractive', '-Command', `Start-Process -FilePath '${path.replace(/'/g, "''")}'`]
352 return [os === 'mac' ? 'open' : 'xdg-open', path]
353}
354hooks/cost.ts 307 lines1import type { CtxCounts, CtxSample, CtxSpend, CtxTurn } from '../types'
2import { fmtTokens } from './fmt'
3
4/** One request's token counts in the API's spelling (ModelUsage, TurnUsage). */
5export type ApiUsage = {
6 input_tokens: number
7 output_tokens: number
8 cache_read_input_tokens: number
9 cache_creation_input_tokens: number
10 model?: string
11}
12
13/** A model's prices as learned from the ledger, US dollars per million tokens. */
14export type Rates = {
15 /** Uncached input; output is priced at OUTPUT_RATIO times it. */
16 inOut: number
17 read: number
18 write: number
19}
20
21// Output costs five times input on every current model, so the two share one price to learn
22export const OUTPUT_RATIO = 5
23const M = 1_000_000
24const TURNS_KEPT = 48
25const SAMPLES_KEPT = 24
26// A request that wrote this many tokens fresh, more than half its prompt, missed the cache
27const MISS_MIN = 20_000
28// An idle gap shorter than this says nothing about how long the cache lives
29const GAP_MIN = 4 * 60_000
30const FIVE_MIN = 5 * 60_000
31const HOUR = 60 * 60_000
32// The fit stands only if every turn it kept is priced this closely
33const FIT_TOLERANCE = 0.05
34
35export const ZERO: CtxCounts = { input: 0, output: 0, read: 0, write: 0 }
36export const EMPTY_SPEND: CtxSpend = { usds: [], samples: [], requests: 0, misses: 0, turns: 0, maxHitGap: 0 }
37
38export function countsOf(u: ApiUsage): CtxCounts {
39 return { input: u.input_tokens, output: u.output_tokens, read: u.cache_read_input_tokens, write: u.cache_creation_input_tokens }
40}
41
42function add(a: CtxCounts, b: CtxCounts): CtxCounts {
43 return { input: a.input + b.input, output: a.output + b.output, read: a.read + b.read, write: a.write + b.write }
44}
45
46export function isMiss(c: CtxCounts): boolean {
47 return c.write >= MISS_MIN && c.write > 0.5 * (c.input + c.read + c.write)
48}
49
50// The share of the prompt the cache served
51export function hitRate(c: CtxCounts): number | undefined {
52 const all = c.input + c.read + c.write
53 return all > 0 ? c.read / all : undefined
54}
55
56function newTurn(base: number): CtxTurn {
57 return { base, usd: 0, requests: 0, main: ZERO, model: '', mixed: false, sub: ZERO, subRuns: 0, missTokens: 0, cold: false, compacted: false, done: false }
58}
59
60// A turn the ledger priced from the main model's own counts alone: nothing
61// else (a subagent, a compaction, a second model) is mixed into its dollars
62function isClean(t: CtxTurn): boolean {
63 return t.done && !t.mixed && !t.compacted && t.subRuns === 0 && t.sub.input + t.sub.read + t.sub.write === 0 && t.requests > 0 && t.usd > 0 && !!t.model
64}
65
66// A new main-loop turn: the one before is frozen, its dollars kept, and,
67// when clean, kept as a sample of what the model charges
68export function startTurn(s: CtxSpend): CtxSpend {
69 const ended = s.cur
70 const next: CtxSpend = { ...s, cur: newTurn(s.ledger ?? 0) }
71 if (!ended || (ended.requests === 0 && ended.usd === 0)) return next
72 next.last = ended
73 if (ended.done) next.usds = [...s.usds, ended.usd].slice(-TURNS_KEPT)
74 if (isClean(ended)) {
75 const m = ended.main
76 const sample: CtxSample = { model: ended.model, inOut: (m.input + OUTPUT_RATIO * m.output) / M, read: m.read / M, write: m.write / M, usd: ended.usd }
77 next.samples = [...s.samples, sample].slice(-SAMPLES_KEPT)
78 }
79 return next
80}
81
82// One model request finished: main-loop requests count toward the turn and
83// the cache's record; a subagent's only toward the turn's subagent share. The
84// session's first request, and the first after a compaction, write the prompt
85// afresh by nature: a miss that costs (and is counted) but is never shown
86export function stepDone(s: CtxSpend, u: ApiUsage, at: { agentId?: string; startedAt: number; endedAt: number }): CtxSpend {
87 const cur = s.cur ?? newTurn(s.ledger ?? 0)
88 const c = countsOf(u)
89 if (at.agentId) return { ...s, cur: { ...cur, sub: add(cur.sub, c) } }
90 const miss = isMiss(c)
91 const cold = s.lastStepAt === undefined
92 const model = u.model ?? cur.model
93 const next: CtxSpend = {
94 ...s,
95 cur: {
96 ...cur,
97 requests: cur.requests + 1,
98 main: add(cur.main, c),
99 model,
100 mixed: cur.mixed || (!!cur.model && !!u.model && u.model !== cur.model),
101 missTokens: miss && !cold ? Math.max(cur.missTokens, c.write) : cur.missTokens,
102 cold: cur.cold || cold,
103 },
104 requests: s.requests + 1,
105 misses: s.misses + (miss ? 1 : 0),
106 lastStepAt: at.endedAt,
107 }
108 if (s.lastStepAt !== undefined) {
109 const gap = at.startedAt - s.lastStepAt
110 if (miss && gap >= GAP_MIN) next.minMissGap = Math.min(s.minMissGap ?? Infinity, gap)
111 else if (!miss && c.read > 0) next.maxHitGap = Math.max(s.maxHitGap, gap)
112 }
113 return next
114}
115
116// A turn ended: the main loop's closes the turn; a subagent's run is counted in it
117export function turnDone(s: CtxSpend, agentId?: string): CtxSpend {
118 if (!s.cur) return s
119 if (agentId) return { ...s, cur: { ...s.cur, subRuns: s.cur.subRuns + 1 } }
120 return { ...s, cur: { ...s.cur, done: true }, turns: s.turns + 1 }
121}
122
123// The ledger moved: the running turn has spent what it grew by since the turn began
124export function ledgerAt(s: CtxSpend, usd: number): CtxSpend {
125 return { ...s, ledger: usd, ...(s.cur ? { cur: { ...s.cur, usd: Math.max(0, usd - s.cur.base) } } : {}) }
126}
127
128// A compaction ran: its turn teaches no prices, and its size and cost are kept.
129// The prefix changed, so the next request writes afresh whatever the cache's
130// lifetime: it starts the idle record over rather than teaching it
131export function compacted(s: CtxSpend, c: { after?: number; usd?: number; summary?: number }): CtxSpend {
132 const { lastStepAt: _, ...rest } = s
133 return { ...rest, compact: c, ...(s.cur ? { cur: { ...s.cur, compacted: true } } : {}) }
134}
135
136// The latest turn that finished
137export function shownTurn(s: CtxSpend): CtxTurn | undefined {
138 return s.cur?.done ? s.cur : s.last?.done ? s.last : undefined
139}
140
141export function median(xs: readonly number[]): number | undefined {
142 if (xs.length === 0) return undefined
143 const v = [...xs].sort((a, b) => a - b)
144 const mid = v.length >> 1
145 return v.length % 2 ? v[mid]! : (v[mid - 1]! + v[mid]!) / 2
146}
147
148// The three prices that best explain the samples, by least squares
149function solve(pts: readonly CtxSample[]): Rates | undefined {
150 const xs = pts.map(p => [p.inOut, p.read, p.write] as const)
151 const a = [0, 1, 2].map(i => [0, 1, 2].map(j => xs.reduce((sum, x) => sum + x[i]! * x[j]!, 0)))
152 const b = [0, 1, 2].map(i => xs.reduce((sum, x, k) => sum + x[i]! * pts[k]!.usd, 0))
153 const det = (m: number[][]) =>
154 m[0]![0]! * (m[1]![1]! * m[2]![2]! - m[1]![2]! * m[2]![1]!) -
155 m[0]![1]! * (m[1]![0]! * m[2]![2]! - m[1]![2]! * m[2]![0]!) +
156 m[0]![2]! * (m[1]![0]! * m[2]![1]! - m[1]![1]! * m[2]![0]!)
157 const d = det(a)
158 // turns too alike to tell the prices apart
159 if (!(Math.abs(d) > 1e-6 * a[0]![0]! * a[1]![1]! * a[2]![2]!)) return undefined
160 const col = (k: number) => det(a.map((row, i) => row.map((v, j) => (j === k ? b[i]! : v))))
161 return { inOut: col(0) / d, read: col(1) / d, write: col(2) / d }
162}
163
164const predict = (r: Rates, p: CtxSample) => p.inOut * r.inOut + p.read * r.read + p.write * r.write
165
166// What the model charges, learned from the ledger's own turns. The ledger is
167// exact, so clean turns fit exactly; a turn the fit misses (a tool's own model
168// call billed in it) is dropped, worst first. None until three turns agree,
169// and none that breaks how prices relate (a read is cheaper than input, a
170// write dearer)
171export function fitRates(samples: readonly CtxSample[], model: string, n = 12): Rates | undefined {
172 let pts = samples.filter(x => x.model === model).slice(-n)
173 const keep = Math.max(3, Math.ceil(pts.length / 2))
174 while (pts.length >= keep) {
175 const r = solve(pts)
176 if (!r) return undefined
177 const errs = pts.map(p => Math.abs(predict(r, p) - p.usd) / p.usd)
178 const worst = errs.indexOf(Math.max(...errs))
179 if (errs[worst]! <= FIT_TOLERANCE) return r.read > 0 && r.read < r.inOut && r.write >= r.inOut ? r : undefined
180 pts = pts.filter((_, i) => i !== worst)
181 }
182 return undefined
183}
184
185export function price(r: Rates, c: CtxCounts): number {
186 return ((c.input + OUTPUT_RATIO * c.output) * r.inOut + c.read * r.read + c.write * r.write) / M
187}
188
189// What the subagents cost: the turn's dollars less what its main-loop counts explain
190export function subUsd(t: CtxTurn, r: Rates | undefined): number | undefined {
191 return r ? Math.max(0, t.usd - price(r, t.main)) : undefined
192}
193
194// Re-reading `tokens` from the cache once
195export const carry = (tokens: number, r: Rates) => (tokens * r.read) / M
196// Writing `tokens` into the cache afresh
197export const rewrite = (tokens: number, r: Rates) => (tokens * r.write) / M
198
199// Re-reading a window that grows `perTurn` a turn, `rpt` times a turn, for `turns` turns
200export function untilCompact(tokens: number, perTurn: number, turns: number, rpt: number, r: Rates): number {
201 return ((turns * rpt * r.read) / M) * (tokens + (perTurn * (turns + 1)) / 2)
202}
203
204// Compacting now: what each later request saves, what the compaction costs
205// once (the summarizer reading the window and writing the summary, then the
206// smaller window cached afresh), and after how many requests it pays back
207export function compactPlan(tokens: number, after: number, r: Rates, summary: number) {
208 const saving = ((tokens - after) * r.read) / M
209 if (saving <= 0) return undefined
210 const once = (tokens * r.read + summary * OUTPUT_RATIO * r.inOut + after * r.write) / M
211 return { saving, once, payback: Math.ceil(once / saving) }
212}
213
214// A server's schemas, re-read on every request and rewritten on every miss, over the sessions that logged both
215export function idleCost(tokens: number, sessions: readonly { requests?: number; misses?: number }[], r: Rates) {
216 const known = sessions.filter(x => x.requests !== undefined)
217 if (known.length === 0) return undefined
218 const total = known.reduce((sum, x) => sum + (tokens * ((x.requests ?? 0) * r.read + (x.misses ?? 0) * r.write)) / M, 0)
219 return { total, perSession: total / known.length, n: known.length }
220}
221
222// How long the cache lives, as this session has seen it: a hit after more
223// than five idle minutes means the hour-long cache; a miss after a long gap,
224// the five-minute one. Nothing seen, nothing said
225export function ttlMs(s: CtxSpend): number | undefined {
226 if (s.maxHitGap > FIVE_MIN * 1.1) return HOUR
227 if (s.minMissGap !== undefined) return s.minMissGap < HOUR ? FIVE_MIN : HOUR
228 return undefined
229}
230
231// "$0.007", "$1.84", "$12.3", "$140": a small window's per-request cost needs the third decimal
232export function fmtUsd(n: number): string {
233 if (!Number.isFinite(n) || n <= 0) return '$0'
234 if (n < 0.001) return '<$0.001'
235 if (n < 0.01) return '$' + n.toFixed(3)
236 if (n < 10) return '$' + n.toFixed(2)
237 if (n < 100) return '$' + n.toFixed(1)
238 return '$' + Math.round(n).toLocaleString('en-US')
239}
240
241// "7m", "1h 4m"
242export function fmtIdle(ms: number): string {
243 const m = Math.floor(ms / 60_000)
244 return m < 60 ? `${m}m` : `${Math.floor(m / 60)}h ${m % 60}m`
245}
246
247export type Piece = { text: string; tone: 'plain' | 'dim' | 'sub' | 'warning' | 'error' }
248
249// The band's last-turn suffix: the dollars always, then each piece only when
250// it says something, dropped from the right as the band narrows
251export function bandSuffix(t: CtxTurn, cols: number, o: { median?: number; subUsd?: number }): Piece[] {
252 const hot = o.median !== undefined && o.median > 0 && t.usd > 3 * o.median
253 const pieces: Piece[] = [{ text: '+' + fmtUsd(t.usd), tone: hot ? 'error' : 'plain' }]
254 if (cols >= 120) {
255 pieces.push({ text: `·${t.requests}r`, tone: 'dim' })
256 if (t.subRuns > 0) pieces.push({ text: '·⑂' + (o.subUsd !== undefined ? '~' + fmtUsd(o.subUsd) : ''), tone: 'sub' })
257 }
258 // a cold start or a compaction writes the prompt afresh by nature: nothing out of the ordinary
259 const hit = t.cold || t.compacted ? undefined : hitRate(t.main)
260 if (hit !== undefined && hit < 0.9 && cols >= 100) {
261 const pct = Math.round(hit * 100)
262 pieces.push({ text: cols >= 120 ? `·●${pct}% hit` : `·●${pct}%`, tone: hit < 0.5 ? 'error' : 'warning' })
263 }
264 return pieces
265}
266
267// "last turn +$1.84 (6 requests · 1 subagent ~$0.31 · cache 98% hit)"
268export function turnLine(t: CtxTurn, sub: number | undefined): string {
269 const parts = [`${t.requests} ${t.requests === 1 ? 'request' : 'requests'}`]
270 if (t.subRuns > 0) parts.push(`${t.subRuns} ${t.subRuns === 1 ? 'subagent' : 'subagents'}` + (sub !== undefined ? ` ~${fmtUsd(sub)}` : ''))
271 const hit = hitRate(t.main)
272 if (hit !== undefined) parts.push(`cache ${Math.round(hit * 100)}% hit`)
273 return `last turn +${fmtUsd(t.usd)} (${parts.join(' · ')})`
274}
275
276// "session $14.20 · last turn was 13% of it": the total is the denominator for
277// the turn's dollars, not a billing figure
278export function sessionLine(total: number, last: number | undefined): string | undefined {
279 const p = sessionParts(total, last)
280 return p && `session ${p.amount}${p.tail}`
281}
282
283// The same line in two parts, so the pane can pick the dollars out
284export function sessionParts(total: number, last: number | undefined): { amount: string; tail: string } | undefined {
285 if (!Number.isFinite(total) || total <= 0) return undefined
286 let tail = ''
287 if (last !== undefined && last > 0) {
288 const share = Math.min(100, Math.round((last / total) * 100))
289 tail = ` · last turn was ${share < 1 ? '<1' : share}% of it`
290 }
291 return { amount: fmtUsd(total), tail }
292}
293
294// "carrying ~$0.08/request · ~$0.49/turn · ~$58.5 until auto-compact"
295export function carryLine(tokens: number, r: Rates, rpt: number | undefined, pace: { perTurn?: number; turnsLeft?: number }): string {
296 const per = carry(tokens, r)
297 const parts = [`carrying ~${fmtUsd(per)}/request`]
298 if (rpt) parts.push(`~${fmtUsd(per * rpt)}/turn`)
299 if (rpt && pace.turnsLeft !== undefined) parts.push(`~${fmtUsd(untilCompact(tokens, pace.perTurn ?? 0, pace.turnsLeft, rpt, r))} until auto-compact`)
300 return parts.join(' · ')
301}
302
303// "● cache miss: a request wrote 412k fresh · ~$3.30"
304export function missLine(t: CtxTurn, r: Rates | undefined): string {
305 return `● cache miss: a request wrote ${fmtTokens(t.missTokens)} fresh` + (r ? ` · ~${fmtUsd(rewrite(t.missTokens, r))}` : '')
306}
307hooks/compact.ts 73 lines1import type { CtxWarn } from '../types'
2import { fmtTokens } from './fmt'
3
4/** Marks instructions this mod wrote, so a compaction never gets them twice. */
5export const KEEP_MARK = '[ctx keep]'
6
7// Keeps the newest `limit` distinct items, newest last
8export function addRecent(list: readonly string[], item: string, limit: number): string[] {
9 return [...list.filter(x => x !== item), item].slice(-limit)
10}
11
12// A prompt as the summary should remember it: one line, at most `n` characters
13export function clipAsk(text: string, n = 160): string {
14 const one = text.replace(/\s+/g, ' ').trim()
15 return one.length > n ? one.slice(0, n - 1) + '…' : one
16}
17
18// What a compaction's summary should keep, from what the session did: the
19// focus the person typed, the files being changed, the latest requests
20export function keepInstructions(input: { focus?: string; edited: readonly string[]; asks: readonly string[] }): string {
21 const lines = [`${KEEP_MARK} Besides the usual summary, preserve:`]
22 const focus = input.focus?.trim()
23 if (focus) lines.push(`- The focus going forward: ${focus}`)
24 if (input.edited.length) lines.push(`- The files being worked on, with what was changed in each and why: ${input.edited.join(', ')}`)
25 if (input.asks.length) {
26 lines.push('- The latest requests, newest last, and where each one stands:')
27 input.asks.forEach((a, i) => lines.push(` ${i + 1}. "${a}"`))
28 }
29 if (lines.length === 1) lines.push('- The task in progress and the next step.')
30 return lines.join('\n')
31}
32
33// Adds the mod's instructions after any the person or the engine gave
34export function mergeInstructions(existing: string | undefined, keep: string): string {
35 const given = existing?.trim()
36 if (given?.includes(KEEP_MARK)) return given
37 return given ? `${given}\n\n${keep}` : keep
38}
39
40// The pace counts only once this much of the threshold is filled: early on, one
41// heavy turn sets the pace alone and would warn at a tenth full
42const PACE_FLOOR = { near: 0.4, imminent: 0.6 }
43
44// How close auto-compaction is: by the turns left at the session's pace once
45// the window is well on its way, or by how much of the threshold is filled
46export function warnLevel(tokens: number, compactAt: number | undefined, turnsLeft: number | undefined): CtxWarn {
47 if (!compactAt || compactAt <= 0) return 'none'
48 const filled = tokens / compactAt
49 const within = (turns: number, floor: number) => turnsLeft !== undefined && turnsLeft <= turns && filled >= floor
50 if (filled >= 0.95 || within(3, PACE_FLOOR.imminent)) return 'imminent'
51 if (filled >= 0.85 || within(10, PACE_FLOOR.near)) return 'near'
52 return 'none'
53}
54
55const RANK: Record<CtxWarn, number> = { none: 0, near: 1, imminent: 2 }
56
57// A toast only as the level climbs: each step warns once, and a fall (a
58// compaction) re-arms them
59export function shouldWarn(was: CtxWarn, now: CtxWarn): boolean {
60 return RANK[now] > RANK[was]
61}
62
63export function warnText(level: CtxWarn, tokens: number, compactAt: number, turnsLeft: number | undefined): string {
64 const left = turnsLeft !== undefined ? `~${turnsLeft} ${turnsLeft === 1 ? 'turn' : 'turns'} left` : `${Math.round((tokens / compactAt) * 100)}% of the way`
65 const head = level === 'imminent' ? 'Auto-compact is close' : 'Auto-compact is coming'
66 return `${head}: ${left} (${fmtTokens(tokens)} / ${fmtTokens(compactAt)}). /ctx compact keeps what matters.`
67}
68
69// The band's badge: the turns left when the pace gives them, else the fill
70export function warnBadge(tokens: number, compactAt: number, turnsLeft: number | undefined): string {
71 return turnsLeft !== undefined ? `⚠ ~${turnsLeft} ${turnsLeft === 1 ? 'turn' : 'turns'}` : `⚠ ${Math.round((tokens / compactAt) * 100)}% to compact`
72}
73hooks/usage.ts 118 lines1import type { CtxEater, CtxProjectLog, CtxUsage } from '../types'
2import { shortPath } from './fmt'
3
4// What one tool call was about, in a few words: the file, the command, the
5// pattern; the tool's name alone when nothing says more
6export function toolLabel(tool: string, args: Record<string, unknown>): string {
7 const str = (k: string) => (typeof args[k] === 'string' ? (args[k] as string) : '')
8 const clip = (s: string, n: number) => {
9 const one = s.replace(/\s+/g, ' ').trim()
10 return one.length > n ? one.slice(0, n - 1) + '…' : one
11 }
12 const mcp = /^mcp__(.+?)__(.+)$/.exec(tool)
13 if (mcp) return `${mcp[1]}: ${mcp[2]}`
14 switch (tool) {
15 case 'Read': {
16 const range = typeof args.offset === 'number' ? ` @${args.offset}` : ''
17 return `Read ${shortPath(str('file_path'))}${range}`
18 }
19 case 'Edit':
20 case 'Write':
21 case 'NotebookEdit':
22 return `${tool} ${shortPath(str('file_path') || str('notebook_path'))}`
23 case 'Bash':
24 case 'PowerShell':
25 return `${tool} ${clip(str('command'), 32)}`
26 case 'Grep':
27 case 'Glob':
28 return `${tool} "${clip(str('pattern'), 24)}"`
29 case 'WebFetch':
30 return `WebFetch ${clip(str('url').replace(/^https?:\/\//, ''), 32)}`
31 case 'WebSearch':
32 return `WebSearch "${clip(str('query'), 24)}"`
33 case 'Agent':
34 case 'Task':
35 return `Agent ${clip(str('description') || str('subagent_type'), 28)}`
36 case 'Skill':
37 return `Skill ${str('skill')}`
38 default:
39 return tool
40 }
41}
42
43/** Characters per token before the session has taught us better. */
44export const DEFAULT_CPT = 4
45
46export function estimateTokens(chars: number, cpt: number): number {
47 return Math.round(chars / (cpt > 0 ? cpt : DEFAULT_CPT))
48}
49
50// Learns the session's characters per token from a turn whose growth was mostly
51// tool results: the turn's result characters over what the window grew by. A
52// turn of mostly talk, or a small one, teaches nothing; one sample moves the
53// figure a third of the way, inside the range real text falls in
54export function calibrate(cpt: number, chars: number, grew: number): number {
55 if (grew < 2000 || chars / DEFAULT_CPT < grew * 0.5) return cpt
56 const sample = chars / grew
57 return Math.min(6, Math.max(2.5, cpt * 0.7 + sample * 0.3))
58}
59
60// Keeps the `limit` heaviest results, heaviest first
61export function addEater(list: readonly CtxEater[], eater: CtxEater, limit = 8): CtxEater[] {
62 return [...list, eater].sort((a, b) => b.chars - a.chars).slice(0, limit)
63}
64
65/** What a call used, for the dead-weight count: an MCP server, a skill, an agent type. */
66export type UsageHit = { kind: keyof CtxUsage; name: string }
67
68export function usageOf(tool: string, args: Record<string, unknown>): UsageHit | undefined {
69 const mcp = /^mcp__(.+?)__/.exec(tool)
70 if (mcp) return { kind: 'mcp', name: mcp[1]! }
71 if (tool === 'Skill' && typeof args.skill === 'string') return { kind: 'skills', name: args.skill.replace(/^\//, '') }
72 if (tool === 'Agent' || tool === 'Task') {
73 return { kind: 'agents', name: typeof args.subagent_type === 'string' && args.subagent_type ? args.subagent_type : 'general-purpose' }
74 }
75 return undefined
76}
77
78export function addUsage(u: CtxUsage, hit: UsageHit): CtxUsage {
79 const bucket = u[hit.kind]
80 return { ...u, [hit.kind]: { ...bucket, [hit.name]: (bucket[hit.name] ?? 0) + 1 } }
81}
82
83export const EMPTY_USAGE: CtxUsage = { mcp: {}, skills: {}, agents: {} }
84
85const LOG_SESSIONS = 30
86
87type LoggedSession = CtxProjectLog['sessions'][number]
88
89// Writes this session's line into the project's log: the MCP servers it had
90// loaded (with their tokens), the ones it called, and its requests and cache
91// misses, which price what an idle server cost; the newest session last
92export function logSession(
93 log: CtxProjectLog | undefined,
94 id: string,
95 loaded: Record<string, number>,
96 used: readonly string[],
97 spent?: { requests: number; misses: number },
98): CtxProjectLog {
99 const sessions = (log?.sessions ?? []).filter(s => s.id !== id)
100 sessions.push({ id, loaded, used: [...used], ...(spent ? { requests: spent.requests, misses: spent.misses } : {}) })
101 return { sessions: sessions.slice(-LOG_SESSIONS) }
102}
103
104// The sessions in a row, newest back, that had the server loaded and never
105// called it; a session without it loaded neither counts nor breaks the run
106export function idleSessions(log: CtxProjectLog | undefined, server: string): LoggedSession[] {
107 const run: LoggedSession[] = []
108 for (const s of [...(log?.sessions ?? [])].reverse()) {
109 if (s.used.includes(server)) break
110 if (s.loaded[server] !== undefined) run.push(s)
111 }
112 return run
113}
114
115export function idleStreak(log: CtxProjectLog | undefined, server: string): number {
116 return idleSessions(log, server).length
117}
118hooks/pace.ts 130 lines1import type { CtxLimit } from '../types'
2import { fmtUsd } from './cost'
3
4// The plan's rate-limit windows as the band draws them: the HUD's Patch 3
5// (percent used, time left, how far ahead of or behind an even spend), in the
6// HUD's rounding and colors. Pure: no engine in here
7
8export const FIVE_HOUR_MS = 5 * 3_600_000
9export const SEVEN_DAY_MS = 7 * 86_400_000
10
11// The windows ctx paces, in the order they are drawn
12const WINDOWS = [
13 ['five_hour', FIVE_HOUR_MS],
14 ['seven_day', SEVEN_DAY_MS],
15] as const
16
17export type Limit = CtxLimit
18
19export type PaceWindow = {
20 kind: (typeof WINDOWS)[number][0]
21 /** Percent used, whole. */
22 percent: number
23 /** Time to the reset; absent when the reset is unknown or past. */
24 left?: string
25 /** Percent used minus the percent of the window gone, whole. */
26 delta?: number
27}
28
29export type Tone = 'dim' | 'success' | 'warning' | 'error'
30export type PacePiece = { text: string; tone: Tone }
31
32/** How much of the pace fits: all of it, no countdown, the deltas alone, nothing. */
33export type PaceStep = 'full' | 'short' | 'delta' | 'none'
34
35// "45m", "3h 40m", "4d 16h": minutes rounded up, as the HUD prints them
36export function duration(ms: number): string {
37 const total = Math.ceil(ms / 60_000)
38 if (total < 60) return `${total}m`
39 const hours = Math.floor(total / 60)
40 if (hours >= 24) {
41 const days = Math.floor(hours / 24)
42 return hours % 24 > 0 ? `${days}d ${hours % 24}h` : `${days}d`
43 }
44 const mins = total % 60
45 return mins > 0 ? `${hours}h ${mins}m` : `${hours}h`
46}
47
48// The share of the window gone, whole and held to 0-100 (rounded before the
49// difference is taken, as the HUD does)
50function gone(resetsAt: number, windowMs: number, now: number): number {
51 return Math.max(0, Math.min(100, Math.round(((now - (resetsAt - windowMs)) / windowMs) * 100)))
52}
53
54export function paceWindows(limits: readonly Limit[], now: number): PaceWindow[] {
55 const out: PaceWindow[] = []
56 for (const [kind, windowMs] of WINDOWS) {
57 const l = limits.find(x => x.kind === kind)
58 if (!l) continue
59 const percent = Math.round(l.percentUsed)
60 const resetsAt = l.resetsAt ? Date.parse(l.resetsAt) : NaN
61 const remaining = resetsAt - now
62 if (!(remaining > 0)) {
63 out.push({ kind, percent })
64 continue
65 }
66 out.push({ kind, percent, left: duration(remaining), delta: Math.round(percent - gone(resetsAt, windowMs, now)) })
67 }
68 return out
69}
70
71// The delta by its value: under an even spend green, a little over yellow, well over red
72export function deltaTone(delta: number): Tone {
73 return delta < 0 ? 'success' : delta <= 15 ? 'warning' : 'error'
74}
75
76// The percent by how much of the window is used
77export function percentTone(percent: number): Tone {
78 return percent >= 90 ? 'error' : percent >= 75 ? 'warning' : 'success'
79}
80
81const signed = (n: number) => `${n >= 0 ? '+' : ''}${n}%`
82
83/** `🐾 25% (3h 40m/-2%) · 22% (4d 16h/-11%)`, drawn narrower as the step falls. */
84export function paceLine(windows: readonly PaceWindow[], step: PaceStep): PacePiece[] {
85 if (step === 'none' || windows.length === 0) return []
86 const out: PacePiece[] = [{ text: '🐾 ', tone: 'dim' }]
87 windows.forEach((w, i) => {
88 if (i > 0) out.push({ text: ' · ', tone: 'dim' })
89 const hasDelta = w.delta !== undefined && w.left !== undefined
90 if (step === 'delta' && hasDelta) {
91 out.push({ text: signed(w.delta!), tone: deltaTone(w.delta!) })
92 return
93 }
94 out.push({ text: `${w.percent}%`, tone: percentTone(w.percent) })
95 if (!hasDelta) return
96 out.push({ text: step === 'full' ? ` (${w.left}/` : ' (', tone: 'dim' })
97 out.push({ text: signed(w.delta!), tone: deltaTone(w.delta!) })
98 out.push({ text: ')', tone: 'dim' })
99 })
100 return out
101}
102
103// How much of the pace the band has room for. The desktop passes the band no
104// width (it would read as 80) and has the room
105export function paceStep(cols: number | undefined, surface: string): PaceStep {
106 if (surface === 'desktop') return 'full'
107 const c = cols ?? 80
108 return c >= 130 ? 'full' : c >= 100 ? 'short' : c >= 80 ? 'delta' : 'none'
109}
110
111/**
112 * What the band says about the budget being spent: a subscription's windows
113 * paced; failing those a gateway's spend limit as a percent (no window length
114 * is given, so no pace); failing that the session total, where the ledger has
115 * one and dollars are on. Nothing otherwise.
116 */
117export function bandPace(o: { limits: readonly Limit[]; usd: number | undefined; costOn: boolean; step: PaceStep; now: number }): PacePiece[] {
118 if (o.step === 'none') return []
119 const windows = paceWindows(o.limits, o.now)
120 if (windows.length > 0) return paceLine(windows, o.step)
121 const label = (text: string): PacePiece[] => (o.step === 'full' ? [{ text, tone: 'dim' }] : [])
122 const spend = o.limits.find(l => l.kind === 'spend_limit')
123 if (spend) {
124 const percent = Math.round(spend.percentUsed)
125 return [...label('spend '), { text: `${percent}%`, tone: percentTone(percent) }]
126 }
127 if (!o.costOn || o.usd === undefined || !(o.usd > 0)) return []
128 return [...label('session '), { text: fmtUsd(o.usd), tone: 'success' }]
129}
130hooks/version.ts 5 lines1// The host gives a hooks module no way to read its own manifest (not through
2// "node:fs", not as a JSON import), so the pane's footer carries a copy.
3// Bump it with plugin.json on every release.
4export const VERSION = '0.8.6'
5hooks/palette.ts 365 lines1// The look's colours. Everything down to `mix` is COPIED from agent-pulse/hooks/palette.ts (each mod
2// is installed alone, so there is no import across mods): keep the values in step with Agent-Pulse.
3// palette.test.ts pins a few, so a drift is a deliberate edit. Below `mix`: resolveLook (as waypoints
4// and subagent-progress have it) and what ctx paints with, the category tints, the water, a breath.
5
6export type ActivityPhase = 'idle' | 'requesting' | 'thinking' | 'writing' | 'composing' | 'tool' | 'agent' | 'approval' | 'question' | 'compacting'
7export type ActivityOutcome = 'ok' | 'error' | 'denied' | 'interrupted'
8
9/** How much the box moves: `userConfig.animation`. */
10export type Level = 'off' | 'subtle' | 'full'
11
12export type PaletteName = 'ember' | 'claude' | 'neon' | 'mono'
13
14/**
15 * The colors one palette paints with. `phase` and `outcome` are what `Text`
16 * and borders take, theme keys where one means the same, so they follow the
17 * person's theme; `hex` is the same color as a hex string, for what mixes or
18 * draws in SVG.
19 */
20export type Palette = {
21 phase: Record<ActivityPhase, string>
22 hex: Record<ActivityPhase, string>
23 /**
24 * Each phase's second stop, hex: what its color shades toward across the
25 * strip, cycles toward on the spinner and breathes from on the border. The
26 * same as `hex` in a flat palette.
27 */
28 glow: Record<ActivityPhase, string>
29 outcome: Record<ActivityOutcome, string>
30 outcomeHex: Record<ActivityOutcome, string>
31 /** The colors the turn-end sparkle cycles through. */
32 sparkle: readonly string[]
33 /** Amber, orange, red: a step that runs past 30 s, 2 min, 5 min. */
34 heat: readonly [string, string, string]
35 /** One color per subagent, picked by its name. */
36 agents: readonly string[]
37}
38
39const CLAUDE_HEX: Record<ActivityPhase, string> = {
40 idle: '#8a8a8a',
41 requesting: '#8fa8f8',
42 thinking: '#c084fc',
43 writing: '#4eba65',
44 composing: '#47a8e5',
45 tool: '#d97757',
46 agent: '#2ec4b6',
47 approval: '#ffc107',
48 question: '#ffc107',
49 compacting: '#48968c',
50}
51
52const EMBER_HEX: Record<ActivityPhase, string> = {
53 idle: '#857a74',
54 requesting: '#f2b8a0',
55 thinking: '#c6a4ec',
56 writing: '#f6c177',
57 composing: '#ee9aa4',
58 tool: '#d97757',
59 agent: '#8cc7b5',
60 approval: '#ffcf5c',
61 question: '#ffcf5c',
62 compacting: '#9fa8e0',
63}
64
65const EMBER_GLOW: Record<ActivityPhase, string> = {
66 idle: '#9a8f88',
67 requesting: '#e8957a',
68 thinking: '#e7a3c8',
69 writing: '#f2a98a',
70 composing: '#d98fbf',
71 tool: '#f3a97c',
72 agent: '#b6d99a',
73 approval: '#ffb347',
74 question: '#ffb347',
75 compacting: '#c79bd9',
76}
77
78/** Bioluminescent: cool sea colors, with warm amber kept for what needs you. */
79const NEON_HEX: Record<ActivityPhase, string> = {
80 idle: '#5b6785',
81 requesting: '#7aa2ff',
82 thinking: '#c4a1ff',
83 writing: '#5eead4',
84 composing: '#38bdf8',
85 tool: '#22e5f0',
86 agent: '#4ade80',
87 approval: '#ffd166',
88 question: '#ffd166',
89 compacting: '#8b93f8',
90}
91
92const NEON_GLOW: Record<ActivityPhase, string> = {
93 idle: '#6f7a99',
94 requesting: '#b39dff',
95 thinking: '#ff8ad8',
96 writing: '#7dd3fc',
97 composing: '#818cf8',
98 tool: '#6ef0c8',
99 agent: '#bef264',
100 approval: '#ff9f6e',
101 question: '#ff9f6e',
102 compacting: '#c79bf2',
103}
104
105const MONO_HEX: Record<ActivityPhase, string> = {
106 idle: '#7a7a7a',
107 requesting: '#b8b8b8',
108 thinking: '#b8b8b8',
109 writing: '#b8b8b8',
110 composing: '#b8b8b8',
111 tool: '#d0d0d0',
112 agent: '#d0d0d0',
113 approval: '#ffc107',
114 question: '#ffc107',
115 compacting: '#b8b8b8',
116}
117
118const OUTCOME_HEX: Record<ActivityOutcome, string> = {
119 ok: '#4eba65',
120 error: '#ff6b80',
121 denied: '#ffc107',
122 interrupted: '#8a8a8a',
123}
124
125const OUTCOME_THEME: Record<ActivityOutcome, string> = {
126 ok: 'success',
127 error: 'error',
128 denied: 'warning',
129 interrupted: 'inactive',
130}
131
132const EMBER_OUTCOME: Record<ActivityOutcome, string> = { ok: '#8fd694', error: '#ff6b6b', denied: '#ffcf5c', interrupted: '#857a74' }
133const NEON_OUTCOME: Record<ActivityOutcome, string> = { ok: '#4ade80', error: '#ff5c7a', denied: '#ffd166', interrupted: '#6f7a99' }
134
135/** Steps on the spinner's color cycle, core to glow and back. */
136const SHIMMER_STEPS = 12
137
138const PALETTES: Record<PaletteName, Palette> = {
139 ember: {
140 phase: EMBER_HEX,
141 hex: EMBER_HEX,
142 glow: EMBER_GLOW,
143 outcome: EMBER_OUTCOME,
144 outcomeHex: EMBER_OUTCOME,
145 sparkle: ['#d97757', '#e8957a', '#f3a97c', '#f6c177', '#ffe3b0', '#f6c177', '#f3a97c', '#e8957a'],
146 heat: ['#f6d36b', '#ff9a4d', '#ff5c5c'],
147 agents: ['#8cc7b5', '#f2b8a0', '#c6a4ec', '#f6c177', '#ee9aa4', '#9fc7e8'],
148 },
149 claude: {
150 phase: {
151 idle: 'inactive',
152 requesting: 'suggestion',
153 thinking: CLAUDE_HEX.thinking,
154 writing: 'success',
155 composing: 'ide',
156 tool: 'claude',
157 agent: CLAUDE_HEX.agent,
158 approval: 'warning',
159 question: 'warning',
160 compacting: 'planMode',
161 },
162 hex: CLAUDE_HEX,
163 glow: CLAUDE_HEX,
164 outcome: OUTCOME_THEME,
165 outcomeHex: OUTCOME_HEX,
166 sparkle: ['#d97757', '#e48a66', '#f0a47f', '#fbc8a8', '#ffe6d5', '#fbc8a8', '#f0a47f', '#e48a66'],
167 heat: ['#e0af68', '#ff9e64', 'error'],
168 agents: ['#2ec4b6', '#f4a261', '#a78bfa', '#60a5fa', '#f472b6', '#84cc16'],
169 },
170 neon: {
171 phase: NEON_HEX,
172 hex: NEON_HEX,
173 glow: NEON_GLOW,
174 outcome: NEON_OUTCOME,
175 outcomeHex: NEON_OUTCOME,
176 sparkle: ['#22e5f0', '#5eead4', '#7dd3fc', '#b39dff', '#ff8ad8', '#c4a1ff', '#7aa2ff', '#38bdf8'],
177 heat: ['#ffd166', '#ff9f6e', '#ff5c7a'],
178 agents: ['#5eead4', '#ff8ad8', '#bef264', '#ffd166', '#b39dff', '#7dd3fc'],
179 },
180 mono: {
181 phase: {
182 idle: 'inactive',
183 requesting: 'text',
184 thinking: 'text',
185 writing: 'text',
186 composing: 'text',
187 tool: 'text',
188 agent: 'text',
189 approval: 'warning',
190 question: 'warning',
191 compacting: 'text',
192 },
193 hex: MONO_HEX,
194 glow: MONO_HEX,
195 outcome: OUTCOME_THEME,
196 outcomeHex: OUTCOME_HEX,
197 sparkle: ['#6e6e6e', '#8a8a8a', '#a8a8a8', '#c8c8c8', '#e8e8e8', '#c8c8c8', '#a8a8a8', '#8a8a8a'],
198 heat: ['warning', 'warning', 'error'],
199 agents: ['#d0d0d0', '#a8a8a8', '#e8e8e8', '#8a8a8a'],
200 },
201}
202
203export function paletteOf(name: unknown): Palette {
204 return PALETTES[name === 'claude' || name === 'neon' || name === 'mono' ? name : 'ember']
205}
206
207/**
208 * A phase's color `t` of the way from its core to its glow. A flat palette
209 * keeps its own color, which may be a theme key.
210 */
211export function shadeOf(palette: Palette, phase: ActivityPhase, t: number): string {
212 const core = palette.hex[phase]
213 const glow = palette.glow[phase]
214
215 return core === glow ? palette.phase[phase] : mix(core, glow, t)
216}
217
218/** The spinner's colors, one per frame: core to glow and back, or the one color of a flat palette. */
219export function shimmerOf(palette: Palette, phase: ActivityPhase): string[] {
220 if (palette.hex[phase] === palette.glow[phase]) {
221 return [palette.phase[phase]]
222 }
223
224 return Array.from({ length: SHIMMER_STEPS }, (_, i) => shadeOf(palette, phase, (1 - Math.cos((i / SHIMMER_STEPS) * 2 * Math.PI)) / 2))
225}
226
227export function levelOf(value: unknown): Level {
228 return value === 'off' || value === 'full' ? value : 'subtle'
229}
230
231/**
232 * The color a step's timer takes as it runs long, or `undefined` while it is
233 * young (drawn dim).
234 */
235export function heatOf(palette: Palette, ms: number): string | undefined {
236 return ms >= 300_000 ? palette.heat[2] : ms >= 120_000 ? palette.heat[1] : ms >= 30_000 ? palette.heat[0] : undefined
237}
238
239/** One color per agent, the same each time its name comes up. */
240export function agentColorOf(palette: Palette, name: string): string {
241 let hash = 0
242
243 for (const char of name) {
244 hash = (hash * 31 + char.charCodeAt(0)) | 0
245 }
246
247 return palette.agents[Math.abs(hash) % palette.agents.length] ?? palette.hex.agent
248}
249
250/**
251 * Mixes two hex colors, `t` 0 being `a` and 1 being `b`.
252 */
253export function mix(a: string, b: string, t: number): string {
254 const channels = (hex: string) => [1, 3, 5].map(i => parseInt(hex.slice(i, i + 2), 16))
255 const [from, to] = [channels(a), channels(b)]
256 const k = Math.min(1, Math.max(0, t))
257
258 return `#${from.map((c, i) => Math.round(c + ((to[i] ?? c) - c) * k).toString(16).padStart(2, '0')).join('')}`
259}
260
261export const PALETTE_NAMES: readonly PaletteName[] = ['ember', 'claude', 'neon', 'mono']
262export const FOLLOW_KEYS = { palette: 'agent-pulse.palette', animation: 'agent-pulse.animation' } as const
263
264export type Look = { palette: PaletteName; level: Level }
265
266/**
267 * The look to draw with. `options`: the userConfig values ('follow' or explicit); `rows`: `$.config.list()`.
268 * 'follow' takes Agent-Pulse's own value, or ember / subtle without it.
269 */
270export function resolveLook(options: { palette?: unknown; animation?: unknown } | undefined, rows: unknown): Look {
271 const o = options ?? {}
272 const list = Array.isArray(rows) ? (rows as { key?: unknown; value?: unknown }[]) : []
273 const fromRow = (key: string): unknown => list.find(r => r && r.key === key)?.value
274 const palette = o.palette && o.palette !== 'follow' ? o.palette : fromRow(FOLLOW_KEYS.palette)
275 const animation = o.animation && o.animation !== 'follow' ? o.animation : fromRow(FOLLOW_KEYS.animation)
276 return { palette: PALETTE_NAMES.find(n => n === palette) ?? 'ember', level: levelOf(animation) }
277}
278
279/** A category's two colours: hex core and glow, or the engine's theme key twice in a palette that follows the theme. */
280export type Tint = { core: string; glow: string }
281
282// Each listed category paints with an Agent-Pulse phase, so a palette means the same in every band
283const CATEGORY_PHASE: Record<string, ActivityPhase> = {
284 Messages: 'tool',
285 'System prompt': 'requesting',
286 'System tools': 'composing',
287 'MCP tools': 'agent',
288 'Memory files': 'writing',
289 Skills: 'thinking',
290}
291
292// Only ember and neon shade: claude and mono keep the engine's own colours, as before 0.8
293const shades = (look: Look) => look.palette === 'ember' || look.palette === 'neon'
294
295/**
296 * The colours of the breakdown's rows. A listed name takes its phase; any other name the palette's
297 * agent colours in order, skipping one already taken, so a row keeps its colour as others come and go.
298 */
299export function categoryTints(look: Look, rows: readonly { name: string; color: string; kind: string }[]): Record<string, Tint> {
300 const out: Record<string, Tint> = {}
301 if (!shades(look)) {
302 for (const r of rows) out[r.name] = { core: r.color, glow: r.color }
303 return out
304 }
305 const p = paletteOf(look.palette)
306 const taken = new Set(Object.values(CATEGORY_PHASE).map(ph => p.hex[ph]))
307 for (const [name, ph] of Object.entries(CATEGORY_PHASE)) out[name] = { core: p.hex[ph], glow: p.glow[ph] }
308 const others = rows.map(r => r.name).filter(n => !(n in CATEGORY_PHASE) && !(n in out))
309 // sorted, so the colour a name gets does not hang on which other names are present before it
310 for (const name of [...new Set(others)].sort()) {
311 // the agent colours first, then the sparkle and the glows: a long list of names still gets distinct colours
312 const pool = [...p.agents, ...p.sparkle, ...Object.values(p.glow)]
313 const free = pool.find(c => !taken.has(c)) ?? agentColorOf(p, name)
314 taken.add(free)
315 out[name] = { core: free, glow: free }
316 }
317 return out
318}
319
320/** The water (free space) and its foam, in a palette that shades; none in claude and mono. */
321export function waterOf(look: Look): { water: string; foam: string } | undefined {
322 if (!shades(look)) return undefined
323 const p = paletteOf(look.palette)
324 return { water: p.hex.compacting, foam: p.glow.compacting }
325}
326
327/** A breath: `steps` colours from dim up to `color` and back. A theme key cannot be mixed, so it holds still. */
328export function breath(color: string, steps = 20): string[] {
329 if (!/^#[0-9a-f]{6}$/i.test(color)) return [color]
330 const dim = mix(color, '#000000', 0.55)
331 return Array.from({ length: steps }, (_, i) => mix(dim, color, (1 - Math.cos((i / steps) * 2 * Math.PI)) / 2))
332}
333
334/** Amber, orange, red for the pane's heat: the palette's scale, or the theme keys of 0.7 in claude and mono. */
335export function heatKeys(look: Look): readonly [string, string, string] {
336 return shades(look) ? paletteOf(look.palette).heat : ['warning', 'warning', 'error']
337}
338
339/** The sparkline's `n` past glyphs: a dimmed core shading to the glow; none in a palette that follows the theme. */
340export function sparkColors(look: Look, tint: Tint | undefined, n: number): string[] | undefined {
341 if (!shades(look) || !tint || !/^#/.test(tint.core)) return undefined
342 const from = mix(tint.core, '#000000', 0.35)
343 return Array.from({ length: n }, (_, i) => mix(from, tint.glow, n > 1 ? i / (n - 1) : 1))
344}
345
346/**
347 * The rows' colours for an SVG, which takes no theme keys: the look's own tints in ember and neon,
348 * the phase hex of claude and mono otherwise, so the Desktop pill draws in every palette.
349 */
350export function svgTints(look: Look, rows: readonly { name: string; color: string; kind: string }[]): Record<string, Tint> {
351 if (shades(look)) return categoryTints(look, rows)
352 const p = paletteOf(look.palette)
353 const out: Record<string, Tint> = {}
354 for (const [name, ph] of Object.entries(CATEGORY_PHASE)) out[name] = { core: p.hex[ph], glow: p.hex[ph] }
355 for (const r of rows) if (!(r.name in out)) out[r.name] = { core: r.kind === 'used' ? agentColorOf(p, r.name) : p.hex.idle, glow: r.kind === 'used' ? agentColorOf(p, r.name) : p.hex.idle }
356 return out
357}
358
359/** A heat colour an SVG can draw: the palette's, or its outcome hex where the palette names a theme key. */
360export function hexHeat(look: Look, i: 0 | 1 | 2): string {
361 const p = paletteOf(look.palette)
362 const c = p.heat[i]
363 return /^#/.test(c) ? c : i === 2 ? p.outcomeHex.error : p.outcomeHex.denied
364}
365hooks/svg.ts 137 lines1// The Desktop's drawings, as SVG sources: the band's bar as a small pill, and
2// the pane's breathing ⚠. The browser runs the motion (CSS @keyframes), so the
3// mod draws again only when the data changes. A source must not change between
4// redraws unless the data did (a new source restarts its animations): nothing
5// here carries a time, and a one-shot carries its event's id, so it plays once.
6
7import type { Level } from './palette'
8
9type Cell = { ch: string; color: string; bg?: string; dim?: boolean; scope: string }
10
11const CELL_PX = 8
12const H = 12
13// The row under a labelled bar, and the width a 10 px label character is taken to need
14const LABEL_H = 14
15const LABEL_CHAR = 5.6
16const REDUCED = '@media (prefers-reduced-motion: reduce){*{animation:none!important}}'
17
18const esc = (s: string) => s.replace(/&/g, '&').replace(/</g, '<').replace(/"/g, '"')
19
20// Consecutive cells of one category, with the colours at their two ends
21function segments(cells: readonly Cell[]) {
22 const segs: { scope: string; kind: 'used' | 'free' | 'buffer'; from: number; to: number; first: string; last: string }[] = []
23 cells.forEach((c, i) => {
24 const kind = c.ch === '░' ? 'buffer' : c.ch === '~' || c.ch === '≈' || c.ch === '·' ? 'free' : 'used'
25 const seg = segs[segs.length - 1]
26 if (seg && seg.scope === c.scope && seg.kind === kind) {
27 seg.to = i + 1
28 if (kind !== 'free' || c.ch !== '≈') seg.last = c.color
29 } else segs.push({ scope: c.scope, kind, from: i, to: i + 1, first: c.color, last: c.color })
30 })
31 return segs
32}
33
34export type BandSvg = {
35 cells: readonly Cell[]
36 level: Level
37 /** The water's edge, or -1. */
38 edge: number
39 /** The auto-compact point, as a cell column. */
40 tick?: number
41 /** Near auto-compact: the colour the tick and the edge breathe in. */
42 warn?: string
43 growth?: { id: number; from: number; to: number; colors: readonly string[] }
44 sweep?: { id: number; from: number; to: number }
45 /** Pixels a cell takes; 8 unless the bar is drawn at a width of its own (the pane's). */
46 cellPx?: number
47 /** Words under the bar at the tick, with a caret; needs a tick. */
48 label?: string
49}
50
51/** The bar on Desktop: a rounded pill, `cells.length × cellPx` (8) by 12 px, a label's row under it when asked. */
52export function bandSvg(o: BandSvg): { source: string; width: number; height: number } {
53 const px = o.cellPx ?? CELL_PX
54 const W = o.cells.length * px
55 const moving = o.level !== 'off'
56 const segs = segments(o.cells)
57 const water = segs.find(s => s.kind === 'free')
58 const foam = o.edge >= 0 ? o.cells[o.edge]?.color : undefined
59 const hasWater = Boolean(water && o.cells.some(c => c.ch === '~' || c.ch === '≈'))
60 const defs: string[] = [`<clipPath id="c"><rect width="${W}" height="${H}" rx="${H / 2}"/></clipPath>`]
61 const body: string[] = []
62 segs.forEach((s, i) => {
63 const x = s.from * px
64 const w = (s.to - s.from) * px
65 if (s.kind === 'used') {
66 defs.push(`<linearGradient id="u${i}" x1="0" x2="1"><stop offset="0" stop-color="${esc(s.first)}"/><stop offset="1" stop-color="${esc(s.last)}"/></linearGradient>`)
67 body.push(`<rect x="${x}" width="${w}" height="${H}" fill="url(#u${i})"/>`)
68 } else if (s.kind === 'buffer') {
69 defs.push(`<pattern id="h" width="3" height="3" patternUnits="userSpaceOnUse" patternTransform="rotate(45)"><rect width="1.2" height="3" fill="${esc(s.first)}"/></pattern>`)
70 body.push(`<rect x="${x}" width="${w}" height="${H}" fill="${esc(s.first)}" opacity="0.18"/><rect x="${x}" width="${w}" height="${H}" fill="url(#h)" opacity="0.6"/>`)
71 } else if (hasWater) {
72 body.push(`<rect x="${x}" width="${w}" height="${H}" fill="${esc(s.last)}" opacity="0.28"/>`)
73 // the wave along the water's surface, wider than the water so it can drift
74 const crest = Array.from({ length: Math.ceil(w / 8) + 3 }, (_, k) => `q2 -2 4 0 t4 0`).join(' ')
75 body.push(`<path class="wave" d="M${x - 16} 4 ${crest}" fill="none" stroke="${esc(foam ?? s.last)}" stroke-width="1.2" opacity="0.8"/>`)
76 if (o.level === 'full') {
77 for (const k of [0.25, 0.55, 0.8]) body.push(`<circle class="glint" cx="${(x + w * k).toFixed(1)}" cy="8" r="0.9" fill="#ffffff"/>`)
78 }
79 } else {
80 body.push(`<rect x="${x}" width="${w}" height="${H}" fill="${esc(s.first)}" opacity="0.18"/>`)
81 }
82 })
83 if (foam && hasWater) body.push(`<rect class="${o.warn ? 'edge breathe' : 'edge'}" x="${o.edge * px}" width="1.5" height="${H}" fill="${esc(o.warn ?? foam)}"/>`)
84 if (o.tick !== undefined) body.push(`<rect class="tick${o.warn ? ' breathe' : ''}" x="${Math.min(W - 1.5, o.tick * px)}" width="1.5" height="${H}" fill="${esc(o.warn ?? '#ffffff')}" opacity="0.85"/>`)
85 if (moving && o.growth && o.growth.to > o.growth.from) {
86 const c = o.growth.colors[Math.floor(o.growth.colors.length / 2)] ?? '#ffffff'
87 body.push(`<rect id="g${o.growth.id}" class="grow" x="${o.growth.from * px}" width="${(o.growth.to - o.growth.from) * px}" height="${H}" fill="${esc(c)}"/>`)
88 }
89 if (o.level === 'full' && o.sweep && o.sweep.to > o.sweep.from) {
90 const from = o.sweep.from * px
91 const span = (o.sweep.to - o.sweep.from) * px
92 body.push(
93 `<rect id="s${o.sweep.id}" class="sweep" x="${from}" width="${span}" height="${H}" fill="${esc(foam ?? '#ffffff')}" style="transform-origin:${from}px 0"/>`,
94 )
95 }
96 const css = moving
97 ? [
98 '@keyframes drift{to{transform:translateX(-8px)}}',
99 '.wave{animation:drift 2.4s linear infinite}',
100 '@keyframes twinkle{0%,100%{opacity:0}50%{opacity:.85}}',
101 '.glint{opacity:0;animation:twinkle 2.6s ease-in-out infinite}',
102 '.glint:nth-of-type(2n){animation-delay:.9s}',
103 '.glint:nth-of-type(3n){animation-delay:1.7s}',
104 '@keyframes breathe{0%,100%{opacity:.35}50%{opacity:1}}',
105 '.breathe{animation:breathe 2s ease-in-out infinite}',
106 '@keyframes grow{0%{opacity:.9}100%{opacity:0}}',
107 '.grow{opacity:0;animation:grow 1.5s ease-out 1}',
108 '@keyframes sweep{0%{transform:scaleX(1);opacity:.9}100%{transform:scaleX(0);opacity:.4}}',
109 '.sweep{transform:scaleX(0);animation:sweep 1.2s ease-in 1}',
110 ].join('')
111 : ''
112 // the auto-compact caret and its words under the bar: after the tick when they fit, else ending at it
113 const labelled = o.label !== undefined && o.tick !== undefined
114 const total = labelled ? H + LABEL_H : H
115 let under = ''
116 if (labelled) {
117 const tx = Math.min(W - 3, o.tick! * px + 0.75)
118 const fits = tx + 6 + o.label!.length * LABEL_CHAR <= W
119 under =
120 `<path d="M${(tx - 3).toFixed(1)} ${H + 8} l3 -5 l3 5z" fill="#8a8f98"/>` +
121 `<text x="${(fits ? tx + 7 : tx + 3).toFixed(1)}" y="${H + 12}" font-size="10" fill="#8a8f98"${fits ? '' : ' text-anchor="end"'}>${esc(o.label!)}</text>`
122 }
123 const source =
124 `<svg xmlns="http://www.w3.org/2000/svg" width="${W}" height="${total}" viewBox="0 0 ${W} ${total}">` +
125 `<style>${css}${REDUCED}</style><defs>${defs.join('')}</defs><g clip-path="url(#c)">${body.join('')}</g>${under}</svg>`
126 return { source, width: W, height: total }
127}
128
129/** The pane's ⚠ near auto-compact, breathing in `color`: 10 by 12 px. */
130export function breathSvg(color: string): { source: string; width: 10; height: 12 } {
131 const source =
132 `<svg xmlns="http://www.w3.org/2000/svg" width="10" height="12" viewBox="0 0 10 12">` +
133 `<style>@keyframes breathe{0%,100%{opacity:.35}50%{opacity:1}}text{animation:breathe 2s ease-in-out infinite}${REDUCED}</style>` +
134 `<text x="0" y="10" font-size="10" font-weight="700" fill="${esc(color)}">⚠</text></svg>`
135 return { source, width: 10, height: 12 }
136}
137hooks/tide.tsx 136 lines1import type { ClientModule } from 'claude-code'
2
3// Tide: the bar's motion, one Client region of a fixed width, so the band's
4// layout never moves under it. It runs on the surface's frame clock; the hooks
5// never run per frame. It imports nothing from the mod (a Client module stands
6// alone): the hooks hand it every colour already mixed.
7//
8// - the foam at the water's edge laps (`lap`), and at `full` a brighter `~` drifts along the water
9// - `breathe`: the cells at `at` cycle `colors` (auto-compact is near)
10// - `growth`: one-shot, the cells a turn added shimmer through `colors` for 1.5 s
11// - `sweep`: one-shot, a wave runs from the old edge back to the new one over 1.2 s
12//
13// A one-shot plays once per `id`: a redraw with the same id does not start it again.
14
15/** One cell of the bar; `scope` is the category it draws, for hover. */
16export type Cell = { ch: string; color: string; bg?: string; dim?: boolean; scope: string }
17
18export type TideProps = {
19 cells: Cell[]
20 level: 'subtle' | 'full'
21 /** The water's edge (the foam), or -1. */
22 edge: number
23 /** The foam's two colours, core then glow. */
24 lap?: string[]
25 /** The drifting `~`'s colour, at `full` only. */
26 drift?: string
27 breathe?: { at: number[]; colors: string[] }
28 /** Cells `from` to `to - 1`. */
29 growth?: { id: number; from: number; to: number; colors: string[] }
30 /** The crest runs from `to - 1` down to `from`: the old shore before it, water behind. */
31 sweep?: { id: number; from: number; to: number; shore: string; water: string; foam: string }
32}
33
34type TideState = { frame: number; growthId?: number; growthAt?: number; sweepId?: number; sweepAt?: number }
35
36// In frames of 100 ms
37const FRAME_MS = 100
38const LAP = 10
39const DRIFT = 6
40const GROWTH = 15
41const SWEEP = 12
42
43/** The bar at `frame`; `starts` holds the frame each one-shot began at. */
44export function frameAt(props: TideProps, frame: number, starts: { growth?: number; sweep?: number }): Cell[] {
45 const cells = props.cells.map(c => ({ ...c }))
46 const { edge } = props
47 if (edge >= 0 && edge < cells.length) {
48 if (props.lap && props.lap.length > 0) {
49 const half = Math.floor(frame / (LAP / 2)) % 2
50 cells[edge] = { ...cells[edge]!, ch: half === 0 ? '≈' : '~', color: props.lap[half % props.lap.length]!, dim: false }
51 }
52 if (props.level === 'full' && props.drift) {
53 const water = cells.map((c, i) => (i > edge && c.ch === '~' ? i : -1)).filter(i => i >= 0)
54 const at = water[Math.floor(frame / DRIFT) % Math.max(1, water.length)]
55 if (at !== undefined) cells[at] = { ...cells[at]!, color: props.drift, dim: false }
56 }
57 }
58 if (props.breathe && props.breathe.colors.length > 0) {
59 const color = props.breathe.colors[frame % props.breathe.colors.length]!
60 for (const i of props.breathe.at) if (cells[i]) cells[i] = { ...cells[i]!, color, dim: false }
61 }
62 const g = props.growth
63 if (g && starts.growth !== undefined && frame >= starts.growth && frame - starts.growth < GROWTH && g.colors.length > 0) {
64 for (let i = Math.max(0, g.from); i < Math.min(cells.length, g.to); i++) {
65 cells[i] = { ...cells[i]!, color: g.colors[(i + frame) % g.colors.length]!, dim: false }
66 }
67 }
68 const s = props.sweep
69 if (s && starts.sweep !== undefined && frame >= starts.sweep && frame - starts.sweep < SWEEP && s.to > s.from) {
70 const crest = Math.max(s.from, s.to - 1 - Math.round(((frame - starts.sweep) / SWEEP) * (s.to - s.from)))
71 for (let i = s.from; i < Math.min(cells.length, s.to); i++) {
72 const c = cells[i]!
73 cells[i] =
74 i < crest
75 ? { ...c, ch: '█', color: s.shore, dim: false, bg: undefined }
76 : i === crest
77 ? { ...c, ch: '≈', color: s.foam, dim: false, bg: undefined }
78 : { ...c, ch: '~', color: s.water, dim: true, bg: undefined }
79 }
80 }
81 return cells
82}
83
84const moves = (p: TideProps) => Boolean(p.lap || p.breathe || p.growth || p.sweep || (p.level === 'full' && p.drift))
85
86const Tide: ClientModule<TideProps, TideState> = (props, surface) => {
87 const { Box, Text } = surface.elements
88 const st = surface.state
89
90 if (st === undefined) {
91 const first: TideState = { frame: 0 }
92 if (props.growth) Object.assign(first, { growthId: props.growth.id, growthAt: 0 })
93 if (props.sweep) Object.assign(first, { sweepId: props.sweep.id, sweepAt: 0 })
94 surface.setState(first)
95 if (moves(props)) {
96 surface.every(FRAME_MS, () => {
97 const now = surface.state ?? { frame: 0 }
98 surface.setState({ ...now, frame: now.frame + 1 })
99 })
100 }
101 } else if ((props.growth && props.growth.id !== st.growthId) || (props.sweep && props.sweep.id !== st.sweepId)) {
102 // a new event: it starts at this frame, once
103 surface.setState({
104 ...st,
105 ...(props.growth && props.growth.id !== st.growthId ? { growthId: props.growth.id, growthAt: st.frame } : {}),
106 ...(props.sweep && props.sweep.id !== st.sweepId ? { sweepId: props.sweep.id, sweepAt: st.frame } : {}),
107 })
108 }
109
110 const now = surface.state ?? { frame: 0 }
111 const cells = frameAt(props, now.frame, { growth: now.growthAt, sweep: now.sweepAt })
112 const runs: Cell[] = []
113 for (const c of cells) {
114 const last = runs[runs.length - 1]
115 if (last && last.color === c.color && last.bg === c.bg && Boolean(last.dim) === Boolean(c.dim) && last.scope === c.scope) last.ch += c.ch
116 else runs.push({ ...c })
117 }
118 return (
119 <Box flexDirection="row" flexShrink={0}>
120 {runs.map((r, i) => (
121 <Text
122 key={`t${i}`}
123 color={r.color}
124 {...(r.bg ? { backgroundColor: r.bg } : {})}
125 {...(r.dim ? { dimColor: true } : {})}
126 hover={{ scope: 'ctx:' + r.scope, inverse: true }}
127 >
128 {r.ch}
129 </Text>
130 ))}
131 </Box>
132 )
133}
134
135export default Tide
136types/index.d.ts 189 lines1export type CtxRow = {
2 name: string
3 tokens: number
4 color: string
5 kind: 'used' | 'free' | 'buffer' | 'deferred'
6}
7
8/** One MCP server: its schemas in the window, and those loaded on demand. */
9export type CtxServer = {
10 name: string
11 /** The server as its tools' wire names spell it (`mcp__<key>__tool`). */
12 key: string
13 tokens: number
14 count: number
15 deferredTokens: number
16 deferredCount: number
17}
18export type CtxMemoryFile = { path: string; type: string; tokens: number }
19export type CtxSkill = { name: string; tokens: number }
20export type CtxAgent = { name: string; tokens: number }
21
22/** One heavy tool result in the main conversation. */
23export type CtxEater = { tool: string; label: string; chars: number; turn: number }
24
25/** Calls this session, by MCP server key, skill name and agent type. */
26export type CtxUsage = {
27 mcp: Record<string, number>
28 skills: Record<string, number>
29 agents: Record<string, number>
30}
31
32/**
33 * A project's recent sessions: the MCP servers each had loaded, and the ones it called.
34 * `requests` and `misses` (from 0.6.0) price each server's idle overhead; older lines lack them.
35 */
36export type CtxProjectLog = {
37 sessions: { id: string; loaded: Record<string, number>; used: string[]; requests?: number; misses?: number }[]
38}
39
40/** Token counts as the API reports them, summed. */
41export type CtxCounts = { input: number; output: number; read: number; write: number }
42
43/** One main-loop turn's spend: the ledger's growth and the requests behind it. */
44export type CtxTurn = {
45 /** The session's cost ledger, in US dollars, when the turn began. */
46 base: number
47 /** What the ledger grew by since: real dollars, subagents included. */
48 usd: number
49 /** Main-loop model requests in the turn. */
50 requests: number
51 main: CtxCounts
52 /** The API model id of the main loop's last response. */
53 model: string
54 /** More than one model answered the main loop. */
55 mixed: boolean
56 /** Subagents' requests, summed. */
57 sub: CtxCounts
58 subRuns: number
59 /** The largest cache write of a main-loop request that missed the cache. */
60 missTokens: number
61 /**
62 * The turn wrote its prompt afresh as a matter of course: the session's
63 * first request, or the first after a compaction. No miss is shown for it.
64 */
65 cold: boolean
66 /** A compaction ran during the turn. */
67 compacted: boolean
68 /** The turn's `turn.complete` came. */
69 done: boolean
70}
71
72/** One clean turn, for learning the model's prices: tokens in millions, and the dollars they cost. */
73export type CtxSample = { model: string; inOut: number; read: number; write: number; usd: number }
74
75/** What the session has spent, turn by turn, and what that says about its cache. */
76export type CtxSpend = {
77 /** The cost ledger's latest figure; absent where the host keeps none. */
78 ledger?: number
79 /** The turn running, or the last one until the next begins. */
80 cur?: CtxTurn
81 /** The turn before `cur`. */
82 last?: CtxTurn
83 /** Finished turns' dollars, oldest first. */
84 usds: number[]
85 samples: CtxSample[]
86 /** Main-loop requests and cache misses this session, and finished turns. */
87 requests: number
88 misses: number
89 turns: number
90 /** When the main loop's last request ended. */
91 lastStepAt?: number
92 /** The longest idle gap the cache survived, and the shortest (of 4+ minutes) it did not. */
93 maxHitGap: number
94 minMissGap?: number
95 /** The last compaction: its size after, and what it cost. */
96 compact?: { after?: number; usd?: number; summary?: number }
97}
98
99/** One rate-limit window as the engine reports it: `five_hour`, `seven_day`, or a gateway's `spend_limit`. */
100export type CtxLimit = { kind: string; percentUsed: number; resetsAt?: string }
101
102/** How close auto-compaction is. */
103export type CtxWarn = 'none' | 'near' | 'imminent'
104
105/** How a breakdown is counted: estimated locally, or with the token-count API. */
106export type CtxDetail = 'summary' | 'full'
107
108/** A slim copy of /context's breakdown: no 200-square grid, just what is drawn. */
109export type CtxSnapshot = {
110 rows: CtxRow[]
111 total: number
112 max: number
113 percent: number
114 detail: CtxDetail
115 at: number
116 model: string
117 /** Tokens at which auto-compaction runs; absent when it is off. */
118 compactAt?: number
119 mcpTokens: number
120 mcpCount: number
121 mcpDeferredTokens: number
122 mcpDeferredCount: number
123 servers: CtxServer[]
124 memory: CtxMemoryFile[]
125 skillCount: number
126 skillIncluded: number
127 skillTokens: number
128 /** Every skill listing, largest first; the pane shows the top few. */
129 skills: CtxSkill[]
130 agentTokens: number
131 agents: CtxAgent[]
132 commandCount: number
133 commandIncluded: number
134 commandTokens: number
135}
136
137/** One effect event: its id (a one-shot plays once per id), when it landed, and the tokens it moved. */
138export type CtxFxEvent = { id: number; at: number; delta: number }
139/** The last growth (a turn added to the window) and the last sweep (a compaction freed room). */
140export type CtxFx = { growth?: CtxFxEvent; sweep?: CtxFxEvent }
141
142declare module 'claude-code' {
143 interface PluginState {
144 ctx: {
145 snap: CtxSnapshot | null
146 isVisible: boolean
147 opened: string[]
148 mode: CtxDetail
149 stale: boolean
150 tick: number
151 /** The window's tokens after each turn, oldest first, as the API reported them. */
152 history: number[]
153 /** The heaviest tool results of the main conversation, heaviest first. */
154 eaters: CtxEater[]
155 /** Characters per token, learned from this session's turns. */
156 cpt: number
157 usage: CtxUsage
158 /** This project's log as it stood when the session started. */
159 project: CtxProjectLog | null
160 /** Per `history` reading: whether a compaction came just before it. */
161 compacted: boolean[]
162 /** Files the session changed, newest last. */
163 edited: string[]
164 /** The person's latest prompts, newest last, clipped. */
165 asks: string[]
166 /** Whether every compaction gets the mod's keep instructions. */
167 autokeep: boolean
168 /** The highest warning given since the last compaction. */
169 warned: CtxWarn
170 /** What the session spent, per turn, from the engine's cost ledger. */
171 spend: CtxSpend
172 /** Whether dollar figures are shown. */
173 costOn: boolean
174 /** Whether the Desktop footer shows `ctx N%`; off until `/ctx footer on`. */
175 footerOn: boolean
176 /** The plan's rate-limit windows as the last response reported them; empty off a subscription. */
177 limits: CtxLimit[]
178 /** Bumped once a minute while there are windows, so the band's countdown moves. */
179 paceTick: number
180 /** The look's effect events (0.8.0), so a hot reload keeps their ids. */
181 fx: CtxFx
182 /** A main-loop turn is running: the sparkline's newest point pulses. */
183 turnRunning: boolean
184 /** Bumped while a one-shot plays on a surface with no Client, so the Desktop pane redraws it. */
185 fxTick: number
186 }
187 }
188}
189