Line under the prompt input, a band above the prompt on the desktop: context meter, cache expiry, single-call streak, 5h limit, session time, turns and cost…

From a business need to tested, audited code — Claude Code does the work, you make the decisions.
cctoolkit is a Claude Code plugin for DDD / clean-architecture repos. You describe a feature; Claude writes the spec with you, plans it, then builds it batch by batch under strict TDD and audits the result before you commit. What the product does is kept in a business knowledge base beside the code, so every new spec starts from it.
.NET first; Python, Java/Kotlin and TypeScript repos work through their layout and test tags.
claude plugin marketplace add pierrebelin/claude-code-toolkit --scope project
claude plugin install cctoolkit@cctoolkit --scope project
Restart Claude Code, then run /cctoolkit:kit-init: it reads your repo, asks a few questions and sets everything up.
Requirements, options and what kit-init writes: INSTALL.md.
Three commands, one per step. Each one writes a file the next one reads.
flowchart LR
S["<b>1. Spec</b><br/>/business-spec"] -->|SPEC.md| P["<b>2. Plan</b><br/>/plan-implementation"]
P -->|"PLAN.md + one sheet per batch"| R["<b>3. Build</b><br/>/run-plan or /run-lot"]
R -->|"code, tests, report"| C(["you review and commit"])
/cctoolkit:business-spec — Claude asks you one question at a time, then writes a short business spec: rules, use cases, no technical detail. A second agent tries to poke holes in it./cctoolkit:plan-implementation — turns the spec into a technical plan, split into small batches.| Whole plan | Batch by batch | |
|---|---|---|
| Command | /cctoolkit:run-plan <plan> | /cctoolkit:run-lot <sheet> |
| Runs | every batch, in dependency order | one batch |
| You step in | once, at the end | after each batch: review, /clear, next |
| Stops | a batch that cannot pass is set aside, only its dependents wait; batches set aside for one shared cause stop the plan | the batch comes back DONE, or with what needs your eyes |
| Fits | a plan you trust, a run over lunch or overnight | a new plan, a tricky batch, a team that reviews every commit |
Whole plan runs the batches in the order the plan allows. Nothing waits for you: an ambiguity is decided by the agent that meets it, and what was decided without you opens the run report, to read after the plan. A batch that still cannot pass is set aside with its partial work saved, the next run picking it up where it stopped, and the batches that do not depend on it carry on. Each batch that passes gets its own commit; you review them together at the end.
Batch by batch keeps you in the loop: each batch ends on a report and its own commit, you read it and start the next one with a clean context.
On a new plan, or a batch you are unsure of, go batch by batch until the first ones come back clean.
Inside run-lot, each behaviour of the batch is one loop:
flowchart LR
I["run-lot"] --> R
I -->|"compact contract:<br/>RM/CU, scenario, signatures,<br/>invariants, expected cost"| A["tdd-cycle subagent"]
A --> R["RED<br/>writes the red test"]
R --> K["checkpoint<br/>the hook checks the disk:<br/>red, on an assertion"]
K --> G["GREEN + REFACTOR<br/>writes the production code"]
G -->|"green + cost stated<br/>or BLOCKED"| I
I -.->|"next behaviour"| A
I ==>|"whole batch green"| V["audit<br/>ddd-tdd-auditor"]
The orchestrator writes neither tests nor code: it splits the work, checks the reports and settles the design. One agent per behaviour writes the failing test, passes a checkpoint read off the disk, then makes it pass; a test it changes after that checkpoint is recorded with its assertions and judged by the audit. Another agent audits.
A batch that stops short: fix the cause and run /cctoolkit:run-lot on the same sheet again, it resumes from the cycles already done. /cctoolkit:implement-tdd launches the chain from a plan path, /cctoolkit:verify-ddd-tdd audits a batch on demand.
Want to see the files? examples/ walks one small feature from spec to report.
What the product does and why lives in the repo, under docs/business/ by default: one folder per bounded context, one file per use case with its rules, the business decisions, the ADRs, and a history of every change. Each use case, rule and decision has a global id (CAT-RM-003) that the specs and plans cite.
flowchart LR
K[("knowledge base")] -->|read by levels| S["/business-spec<br/>writes a delta"]
S --> P["plan, build"]
P -->|"plan delivered:<br/>merge staged"| M["/knowledge-merge<br/>you confirm"]
M --> K
H["code changed<br/>outside the kit"] -->|"/knowledge-sync"| K
/cctoolkit:knowledge-sync builds the base from your code the first time, then catches up with what changed outside the kit. Nothing is written until you confirm./cctoolkit:business-spec reads the base first and writes the spec as a delta: what the feature adds, changes or retires.run-plan stages the merge; /cctoolkit:knowledge-merge shows the diff and writes it on your word./cctoolkit:ask answers how the product behaves, or why, from the base, each fact cited by its id.The base is plain Markdown, so you can review and commit it like code. The worked example is under examples/docs/business/.
A batch takes tens of minutes and a dozen agents, a whole plan several times that. The run-lot-pane mod shows it live inside Claude Code. On a plan, it opens on the plan: each batch with its state, time and tokens, and the supervisor checking between batches.

