Stare deeply into your contexts

hooks/register.tsx 531 lines1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, Register, UiOpenResult } from 'claude-code'
3
4import type { Row, Shift, Snapshot } from '../types'
5import { classify, describe, EMPTY_LEDGER, toRow } from './attribution'
6import { buildTable } from './contributions'
7import { columnBadges, COUNT_MODES, pathTail, toCountMode } from './display'
8import type { CountMode } from './display'
9import type { Node } from './contributions'
10import type { Row as AttributionRow } from './attribution'
11import { apply, INITIAL, isOverViewport } from './viewport-model'
12import type { Intent, ViewportProps } from './viewport-model'
13
14export const PANE = 'xray-mod'
15const TITLE = 'Context'
16const LOG_SIZE = 12
17// Ignore estimate jitter below this many tokens when logging a shift.
18const NOISE = 100
19
20const snapshot = atom({ plugin: 'xray-mod', key: 'snapshot' } as const, null)
21const log = atom({ plugin: 'xray-mod', key: 'log' } as const, [])
22// Each viewport's scroll offset and collapsed flag, keyed by its Client key.
23const viewports = atom({ plugin: 'xray-mod', key: 'viewports' } as const, {})
24
25// --- T1 viewport spike: a demo pane holding one viewport over 500 lines -----
26// The demo pane's tree, top to bottom (row numbers matter for the wheel math):
27// row 0 hint text
28// row 1 blank
29// row 2 viewport title row
30// rows 3.. viewport body (DEMO_HEIGHT rows)
31// then filler rows, so the pane itself has something to scroll
32// Pane ids allow only letters, digits, `_` and `-` (PaneOpenArgs.id); any
33// other character makes $.ui.open reject and the hook calling it fail.
34export const DEMO_PANE = 'xray-mod-viewport-demo'
35const DEMO_KEY = 'demo'
36const DEMO_BODY_TOP = 3
37const DEMO_HEIGHT = 12
38const DEMO_LINES = Array.from(
39 { length: 500 },
40 (_, index) => `demo line ${index + 1}: ${'·'.repeat(index % 40)}|`,
41)
42// The pane's own scroll offset as last passed through ui.scroll; the wheel
43// pointer's row is relative to what the pane shows, so we need it to find the
44// row in the pane's full tree (viewport-model.ts#isOverViewport).
45let demoPaneOffset = 0
46
47// Fold one Intent into the demo viewport's stored state; the atom write
48// redraws the pane, which hands the Client its new slice.
49const applyToDemo = (
50 $: EngineInterface,
51 intent: Intent,
52) =>
53 update($, viewports, all => ({
54 ...all,
55 [DEMO_KEY]: apply(all[DEMO_KEY] ?? INITIAL, intent, DEMO_LINES.length, DEMO_HEIGHT),
56 }))
57
58export const fmt = (n: number): string =>
59 Math.abs(n) >= 1000 ? `${(n / 1000).toFixed(1)}k` : String(n)
60
61const signed = (n: number): string => (n > 0 ? `+${fmt(n)}` : `-${fmt(-n)}`)
62
63// --- T2 attribution spike: tally each source's share of the window ----------
64// Every transcript row passes through the session.append hook below and is
65// classified (attribution.ts); the running tally lives in $.state, so a
66// module reload keeps it. Keyed "source:item", e.g. "skill:plugin-authoring".
67const attribution = atom(
68 { plugin: 'xray-mod', key: 'attribution' } as const,
69 { ledger: EMPTY_LEDGER, tally: {} },
70)
71
72// Fold one row's contributions into the stored tally:
73// 1. classify the row against the stored ledger (links results to calls)
74// 2. add each contribution's chars to its source:item total
75// 3. count a call once, on its first contribution (the tool_use itself)
76// 4. remember whether any of an item's chars were linked by arrival order
77const recordRow = ($: EngineInterface, row: AttributionRow) =>
78 update($, attribution, ({ ledger, tally }) => {
79 const out = classify(row, ledger) // 1
80 const next = { ...tally }
81 for (const part of out.contributions) {
82 const key = `${part.source}:${part.item}`
83 const before = next[key] ?? { source: part.source, item: part.item, chars: 0, calls: 0, isInferred: false }
84 next[key] = {
85 ...before,
86 chars: before.chars + part.chars, // 2
87 calls: before.calls + (part.callId && !ledger.calls[part.callId] ? 1 : 0), // 3
88 isInferred: before.isInferred || part.isInferred === true, // 4
89 }
90 }
91
92 return { ledger: out.ledger, tally: next }
93 })
94
95export const diffRows = (
96 rows: Omit<Row, 'delta'>[],
97 previous: Snapshot | null,
98): Row[] =>
99 rows.map(row => {
100 const before = previous?.rows.find(one => one.name === row.name)
101
102 return { ...row, delta: before ? row.tokens - before.tokens : 0 }
103 })
104
105export const summarize = (rows: Row[]): string =>
106 rows
107 .filter(row => (row.kind === 'used' || row.kind === 'deferred') && Math.abs(row.delta) >= NOISE)
108 .map(row => `${row.name} ${signed(row.delta)}`)
109 .join(', ')
110
111const pushShift = ($: EngineInterface, shift: Shift) =>
112 update($, log, list => [...list, shift].slice(-LOG_SIZE))
113
114const measure = async (
115 $: EngineInterface,
116 detail: 'summary' | 'full',
117 cause: string,
118 isForced = false,
119) => {
120 const usage = await $.session.usage({ breakdown: detail })
121 const b = usage.context.breakdown
122 if (!b) return
123
124 const previous = await read($, snapshot)
125 const rows = diffRows(
126 b.categories.map(c => ({ name: c.name, kind: c.kind, color: c.color, tokens: c.tokens })),
127 previous,
128 )
129
130 const servers = new Map<string, { loaded: number; deferred: number; tokens: number }>()
131 for (const tool of b.mcpTools) {
132 const s = servers.get(tool.serverName) ?? { loaded: 0, deferred: 0, tokens: 0 }
133 if (tool.isLoaded) s.loaded += 1
134 else s.deferred += 1
135 s.tokens += tool.tokens
136 servers.set(tool.serverName, s)
137 }
138
139 const at = await $.clock.now()
140 const next: Snapshot = {
141 at,
142 detail,
143 model: b.model,
144 total: b.totalTokens,
145 max: b.rawMaxTokens,
146 percent: b.percentage,
147 autoCompactAt: b.autoCompactThreshold,
148 rows,
149 memory: [...b.memoryFiles].sort((x, y) => y.tokens - x.tokens),
150 mcp: [...servers].map(([server, s]) => ({ server, ...s })).sort((x, y) => y.tokens - x.tokens),
151 skills: b.skills && {
152 included: b.skills.includedSkills,
153 total: b.skills.totalSkills,
154 tokens: b.skills.tokens,
155 top: [...b.skills.skillFrontmatter]
156 .sort((x, y) => y.tokens - x.tokens)
157 .slice(0, 5)
158 .map(s => ({ name: s.name, tokens: s.tokens })),
159 },
160 agents: b.agents.map(a => ({ name: a.agentType, tokens: a.tokens })),
161 }
162 await update($, snapshot, () => next)
163
164 const changes = summarize(rows)
165 if (changes !== '' || isForced) {
166 await pushShift($, { at, cause, changes: changes || 'no change' })
167 }
168}
169
170// Measurements run one at a time, in order, so each diff is against the last.
171let queue: Promise<void> = Promise.resolve()
172// The countMode setting (plugin.json userConfig), set by register() at each
173// load. It governs the on-open and after-turn counts: exact -> a full
174// breakdown, estimate -> a summary one. Mid-turn counts are always summary.
175let countMode: CountMode = 'exact'
176const settledDetail = () => (countMode === 'exact' ? 'full' : 'summary')
177// Main-thread tool calls since the last measurement, named for the shift log.
178const causes: string[] = []
179
180const enqueue = (
181 $: EngineInterface,
182 detail: 'summary' | 'full',
183 cause: string,
184 isForced = false,
185) => {
186 queue = queue.then(() => measure($, detail, cause, isForced)).catch(() => {})
187}
188
189// A command's reply after opening a pane: the success line only when the pane
190// is actually drawn; otherwise the engine's own reason it waits undrawn
191// (UiOpenResult.reason: no surface attached, one that places no panes, ...).
192const openedText = (opened: UiOpenResult, okText: string): string =>
193 opened.isPlaced ? okText : `Open but not drawn: ${opened.reason}`
194
195const openPane = async ($: EngineInterface) => {
196 const opened = await $.ui.open({ id: PANE, title: TITLE })
197 enqueue($, settledDetail(), 'opened') // the count mode decides estimate vs exact (T4)
198
199 return opened
200}
201
202// What both /xray-mod and /xrm do: open the pane (which starts an exact count).
203// The engine prefixes command output with the plugin name, so the text omits it.
204const openCommand = async ($: EngineInterface) => ({
205 text: openedText(await openPane($), 'Opened; exact count running.'),
206})
207
208export const register: Register = (on, options) => {
209 // The countMode setting (plugin.json userConfig). Changing it, in /config or
210 // with /xray-mod-count, reloads this module, so reading it once here is enough.
211 countMode = toCountMode(options.countMode)
212
213 on('session.start', async ($, e, next) => {
214 await $.command.register({
215 name: 'xray-mod',
216 description: 'Open the context x-ray: every token, traced to its source',
217 })
218 await $.command.register({ name: 'xrm', description: 'Same as /xray-mod' })
219 await $.command.register({
220 name: 'xray-mod-attribution',
221 description: 'Preview the context table: static vs active, per source',
222 })
223 await $.command.register({
224 name: 'xray-mod-viewport-demo',
225 description: 'T1 spike: open a pane with one scrollable viewport over 500 lines',
226 })
227 await $.command.register({
228 name: 'xray-mod-count',
229 description: 'Show or set how xray-mod counts tokens: estimate | exact',
230 })
231
232 return next(e)
233 })
234
235 // /xray-mod-count [estimate|exact]: shows the mode, or sets it through the
236 // engine's config row (xray-mod.countMode), the same one /config shows, so
237 // the setting stays the single source of truth. Setting it reloads the mod.
238 on('command.run', { command: 'xray-mod-count' }, async ($, e) => {
239 const wanted = e.args.trim().toLowerCase()
240 const badges = columnBadges(countMode)
241 if (wanted === '') {
242 return { text: `Count mode: ${countMode} (static ${badges.static}, active ${badges.active}).` }
243 }
244 if (!COUNT_MODES.includes(wanted as CountMode)) {
245 return { text: `Unknown mode "${wanted}". Use: /xray-mod-count ${COUNT_MODES.join(' | ')}` }
246 }
247 await $.config.set({ key: 'xray-mod.countMode', value: wanted })
248
249 return {
250 text:
251 wanted === 'exact'
252 ? 'Count mode: exact. Tool schemas and memory files are counted by the token-count API (one request each); per-call activity stays estimated.'
253 : 'Count mode: estimate. Local estimates only, no API calls.',
254 }
255 })
256
257 on('command.run', { command: 'xray-mod-viewport-demo' }, async $ => {
258 const opened = await $.ui.open({ id: DEMO_PANE, title: 'Viewport spike' })
259
260 return {
261 text: openedText(opened, 'Viewport spike opened: wheel over it, click it then use arrows, try [copy].'),
262 }
263 })
264
265 // Draw the demo pane: hint, the viewport (a Client), then filler.
266 // 1. read this viewport's state (offset, collapsed)
267 // 2. hand the Client only the visible slice of DEMO_LINES
268 // 3. size the Client: title row + body, or the title row alone when collapsed
269 on('ui.render', { component: 'Pane', requestId: DEMO_PANE }, async ($, e) => {
270 const elements = $.ui.resolve(e)
271 const { Box, Text } = elements
272 const state = (await read($, viewports))[DEMO_KEY] ?? INITIAL
273 const props: ViewportProps = {
274 title: 'demo.txt',
275 lines: DEMO_LINES.slice(state.offset, state.offset + DEMO_HEIGHT),
276 startLine: state.offset,
277 total: DEMO_LINES.length,
278 height: DEMO_HEIGHT,
279 collapsed: state.collapsed,
280 }
281
282 return (
283 <Box flexDirection="column">
284 <Text dimColor>Wheel over the viewport scrolls it; elsewhere scrolls the pane.</Text>
285 <Text> </Text>
286 {'Client' in elements ? (
287 <elements.Client
288 key={DEMO_KEY}
289 module="./viewport.tsx"
290 props={props}
291 height={state.collapsed ? 1 : DEMO_HEIGHT + 1}
292 />
293 ) : (
294 // Mobile draws no Client: show the same slice as plain text.
295 props.lines.map((line, index) => <Text key={`line-${index}`}>{line}</Text>)
296 )}
297 {Array.from({ length: 30 }, (_, index) => (
298 <Text key={`filler-${index}`} dimColor>
299 pane filler {index + 1}
300 </Text>
301 ))}
302 </Box>
303 )
304 })
305
306 // The viewport posted an Intent (viewport.tsx). Act on it:
307 // - copy: the FULL text (not just the slice) goes to the clipboard
308 // - expand: pop-out lands in T7; say so instead of doing nothing
309 // - scroll / toggle: fold into the atom, which redraws the pane
310 on('ui.message', async ($, e, next) => {
311 if (e.requestId !== DEMO_PANE || e.element !== DEMO_KEY) return next(e)
312 const intent = e.data as Intent
313
314 if (intent.type === 'copy') {
315 const copied = await $.ui.copy({ text: DEMO_LINES.join('\n'), surface: e.surface })
316 $.ui.toast(copied.isCopied ? `Copied ${DEMO_LINES.length} lines` : `Copy failed: ${copied.reason}`)
317 } else if (intent.type === 'expand') {
318 $.ui.toast('Pop-out arrives in T7')
319 } else {
320 await applyToDemo($, intent)
321 }
322
323 return {}
324 })
325
326 // The wheel reaches the pane, never the Client. A person's tick whose
327 // pointer is over the viewport body scrolls the viewport and the pane stays
328 // put (returning without next() leaves the pane where it is); any other
329 // scroll moves the pane as usual, and we remember where it went.
330 on('ui.scroll', { component: 'Pane', requestId: DEMO_PANE }, async ($, e, next) => {
331 const state = (await read($, viewports))[DEMO_KEY] ?? INITIAL
332 const isOnViewport =
333 e.origin.kind === 'person' &&
334 e.pointer !== undefined &&
335 !state.collapsed &&
336 isOverViewport(demoPaneOffset, e.pointer.row, DEMO_BODY_TOP, DEMO_HEIGHT)
337
338 if (isOnViewport) {
339 await applyToDemo($, { type: 'scroll', by: e.by })
340
341 return {}
342 }
343 demoPaneOffset = e.offset
344
345 return next(e)
346 })
347
348 // Every row on its way into the transcript: let it be stored, then classify
349 // it. Observe only; a failure here must never cost the session a row.
350 on('session.append', async ($, e, next) => {
351 const stored = await next(e)
352 await recordRow($, toRow(e))
353
354 return stored
355 }).catch(($, e, next) => next(e))
356
357 // T3 preview: the two-column table (contributions.ts) built from the live
358 // window and the stored tally, as text until the T5 pane draws it.
359 // 1. read a breakdown: summary (local estimate) or, in exact mode, full
360 // (the engine counts each tool schema and memory file exactly)
361 // 2. build the table: static | active | calls per group, top 3 children;
362 // memory files show their path's tail (display.ts#pathTail)
363 // 3. head each column with its badge; close with the sum check
364 on('command.run', { command: 'xray-mod-attribution' }, async $ => {
365 const { tally } = await read($, attribution)
366 const detail = countMode === 'exact' ? 'full' : 'summary'
367 const breakdown = (await $.session.usage({ breakdown: detail })).context.breakdown
368 if (!breakdown) return { text: 'No breakdown yet: the window has no measured response.' }
369
370 const table = buildTable(breakdown, tally)
371 const badges = columnBadges(countMode)
372 const cell = (tokens: number) => (tokens ? fmt(tokens) : '—').padStart(9)
373 const line = (label: string, row: Node, indent: string) =>
374 `${indent}${label.slice(0, 30 - indent.length).padEnd(30 - indent.length)}${cell(row.static)}${cell(row.active)}` +
375 `${row.calls ? ` ×${row.calls}` : ''}${row.isInferred ? ' ~' : ''}`
376 const lines = table.nodes.flatMap(group => [
377 line(group.label, group, ''),
378 ...group.children
379 .slice(0, 3)
380 .map(child => line(group.key === 'memory' ? pathTail(child.label) : child.label, child, ' ')),
381 ])
382 const sum = table.nodes.reduce((total, group) => total + group.static + group.active, 0)
383
384 return {
385 text:
386 `${`tokens · ${countMode} mode`.padEnd(30)}${'static'.padStart(9)}${'active'.padStart(9)}\n` +
387 `${''.padEnd(30)}${badges.static.padStart(9)}${badges.active.padStart(9)}\n${lines.join('\n')}\n` +
388 `sum ${fmt(sum)} of ${fmt(table.total)} used` +
389 `${table.scale < 1 ? ` · active scaled ×${table.scale.toFixed(2)} to fit Messages` : ''}`,
390 }
391 })
392
393 // /xray-mod and its short alias /xrm share one handler (openCommand, above).
394 on('command.run', { command: 'xray-mod' }, openCommand)
395 on('command.run', { command: 'xrm' }, openCommand)
396
397 // Note which main-thread tools ran; the next model step measures what they
398 // added. A skill's body or a searched tool's schema enters the window after
399 // the tool result, so measuring at the result would miss it.
400 on('tool.call', async ($, e, next) => {
401 const ran = await next(e)
402 if (!e.agentId) {
403 // A tool's arguments sit on the event itself (e.skill, e.query, ...).
404 causes.push(describe(e.tool, e as unknown as Record<string, unknown>))
405 }
406
407 return ran
408 }).catch(($, e, next) => next(e)) // an observer never blocks a tool
409
410 // turn.step streams, so its hook is an async generator forwarding the chunks.
411 on('turn.step', async function* ($, e, next) {
412 if (e.agentId) {
413 // Subagents run in windows of their own: log their steps, don't measure them.
414 await pushShift($, {
415 at: await $.clock.now(),
416 cause: `subagent step ${e.index}`,
417 changes: `${e.messageCount} msgs, own window`,
418 agentId: e.agentId,
419 })
420 } else if (e.index > 0) {
421 // Main thread, mid-turn: everything since the last request is in the window now.
422 const cause = causes.splice(0).join(', ') || 'between requests'
423 enqueue($, 'summary', cause)
424 }
425
426 return yield* next(e)
427 })
428
429 // After each main turn, when the context fill moved: the exact count.
430 // Rate-limit and cost ticks fire this too; a full count there would be waste.
431 on('session.measure', ($, e, next) => {
432 if (e.changed.includes('context')) {
433 enqueue($, settledDetail(), causes.splice(0).join(', ') || 'turn end')
434 }
435
436 return next(e)
437 })
438
439 on('session.compact', async ($, e, next) => {
440 const done = await next(e)
441 if (!e.agentId) enqueue($, 'summary', `compaction (${e.trigger})`, true)
442
443 return done
444 }).catch(($, e, next) => next(e))
445
446 // The opener: a live percentage pill beside the footer's mode labels.
447 on('ui.render', { component: 'SessionMode' }, async ($, e, next) => {
448 const { Box, Button } = $.ui.resolve(e)
449 const snap = await read($, snapshot)
450 const own = await next(e)
451 const label = snap ? `◧ ${snap.percent}%` : '◧ context'
452
453 return (
454 <Box>
455 {own}
456 <Button key="xray-mod" label={label} onPress={() => openPane($)} />
457 </Box>
458 )
459 })
460
461 on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
462 const { Box, Text } = $.ui.resolve(e)
463 const snap = await read($, snapshot)
464 const shifts = await read($, log)
465
466 if (!snap) return <Text dimColor>Measuring…</Text>
467
468 const used = snap.rows.filter(row => row.kind !== 'deferred')
469 const deferred = snap.rows.filter(row => row.kind === 'deferred')
470
471 return (
472 <Box flexDirection="column">
473 <Text bold>
474 {fmt(snap.total)} / {fmt(snap.max)} ({snap.percent}%) · {snap.model}
475 </Text>
476 <Text dimColor>
477 {snap.detail === 'full' ? 'exact count' : 'estimate'}
478 {snap.autoCompactAt ? ` · autocompact at ${fmt(snap.autoCompactAt)}` : ' · autocompact off'}
479 </Text>
480
481 <Text> </Text>
482 {used.map(row => (
483 <Text key={row.name}>
484 <Text color={row.color}>■ </Text>
485 {row.name.padEnd(22)} {fmt(row.tokens).padStart(7)}{' '}
486 {Math.abs(row.delta) >= NOISE && <Text color={row.delta > 0 ? 'warning' : 'success'}>{signed(row.delta)}</Text>}
487 </Text>
488 ))}
489 {deferred.map(row => (
490 <Text key={row.name} dimColor>
491 □ {row.name.padEnd(22)} {fmt(row.tokens).padStart(7)} (outside window)
492 </Text>
493 ))}
494
495 {snap.memory.length > 0 && <Text bold>{'\n'}Memory files</Text>}
496 {snap.memory.slice(0, 6).map(m => (
497 <Text key={m.path} dimColor>
498 {fmt(m.tokens).padStart(6)} {m.type.padEnd(8)} {m.path}
499 </Text>
500 ))}
501
502 {snap.skills && (
503 <Text bold>
504 {'\n'}Skills {snap.skills.included}/{snap.skills.total} listed · {fmt(snap.skills.tokens)}
505 </Text>
506 )}
507 {snap.skills?.top.map(s => (
508 <Text key={s.name} dimColor>
509 {fmt(s.tokens).padStart(6)} {s.name}
510 </Text>
511 ))}
512
513 {snap.mcp.length > 0 && <Text bold>{'\n'}MCP servers</Text>}
514 {snap.mcp.slice(0, 6).map(s => (
515 <Text key={s.server} dimColor>
516 {fmt(s.tokens).padStart(6)} {s.server} ({s.loaded} loaded, {s.deferred} deferred)
517 </Text>
518 ))}
519
520 <Text bold>{'\n'}Shifts</Text>
521 {shifts.length === 0 && <Text dimColor>None yet.</Text>}
522 {[...shifts].reverse().map((s, i) => (
523 <Text key={`${s.at}-${i}`} dimColor={!!s.agentId}>
524 {new Date(s.at).toTimeString().slice(0, 5)} {s.cause} → {s.changes}
525 </Text>
526 ))}
527 </Box>
528 )
529 })
530}
531hooks/attribution.ts 187 lines1// Attribution: which source put each piece of text into the context window.
2//
3// Fed one transcript row at a time from the `session.append` hook
4// (register.tsx), so the ledger grows incrementally and never re-walks the
5// transcript. Pure: no engine calls, so every rule below is unit-tested
6// (attribution.test.ts) against row shapes seen in a real transcript.
7//
8// The flow for one row:
9// 1. toRow() flatten the engine's event into a plain Row (sizes, ids)
10// 2. classify() turn the Row into Contributions, using the Ledger to link
11// a tool's result (and anything it hands over) to its call
12// 3. the caller stores the new Ledger (it is plain JSON, kept in $.state)
13
14import type { Ledger, Source } from '../types'
15
16export type { Ledger, Source }
17
18// --- Shapes -----------------------------------------------------------------
19// Source and Ledger live in the state contract (types/index.d.ts), since the
20// ledger is stored in $.state.
21
22export type Contribution = {
23 source: Source
24 item: string // the row in the table: a tool, skill, server, attachment kind
25 callId?: string // the tool call it belongs to, when there is one
26 chars: number
27 isInferred?: true // linked by arrival order rather than an explicit id
28 agentId?: string // set when the row is in a subagent's own window
29}
30
31// One transcript row, flattened from SessionAppendInput by toRow().
32export type Row = {
33 door: string
34 originKind: string
35 originTool?: string
36 type: string
37 name?: string // an attachment's kind
38 isMeta?: boolean
39 agentId?: string
40 blocks: Block[]
41}
42
43export type Block =
44 | { kind: 'text'; chars: number }
45 | { kind: 'tool_use'; id: string; tool: string; input: Record<string, unknown>; chars: number }
46 | { kind: 'tool_result'; toolUseId: string; chars: number }
47
48export const EMPTY_LEDGER: Ledger = { calls: {} }
49
50// --- Naming -----------------------------------------------------------------
51
52// Names a call by what it touched: which skill, which search, which file.
53// Also the shift log's cause label (register.tsx).
54export const describe = (tool: string, input: Readonly<Record<string, unknown>>): string => {
55 const arg =
56 tool === 'Skill' ? input.skill
57 : tool === 'ToolSearch' ? input.query
58 : tool === 'Agent' ? input.subagent_type
59 : tool === 'Read' ? String(input.file_path ?? '').split(/[\\/]/).pop()
60 : undefined
61
62 return typeof arg === 'string' && arg !== '' ? `${tool}(${arg})` : tool
63}
64
65// Which category a tool's traffic belongs to, and the row it lands on:
66// - Skill -> skill, one row per skill name
67// - Agent -> agent, one row per subagent type
68// - mcp__<server>__<tool> -> mcp, one row per server
69// - anything else -> tool, one row per tool name
70export const sourceFor = (
71 tool: string,
72 input: Readonly<Record<string, unknown>>,
73): { source: Source; item: string } => {
74 if (tool === 'Skill') return { source: 'skill', item: String(input.skill ?? 'unknown') }
75 if (tool === 'Agent') return { source: 'agent', item: String(input.subagent_type ?? 'general-purpose') }
76 const mcp = /^mcp__(.+?)__/.exec(tool)
77 if (mcp) return { source: 'mcp', item: mcp[1] ?? tool }
78
79 return { source: 'tool', item: tool }
80}
81
82// --- Flattening -------------------------------------------------------------
83
84type ContentBlock = { type: string; [key: string]: unknown }
85
86// Character count of a tool_result's content, which is a string or blocks.
87const resultChars = (content: unknown): number =>
88 typeof content === 'string' ? content.length
89 : Array.isArray(content) ? content.reduce((sum: number, block: { text?: unknown }) => sum + String(block.text ?? '').length, 0)
90 : 0
91
92// Flatten a session.append event into a Row:
93// - keep the door, the origin's kind and tool, the attachment name, isMeta
94// - reduce each content block to its size (and ids, for tool traffic)
95// - text and thinking both count as text; images and others are skipped
96export const toRow = (event: {
97 door: string
98 origin: { kind: string; tool?: string }
99 agentId?: string
100 message: { type: string; name?: string; isMeta?: true; content: readonly ContentBlock[] }
101}): Row => ({
102 door: event.door,
103 originKind: event.origin.kind,
104 originTool: event.origin.tool,
105 type: event.message.type,
106 name: event.message.name,
107 isMeta: event.message.isMeta === true,
108 agentId: event.agentId,
109 blocks: event.message.content.flatMap((block): Block[] => {
110 if (block.type === 'text') return [{ kind: 'text', chars: String(block.text ?? '').length }]
111 if (block.type === 'thinking') return [{ kind: 'text', chars: String(block.thinking ?? '').length }]
112 if (block.type === 'tool_use') {
113 const input = (block.input ?? {}) as Record<string, unknown>
114 return [{ kind: 'tool_use', id: String(block.id), tool: String(block.name), input, chars: JSON.stringify(input).length }]
115 }
116 if (block.type === 'tool_result') {
117 return [{ kind: 'tool_result', toolUseId: String(block.tool_use_id), chars: resultChars(block.content) }]
118 }
119
120 return []
121 }),
122})
123
124// --- Classification ---------------------------------------------------------
125
126// Doors with no tool traffic map straight to a source.
127const SOURCE_BY_DOOR: Record<string, Source> = {
128 prompt: 'prompt',
129 attachment: 'injection',
130 'hook-context': 'hook',
131}
132
133const textChars = (row: Row): number =>
134 row.blocks.reduce((sum, block) => sum + (block.kind === 'text' ? block.chars : 0), 0)
135
136// Turn one Row into Contributions, returning the updated Ledger too.
137//
138// 1. Tool calls (assistant rows): each tool_use is registered in the ledger
139// under its id, and its input counts toward that call's item.
140// 2. Tool results: looked up by tool_use_id, so a result always lands on
141// the call that asked for it; it becomes the ledger's lastResultId.
142// 3. Rows a tool hands over beside its result (origin kind `tool`, e.g. a
143// skill's body, which arrives isMeta right after "Launching skill"):
144// no id links them, so they join the last result's call when the tool
145// names match. That link is by arrival order: marked isInferred.
146// 4. Everything else is text by door: prompt, attachment (by its kind),
147// hook context, the model's own text, or `other`.
148export const classify = (row: Row, ledger: Ledger): { contributions: Contribution[]; ledger: Ledger } => {
149 const contributions: Contribution[] = []
150 const calls = { ...ledger.calls }
151 let lastResultId = ledger.lastResultId
152 const add = (contribution: Contribution) =>
153 contributions.push(row.agentId ? { ...contribution, agentId: row.agentId } : contribution)
154
155 for (const block of row.blocks) {
156 if (block.kind === 'tool_use') { // step 1
157 const { source, item } = sourceFor(block.tool, block.input)
158 calls[block.id] = { source, item, tool: block.tool }
159 add({ source, item, callId: block.id, chars: block.chars })
160 } else if (block.kind === 'tool_result') { // step 2
161 const call = calls[block.toolUseId]
162 add(
163 call
164 ? { source: call.source, item: call.item, callId: block.toolUseId, chars: block.chars }
165 : { source: 'tool', item: 'unknown', callId: block.toolUseId, chars: block.chars },
166 )
167 lastResultId = block.toolUseId
168 }
169 }
170
171 const chars = textChars(row)
172 if (chars > 0) {
173 const last = lastResultId ? calls[lastResultId] : undefined
174 if (row.originKind === 'tool' && last && last.tool === row.originTool) { // step 3
175 add({ source: last.source, item: last.item, callId: lastResultId, chars, isInferred: true })
176 } else if (row.door === 'response') { // step 4
177 add({ source: 'assistant', item: 'text', chars })
178 } else {
179 const source = SOURCE_BY_DOOR[row.door] ?? 'other'
180 const item = source === 'injection' ? (row.name ?? 'attachment') : row.door
181 add({ source, item, chars })
182 }
183 }
184
185 return { contributions, ledger: { calls, lastResultId } }
186}
187hooks/contributions.ts 204 lines1// T3 · The contribution model: one table of what fills the context window,
2// split into STATIC overhead (paid on every request) and ACTIVE contributions
3// (what each source has added to the conversation).
4//
5// Two inputs, both already collected elsewhere:
6// - the engine's breakdown ($.session.usage({ breakdown })): the window by
7// category, plus per-item lists (skills, MCP tools, memory files, agents)
8// -> the STATIC column
9// - the attribution tally (attribution.ts via register.tsx#recordRow):
10// characters per source:item since the mod loaded -> the ACTIVE column
11//
12// The flow of buildTable():
13// 1. read the window's used total and its Messages row
14// 2. static: itemize skills / MCP servers / memory files / agents from the
15// breakdown's lists; whatever used, non-Messages tokens remain are the
16// system prompt and built-in tool schemas
17// 3. active: convert tally chars to tokens, then reconcile against Messages
18// (reconcile(), below): scale DOWN if the estimates overshoot, never up
19// 4. whatever Messages holds beyond the tally is its own honest row,
20// "Before xray-mod loaded", instead of being smeared over every item
21// 5. group into nodes, largest first
22// By construction static + active + unattributed = the used total, so the
23// columns add up to what /context reports.
24//
25// Pure: no engine calls, so every rule is unit-tested (contributions.test.ts).
26
27import type { Source, Tally } from '../types'
28
29// The estimate T2 uses; T4 adds an exact mode and the on-screen badge.
30export const CHARS_PER_TOKEN = 4
31
32// The slice of SessionContextBreakdown this model reads (fixtures build it).
33export type BreakdownInput = {
34 categories: { name: string; kind: 'used' | 'free' | 'buffer' | 'deferred'; tokens: number }[]
35 skills?: { skillFrontmatter: { name: string; tokens: number }[] }
36 mcpTools: { serverName: string; tokens: number; isLoaded: boolean }[]
37 memoryFiles: { path: string; tokens: number }[]
38 agents: { agentType: string; tokens: number }[]
39}
40
41// The table's top-level rows. Order here is display order.
42export type Group =
43 | 'system'
44 | 'skill'
45 | 'mcp'
46 | 'memory'
47 | 'agent'
48 | 'tool'
49 | 'injection'
50 | 'conversation'
51 | 'unattributed'
52
53export type Node = {
54 key: string
55 label: string
56 static: number
57 active: number
58 calls: number
59 isInferred: boolean // some of `active` was linked by arrival order (`~`)
60 children: Node[]
61}
62
63export type Table = {
64 nodes: Node[]
65 total: number // the window's used tokens, which the columns sum to
66 scale: number // 1, or < 1 when active estimates were scaled down to fit
67}
68
69const LABELS: Record<Group, string> = {
70 system: 'System prompt & tools',
71 skill: 'Skills',
72 mcp: 'MCP servers',
73 memory: 'Memory files',
74 agent: 'Agents',
75 tool: 'Built-in tools',
76 injection: 'Engine injections',
77 conversation: 'Conversation',
78 unattributed: 'Before xray-mod loaded',
79}
80
81// Which table row a tally source lands in. The conversation row gathers the
82// person's prompts, the model's own text, hook context and notices.
83const GROUP_OF_SOURCE: Record<Source, Group> = {
84 skill: 'skill',
85 mcp: 'mcp',
86 agent: 'agent',
87 tool: 'tool',
88 injection: 'injection',
89 prompt: 'conversation',
90 assistant: 'conversation',
91 hook: 'conversation',
92 other: 'conversation',
93}
94
95// Reconcile estimated active tokens against the real Messages row:
96// - estimates within Messages: keep them (scale 1); the rest is unattributed
97// - estimates above Messages: shrink every item by the same factor so they
98// fit exactly, leaving nothing unattributed
99// Never scale up: a tally that started late must not be inflated to cover
100// conversation it never saw.
101export const reconcile = (knownTokens: number, messages: number): number =>
102 knownTokens > messages && knownTokens > 0 ? messages / knownTokens : 1
103
104const emptyNode = (key: string, label: string): Node => ({
105 key,
106 label,
107 static: 0,
108 active: 0,
109 calls: 0,
110 isInferred: false,
111 children: [],
112})
113
114// Find the child with this label, creating it on first use, so static and
115// active amounts for the same skill (or server, or agent) share one row.
116const childOf = (parent: Node, label: string): Node => {
117 let child = parent.children.find(one => one.label === label)
118 if (!child) {
119 child = emptyNode(`${parent.key}/${label}`, label)
120 parent.children.push(child)
121 }
122
123 return child
124}
125
126// A group's own numbers are the sum of its children, largest child first.
127const rollUp = (node: Node): Node => {
128 if (node.children.length === 0) return node
129 node.children.sort((a, b) => b.static + b.active - (a.static + a.active))
130 node.static = node.children.reduce((sum, child) => sum + child.static, 0)
131 node.active = node.children.reduce((sum, child) => sum + child.active, 0)
132 node.calls = node.children.reduce((sum, child) => sum + child.calls, 0)
133 node.isInferred = node.children.some(child => child.isInferred)
134
135 return node
136}
137
138export const buildTable = (breakdown: BreakdownInput, tally: Readonly<Record<string, Tally>>): Table => {
139 // 1. The window: used tokens in all, and the Messages row within them.
140 // Rows carry no kind for "messages", so this one row is found by name.
141 const used = breakdown.categories.filter(row => row.kind === 'used')
142 const total = used.reduce((sum, row) => sum + row.tokens, 0)
143 const messages = used.find(row => /^messages$/i.test(row.name))?.tokens ?? 0
144
145 const groups = new Map<Group, Node>()
146 const group = (name: Group) => {
147 let node = groups.get(name)
148 if (!node) {
149 node = emptyNode(name, LABELS[name])
150 groups.set(name, node)
151 }
152
153 return node
154 }
155
156 // 2. Static, itemized from the breakdown's own lists.
157 for (const skill of breakdown.skills?.skillFrontmatter ?? []) {
158 childOf(group('skill'), skill.name).static += skill.tokens
159 }
160 for (const tool of breakdown.mcpTools) {
161 if (tool.isLoaded) childOf(group('mcp'), tool.serverName).static += tool.tokens // deferred schemas sit outside the window
162 }
163 for (const file of breakdown.memoryFiles) childOf(group('memory'), file.path).static += file.tokens
164 for (const agent of breakdown.agents) childOf(group('agent'), agent.agentType).static += agent.tokens
165 for (const node of groups.values()) rollUp(node)
166
167 const itemized = [...groups.values()].reduce((sum, node) => sum + node.static, 0)
168 group('system').static = Math.max(0, total - messages - itemized) // system prompt + built-in tool schemas
169
170 // 3. Active, from the tally, reconciled against Messages.
171 const entries = Object.values(tally)
172 const knownTokens = entries.reduce((sum, entry) => sum + entry.chars / CHARS_PER_TOKEN, 0)
173 const scale = reconcile(knownTokens, messages)
174 let attributed = 0
175 for (const entry of entries) {
176 const tokens = Math.round((entry.chars / CHARS_PER_TOKEN) * scale)
177 const target = GROUP_OF_SOURCE[entry.source]
178 // Conversation rows name their source too ("assistant text", "other command"),
179 // except where the two are the same word ("prompt", not "prompt prompt").
180 const label =
181 target !== 'conversation' ? entry.item
182 : entry.item === entry.source ? entry.source
183 : `${entry.source} ${entry.item}`
184 const child = childOf(group(target), label)
185 child.active += tokens
186 child.calls += entry.calls
187 child.isInferred = child.isInferred || entry.isInferred
188 attributed += tokens
189 }
190
191 // 4. What Messages holds beyond the tally: its own row, never smeared.
192 const unattributed = Math.max(0, messages - attributed)
193 if (unattributed > 0) group('unattributed').active = unattributed
194
195 // 5. Roll groups up and order them as LABELS lists them.
196 const order = Object.keys(LABELS) as Group[]
197 const nodes = order.flatMap(name => {
198 const node = groups.get(name)
199 return node ? [rollUp(node)] : []
200 })
201
202 return { nodes, total, scale }
203}
204hooks/display.ts 32 lines1// Display helpers shared by the text preview (/xray-mod-attribution) and the
2// T5 pane. Pure: unit-tested in display.test.ts.
3
4// How the numbers were counted, from the countMode setting (plugin.json
5// userConfig): `estimate` sends no API calls; `exact` asks the engine for a
6// full breakdown, which counts each tool schema and memory file exactly.
7export type CountMode = 'estimate' | 'exact'
8
9export const COUNT_MODES: readonly CountMode[] = ['estimate', 'exact']
10
11// Read the setting defensively: anything unexpected falls back to estimate,
12// the mode that costs nothing.
13export const toCountMode = (value: unknown): CountMode => (value === 'exact' ? 'exact' : 'estimate')
14
15// The signpost over each column, so nobody mistakes an estimate for a count:
16// - static: exact only when the engine counted it (full breakdown)
17// - active: always an estimate; no per-item count exists for a tool's
18// output or a skill's body, so it is never labelled exact
19export const columnBadges = (mode: CountMode): { static: string; active: string } => ({
20 static: mode === 'exact' ? 'exact' : '≈ est.',
21 active: '≈ chars÷4',
22})
23
24// Long paths share their beginnings (every rules file starts
25// C:\Users\...\.claude\rules), so cutting from the right hides the part that
26// differs. Keep the tail instead: the last `segments` parts, prefixed "…".
27export const pathTail = (path: string, segments = 2): string => {
28 const parts = path.split(/[\\/]+/).filter(Boolean)
29
30 return parts.length <= segments ? path : `…/${parts.slice(-segments).join('/')}`
31}
32hooks/viewport-model.ts 122 lines1// Pure viewport logic, shared by the hooks module (register.tsx) and the
2// Client module (viewport.tsx). No engine calls here, so it is unit-testable.
3//
4// Who owns what:
5// - The HOOKS own each viewport's ViewportState (scroll offset, collapsed),
6// kept in the `viewports` atom (types/index.d.ts).
7// - The CLIENT only draws the slice of lines it is handed, and posts Intents
8// (scroll / copy / toggle / expand) back to the hooks.
9// - The mouse wheel never reaches a Client: it arrives at the pane as a
10// `ui.scroll` event, which the hooks redirect here via isOverViewport().
11
12export type ViewportState = { offset: number; collapsed: boolean }
13
14// What the Client asks the hooks to do.
15export type Intent =
16 | { type: 'scroll'; by: number } // move the window by N lines (negative = up)
17 | { type: 'copy' } // put the FULL text on the clipboard
18 | { type: 'toggle' } // collapse <-> expand in place
19 | { type: 'expand' } // pop out into a pane of its own (T7)
20
21// What the hooks hand the Client on each draw: only the visible slice,
22// which keeps props far below the 100k-character Client props cap.
23export type ViewportProps = {
24 title: string
25 lines: string[] // the visible slice only
26 startLine: number // 0-based index of lines[0] in the full text
27 total: number // line count of the full text
28 height: number // body rows the viewport shows when expanded
29 collapsed: boolean
30}
31
32export const INITIAL: ViewportState = { offset: 0, collapsed: false }
33
34// Keep the window inside the text:
35// - never above line 0
36// - never so low that the last page is short (offset <= total - height)
37// - a text shorter than the window always sits at offset 0
38export const clampOffset = (offset: number, total: number, height: number): number =>
39 Math.max(0, Math.min(offset, Math.max(0, total - height)))
40
41// Apply one Intent to a viewport's state, returning the new state:
42// - scroll: shift the offset, then clamp it to the text
43// - toggle: flip collapsed
44// - copy / expand: no state change (the hooks act on them directly)
45export const apply = (
46 state: ViewportState,
47 intent: Intent,
48 total: number,
49 height: number,
50): ViewportState => {
51 if (intent.type === 'scroll') {
52 return { ...state, offset: clampOffset(state.offset + intent.by, total, height) }
53 }
54 if (intent.type === 'toggle') return { ...state, collapsed: !state.collapsed }
55
56 return state
57}
58
59// Translate a key the focused Client received into a scroll Intent:
60// - up/down move one line, pageup/pagedown one window
61// - home/end move by the whole length; clampOffset lands them on the edges
62// - any other key is not ours (null)
63// Key names are the engine's (`up`, `pageup`, ...): ClientKeyEvent.key.
64export const keyToIntent = (key: string, height: number, total: number): Intent | null => {
65 const distanceByKey: Record<string, number> = {
66 up: -1,
67 down: 1,
68 pageup: -height,
69 pagedown: height,
70 home: -total,
71 end: total,
72 }
73
74 return key in distanceByKey ? { type: 'scroll', by: distanceByKey[key] ?? 0 } : null
75}
76
77type Hit = { from: number; to: number; intent: Intent }
78
79// Build the title row's text AND the column range of each clickable control,
80// so the Client can map a pointer click's x to the control under it:
81// 1. arrow + title + "first–last/total" line range
82// 2. append each control label, recording [from, to) columns as we go
83// Example: "▾ transcript 1–12/500 [−] [copy] [⤢]"
84export const titleBar = (
85 title: string,
86 startLine: number,
87 shown: number,
88 total: number,
89 collapsed: boolean,
90): { text: string; hits: Hit[] } => {
91 const controls: [string, Intent][] = [
92 [collapsed ? '[+]' : '[−]', { type: 'toggle' }],
93 ['[copy]', { type: 'copy' }],
94 ['[⤢]', { type: 'expand' }],
95 ]
96 const range = total === 0 ? 'empty' : `${startLine + 1}–${startLine + shown}/${total}`
97 let text = `${collapsed ? '▸' : '▾'} ${title} ${range} `
98 const hits: Hit[] = []
99 for (const [label, intent] of controls) {
100 text += ' '
101 hits.push({ from: text.length, to: text.length + label.length, intent }) // columns this label occupies
102 text += label
103 }
104
105 return { text, hits }
106}
107
108// Does a wheel tick at the pane body's visible `row` land on the viewport body?
109// - pointer rows count from the top of what the pane SHOWS, so add the
110// pane's own scroll offset to get the row in the pane's full tree
111// - the viewport body spans [top, top + height) in that tree
112export const isOverViewport = (
113 paneOffset: number,
114 row: number,
115 top: number,
116 height: number,
117): boolean => {
118 const treeRow = paneOffset + row
119
120 return treeRow >= top && treeRow < top + height
121}
122hooks/viewport.tsx 53 lines1import type { ClientModule } from 'claude-code'
2
3import { keyToIntent, titleBar } from './viewport-model'
4import type { ViewportProps } from './viewport-model'
5
6// The reusable mini-viewport: a Client surface module.
7//
8// It is deliberately dumb. Each draw it:
9// 1. builds the title row (and the click ranges of its controls) from props
10// 2. (re)binds the key and pointer listeners so they see this draw's props
11// 3. draws the title plus the visible slice of lines, with a line gutter
12// It keeps no scroll state of its own: every change is posted to the hooks
13// (register.tsx, the `ui.message` hook), which update the `viewports` atom
14// and redraw this instance with its next slice. See viewport-model.ts.
15const Viewport: ClientModule<ViewportProps> = (props, surface) => {
16 const { Box, Text } = surface.elements
17 const bar = titleBar(props.title, props.startLine, props.lines.length, props.total, props.collapsed)
18
19 // Keys arrive only while a click has given this instance the focus.
20 surface.onKey(event => {
21 const intent = keyToIntent(event.key, props.height, props.total)
22 if (intent) surface.post(intent)
23 })
24
25 // Clicks on the title row (y = 0) hit the controls by column range.
26 surface.onPointer(event => {
27 if (event.type !== 'down' || event.y !== 0) return
28 const hit = bar.hits.find(one => event.x >= one.from && event.x < one.to)
29 if (hit) surface.post(hit.intent)
30 })
31
32 // Gutter: right-aligned 1-based line numbers, as wide as the largest one.
33 // Lines are cut to the region's width so one long line never wraps into two
34 // rows, which would throw off the hooks' row math (isOverViewport).
35 const gutterWidth = String(props.total).length
36 const width = surface.columns > 0 ? surface.columns : 200 // 0 before the first layout
37 const textWidth = Math.max(1, width - gutterWidth - 3) // 3 = " │ "
38 const body = props.collapsed
39 ? []
40 : props.lines.map((line, index) =>
41 Text({
42 children: `${String(props.startLine + index + 1).padStart(gutterWidth)} │ ${line.slice(0, textWidth)}`,
43 }),
44 )
45
46 return Box({
47 flexDirection: 'column',
48 children: [Text({ bold: true, children: bar.text }), ...body],
49 })
50}
51
52export default Viewport
53types/index.d.ts 69 lines1export type Row = {
2 name: string
3 kind: 'used' | 'free' | 'buffer' | 'deferred'
4 color: string
5 tokens: number
6 delta: number
7}
8
9export type Snapshot = {
10 at: number
11 detail: 'summary' | 'full'
12 model: string
13 total: number
14 max: number
15 percent: number
16 autoCompactAt?: number
17 rows: Row[]
18 memory: { path: string; type: string; tokens: number }[]
19 mcp: { server: string; loaded: number; deferred: number; tokens: number }[]
20 skills?: { included: number; total: number; tokens: number; top: { name: string; tokens: number }[] }
21 agents: { name: string; tokens: number }[]
22}
23
24export type Shift = {
25 at: number
26 cause: string
27 changes: string
28 agentId?: string
29}
30
31// The state contract must be self-contained (no imports), so the attribution
32// types stored in $.state are declared here and hooks/attribution.ts imports
33// them from this file.
34
35// Where a contribution came from; the table's top-level categories (T3).
36export type Source =
37 | 'prompt' // what the person typed
38 | 'assistant' // the model's own text and thinking
39 | 'tool' // a built-in tool's call input and result
40 | 'skill' // a Skill call, its result, and the skill body it loads
41 | 'agent' // an Agent call and the subagent's report
42 | 'mcp' // an MCP tool's call and result, grouped by server
43 | 'injection' // an engine attachment: memory, reminders, tool deltas, ...
44 | 'hook' // context a settings hook added
45 | 'other' // notices, commands, deliveries, compaction rows
46
47// What attribution.ts#classify remembers between rows: each call's identity,
48// and the call whose result landed most recently.
49export type Ledger = {
50 calls: Record<string, { source: Source; item: string; tool: string }>
51 lastResultId?: string
52}
53
54// One source:item's running total of what it put into the window.
55export type Tally = { source: Source; item: string; chars: number; calls: number; isInferred: boolean }
56
57export type ViewportState = { offset: number; collapsed: boolean }
58
59declare module 'claude-code' {
60 interface PluginState {
61 'xray-mod': {
62 snapshot: Snapshot | null
63 log: Shift[]
64 attribution: { ledger: Ledger; tally: Record<string, Tally> }
65 viewports: Record<string, ViewportState>
66 }
67 }
68}
69