Records what Claude Code spends, message by message, and shows where it went: on which feature, and how much of it is on features at all.

Records what Claude Code spends, message by message, and shows where it went without leaving the session. It runs in the terminal on macOS, Windows and Linux and in the Code tab of the Claude desktop app. In the VS Code panel, in CI and in cloud sessions it records messages and shows nothing.
# inside Claude Code
/plugin install token-controller --marketplace tokencontroller/tokencontroller
The mod keeps its messages through the CLI, tc (install). Connect it to your organization with tc connect, or leave it local. Until tc is installed, the mod keeps the session's summary and tags on the machine and the band says how to install it.
tc, which reads the turn from Claude Code's own session files: every message with its token counts by kind (input, output, cache read, cache write) and model, the working directory, the branch, and feature keys in your prompts. Only the keys leave a prompt, never its text.tc record, with the session facts it counts (turns, duration, subagent turns) and the feature and tags you set by hand.tc builds the session record and splits it by your rules. The mod does not split anything itself (ADR 0010).$41.87 today · 91% on features · KD-214, and a note when an org manager asks everyone to submit before the cutoff moves./tc) shows the check list, where you fix a feature and submit; a report by feature, project, team or day; and your personal rules./tc feature KD-214, /tc tag purpose=spike, /tc report [by] and /tc submit run at once, without a turn. Claude can call the mod's report tool to answer "what did KD-214 cost this week?".Everything the docs promise is on the Claude Code mod page.
| Path | What it holds |
|---|---|
.claude-plugin/plugin.json | The manifest. The marketplace that lists it is .claude-plugin/marketplace.json at the repo root. |
hooks/register.tsx | The hooks: recording, the band, the pane, /tc and the report tool. |
hooks/lib/ | The plain logic: the record for tc record, reading tc --json, formatting, the summary prompt. |
types/index.d.ts | The session values the band and the pane draw from. |
tests/ | Tests that run the hooks inside Claude Code's own engine against a tc answered from memory. |
pnpm lint && pnpm typecheck && pnpm test # what CI runs: hooks/lib and its *.spec.ts files
claude plugin validate . # what the engine will load, and what it refuses
claude plugin test . # tests/*.test.ts inside the engine
claude --plugin-dir . # a session with this folder loaded, reloaded on save
CI has no Claude Code, so it checks hooks/lib only. Run claude plugin validate and claude plugin test before every change to hooks/register.tsx. MIT license.
hooks/register.tsx 616 lines1import type { EngineInterface, Register } from 'claude-code'
2import { atom, read, update } from 'claude-code'
3
4import type { Tab } from '../types'
5import {
6 assignedLine,
7 bar,
8 headline,
9 money,
10 percent,
11 reportTable,
12 reportText,
13 rowLabel,
14 sessionFeature,
15 splitLine,
16 statusNote,
17 submittedText,
18 when,
19} from './lib/format.ts'
20import { countTurn, HELP, NO_FACTS, parseCommand, sessionRecord } from './lib/records.ts'
21import { cleanSummary, SUMMARY_MODEL, SUMMARY_SYSTEM, summaryPrompt } from './lib/summary.ts'
22import {
23 parseJson,
24 readReport,
25 readReview,
26 readRules,
27 readStatus,
28 readSubmitted,
29 reason,
30} from './lib/tc.ts'
31
32type $ = EngineInterface
33
34const PANE = 'token-controller'
35const TOOL = 'mcp__token-controller__report'
36const INSTALL =
37 'Install tc to keep your messages: brew tap tokencontroller/tap https://github.com/tokencontroller/tokencontroller && brew install tc'
38
39const status = atom({ plugin: 'token-controller', key: 'status' } as const, null)
40const review = atom({ plugin: 'token-controller', key: 'review' } as const, [])
41const report = atom({ plugin: 'token-controller', key: 'report' } as const, null)
42const reportBy = atom({ plugin: 'token-controller', key: 'reportBy' } as const, 'feature')
43const rules = atom({ plugin: 'token-controller', key: 'rules' } as const, [])
44const tab = atom({ plugin: 'token-controller', key: 'tab' } as const, 'review')
45const editing = atom({ plugin: 'token-controller', key: 'editing' } as const, null)
46const notice = atom({ plugin: 'token-controller', key: 'notice' } as const, null)
47const problem = atom({ plugin: 'token-controller', key: 'problem' } as const, null)
48const feature = atom({ plugin: 'token-controller', key: 'feature' } as const, null)
49const handTags = atom({ plugin: 'token-controller', key: 'handTags' } as const, {})
50const summary = atom({ plugin: 'token-controller', key: 'summary' } as const, null)
51const facts = atom({ plugin: 'token-controller', key: 'facts' } as const, NO_FACTS)
52
53/** Where tc may be when the session's PATH does not have it (the desktop app). */
54const FALLBACK_PATHS = [
55 '/opt/homebrew/bin/tc',
56 '/usr/local/bin/tc',
57 '/home/linuxbrew/.linuxbrew/bin/tc',
58]
59
60type TcRun = { ok: boolean; missing: boolean; stdout: string; stderr: string }
61
62// The module's own values start over when it reloads; nothing here needs to last.
63let tcPath: string | undefined
64let queue: Promise<unknown> = Promise.resolve()
65let isSummarizing = false
66let isInteractive = true
67
68/** Runs one thing after another, so store writes never overlap. */
69function serial<T>(work: () => Promise<T>): Promise<T> {
70 const run = queue.then(work, work)
71 queue = run.catch(() => undefined)
72 return run
73}
74
75async function tc($: $, args: string[], stdin?: string): Promise<TcRun> {
76 const home = await $.env.get('HOME')
77 const paths = tcPath
78 ? [tcPath]
79 : ['tc', ...FALLBACK_PATHS, ...(home ? [`${home}/.local/bin/tc`, `${home}/.cargo/bin/tc`] : [])]
80 for (const path of paths) {
81 try {
82 const run = await $.process.run([path, ...args], {
83 env: { NO_COLOR: '1' },
84 timeoutMs: 20_000,
85 ...(stdin === undefined ? {} : { stdin }),
86 })
87 tcPath = path
88 return { ok: run.exitCode === 0, missing: false, stdout: run.stdout, stderr: run.stderr }
89 } catch (error) {
90 const text = error instanceof Error ? error.message : String(error)
91 if (!/ENOENT|not found|no such file|cannot (start|find)|spawn/i.test(text)) {
92 return { ok: false, missing: false, stdout: '', stderr: text }
93 }
94 }
95 }
96 return { ok: false, missing: true, stdout: '', stderr: '' }
97}
98
99async function setProblem($: $, run: TcRun | null): Promise<void> {
100 const text =
101 run === null ? null : run.missing ? INSTALL : reason(run.stderr, run.stdout, 'tc failed')
102 await update($, problem, () => text)
103}
104
105/**
106 * Keeps this session's record in the machine's store until tc has taken it.
107 * The record is the whole picture so far, so only the newest one waits.
108 */
109function remember($: $): Promise<void> {
110 return serial(async () => {
111 const [sessionId, line, counted, tags] = await Promise.all([
112 $.session.id(),
113 read($, summary),
114 read($, facts),
115 read($, handTags),
116 ])
117 await $.store.set(`record/${sessionId}`, sessionRecord(sessionId, line, counted, tags))
118 })
119}
120
121/** Hands every waiting record, this session's and earlier ones', to tc. */
122function flush($: $): Promise<void> {
123 return serial(async () => {
124 const waiting = (await $.store.keys()).filter(key => key.startsWith('record/'))
125 for (const key of waiting) {
126 const record = await $.store.get(key)
127 if (record !== undefined) {
128 const run = await tc($, ['record', '--json'], `${JSON.stringify(record)}\n`)
129 if (!run.ok) {
130 await setProblem($, run)
131 return
132 }
133 }
134 await $.store.delete(key)
135 }
136 await setProblem($, null)
137 })
138}
139
140/** Reads today's figures and the check list from tc for the band and the pane. */
141async function refresh($: $): Promise<void> {
142 const run = await tc($, ['status', '--json'])
143 if (!run.ok) {
144 await setProblem($, run)
145 return
146 }
147 await update($, status, () => readStatus(parseJson(run.stdout)))
148 const listed = await tc($, ['review', '--json'])
149 if (listed.ok) {
150 const rows = readReview(parseJson(listed.stdout))
151 await update($, review, () => rows)
152 const split = sessionFeature(rows, await $.session.id())
153 await update($, feature, () => split)
154 }
155}
156
157async function refreshReport($: $): Promise<void> {
158 const by = await read($, reportBy)
159 const run = await tc($, ['report', '--by', by, '--json'])
160 if (run.ok) await update($, report, () => readReport(parseJson(run.stdout), by))
161 else await update($, notice, () => reason(run.stderr, run.stdout, 'tc report failed'))
162}
163
164async function refreshRules($: $): Promise<void> {
165 const run = await tc($, ['rules', '--json'])
166 if (run.ok) await update($, rules, () => readRules(parseJson(run.stdout)))
167}
168
169/**
170 * After a turn: the mod counts the turn into the session facts and writes the
171 * summary; tc reads the session's messages from Claude Code's own session
172 * files whenever it runs, so asking it for the band's figures is what brings
173 * the turn into the session record.
174 */
175async function afterTurn($: $, isMain: boolean): Promise<void> {
176 if (isMain) await summarize($)
177 else await remember($)
178 await flush($)
179 if (isInteractive) await refresh($)
180}
181
182/** Writes the one-line summary with a small model call of the mod's own. */
183async function summarize($: $): Promise<void> {
184 if (isSummarizing) return
185 isSummarizing = true
186 try {
187 const messages = (await $.session.messages()).map(m => ({ role: m.role, text: m.text }))
188 const previous = await read($, summary)
189 const answer = await $.model.complete({
190 model: SUMMARY_MODEL,
191 system: SUMMARY_SYSTEM,
192 prompt: summaryPrompt(previous, messages.slice(-12)),
193 maxTokens: 120,
194 })
195 const line = answer.isAnswered ? cleanSummary(answer.text) : null
196 if (line === null || line === previous) return
197 await update($, summary, () => line)
198 await remember($)
199 } finally {
200 isSummarizing = false
201 }
202}
203
204async function setTags($: $, tags: Record<string, string>): Promise<string> {
205 await update($, handTags, current => ({ ...current, ...tags }))
206 await remember($)
207 await flush($)
208 await refresh($)
209 const problemNow = await read($, problem)
210 const set = Object.entries(tags)
211 .map(([name, value]) => `${name} ${value}`)
212 .join(' · ')
213 return problemNow === null ? `This session: ${set}` : `This session: ${set}. ${problemNow}`
214}
215
216async function submit($: $): Promise<string> {
217 await flush($)
218 const run = await tc($, ['submit', '--json'])
219 await refresh($)
220 if (run.missing) return INSTALL
221 return run.ok
222 ? submittedText(readSubmitted(parseJson(run.stdout)))
223 : reason(run.stderr, run.stdout, 'tc submit failed')
224}
225
226function openPane($: $) {
227 return $.ui.open({ id: PANE, title: 'Token Controller' })
228}
229
230export const register: Register = on => {
231 on('session.start', async ($, e, next) => {
232 const started = await next(e)
233 isInteractive = e.isInteractive
234 await $.command.register({
235 name: 'tc',
236 description:
237 'Token Controller: put this session on a feature, see reports, submit your sessions',
238 argumentHint: '[feature KEY | tag NAME=VALUE | report [BY] | submit]',
239 })
240 await $.tool.register({
241 name: 'report',
242 description:
243 'Token Controller report: what agent work cost, grouped by feature, project, team, any other tag or attribute name, or day. ' +
244 'Use it when the person asks what something cost, such as "what did KD-214 cost this week?" ' +
245 '(by day, filter feature=KD-214, then add up the days of this week), and answer with the table it returns.',
246 inputSchema: {
247 type: 'object',
248 properties: {
249 by: { type: 'string', description: 'feature, project, team, any tag name, or day' },
250 filter: {
251 type: 'string',
252 description: 'Limit to one tag value, as name=value, such as feature=KD-214',
253 },
254 },
255 required: ['by'],
256 },
257 isDeferred: false,
258 })
259 // Records left by sessions that ended before tc took them go first.
260 await flush($)
261 await refresh($)
262 $.clock.every(5 * 60_000, () => {
263 void refresh($)
264 })
265 return started
266 })
267
268 on('turn.complete', async ($, e, next) => {
269 const result = await next(e)
270 const isMain = e.agentId === undefined && e.reason === 'answer'
271 await update($, facts, counted => countTurn(counted, e.durationMs, e.agentId !== undefined))
272 if (isInteractive) {
273 // Outside the turn's dispatch, so tc and the summary never hold up the prompt.
274 $.clock.after(0, () => void afterTurn($, isMain))
275 } else if (isMain) {
276 // A headless run (claude -p, CI) ends with its turn: record before it does.
277 await afterTurn($, isMain)
278 }
279 return result
280 })
281
282 on('session.end', async ($, e, next) => {
283 // All session.end hooks share 1.5 seconds. What tc does not take now
284 // stays in the store and goes at the next session's start.
285 await Promise.race([flush($), $.clock.sleep(1_000)])
286 return next(e)
287 })
288
289 on('command.run', { command: 'tc' }, async ($, e) => {
290 const command = parseCommand(e.args)
291 switch (command.kind) {
292 case 'open':
293 await openPane($)
294 return { text: 'Opened the Token Controller pane.' }
295 case 'tags':
296 return { text: await setTags($, command.tags) }
297 case 'report': {
298 const run = await tc($, ['report', '--by', command.by, '--json'])
299 if (run.missing) return { text: INSTALL }
300 if (!run.ok) return { text: reason(run.stderr, run.stdout, 'tc report failed') }
301 return {
302 text: reportText(
303 readReport(parseJson(run.stdout), command.by),
304 e.presentation.columns - 4,
305 ),
306 }
307 }
308 case 'submit':
309 return { text: await submit($) }
310 case 'help':
311 return { text: [command.problem, HELP].filter(Boolean).join('\n\n') }
312 }
313 })
314
315 on('tool.call', { tool: TOOL }, async ($, e) => {
316 const input = e.input as { by?: unknown; filter?: unknown }
317 const by = typeof input.by === 'string' && input.by !== '' ? input.by : 'feature'
318 const args = ['report', '--by', by, '--json']
319 if (typeof input.filter === 'string' && input.filter !== '') args.push('--filter', input.filter)
320 const run = await tc($, args)
321 if (run.missing) return { result: INSTALL }
322 if (!run.ok) return { result: reason(run.stderr, run.stdout, 'tc report failed') }
323 return { result: reportTable(readReport(parseJson(run.stdout), by)) }
324 }).catch(() => ({ deny: 'Token Controller could not make the report.' }))
325
326 on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
327 if (e.props.hasSurvey) return next(e)
328 const [current, trouble, featureNow] = await Promise.all([
329 read($, status),
330 read($, problem),
331 read($, feature),
332 ])
333 if (current === null && trouble === null) return next(e)
334 const { Box, Text, Button } = $.ui.resolve(e)
335 const note = current === null ? null : statusNote(current)
336 // A note gets its own row when the band may take two, so the headline never wraps.
337 const isNoteBelow = note !== null && e.props.maxRows >= 2
338 const top = (
339 <Box flexDirection="row" gap={1}>
340 {current !== null && <Text wrap="truncate-end">{headline(current, featureNow)}</Text>}
341 {note !== null && !isNoteBelow && (
342 <Text color="warning" wrap="truncate-end">
343 · {note}
344 </Text>
345 )}
346 {trouble !== null && (
347 <Text color="warning" wrap="truncate-end">
348 {trouble}
349 </Text>
350 )}
351 <Button key="open" plain dimColor label="details" onPress={() => void openPane($)} />
352 </Box>
353 )
354 if (!isNoteBelow) return top
355 return (
356 <Box flexDirection="column">
357 {top}
358 <Text color="warning" wrap="truncate-end">
359 {note}
360 </Text>
361 </Box>
362 )
363 })
364
365 on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
366 const elements = $.ui.resolve(e)
367 const { Box, Text, Button } = elements
368 // The mobile app draws no text field yet: there the pane shows and submits, and fixes wait for a computer.
369 const Input = 'Input' in elements ? elements.Input : undefined
370 const [current, trouble, shown, rows, chosen, said, featureNow, now] = await Promise.all([
371 read($, status),
372 read($, problem),
373 read($, tab),
374 read($, review),
375 read($, editing),
376 read($, notice),
377 read($, feature),
378 $.clock.now(),
379 ])
380 const width = Math.max(30, e.props.bodyColumns)
381 const note = current === null ? null : statusNote(current)
382 const toCheck = rows.filter(row => !row.isRejected)
383 const rejected = rows.length - toCheck.length
384 const show = (next: Tab) => async () => {
385 await update($, tab, () => next)
386 await update($, notice, () => null)
387 if (next === 'report') await refreshReport($)
388 if (next === 'rules') await refreshRules($)
389 if (next === 'review') await refresh($)
390 }
391 const say = (text: string) => update($, notice, () => text)
392
393 const header = (
394 <Box flexDirection="column">
395 {current !== null && <Text bold>{headline(current, featureNow)}</Text>}
396 {current !== null && (
397 <Text dimColor wrap="truncate-end">
398 {[
399 current.organization ?? 'Local only: tc connect to report to your organization',
400 `${toCheck.length} ${toCheck.length === 1 ? 'session' : 'sessions'} to check`,
401 ...(rejected > 0 ? [`${rejected} rejected`] : []),
402 ].join(' · ')}
403 </Text>
404 )}
405 {note !== null && <Text color="warning">{note}</Text>}
406 {trouble !== null && <Text color="warning">{trouble}</Text>}
407 <Box flexDirection="row" gap={1} marginTop={1}>
408 <Button
409 key="tab-review"
410 label="Check"
411 hotkey="r"
412 variant={shown === 'review' ? 'primary' : 'secondary'}
413 onPress={show('review')}
414 />
415 <Button
416 key="tab-report"
417 label="Report"
418 hotkey="p"
419 variant={shown === 'report' ? 'primary' : 'secondary'}
420 onPress={show('report')}
421 />
422 <Button
423 key="tab-rules"
424 label="Rules"
425 hotkey="u"
426 variant={shown === 'rules' ? 'primary' : 'secondary'}
427 onPress={show('rules')}
428 />
429 </Box>
430 {said !== null && <Text dimColor>{said}</Text>}
431 </Box>
432 )
433
434 if (shown === 'report') {
435 const [shownReport, by] = await Promise.all([read($, report), read($, reportBy)])
436 const choices = ['feature', 'project', 'team', 'day']
437 const options = choices.includes(by) ? choices : [...choices, by]
438 const labels = shownReport === null ? [] : shownReport.rows.map(r => rowLabel(r, by))
439 const label = Math.min(20, Math.max(5, ...labels.map(l => l.length)))
440 const barWidth = Math.max(6, width - label - 22)
441 const max = shownReport === null ? 0 : Math.max(0, ...shownReport.rows.map(r => r.cost))
442 return (
443 <Box flexDirection="column" gap={1}>
444 {header}
445 <Box flexDirection="row" gap={1}>
446 {options.map(option => (
447 <Button
448 key={`by-${option}`}
449 label={option}
450 variant={option === by ? 'primary' : 'secondary'}
451 onPress={async () => {
452 await update($, reportBy, () => option)
453 await refreshReport($)
454 }}
455 />
456 ))}
457 </Box>
458 {shownReport === null && <Text dimColor>No report yet.</Text>}
459 {shownReport !== null && shownReport.rows.length === 0 && (
460 <Text dimColor>No cost by {shownReport.by} yet.</Text>
461 )}
462 {shownReport !== null && shownReport.rows.length > 0 && (
463 <Box flexDirection="column">
464 {shownReport.rows.map((row, i) => (
465 <Box key={`row-${row.value ?? ''}`} flexDirection="row" gap={1}>
466 <Text wrap="truncate-end">{(labels[i] ?? '').slice(0, label).padEnd(label)}</Text>
467 <Text>{money(row.cost, shownReport.currency, true).padStart(10)}</Text>
468 <Text dimColor>{(row.share === null ? '' : percent(row.share)).padStart(4)}</Text>
469 <Text color="claude">{bar(row.cost, max, barWidth)}</Text>
470 </Box>
471 ))}
472 <Text bold>
473 {'total'.padEnd(label)}{' '}
474 {money(shownReport.total, shownReport.currency, true).padStart(10)}
475 </Text>
476 </Box>
477 )}
478 </Box>
479 )
480 }
481
482 if (shown === 'rules') {
483 const listed = await read($, rules)
484 return (
485 <Box flexDirection="column" gap={1}>
486 {header}
487 {listed.length === 0 && (
488 <Text dimColor>No personal rules yet. Your organization’s rules still apply.</Text>
489 )}
490 <Box flexDirection="column">
491 {listed.map(rule => (
492 <Box key={`rule-${rule.number}`} flexDirection="row" gap={1}>
493 <Text dimColor>{String(rule.number).padStart(2)}</Text>
494 <Text wrap="truncate-end">{rule.text}</Text>
495 <Button
496 key={`remove-${rule.number}`}
497 plain
498 dimColor
499 label="remove"
500 onPress={async () => {
501 const run = await tc($, ['rules', 'remove', String(rule.number), '--json'])
502 await say(
503 run.ok
504 ? `Removed rule ${rule.number}.`
505 : reason(run.stderr, run.stdout, 'tc rules failed'),
506 )
507 await refreshRules($)
508 }}
509 />
510 </Box>
511 ))}
512 </Box>
513 {Input !== undefined && (
514 <Input
515 key="add-rule"
516 label="Add a rule"
517 placeholder="branch starts-with review/ purpose=code-review"
518 submitLabel="Add"
519 onSubmit={async (text: string) => {
520 if (text.trim() === '') return
521 const run = await tc($, ['rules', 'add', text.trim(), '--json'])
522 await say(
523 run.ok ? 'Added the rule.' : reason(run.stderr, run.stdout, 'tc rules failed'),
524 )
525 await refreshRules($)
526 }}
527 />
528 )}
529 </Box>
530 )
531 }
532
533 const total = toCheck.reduce((sum, row) => sum + (row.cost ?? 0), 0)
534 const currency = current?.currency ?? 'USD'
535 const costText = (row: (typeof rows)[number]) =>
536 row.cost === null ? 'no price' : money(row.cost, currency, true)
537 const whenWidth = Math.max(0, ...rows.map(row => when(row.startedAt, now).length))
538 const costWidth = Math.max(0, ...rows.map(row => costText(row).length))
539 return (
540 <Box flexDirection="column" gap={1}>
541 {header}
542 {rows.length === 0 && (
543 <Text dimColor>No sessions to check. Each Claude Code session shows here.</Text>
544 )}
545 <Box flexDirection="column">
546 {rows.map(row => (
547 <Box key={`entry-${row.number}`} flexDirection="column">
548 <Button
549 key={`pick-${row.number}`}
550 plain
551 onPress={() =>
552 update($, editing, open => (open === row.number ? null : row.number))
553 }
554 >
555 {String(row.number).padStart(2)} {when(row.startedAt, now).padEnd(whenWidth)}{' '}
556 {costText(row).padStart(costWidth)} {splitLine(row)}
557 </Button>
558 {row.summary !== '' && (
559 <Text wrap="truncate-end">
560 {' '}
561 {row.summary}
562 </Text>
563 )}
564 <Text
565 dimColor={!row.isRejected}
566 color={row.isRejected ? 'warning' : undefined}
567 wrap="truncate-end"
568 >
569 {' '}
570 {assignedLine(row)}
571 </Text>
572 {Input !== undefined && chosen === row.number && (
573 <Input
574 key={`tag-${row.number}`}
575 label={`Tags for #${row.number}`}
576 placeholder="KD-231, or name=value"
577 submitLabel="Set"
578 autoFocus
579 onSubmit={async (text: string) => {
580 const pairs = text
581 .split(/\s+/)
582 .filter(Boolean)
583 .map((pair: string) => (pair.includes('=') ? pair : `feature=${pair}`))
584 if (pairs.length === 0) return
585 const run = await tc($, ['tag', String(row.number), ...pairs, '--json'])
586 await say(
587 run.ok
588 ? `#${row.number}: ${pairs.join(' ')}`
589 : reason(run.stderr, run.stdout, 'tc tag failed'),
590 )
591 await update($, editing, () => null)
592 await refresh($)
593 }}
594 />
595 )}
596 </Box>
597 ))}
598 </Box>
599 {toCheck.length > 0 && (
600 <Box flexDirection="row" gap={1}>
601 <Button
602 key="submit"
603 variant="primary"
604 hotkey="s"
605 label={`Submit ${toCheck.length} ${toCheck.length === 1 ? 'session' : 'sessions'} · ${money(total, currency, true)}`}
606 onPress={async () => {
607 await say(await submit($))
608 }}
609 />
610 </Box>
611 )}
612 </Box>
613 )
614 })
615}
616hooks/lib/format.ts 184 lines1import type { Report, ReportRow, ReviewRow, Status, Submitted } from './tc.ts'
2
3const SYMBOLS: Record<string, string> = { USD: '$', EUR: '€', GBP: '£' }
4
5/** `$212`, `$41.87`: whole units from 100 up, cents below. */
6export function money(amount: number, currency: string, exact = false): string {
7 const symbol = SYMBOLS[currency]
8 const digits = exact || Math.abs(amount) < 100 ? 2 : 0
9 const text = amount.toLocaleString('en-US', {
10 minimumFractionDigits: digits,
11 maximumFractionDigits: digits,
12 })
13 return symbol === undefined ? `${text} ${currency}` : `${symbol}${text}`
14}
15
16export function percent(share: number): string {
17 return `${Math.round(share * 100)}%`
18}
19
20/**
21 * The headline of the band and the pane: today's cost, the share on features,
22 * and this session's feature, such as `$41.87 today · 91% on features · KD-214`.
23 */
24export function headline(status: Status, feature: string | null): string {
25 const parts = [`${money(status.today, status.currency)} today`]
26 if (status.shareOnFeatures !== null) {
27 parts.push(`${percent(status.shareOnFeatures)} on features`)
28 }
29 if (feature) parts.push(feature)
30 return parts.join(' · ')
31}
32
33const MONTHS = [
34 'January',
35 'February',
36 'March',
37 'April',
38 'May',
39 'June',
40 'July',
41 'August',
42 'September',
43 'October',
44 'November',
45 'December',
46]
47
48/** `30 September 2026` for `2026-09-30`; anything else as tc sent it. */
49export function dateName(date: string): string {
50 const match = /^(\d{4})-(\d{2})-(\d{2})$/.exec(date)
51 const month = match === null ? undefined : MONTHS[Number(match[2]) - 1]
52 return match === null || month === undefined ? date : `${Number(match[3])} ${month} ${match[1]}`
53}
54
55/**
56 * The org manager's request to submit before the cutoff moves, such as
57 * `Nadia Berger asks you to submit before the cutoff moves to 30 September 2026`.
58 */
59export function statusNote(status: Status): string | null {
60 const asked = status.askedToSubmit
61 if (asked === null) return null
62 const until = `before the cutoff moves to ${dateName(asked.cutoff)}`
63 return asked.askedBy === null
64 ? `asked to submit ${until}`
65 : `${asked.askedBy} asks you to submit ${until}`
66}
67
68function features(row: ReviewRow): string[] {
69 return [...new Set(row.splits.flatMap(split => (split.tags.feature ? [split.tags.feature] : [])))]
70}
71
72/** The feature tc split this session on, if any: `KD-214`, or `KD-231 +1` when split. */
73export function sessionFeature(rows: readonly ReviewRow[], sessionId: string): string | null {
74 const row = rows.find(r => r.sessionId === sessionId)
75 if (row === undefined) return null
76 const [first, ...rest] = features(row)
77 if (first === undefined) return null
78 return rest.length === 0 ? first : `${first} +${rest.length}`
79}
80
81/** `feature KD-214 · team web`, the check list's tag column. */
82export function tagLine(tags: Record<string, string>): string {
83 const order = ['feature', 'project']
84 const names = Object.keys(tags).sort((a, b) => {
85 const ia = order.indexOf(a)
86 const ib = order.indexOf(b)
87 return (ia === -1 ? 9 : ia) - (ib === -1 ? 9 : ib) || a.localeCompare(b)
88 })
89 return names.map(name => `${name} ${tags[name]}`).join(' · ')
90}
91
92/** Where a session sits: its tags, or each split's feature or tags with its fraction. */
93export function splitLine(row: ReviewRow): string {
94 if (row.splits.length <= 1) return tagLine(row.splits[0]?.tags ?? {}) || 'no project'
95 return row.splits
96 .map(split => {
97 const place = split.tags.feature ?? (tagLine(split.tags) || 'no project')
98 return split.fraction === null ? place : `${place} ${percent(split.fraction)}`
99 })
100 .join(' · ')
101}
102
103/** The line under a session: what assigned it and its label, or why it came back. */
104export function assignedLine(row: ReviewRow): string {
105 if (row.isRejected) return `rejected: ${row.rejectedReason ?? 'see the web app'}`
106 const parts: string[] = []
107 if (row.assignedBy !== null) parts.push(row.assignedBy)
108 if (row.label !== null) parts.push(row.label)
109 return parts.join(' · ') || 'no rule matched'
110}
111
112const DAYS = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']
113
114/** `09:12` today, `Mon 09:12` this week, `2026-09-18` before. */
115export function when(iso: string | null, now: number): string {
116 if (iso === null) return ''
117 const at = new Date(iso)
118 if (Number.isNaN(at.getTime())) return ''
119 const time = `${String(at.getHours()).padStart(2, '0')}:${String(at.getMinutes()).padStart(2, '0')}`
120 const days = (now - at.getTime()) / 86_400_000
121 if (new Date(now).toDateString() === at.toDateString()) return time
122 if (days < 6) return `${DAYS[at.getDay()]} ${time}`
123 return at.toISOString().slice(0, 10)
124}
125
126const EIGHTHS = ['', '▏', '▎', '▍', '▌', '▋', '▊', '▉']
127
128/** A bar of `width` cells for `value` out of `max`, in eighths of a cell. */
129export function bar(value: number, max: number, width: number): string {
130 if (max <= 0 || value <= 0 || width <= 0) return ''
131 const eighths = Math.max(1, Math.round((Math.min(value, max) / max) * width * 8))
132 return '█'.repeat(Math.floor(eighths / 8)) + EIGHTHS[eighths % 8]
133}
134
135/** A row's label: its value, or `(no feature)` for the cost without one. */
136export function rowLabel(row: ReportRow, by: string): string {
137 return row.value ?? `(no ${by})`
138}
139
140/** A report as a Markdown table, for the model. */
141export function reportTable(report: Report): string {
142 if (report.rows.length === 0) return `No cost by ${report.by} yet.`
143 const lines = [
144 `| ${report.by} | cost | share |`,
145 '| --- | ---: | ---: |',
146 ...report.rows.map(
147 row =>
148 `| ${rowLabel(row, report.by)} | ${money(row.cost, report.currency, true)} | ${row.share === null ? '' : percent(row.share)} |`,
149 ),
150 `| **total** | **${money(report.total, report.currency, true)}** | |`,
151 ]
152 return lines.join('\n')
153}
154
155/** The same report as aligned text with bars, for a command's output row. */
156export function reportText(report: Report, width = 72): string {
157 if (report.rows.length === 0) return `No cost by ${report.by} yet.`
158 const labels = report.rows.map(row => rowLabel(row, report.by))
159 const label = Math.min(24, Math.max(5, ...labels.map(l => l.length)))
160 const costs = report.rows.map(row => money(row.cost, report.currency, true))
161 const costWidth = Math.max(...costs.map(c => c.length))
162 const barWidth = Math.min(40, Math.max(8, width - label - costWidth - 10))
163 const max = Math.max(...report.rows.map(row => row.cost))
164 const lines = report.rows.map((row, i) => {
165 const share = row.share === null ? '' : percent(row.share)
166 return `${(labels[i] ?? '').slice(0, label).padEnd(label)} ${(costs[i] ?? '').padStart(costWidth)} ${share.padStart(4)} ${bar(row.cost, max, barWidth)}`
167 })
168 return [
169 `Cost by ${report.by}`,
170 '',
171 ...lines,
172 `${'total'.padEnd(label)} ${money(report.total, report.currency, true).padStart(costWidth)}`,
173 ].join('\n')
174}
175
176/** What `tc submit` did, in one line. */
177export function submittedText(done: Submitted): string {
178 if (done.count === 0) return 'Nothing to submit.'
179 const parts = [`Submitted ${done.count} ${done.count === 1 ? 'session' : 'sessions'}`]
180 if (done.cost !== null) parts.push(money(done.cost, done.currency, true))
181 if (done.shareOnFeatures !== null) parts.push(`${percent(done.shareOnFeatures)} on features`)
182 return parts.join(' · ')
183}
184hooks/lib/records.ts 115 lines1/**
2 * What the mod hands to `tc record`: one JSON object with what only Claude
3 * Code knows about a session: its summary, the facts the mod counts, and the
4 * tags the person set by hand. tc reads the session's messages with their
5 * token counts, branches and prompt keys from Claude Code's own session files
6 * and splits the session by the rules (ADR 0010). Each record is the whole
7 * picture so far, so sending it twice changes nothing. Never prompt text.
8 */
9export interface SessionRecord {
10 agent_harness: 'claude-code'
11 session_id: string
12 summary?: string
13 /** Session facts the mod counts: turns, their duration, subagent turns. */
14 facts?: { turns: number; duration_seconds: number; subagents: number }
15 feature?: string
16 /** Every tag but the feature the person set by hand this session. */
17 tags?: Record<string, string>
18}
19
20export interface Facts {
21 turns: number
22 durationSeconds: number
23 subagents: number
24}
25
26export const NO_FACTS: Facts = { turns: 0, durationSeconds: 0, subagents: 0 }
27
28/** The facts after one more turn: a subagent's turn counts as a subagent, a main one as a turn. */
29export function countTurn(facts: Facts, durationMs: number, isSubagent: boolean): Facts {
30 return {
31 turns: facts.turns + (isSubagent ? 0 : 1),
32 durationSeconds: facts.durationSeconds + Math.max(0, durationMs) / 1000,
33 subagents: facts.subagents + (isSubagent ? 1 : 0),
34 }
35}
36
37export function sessionRecord(
38 sessionId: string,
39 summary: string | null,
40 facts: Facts,
41 handTags: Readonly<Record<string, string>>,
42): SessionRecord {
43 const { feature, ...tags } = handTags
44 const hasFacts = facts.turns > 0 || facts.subagents > 0
45 return {
46 agent_harness: 'claude-code',
47 session_id: sessionId,
48 ...(summary === null ? {} : { summary }),
49 ...(hasFacts
50 ? {
51 facts: {
52 turns: facts.turns,
53 duration_seconds: Math.round(facts.durationSeconds),
54 subagents: facts.subagents,
55 },
56 }
57 : {}),
58 ...(feature === undefined ? {} : { feature }),
59 ...(Object.keys(tags).length === 0 ? {} : { tags }),
60 }
61}
62
63/**
64 * Reads `/tc` arguments: `feature KD-214`, `tag purpose=spike`, `report team`,
65 * `submit`, or nothing (opens the pane).
66 */
67export type Command =
68 | { kind: 'open' }
69 | { kind: 'tags'; tags: Record<string, string> }
70 | { kind: 'report'; by: string }
71 | { kind: 'submit' }
72 | { kind: 'help'; problem?: string }
73
74export function parseCommand(args: string): Command {
75 const words = args.trim().split(/\s+/).filter(Boolean)
76 const [verb, ...rest] = words
77 switch (verb) {
78 case undefined:
79 return { kind: 'open' }
80 case 'feature':
81 if (rest.length !== 1 || rest[0] === undefined) {
82 return { kind: 'help', problem: 'Name one feature, such as /tc feature KD-214.' }
83 }
84 return { kind: 'tags', tags: { feature: rest[0] } }
85 case 'tag': {
86 if (rest.length === 0) {
87 return { kind: 'help', problem: 'Name a tag, such as /tc tag purpose=spike.' }
88 }
89 const tags: Record<string, string> = {}
90 for (const pair of rest) {
91 const at = pair.indexOf('=')
92 if (at <= 0 || at === pair.length - 1) {
93 return { kind: 'help', problem: `"${pair}" is not name=value.` }
94 }
95 tags[pair.slice(0, at)] = pair.slice(at + 1)
96 }
97 return { kind: 'tags', tags }
98 }
99 case 'report':
100 return { kind: 'report', by: rest[0] ?? 'feature' }
101 case 'submit':
102 return { kind: 'submit' }
103 default:
104 return { kind: 'help', problem: `/tc has no "${verb}".` }
105 }
106}
107
108export const HELP = [
109 '/tc feature KD-214 put this session on a feature',
110 '/tc tag purpose=spike set any other tag',
111 '/tc report [by] a report table, by feature, project, any tag or day',
112 '/tc submit submit everything since your last submit',
113 '/tc open the pane',
114].join('\n')
115hooks/lib/summary.ts 61 lines1/**
2 * The session's summary: one line on what the session did, written during the
3 * session by a small model call, so it exists even if the session is closed
4 * abruptly. It is the only text of a message besides the tag values, so
5 * it names the work and never quotes code, secrets or customer data.
6 */
7
8export const SUMMARY_MODEL = 'haiku'
9
10export const SUMMARY_SYSTEM = [
11 'You write the one-line summary of a coding agent session for a cost report.',
12 'Say what the work was, in plain words, as a person would log it on a timesheet:',
13 'for example "Fixed rounding in the checkout total and added tests" or',
14 '"Reviewed pull request 88 for the search page".',
15 'One sentence, at most 120 characters, no quotes, no trailing period.',
16 'Never include code, file contents, secrets, names of customers or personal data.',
17 'Answer with the sentence alone.',
18].join(' ')
19
20export interface Message {
21 role: 'user' | 'assistant'
22 text: string
23}
24
25const PER_MESSAGE = 1500
26const IN_ALL = 12_000
27
28/** The prompt: the summary so far and the latest messages, newest last. */
29export function summaryPrompt(previous: string | null, messages: readonly Message[]): string {
30 const picked: string[] = []
31 let room = IN_ALL
32 for (const message of [...messages].reverse()) {
33 const text = message.text.trim()
34 if (text === '') continue
35 const cut = text.length > PER_MESSAGE ? `${text.slice(0, PER_MESSAGE)}…` : text
36 const line = `${message.role === 'user' ? 'Person' : 'Agent'}: ${cut}`
37 if (line.length > room) break
38 picked.unshift(line)
39 room -= line.length
40 }
41 return [
42 previous ? `The summary so far: ${previous}` : 'There is no summary yet.',
43 '',
44 'The latest messages of the session:',
45 ...picked,
46 '',
47 'Write the summary of the whole session so far.',
48 ].join('\n')
49}
50
51/** The model's answer as one clean line, or null when it gave none. */
52export function cleanSummary(answer: string): string | null {
53 const line = answer
54 .split('\n')
55 .map(part => part.trim())
56 .find(part => part !== '')
57 if (line === undefined) return null
58 const bare = line.replace(/^["'“”]+|["'“”]+$/g, '').replace(/\.$/, '')
59 return bare.length > 200 ? `${bare.slice(0, 199)}…` : bare
60}
61hooks/lib/tc.ts 210 lines1/**
2 * The parts of `tc --json` output the mod reads. tc owns local state, rules
3 * and submission (ADR 0010); the mod only shows what tc says and passes on
4 * what the person does. Every reader here is lenient: a field tc leaves out
5 * reads as unknown, never as a crash.
6 */
7
8/** An org manager's request to submit before the cutoff moves. */
9export interface AskedToSubmit {
10 /** The date the cutoff moves to, such as `2026-09-30`. */
11 cutoff: string
12 askedBy: string | null
13}
14
15/** `tc status --json`: today's cost and the share on features. */
16export interface Status {
17 isConnected: boolean
18 organization: string | null
19 currency: string
20 /** Today's cost from the price table. */
21 today: number
22 /** 0 to 1, or null while there is nothing to share. */
23 shareOnFeatures: number | null
24 askedToSubmit: AskedToSubmit | null
25}
26
27export interface Split {
28 /** 0 to 1, or null when tc does not say. */
29 fraction: number | null
30 tags: Record<string, string>
31}
32
33/** One session of `tc review --json`. */
34export interface ReviewRow {
35 number: number
36 sessionId: string | null
37 startedAt: string | null
38 /** The cost from the price table, or null while the model has no price. */
39 cost: number | null
40 summary: string
41 isRejected: boolean
42 rejectedReason: string | null
43 /** What wrote the split: `rule: key in branch`, `hand`, or `no rule matched`. */
44 assignedBy: string | null
45 /** `direct`, `project overhead` or `organization overhead`. */
46 label: string | null
47 splits: Split[]
48}
49
50export interface ReportRow {
51 /** The tag value, or null for the cost that has none. */
52 value: string | null
53 cost: number
54 /** 0 to 1 of the total. */
55 share: number | null
56}
57
58export interface Report {
59 by: string
60 currency: string
61 rows: ReportRow[]
62 total: number
63}
64
65export interface Rule {
66 /** Its place in the list, as `tc rules remove N` takes it. */
67 number: number
68 text: string
69}
70
71/** `tc submit --json`. */
72export interface Submitted {
73 count: number
74 cost: number | null
75 currency: string
76 shareOnFeatures: number | null
77}
78
79type Json = Record<string, unknown>
80
81function object(value: unknown): Json {
82 return typeof value === 'object' && value !== null && !Array.isArray(value) ? (value as Json) : {}
83}
84
85/** A number, or a decimal string as tc sends money and fractions. */
86function num(value: unknown): number | null {
87 if (typeof value === 'number' && Number.isFinite(value)) return value
88 if (typeof value === 'string' && value.trim() !== '' && Number.isFinite(Number(value))) {
89 return Number(value)
90 }
91 return null
92}
93
94function str(value: unknown): string | null {
95 return typeof value === 'string' && value !== '' ? value : null
96}
97
98function fromPercent(percent: unknown): number | null {
99 const n = num(percent)
100 return n === null ? null : n / 100
101}
102
103function tags(value: unknown): Record<string, string> {
104 const out: Record<string, string> = {}
105 for (const [name, v] of Object.entries(object(value))) {
106 if (typeof v === 'string') out[name] = v
107 }
108 return out
109}
110
111function array(value: unknown): unknown[] {
112 return Array.isArray(value) ? value : []
113}
114
115/** A list, bare or under `key`. */
116function list(value: unknown, key: string): unknown[] {
117 return Array.isArray(value) ? value : array(object(value)[key])
118}
119
120export function parseJson(text: string): unknown {
121 try {
122 return JSON.parse(text)
123 } catch {
124 return undefined
125 }
126}
127
128export function readStatus(value: unknown): Status {
129 const top = object(value)
130 const today = object(top.today)
131 const asked = object(top.asked_to_submit)
132 const cutoff = str(asked.cutoff)
133 return {
134 isConnected: top.connected === true,
135 organization: str(top.organization),
136 currency: str(today.currency) ?? 'USD',
137 today: num(today.cost) ?? 0,
138 shareOnFeatures: fromPercent(today.share_on_features_percent),
139 askedToSubmit: cutoff === null ? null : { cutoff, askedBy: str(asked.asked_by) },
140 }
141}
142
143export function readSession(value: unknown): ReviewRow | null {
144 const row = object(value)
145 const number = num(row.number)
146 if (number === null) return null
147 return {
148 number,
149 sessionId: str(row.session_id),
150 startedAt: str(row.started_at),
151 cost: num(row.cost),
152 summary: str(row.summary) ?? '',
153 isRejected: row.status === 'rejected',
154 rejectedReason: str(row.rejected_reason),
155 assignedBy: str(row.assigned_by),
156 label: str(row.label),
157 splits: array(row.splits).map(item => {
158 const split = object(item)
159 return { fraction: num(split.fraction), tags: tags(split.tags) }
160 }),
161 }
162}
163
164export function readReview(value: unknown): ReviewRow[] {
165 return list(value, 'sessions').flatMap(item => {
166 const row = readSession(item)
167 return row === null ? [] : [row]
168 })
169}
170
171export function readReport(value: unknown, by: string): Report {
172 const top = object(value)
173 const rows = list(value, 'rows').flatMap(item => {
174 const row = object(item)
175 const cost = num(row.cost)
176 return cost === null ? [] : [{ value: str(row.value), cost }]
177 })
178 const total = num(top.total) ?? rows.reduce((sum, row) => sum + row.cost, 0)
179 return {
180 by: str(top.by) ?? by,
181 currency: str(top.currency) ?? 'USD',
182 rows: rows.map(row => ({ ...row, share: total > 0 ? row.cost / total : null })),
183 total,
184 }
185}
186
187export function readRules(value: unknown): Rule[] {
188 return list(value, 'rules').flatMap((item, index) => {
189 const row = object(item)
190 const text = str(row.text) ?? str(row.name)
191 return text === null ? [] : [{ number: num(row.number) ?? index + 1, text }]
192 })
193}
194
195export function readSubmitted(value: unknown): Submitted {
196 const top = object(value)
197 return {
198 count: num(top.submitted) ?? 0,
199 cost: num(top.cost),
200 currency: str(top.currency) ?? 'USD',
201 shareOnFeatures: fromPercent(top.share_on_features_percent),
202 }
203}
204
205/** The first line tc wrote on stderr, or a plain fallback: what the person reads. */
206export function reason(stderr: string, stdout: string, fallback: string): string {
207 const line = (stderr.trim() || stdout.trim()).split('\n')[0]?.trim()
208 return line || fallback
209}
210types/index.d.ts 63 lines1// The values the Token Controller mod keeps for a session. What tc says is
2// mirrored here so the band and the pane draw without calling tc.
3
4/** An org manager's request to submit before the cutoff moves to `cutoff`. */
5export type AskedToSubmit = { cutoff: string; askedBy: string | null }
6
7export type Status = {
8 isConnected: boolean
9 organization: string | null
10 currency: string
11 today: number
12 shareOnFeatures: number | null
13 askedToSubmit: AskedToSubmit | null
14}
15
16export type Split = { fraction: number | null; tags: Record<string, string> }
17
18export type ReviewRow = {
19 number: number
20 sessionId: string | null
21 startedAt: string | null
22 cost: number | null
23 summary: string
24 isRejected: boolean
25 rejectedReason: string | null
26 assignedBy: string | null
27 label: string | null
28 splits: Split[]
29}
30
31export type ReportRow = { value: string | null; cost: number; share: number | null }
32
33export type Report = { by: string; currency: string; rows: ReportRow[]; total: number }
34
35export type Rule = { number: number; text: string }
36
37export type Tab = 'review' | 'report' | 'rules'
38
39/** The session facts the mod counts itself; tc reads the rest from the session files. */
40export type Facts = { turns: number; durationSeconds: number; subagents: number }
41
42declare module 'claude-code' {
43 interface PluginState {
44 'token-controller': {
45 status: Status | null
46 review: ReviewRow[]
47 report: Report | null
48 reportBy: string
49 rules: Rule[]
50 tab: Tab
51 editing: number | null
52 notice: string | null
53 problem: string | null
54 /** The feature tc split this session on, for the band. */
55 feature: string | null
56 /** The tags the person set by hand this session, feature included. */
57 handTags: Record<string, string>
58 summary: string | null
59 facts: Facts
60 }
61 }
62}
63