Open a batch and it shows each phase, which agent is working, the tests going red then green, the tokens spent, and the final verdict. The pane also steers the run: review what it decided without you, leave a note for a batch's agents (keys).

claude plugin install run-lot-pane@cctoolkit --scope project
Two more mods — a browser of the knowledge base that spends no model context and shows the spec live as it's written, and a context meter telling you when to /clear: mods/README.md.
This kit encodes one way of working. It will:
DONE batch, nothing else — the workflow commits the batch files only, your earlier changes stay out; never a push.If your team works differently, half of it will feel like noise. Full list: skills/README.md.
| Install, update, dependencies | INSTALL.md |
| A feature from spec to report | examples/ |
| The knowledge base's format | knowledge-format.md |
| Every skill and agent | skills/README.md |
| Layouts and configuration | presets/README.md |
MIT. Take what you want, closed-source projects included.
hooks/register.tsx 620 lines1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, Register, SessionMessage } from 'claude-code'
3
4import type { Band, Contribution } from '../types'
5
6const STEP_TOKENS = 150_000
7const CEILING_TOKENS = 250_000
8const CACHE_TTL_MS = 60 * 60 * 1000
9const CACHE_WARN_MS = 10 * 60 * 1000
10const CACHE_RELEVANT_TOKENS = 30_000
11const STREAK_SHOWN = 3
12const SPARK_TURNS = 12
13const TOP_TURNS = 5
14const TOP_SHOWN = 2
15const TOGGLE_GAP = 3
16const LIST_ROWS = 10
17const METER_CELLS = 8
18// The terminal sets its groups apart by space, not by a rule: a `│` between every figure read as noise.
19const GROUP = ' '
20const LABEL_CELLS = 18
21const TERMINAL_LABEL = 15
22const TOP_LABEL = 36
23const TOP_FIGURE = 6
24const FIVE_HOUR = 'five_hour'
25const HINT_INDENT = 4
26const CHARS_PER_TOKEN = 4
27const TICK_MS = 15_000
28const GRAPHIFY_LOCK = '/tmp/graphify-autosync.lock'
29const GRAPHIFY_LOCK_NAME = 'graphify-autosync.lock'
30const HOOKS_LABEL = 'hook reminders'
31const TEXT_LABEL = 'text'
32
33const EMPTY: Band = {
34 startedAt: 0,
35 readings: [],
36 window: 0,
37 lastTurnAt: null,
38 streak: 0,
39 turn: 0,
40 contributions: [],
41 cost: null,
42 fiveHour: null,
43}
44
45const band = atom({ plugin: 'context-band', key: 'band' } as const, EMPTY)
46const now = atom({ plugin: 'context-band', key: 'now' } as const, 0)
47const isRebuilding = atom({ plugin: 'context-band', key: 'isRebuilding' } as const, false)
48const isExpanded = atom({ plugin: 'context-band', key: 'isExpanded' } as const, false)
49
50const complete = (stored: Band): Band => ({ ...EMPTY, ...stored })
51
52export const kilo = (tokens: number): string => {
53 if (tokens >= 1_000_000) return `${Number((tokens / 1_000_000).toFixed(1))}M`
54 if (tokens >= 1000) return `${(tokens / 1000).toFixed(1)}k`
55 return `${tokens}`
56}
57
58// Colour tells a state, never a name: nothing below 100k, amber from there, red past the 250k ceiling.
59export const tokenColor = (tokens: number): 'warning' | 'error' | undefined => {
60 if (tokens >= CEILING_TOKENS) return 'error'
61 if (tokens >= STEP_TOKENS - 50_000) return 'warning'
62 return undefined
63}
64
65export const stepLabel = (tokens: number): string => {
66 if (tokens >= CEILING_TOKENS) return '250k ceiling passed: /clear with a handoff note'
67 if (tokens >= STEP_TOKENS) return '150k step reached: /clear at the end of the phase (ceiling 250k)'
68 return `/clear advised in ${kilo(STEP_TOKENS - tokens)} (step 150k, ceiling 250k)`
69}
70
71export type CacheState = { label: string; color?: string; detail?: string } | null
72
73export const cacheState = (lastTurnAt: number | null, at: number, tokens: number): CacheState => {
74 if (lastTurnAt === null || tokens < CACHE_RELEVANT_TOKENS) return null
75 const left = CACHE_TTL_MS - (at - lastTurnAt)
76 if (left <= 0) {
77 return { label: 'Cache expired', color: 'red', detail: `next turn rereads ${kilo(tokens)} at full price` }
78 }
79 const minutes = Math.ceil(left / 60_000)
80 return {
81 label: `Cache (${minutes}m)`,
82 color: left < CACHE_WARN_MS ? 'yellow' : undefined,
83 }
84}
85
86export const nextStreak = (streak: number, toolsInStep: number): number => {
87 if (toolsInStep === 1) return streak + 1
88 if (toolsInStep > 1) return 0
89 return streak
90}
91
92export const estimate = (chars: number): number => Math.round(chars / CHARS_PER_TOKEN)
93
94const basename = (path: unknown): string =>
95 typeof path === 'string' ? (path.split(/[\\/]/).pop() ?? path) : ''
96
97const clip = (text: unknown, length: number): string => {
98 if (typeof text !== 'string') return ''
99 const line = text.replace(/\s+/g, ' ').trim()
100 return line.length > length ? `${line.slice(0, length - 1)}…` : line
101}
102
103const host = (url: unknown): string =>
104 typeof url === 'string' ? (url.replace(/^https?:\/\//, '').split('/')[0] ?? '') : ''
105
106export const callLabel = (tool: string, input: Record<string, unknown>): string => {
107 switch (tool) {
108 case 'Read':
109 case 'Edit':
110 case 'Write':
111 return `${tool} ${basename(input.file_path)}`
112 case 'NotebookEdit':
113 return `${tool} ${basename(input.notebook_path)}`
114 case 'Bash':
115 return `Bash ${clip(input.description ?? input.command, 20)}`
116 case 'Grep':
117 case 'Glob':
118 return `${tool} ${clip(input.pattern, 24)}`
119 case 'Agent':
120 return `Agent ${clip(input.description ?? input.subagent_type, 28)}`
121 case 'Skill':
122 return `Skill ${clip(input.skill, 24)}`
123 case 'WebFetch':
124 return `WebFetch ${clip(host(input.url), 24)}`
125 default:
126 return tool
127 }
128}
129
130export const topContributions = (
131 contributions: Contribution[],
132 sinceTurn: number,
133 count: number,
134): { label: string; tokens: number }[] => {
135 const totals = new Map<string, number>()
136 for (const one of contributions) {
137 if (one.turn < sinceTurn) continue
138 totals.set(one.label, (totals.get(one.label) ?? 0) + one.tokens)
139 }
140 return [...totals.entries()]
141 .map(([label, tokens]) => ({ label, tokens }))
142 .filter(one => one.tokens > 0)
143 .sort((a, b) => b.tokens - a.tokens)
144 .slice(0, count)
145}
146
147export const replay = (
148 messages: readonly SessionMessage[],
149): { turn: number; streak: number; contributions: Contribution[] } => {
150 let turn = 0
151 let streak = 0
152 let contributions: Contribution[] = []
153 let toolsInStep = 0
154 for (const message of messages) {
155 if (message.role === 'user') {
156 streak = nextStreak(streak, toolsInStep)
157 toolsInStep = 0
158 }
159 const isPrompt = message.role === 'user' && message.text !== '' && (message.toolResults ?? []).length === 0
160 if (isPrompt) turn += 1
161 if (turn === 0) continue
162 if (message.text !== '') contributions.push({ turn, label: TEXT_LABEL, tokens: estimate(message.text.length) })
163 if (message.role !== 'assistant') continue
164 toolsInStep += message.toolUses.length
165 for (const use of message.toolUses) {
166 contributions.push({
167 turn,
168 label: callLabel(use.tool, use.input),
169 tokens: estimate(JSON.stringify(use.input).length + (use.text ?? '').length),
170 })
171 }
172 }
173 streak = nextStreak(streak, toolsInStep)
174 contributions = contributions.filter(one => one.turn > turn - TOP_TURNS)
175 return { turn, streak, contributions }
176}
177
178export const calibrate = (
179 calls: { label: string; tokens: number }[],
180 delta: number | null,
181): { calls: { label: string; tokens: number }[]; text: number } => {
182 const measured = calls.reduce((sum, one) => sum + one.tokens, 0)
183 if (delta === null || delta <= 0) return { calls, text: 0 }
184 if (measured <= delta) return { calls, text: delta - measured }
185 const ratio = delta / measured
186 return { calls: calls.map(one => ({ ...one, tokens: Math.round(one.tokens * ratio) })), text: 0 }
187}
188
189export const meter = (percent: number): string => {
190 const filled = Math.min(METER_CELLS, Math.max(0, Math.floor((percent * METER_CELLS) / 100)))
191 return '█'.repeat(filled) + '░'.repeat(METER_CELLS - filled)
192}
193
194// A meter's state: green at rest, amber from 60 %, red from 85 %.
195export const meterColor = (percent: number): 'success' | 'warning' | 'error' => {
196 if (percent >= 85) return 'error'
197 if (percent >= 60) return 'warning'
198 return 'success'
199}
200
201// The cache's named colours, read as the theme's status keys on the terminal.
202const THEMED: Record<string, string> = { red: 'error', yellow: 'warning' }
203
204// A contributor's row: its label cut to a column, its tokens right-aligned beside it, the rows of a list aligned.
205export const topLine = (label: string, tokens: number, width: number): { label: string; tokens: string } => {
206 const room = Math.max(4, width)
207 const cut = label.length > room ? `${label.slice(0, room - 1)}…` : label
208 return { label: cut.padEnd(room), tokens: kilo(tokens).padStart(TOP_FIGURE) }
209}
210
211export const span = (ms: number): string => {
212 const minutes = Math.floor(Math.max(0, ms) / 60_000)
213 if (minutes < 1) return `${Math.floor(Math.max(0, ms) / 1000)}s`
214 if (minutes < 60) return `${minutes}m`
215 return `${Math.floor(minutes / 60)}h${minutes % 60}m`
216}
217
218export const dollars = (usd: number): string => `$${usd.toFixed(2)}`
219
220async function recordStep($: EngineInterface, tools: number): Promise<void> {
221 await update($, band, current => {
222 const full = complete(current)
223 return { ...full, streak: nextStreak(full.streak, tools) }
224 })
225}
226
227export const register: Register = on => {
228 let toolsInStep = 0
229 let pending: { label: string; tokens: number }[] = []
230
231 on('session.start', async ($, e, next) => {
232 // graphify-autosync.sh takes its lock in Git Bash's /tmp, which on Windows is
233 // %TEMP%: the engine would read `/tmp` as `C:\tmp`.
234 const temp = /^[A-Za-z]:/.test($.plugin.root) ? await $.env.get('TEMP') : undefined
235 const lock = temp === undefined ? GRAPHIFY_LOCK : `${temp}\\${GRAPHIFY_LOCK_NAME}`
236 const tick = async () => {
237 const at = await $.clock.now()
238 await update($, now, () => at)
239 const isLocked = await $.fs.exists(lock)
240 await update($, isRebuilding, () => isLocked)
241 }
242 $.clock.every(TICK_MS, () => void tick())
243 await tick()
244
245 const result = await next(e)
246 if (complete(await read($, band)).turn === 0) {
247 const usage = await $.session.usage()
248 const replayed = replay(await $.session.messages())
249 const tokens = usage.context.tokens
250 await update($, band, () => ({
251 ...EMPTY,
252 ...replayed,
253 startedAt: usage.startedAt,
254 window: usage.context.window,
255 readings: tokens === undefined || replayed.turn === 0 ? [] : [tokens],
256 cost: usage.cost?.usd ?? null,
257 }))
258 }
259
260 return result
261 })
262
263 on('tool.call', async ($, e, next) => {
264 if (e.agentId !== undefined) return next(e)
265 toolsInStep += 1
266 const result = await next(e)
267 const input = e as unknown as Record<string, unknown>
268 const output = typeof result.deny === 'string' ? result.deny : (result.text ?? '')
269 pending.push({
270 label: callLabel(e.tool, input),
271 tokens: estimate(JSON.stringify(input).length + output.length),
272 })
273 const reminders = (result.context ?? []).reduce((sum, one) => sum + one.length, 0)
274 if (reminders > 0) pending.push({ label: HOOKS_LABEL, tokens: estimate(reminders) })
275
276 return result
277 })
278
279 on('turn.step', async function* ($, e, next) {
280 if (e.agentId === undefined && e.index > 0) {
281 await recordStep($, toolsInStep)
282 toolsInStep = 0
283 }
284
285 return yield* next(e)
286 })
287
288 on('turn.complete', async ($, e, next) => {
289 const result = await next(e)
290 if (e.agentId !== undefined) return result
291 await recordStep($, toolsInStep)
292 toolsInStep = 0
293 const calls = pending
294 pending = []
295 const usage = await $.session.usage()
296 const at = await $.clock.now()
297 const tokens = usage.context.tokens
298 await update($, band, stored => {
299 const current = complete(stored)
300 const base = current.startedAt === usage.startedAt ? current : { ...EMPTY, startedAt: usage.startedAt }
301 const cost = usage.cost?.usd ?? base.cost
302 const limit = usage.rateLimits.find(one => one.kind === FIVE_HOUR)
303 const resetsAt = limit?.resetsAt === undefined ? null : Date.parse(limit.resetsAt)
304 const fiveHour = limit === undefined ? base.fiveHour : { percent: limit.percentUsed, resetsAt }
305 if (tokens === undefined) return { ...base, cost, fiveHour, lastTurnAt: at }
306 const turn = base.turn + 1
307 const previous = base.readings[base.readings.length - 1]
308 const calibrated = calibrate(calls, previous === undefined ? null : tokens - previous)
309 const added: Contribution[] = [
310 ...calibrated.calls.map(one => ({ turn, ...one })),
311 ...(calibrated.text > 0 ? [{ turn, label: TEXT_LABEL, tokens: calibrated.text }] : []),
312 ]
313 return {
314 ...base,
315 turn,
316 cost,
317 fiveHour,
318 window: usage.context.window,
319 readings: [...base.readings, tokens].slice(-SPARK_TURNS),
320 contributions: [...base.contributions, ...added].filter(one => one.turn > turn - TOP_TURNS),
321 lastTurnAt: at,
322 }
323 })
324 await update($, now, () => at)
325
326 return result
327 })
328
329 // The terminal draws the band beside the prompt's hint line; a desktop draws no tail there,
330 // so it goes into the band above the prompt, which the surface stacks plugin by plugin.
331 on('ui.render', { component: 'PromptHint' }, async ($, e, next) => {
332 const state = complete(await read($, band))
333 if (state.readings.length === 0 || e.surface === 'desktop') return next(e)
334 const columns = e.viewport === undefined ? undefined : Math.max(0, e.viewport.columns - HINT_INDENT)
335 return contextView($, e, state, e.props.isWorking, columns, await next(e))
336 })
337
338 on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
339 const state = complete(await read($, band))
340 if (state.readings.length === 0 || e.surface !== 'desktop' || e.props.hasSurvey) return next(e)
341 return desktopView($, e, state, e.props.isWorking)
342 })
343}
344
345// The desktop draws in a proportional face: block-glyph meters and `│` rules read as noise there.
346// It gets drawn bars, the theme's status colours, a type scale and spacing instead of separators.
347const BAR = { width: 64, height: 6 } as const
348// A translucent grey: the details' surface reads on a light or a dark theme alike, no frame needed.
349const SURFACE = '#80808014'
350// A figure that asks for attention (the /clear step reached, the 5-hour limit or the cache running out) takes its
351// tone on its own text and bar, never on a box around it: the band stays one plain line.
352const BAR_INK = { ok: '#3fa66b', warning: '#d99a1e', high: '#d4652c', critical: '#d64545' } as const
353
354const tone = (percent: number): keyof typeof BAR_INK => {
355 if (percent >= 85) return 'critical'
356 if (percent >= 60) return 'warning'
357 return 'ok'
358}
359
360const tokenTone = (tokens: number): keyof typeof BAR_INK | null => {
361 if (tokens >= CEILING_TOKENS) return 'critical'
362 if (tokens >= STEP_TOKENS) return 'high'
363 if (tokens >= STEP_TOKENS - 50_000) return 'warning'
364 return null
365}
366
367const THEME_OF: Record<keyof typeof BAR_INK, string> = { ok: 'success', warning: 'warning', high: 'warning', critical: 'error' }
368
369export const barSource = (percent: number, ink: string): string => {
370 const { width, height } = BAR
371 const filled = Math.round((Math.min(100, Math.max(0, percent)) * width) / 100)
372 const radius = height / 2
373 return `<svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="${height}" viewBox="0 0 ${width} ${height}">`
374 + `<rect width="${width}" height="${height}" rx="${radius}" fill="${ink}" fill-opacity="0.18"/>`
375 + (filled > 0 ? `<rect width="${Math.max(filled, height)}" height="${height}" rx="${radius}" fill="${ink}"/>` : '')
376 + '</svg>'
377}
378
379async function desktopView(
380 $: EngineInterface,
381 e: Parameters<EngineInterface['ui']['resolve']>[0],
382 state: Band,
383 isWorking: boolean,
384): Promise<JSX.Element> {
385 const elements = $.ui.resolve(e)
386 const { Box, Button, Text } = elements
387 const Svg = 'Svg' in elements ? elements.Svg : undefined
388 const at = await read($, now)
389 const tokens = state.readings[state.readings.length - 1] ?? 0
390 const percent = state.window > 0 ? Math.round((tokens * 100) / state.window) : null
391 const stepTone = tokenTone(tokens)
392 const cache = isWorking ? null : cacheState(state.lastTurnAt, at, tokens)
393 const rebuilding = await read($, isRebuilding)
394 const grouping = state.streak >= STREAK_SHOWN
395 const limit = state.fiveHour
396 const resetIn = limit?.resetsAt == null || limit.resetsAt <= at ? null : span(limit.resetsAt - at)
397 const turns = Math.min(TOP_TURNS, state.turn)
398 const all = topContributions(state.contributions, state.turn - TOP_TURNS + 1, Number.MAX_SAFE_INTEGER)
399 const expanded = await read($, isExpanded)
400 const shown = all.slice(0, LIST_ROWS)
401 const cacheTone = cache?.color === 'red' ? 'error' : cache?.color === 'yellow' ? 'warning' : undefined
402
403 const bar = (key: string, value: number, ink: keyof typeof BAR_INK, alt: string) =>
404 Svg === undefined ? null : <Svg key={key} source={barSource(value, BAR_INK[ink])} alt={alt} width={BAR.width} height={BAR.height} />
405 const label = (text: string) => <Text size="footnote" dimColor>{text}</Text>
406 const metric = (key: string, children: (JSX.Element | null)[]) => (
407 <Box key={key} flexDirection="row" alignItems="center" gap="xs" flexShrink={0}>
408 {children}
409 </Box>
410 )
411 const detail = (key: string, name: string, value: JSX.Element) => (
412 <Box key={key} flexDirection="row" gap="sm">
413 <Box width={LABEL_CELLS} flexShrink={0}>{label(name)}</Box>
414 <Box flexGrow={1} flexShrink={1}>{value}</Box>
415 </Box>
416 )
417
418 const metrics = [
419 metric('context', [
420 label('Context'),
421 ...(percent === null ? [] : [bar('context-bar', percent, stepTone ?? tone(percent), `context ${percent}% full`)]),
422 <Text key="tokens" size="footnote" tabular weight={stepTone === null ? 'medium' : 'semibold'} color={stepTone === null ? undefined : THEME_OF[stepTone]}>
423 {kilo(tokens)}
424 </Text>,
425 ...(state.window > 0 ? [<Text key="window" size="footnote" tabular dimColor>/ {kilo(state.window)}</Text>] : []),
426 ]),
427 ...(limit === null ? [] : [metric('limit', [
428 label('5h limit'),
429 bar('limit-bar', limit.percent, tone(limit.percent), `5-hour limit ${Math.round(limit.percent)}% used`),
430 <Text key="limit-percent" size="footnote" tabular color={tone(limit.percent) === 'ok' ? undefined : THEME_OF[tone(limit.percent)]}>
431 {`${Math.round(limit.percent)}%`}
432 </Text>,
433 ...(resetIn === null ? [] : [<Text key="reset" size="footnote" tabular dimColor>{`resets ${resetIn}`}</Text>]),
434 ])]),
435 ...(cache === null ? [] : [metric('cache', [
436 <Text key="cache" size="footnote" tabular color={cacheTone} dimColor={cacheTone === undefined}>{cache.label}</Text>,
437 ])]),
438 ...(grouping ? [metric('streak', [<Text key="streak" size="footnote" color="warning">{`${state.streak} single-call turns`}</Text>])] : []),
439 ...(rebuilding ? [metric('graph', [<Text key="graph" size="footnote" dimColor>graph rebuilding</Text>])] : []),
440 metric('session', [
441 <Text key="session" size="footnote" tabular dimColor>
442 {`${span(at - state.startedAt)} · ${state.turn} turn${state.turn > 1 ? 's' : ''}`}
443 </Text>,
444 ...(state.cost === null ? [] : [<Text key="cost" size="footnote" tabular weight="medium">{dollars(state.cost)}</Text>]),
445 ]),
446 ]
447
448 return (
449 <Box flexDirection="column" gap="xs" paddingX="xs">
450 <Box flexDirection="row" alignItems="center" gap="md">
451 <Box flexDirection="row" flexWrap="wrap" alignItems="center" columnGap="md" rowGap="xs" flexGrow={1} flexShrink={1}>
452 {metrics}
453 </Box>
454 <Button
455 key="top-toggle"
456 label={expanded ? 'Hide details' : 'Details'}
457 plain
458 dimColor
459 onPress={() => update($, isExpanded, value => !value)}
460 />
461 </Box>
462 {expanded && (
463 <Box flexDirection="column" gap="xs" paddingX={2} paddingY="sm" backgroundColor={SURFACE}>
464 {detail('step', 'Next /clear', (
465 <Text size="footnote" color={stepTone === null ? undefined : THEME_OF[stepTone]}>{stepLabel(tokens)}</Text>
466 ))}
467 {cache?.detail !== undefined && detail('cache', 'Cache', <Text size="footnote" color={cacheTone}>{cache.detail}</Text>)}
468 {grouping && detail('batch', 'Batching', (
469 <Text size="footnote" color="warning">
470 {`${state.streak} turns with a single tool call: send independent calls together (each turn resends the whole context)`}
471 </Text>
472 ))}
473 {all.length > 0 && detail('top', `Top ${turns === 1 ? 'last turn' : `${turns} turns`}`, (
474 <Box flexDirection="column">
475 {shown.map((one, index) => (
476 <Box key={`top-${index}`} flexDirection="row" gap="sm">
477 <Box flexGrow={1} flexShrink={1}><Text size="footnote" wrap="truncate-end">{one.label}</Text></Box>
478 <Text size="footnote" tabular weight="medium">{kilo(one.tokens)}</Text>
479 </Box>
480 ))}
481 </Box>
482 ))}
483 </Box>
484 )}
485 </Box>
486 )
487}
488
489// The terminal's band: one line of figures under the hint, each group a dim label and its value, set apart by
490// space. Colour is kept for a figure asking for attention (amber, red); a figure at rest reads in the text colour.
491async function contextView(
492 $: EngineInterface,
493 e: Parameters<EngineInterface['ui']['resolve']>[0],
494 state: Band,
495 isWorking: boolean,
496 columns: number | undefined,
497 below: JSX.Element | null,
498): Promise<JSX.Element> {
499 const { Box, Button, Text } = $.ui.resolve(e)
500 const at = await read($, now)
501 const tokens = state.readings[state.readings.length - 1] ?? 0
502 const percent = state.window > 0 ? Math.round((tokens * 100) / state.window) : null
503 const color = tokenColor(tokens)
504 const cache = isWorking ? null : cacheState(state.lastTurnAt, at, tokens)
505 const cacheColor = cache?.color === undefined ? undefined : THEMED[cache.color]
506 const rebuilding = await read($, isRebuilding)
507 const grouping = state.streak >= STREAK_SHOWN
508 const limit = state.fiveHour
509 const resetIn = limit?.resetsAt == null || limit.resetsAt <= at ? null : span(limit.resetsAt - at)
510 const turns = Math.min(TOP_TURNS, state.turn)
511 const all = topContributions(state.contributions, state.turn - TOP_TURNS + 1, Number.MAX_SAFE_INTEGER)
512 const hidden = Math.max(0, all.length - TOP_SHOWN)
513 const expanded = await read($, isExpanded)
514 const shown = expanded ? all.slice(0, LIST_ROWS) : all.slice(0, TOP_SHOWN)
515 const showsTop = all.length > 0
516 const toggle = (
517 <Button
518 key="top-toggle"
519 label={expanded ? '▾ details' : hidden > 0 ? `▸ details +${hidden}` : '▸ details'}
520 plain
521 dimColor
522 onPress={() => update($, isExpanded, value => !value)}
523 />
524 )
525 const header = `Top ${turns === 1 ? 'last turn' : `${turns} turns`}`
526 // A meter whole in the colour of its state; the figure beside it coloured only when it asks for attention.
527 const gauge = (key: string, value: number) => <Text key={key} color={meterColor(value)}>{meter(value)}</Text>
528 const alarm = (value: number) => (meterColor(value) === 'success' ? undefined : meterColor(value))
529 const labelOf = (text: string) => (
530 <Box width={TERMINAL_LABEL} flexShrink={0}>
531 <Text dimColor>{text}</Text>
532 </Box>
533 )
534 const room = Math.max(...shown.map(one => one.label.length), 0)
535 const topWidth = Math.min(TOP_LABEL, room, Math.max(4, (columns ?? 80) - 2 - TERMINAL_LABEL - TOP_FIGURE - 1))
536
537 return (
538 <Box flexDirection="column">
539 <Box flexDirection="column" width={columns}>
540 <Box height={1}>
541 {/* The toggle follows the figures, never pushed to the far edge; a line too long for the row is cut first. */}
542 <Box flexShrink={1}>
543 <Text wrap="truncate-end">
544 <Text dimColor>Context </Text>
545 {percent !== null && gauge('context-meter', percent)}
546 {percent !== null && <Text> </Text>}
547 <Text color={color} bold={tokens >= STEP_TOKENS}>{kilo(tokens)}</Text>
548 {state.window > 0 && <Text dimColor>/{kilo(state.window)}</Text>}
549 {limit !== null && <Text dimColor>{GROUP}5h </Text>}
550 {limit !== null && gauge('limit-meter', limit.percent)}
551 {limit !== null && <Text color={alarm(limit.percent)}> {Math.round(limit.percent)}%</Text>}
552 {limit !== null && resetIn !== null && <Text dimColor> {resetIn}</Text>}
553 {cache !== null && (
554 <Text key="cache">
555 <Text dimColor>{GROUP}</Text>
556 <Text color={cacheColor} dimColor={cacheColor === undefined}>{cache.label}</Text>
557 </Text>
558 )}
559 {grouping && <Text key="grouping" color="warning">{`${GROUP}${state.streak} single calls`}</Text>}
560 {rebuilding && <Text key="graph" dimColor>{`${GROUP}graph rebuilding`}</Text>}
561 <Text dimColor>{GROUP}{span(at - state.startedAt)} · {state.turn} turn{state.turn > 1 ? 's' : ''}</Text>
562 {state.cost !== null && <Text dimColor> · </Text>}
563 {state.cost !== null && <Text>{dollars(state.cost)}</Text>}
564 {showsTop && !expanded && <Text dimColor>{GROUP}Top </Text>}
565 {showsTop && !expanded && shown.map((one, index) => (
566 <Text key={`top-${index}`}>
567 {index > 0 && <Text dimColor> · </Text>}
568 <Text>{one.label} </Text>
569 <Text dimColor>{kilo(one.tokens)}</Text>
570 </Text>
571 ))}
572 </Text>
573 </Box>
574 <Box flexShrink={0} paddingLeft={TOGGLE_GAP}>{toggle}</Box>
575 </Box>
576 {expanded && (
577 <Box flexDirection="column" paddingLeft={2}>
578 <Box height={1}>
579 {labelOf('Step')}
580 <Text color={color} wrap="truncate-end">{stepLabel(tokens)}</Text>
581 </Box>
582 {cache?.detail !== undefined && (
583 <Box height={1}>
584 {labelOf('Cache')}
585 <Text color={cacheColor} wrap="truncate-end">{cache.detail}</Text>
586 </Box>
587 )}
588 {grouping && (
589 <Box height={1}>
590 {labelOf('Batching')}
591 <Text wrap="truncate-end">
592 <Text color="warning">{`${state.streak} turns with a single tool call`}</Text>
593 <Text dimColor>: send independent calls together, each turn resends the whole context</Text>
594 </Text>
595 </Box>
596 )}
597 {showsTop && (
598 <Box>
599 {labelOf(header)}
600 <Box flexDirection="column">
601 {shown.map((one, index) => {
602 const cells = topLine(one.label, one.tokens, topWidth)
603 return (
604 <Text key={`top-${index}`} wrap="truncate-end">
605 <Text>{cells.label}</Text>
606 <Text>{cells.tokens}</Text>
607 </Text>
608 )
609 })}
610 </Box>
611 </Box>
612 )}
613 </Box>
614 )}
615 </Box>
616 {below}
617 </Box>
618 )
619}
620types/index.d.ts 20 lines1export type Contribution = { turn: number; label: string; tokens: number }
2
3export type Band = {
4 startedAt: number
5 readings: number[]
6 window: number
7 lastTurnAt: number | null
8 streak: number
9 turn: number
10 contributions: Contribution[]
11 cost: number | null
12 fiveHour: { percent: number; resetsAt: number | null } | null
13}
14
15declare module 'claude-code' {
16 interface PluginState {
17 'context-band': { band: Band; now: number; isRebuilding: boolean; isExpanded: boolean }
18 }
19}
20