KOZMOS Stamp: a receipt on every finished turn. The closing 'Baked for 42s' line becomes a compact row of duration, tool calls by family as colored chips…

A receipt on every finished turn. The closing line of a main-loop turn (Baked for 42s) becomes one compact row:
⏱ 42s · 12 tools $5 ✎4 ◉3 · ↑3.1k ↓8.2k tok · $0.31 · ctx 58% (+4%)
The figures come from turn.start, turn.step usage, tool.call and turn.complete, with $.session.usage() read at both ends of the turn.
How a line finds its turn. The TurnDuration line carries only its word and durationMs. Each main-loop turn.complete appends a receipt in order of completion; a line takes the receipt whose duration is closest to its own within 1.5 s (or 3 %), the latest winning a tie. A line with no such receipt (a resumed transcript, a turn from before the mod loaded) keeps the engine's own text.
/stamp toggles it (/stamp on, /stamp off), remembered across sessions; /stamp last prints the last receipt. On a surface with Svg the receipt is one SVG row with pill chips; today the engine raises this line on the terminal only.
Her biten turun altına bir fiş. Ana döngüdeki bir turu kapatan satır (Baked for 42s) tek ve kompakt bir satıra dönüşür: süre, aile renkli glif çipleriyle araç çağrıları, giden/gelen token, turun maliyeti ve bağlam doluluğu ile turun eklediği pay. Satır, turuna durationMs değeriyle eşleşir (tamamlanma sırasıyla kaydedilen fişlerden en yakın süreli olanı, 1,5 sn / %3 tolerans); eşleşme yoksa motorun kendi metni kalır. /stamp aç/kapa yapar ve tercihi saklar; /stamp last son fişi yazar.
hooks/register.tsx 283 lines1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, ModelUsage, Register, RenderNode } from 'claude-code'
3
4import type { StampChip, StampReceipt } from '../types'
5import { KZ, costOf, fmtPct, fmtTokens, fmtUsd, pxOf, svg, svgText, textWidth, toolColor, toolGlyph } from './lib/kz.ts'
6
7// How a TurnDuration line finds its turn
8// ---------------------------------------
9// The line's props carry no turn id: only the sampled word and `durationMs`.
10// Every main-loop turn.complete appends a receipt, in order of completion,
11// holding the same wall-clock `durationMs` the engine formats on that line.
12// A line takes the receipt whose duration is closest to its own within a small
13// tolerance (1.5 s or 3 %), the most recent one winning a tie, so two turns of
14// equal length resolve to the later (the one drawn last). A line with no such
15// receipt (a resumed transcript, a turn from before the mod loaded) keeps the
16// engine's own text. The match needs no write while drawing, which a render
17// hook may not do, and survives a reload: the receipts live in $.state.
18
19const receiptsAtom = atom({ plugin: 'stamp', key: 'receipts' } as const, [])
20const onAtom = atom({ plugin: 'stamp', key: 'isOn' } as const, true)
21const KEEP = 120
22
23type Pending = {
24 turnId: string
25 startedAt: number
26 startCost?: number
27 startCtx?: number
28 tools: number
29 families: Record<string, StampChip>
30 /** The main loop's requests summed; undefined until one reports usage. */
31 steps?: ModelUsage
32 model: string
33}
34
35let current: Pending | undefined
36
37const FAMILY_ORDER = ['shell', 'edit', 'read', 'search', 'agent', 'web', 'task', 'mcp', 'other']
38
39function familyOf(tool: string): string {
40 if (tool === 'Bash' || tool === 'PowerShell') return 'shell'
41 if (tool === 'Edit' || tool === 'Write' || tool === 'NotebookEdit' || tool === 'MultiEdit') return 'edit'
42 if (tool === 'Read') return 'read'
43 if (tool === 'Glob' || tool === 'Grep' || tool === 'LSP') return 'search'
44 if (tool === 'Agent' || tool === 'Task' || tool === 'Workflow') return 'agent'
45 if (tool.startsWith('Web')) return 'web'
46 if (tool.startsWith('Todo') || tool.startsWith('Task')) return 'task'
47 if (tool.startsWith('mcp__')) return 'mcp'
48 return 'other'
49}
50
51/** 42s, 1m 4s, 1h 2m: the way the engine's own line reads. */
52function fmtTurn(ms: number): string {
53 const s = Math.max(0, Math.round(ms / 1000))
54 if (s < 60) return `${s}s`
55 const m = Math.floor(s / 60)
56 if (m < 60) return `${m}m ${s % 60}s`
57 return `${Math.floor(m / 60)}h ${m % 60}m`
58}
59
60/** The receipt a TurnDuration line of `durationMs` belongs to, or undefined. */
61function matchReceipt(receipts: readonly StampReceipt[], durationMs: number): StampReceipt | undefined {
62 const tolerance = Math.max(1500, durationMs * 0.03)
63 let best: StampReceipt | undefined
64 let bestDiff = Infinity
65 for (const r of receipts) {
66 const diff = Math.abs(r.durationMs - durationMs)
67 if (diff <= tolerance && diff <= bestDiff) {
68 best = r
69 bestDiff = diff
70 }
71 }
72 return best
73}
74
75type Seg = { text: string; kind: 'lead' | 'strong' | 'dim' | 'chip' | 'cost' | 'ctx'; color?: string }
76
77/** The receipt as a list of segments both surfaces draw. */
78function segments(r: StampReceipt, durationMs: number): Seg[] {
79 const out: Seg[] = [{ text: '⏱ ', kind: 'lead', color: KZ.violet }, { text: fmtTurn(durationMs), kind: 'strong' }]
80 if (r.tools > 0) {
81 out.push({ text: ` · ${r.tools} tool${r.tools === 1 ? '' : 's'}`, kind: 'dim' })
82 for (const c of r.chips) out.push({ text: `${toolGlyph(c.tool)}${c.n}`, kind: 'chip', color: toolColor(c.tool) })
83 }
84 if (r.inTokens !== undefined && r.outTokens !== undefined) {
85 out.push({ text: ` · ↑${fmtTokens(r.inTokens)} ↓${fmtTokens(r.outTokens)} tok`, kind: 'dim' })
86 }
87 if (r.costUsd !== undefined) out.push({ text: ` · ${fmtUsd(r.costUsd)}`, kind: 'cost', color: KZ.yellow })
88 if (r.ctxPercent !== undefined) {
89 const d = r.ctxDelta !== undefined && Math.abs(r.ctxDelta) >= 1 ? ` (${r.ctxDelta > 0 ? '+' : ''}${Math.round(r.ctxDelta)}%)` : ''
90 const color = r.ctxPercent >= 80 ? KZ.red : r.ctxPercent >= 60 ? KZ.amber : KZ.cyan
91 out.push({ text: ` · ctx ${fmtPct(r.ctxPercent)}${d}`, kind: 'ctx', color })
92 }
93 if (r.reason === 'aborted') out.push({ text: ' · interrupted', kind: 'ctx', color: KZ.amber })
94 else if (r.reason === 'error' || r.reason === 'refusal') out.push({ text: ` · ${r.reason}`, kind: 'ctx', color: KZ.red })
95 return out
96}
97
98const NO_USAGE: ModelUsage = { input_tokens: 0, output_tokens: 0, cache_read_input_tokens: 0, cache_creation_input_tokens: 0 }
99
100function sumUsage(a: ModelUsage | undefined, b: ModelUsage | null): ModelUsage | undefined {
101 if (!b) return a
102 const base = a ?? NO_USAGE
103 return {
104 input_tokens: base.input_tokens + b.input_tokens,
105 output_tokens: base.output_tokens + b.output_tokens,
106 cache_read_input_tokens: base.cache_read_input_tokens + b.cache_read_input_tokens,
107 cache_creation_input_tokens: base.cache_creation_input_tokens + b.cache_creation_input_tokens,
108 }
109}
110
111async function startTurn($: EngineInterface, turnId: string): Promise<void> {
112 const p: Pending = { turnId, startedAt: await $.clock.now(), tools: 0, families: {}, model: '' }
113 current = p
114 try {
115 const u = await $.session.usage()
116 p.startCost = u.cost?.usd
117 p.startCtx = u.context.percent
118 } catch {
119 // No figures at the start: the receipt leaves cost and the context change out.
120 }
121}
122
123async function finishTurn(
124 $: EngineInterface,
125 e: { turnId: string; durationMs: number; reason: string; usage?: ModelUsage & { model: string } },
126): Promise<void> {
127 const p = current?.turnId === e.turnId ? current : undefined
128 if (p) current = undefined
129 const usage: ModelUsage | undefined = e.usage ?? p?.steps
130 const model = e.usage?.model ?? p?.model ?? ''
131 let endCost: number | undefined
132 let ctx: number | undefined
133 try {
134 const u = await $.session.usage()
135 endCost = u.cost?.usd
136 ctx = u.context.percent
137 } catch {
138 // Keep what the turn's own usage says.
139 }
140 const delta = endCost !== undefined && p?.startCost !== undefined ? endCost - p.startCost : undefined
141 const costUsd = delta !== undefined && delta >= 0 ? delta : usage ? costOf(model, usage) : undefined
142 const chips = p
143 ? FAMILY_ORDER.map(f => p.families[f]).filter((c): c is StampChip => c !== undefined)
144 : []
145 const receipt: StampReceipt = {
146 turnId: e.turnId,
147 durationMs: e.durationMs,
148 endedAt: await $.clock.now(),
149 reason: e.reason,
150 tools: p?.tools ?? 0,
151 chips,
152 inTokens: usage ? usage.input_tokens + usage.cache_creation_input_tokens : undefined,
153 outTokens: usage?.output_tokens,
154 cacheRead: usage?.cache_read_input_tokens,
155 costUsd,
156 ctxPercent: ctx,
157 ctxDelta: ctx !== undefined && p?.startCtx !== undefined ? ctx - p.startCtx : undefined,
158 }
159 await update($, receiptsAtom, prev => [...prev.filter(r => r.turnId !== receipt.turnId), receipt].slice(-KEEP))
160}
161
162async function setOn($: EngineInterface, isOn: boolean): Promise<void> {
163 await update($, onAtom, () => isOn)
164 await $.store.set('isOn', isOn)
165}
166
167function lastText(r: StampReceipt | undefined): string {
168 if (!r) return 'no turn finished yet'
169 // A chip reads after a space, as the terminal draws it (` $2`).
170 return segments(r, r.durationMs).map(s => (s.kind === 'chip' ? ' ' : '') + s.text).join('').replace(/\s+/g, ' ').trim()
171}
172
173export const register: Register = on => {
174 on('session.start', async ($, e, next) => {
175 const started = await next(e)
176 current = undefined
177 await $.command.register({ name: 'stamp', description: 'KOZMOS: toggle the turn receipt (/stamp on|off|last)', argumentHint: '[on|off|last]', immediate: true })
178 try {
179 const stored = await $.store.get('isOn')
180 await update($, onAtom, () => stored !== false)
181 } catch {
182 // Default on.
183 }
184 return started
185 })
186
187 on('command.run', { command: 'stamp' }, async ($, e) => {
188 const arg = e.args.trim().toLowerCase()
189 if (arg === 'last') {
190 const list = await read($, receiptsAtom)
191 return { text: `Last turn: ${lastText(list[list.length - 1])}` }
192 }
193 const isOn = arg === 'on' ? true : arg === 'off' ? false : !(await read($, onAtom))
194 await setOn($, isOn)
195 return { text: isOn ? 'Stamp on: each finished turn closes with a receipt.' : 'Stamp off: the engine draws its own closing line.' }
196 })
197
198 on('turn.start', async ($, e, next) => {
199 await startTurn($, e.turnId).catch(() => undefined)
200 return next(e)
201 }).catch(($, e, next) => next(e))
202
203 on('turn.step', async function* ($, e, next) {
204 const r = yield* next(e)
205 if (e.agentId === undefined && current && current.turnId === e.turnId) {
206 current.steps = sumUsage(current.steps, r.usage)
207 current.model = r.usage?.model ?? e.model
208 }
209 return r
210 })
211
212 on('tool.call', async ($, e, next) => {
213 if (e.agentId === undefined && current) {
214 const tool = String(e.tool)
215 const fam = familyOf(tool)
216 current.tools++
217 const c = current.families[fam]
218 current.families[fam] = c ? { ...c, n: c.n + 1 } : { family: fam, tool, n: 1 }
219 }
220 return next(e)
221 }).catch(($, e, next) => next(e))
222
223 on('turn.complete', async ($, e, next) => {
224 const r = await next(e)
225 if (e.agentId === undefined) void finishTurn($, e).catch(() => undefined)
226 return r
227 }).catch(($, e, next) => next(e))
228
229 on('ui.render', { component: 'TurnDuration' }, async ($, e, next) => {
230 if (!(await read($, onAtom))) return next(e)
231 const receipt = matchReceipt(await read($, receiptsAtom), e.props.durationMs)
232 if (!receipt) return next(e)
233 const segs = segments(receipt, e.props.durationMs)
234 const ui = $.ui.resolve(e)
235 const alt = `${e.props.word} for ${lastText({ ...receipt, durationMs: e.props.durationMs })}`
236
237 if ('Svg' in ui && e.surface !== 'terminal') {
238 const { Svg } = ui
239 const W = pxOf(e.viewport?.columns, 90)
240 const { source, width } = receiptSvg(segs, W)
241 return <Svg source={source} alt={alt} width={width} height={22} />
242 }
243
244 const { Box, Text } = ui
245 const parts: RenderNode[] = segs.map((s, i) => {
246 if (s.kind === 'chip') return <Text key={`s${i}`} color={s.color}> {s.text}</Text>
247 if (s.kind === 'strong') return <Text key={`s${i}`} bold>{s.text}</Text>
248 if (s.kind === 'dim') return <Text key={`s${i}`} dimColor>{s.text}</Text>
249 return <Text key={`s${i}`} color={s.color}>{s.text}</Text>
250 })
251 return (
252 <Box flexDirection="row">
253 <Text wrap="truncate-end">{parts}</Text>
254 </Box>
255 )
256 })
257}
258
259/** The receipt as one SVG row: text segments and the family chips as pills. */
260function receiptSvg(segs: readonly Seg[], maxW: number): { source: string; width: number } {
261 const size = 12
262 const body: string[] = []
263 let x = 2
264 for (const s of segs) {
265 if (s.kind === 'chip') {
266 const w = textWidth(s.text, 11) + 12
267 body.push(`<rect x="${x + 4}" y="3" width="${w}" height="16" rx="8" fill="${s.color}" opacity=".18"/>`)
268 body.push(svgText(x + 4 + w / 2, 15, s.text, { size: 11, weight: 650, anchor: 'middle', fill: s.color }))
269 x += w + 4
270 continue
271 }
272 const opts = s.kind === 'strong'
273 ? { size, weight: 650 }
274 : s.kind === 'dim'
275 ? { cls: 's', size }
276 : { size, weight: 600, fill: s.color }
277 body.push(svgText(x, 15, s.text, opts))
278 x += textWidth(s.text, size)
279 }
280 const width = Math.min(maxW, Math.ceil(x + 6))
281 return { source: svg(width, 22, body.join('')), width }
282}
283hooks/lib/kz.ts 510 lines1// GENERATED by scripts/sync-shared.mjs from shared/kz.ts. Do not edit here.
2// KOZMOS shared kit. Source of truth: shared/kz.ts at the bundle root.
3// `node scripts/sync-shared.mjs` copies it into every mod as hooks/lib/kz.ts,
4// because a hooks module may only import files inside its own plugin.
5// Edit the root copy, never a mod's copy.
6
7// ---------------------------------------------------------------------------
8// Palette: one neon family across every KOZMOS mod.
9
10export const KZ = {
11 violet: '#a78bfa',
12 magenta: '#f472b6',
13 cyan: '#22d3ee',
14 teal: '#2dd4bf',
15 green: '#4ade80',
16 lime: '#a3e635',
17 yellow: '#facc15',
18 amber: '#fb923c',
19 red: '#f87171',
20 blue: '#60a5fa',
21 clay: '#d97757',
22 ink: '#1f1e1d',
23 mist: '#9ca3af',
24} as const
25
26/** Tool families, colored the same in every mod. */
27export function toolColor(tool: string): string {
28 const t = String(tool)
29 if (t === 'Bash' || t === 'PowerShell') return KZ.green
30 if (t === 'Edit' || t === 'Write' || t === 'NotebookEdit' || t === 'MultiEdit') return KZ.yellow
31 if (t === 'Read' || t === 'Glob' || t === 'Grep' || t === 'LSP') return KZ.blue
32 if (t === 'Agent' || t === 'Task' || t === 'Workflow') return KZ.violet
33 if (t.startsWith('Web')) return KZ.cyan
34 if (t.startsWith('Todo') || t.startsWith('Task')) return KZ.teal
35 if (t.startsWith('mcp__')) return KZ.magenta
36 return KZ.mist
37}
38
39/** A short glyph per tool family. */
40export function toolGlyph(tool: string): string {
41 const t = String(tool)
42 if (t === 'Bash' || t === 'PowerShell') return '$'
43 if (t === 'Edit' || t === 'Write' || t === 'NotebookEdit') return '✎'
44 if (t === 'Read') return '◉'
45 if (t === 'Glob' || t === 'Grep') return '⌕'
46 if (t === 'Agent') return '◈'
47 if (t.startsWith('Web')) return '◍'
48 if (t.startsWith('Todo') || t.startsWith('Task')) return '☑'
49 if (t.startsWith('mcp__')) return '⬡'
50 return '•'
51}
52
53// ---------------------------------------------------------------------------
54// Colors.
55
56export function hexToRgb(hex: string): [number, number, number] {
57 const h = hex.replace('#', '')
58 const n = parseInt(h.length === 3 ? h.split('').map(c => c + c).join('') : h, 16)
59 return [(n >> 16) & 255, (n >> 8) & 255, n & 255]
60}
61
62export function rgbToHex(r: number, g: number, b: number): string {
63 const c = (v: number) => Math.max(0, Math.min(255, Math.round(v))).toString(16).padStart(2, '0')
64 return `#${c(r)}${c(g)}${c(b)}`
65}
66
67export function mix(a: string, b: string, t: number): string {
68 const [r1, g1, b1] = hexToRgb(a)
69 const [r2, g2, b2] = hexToRgb(b)
70 const k = clamp01(t)
71 return rgbToHex(r1 + (r2 - r1) * k, g1 + (g2 - g1) * k, b1 + (b2 - b1) * k)
72}
73
74/** Green at 0, yellow at 0.6, red at 1: the heat of a gauge. */
75export function heat(t: number): string {
76 const k = clamp01(t)
77 return k < 0.6 ? mix(KZ.green, KZ.yellow, k / 0.6) : mix(KZ.yellow, KZ.red, (k - 0.6) / 0.4)
78}
79
80/** A smooth rainbow for hues 0..1 (for auroras, plasma and the like). */
81export function hue(h: number, s = 0.75, l = 0.6): string {
82 const k = ((h % 1) + 1) % 1
83 const a = s * Math.min(l, 1 - l)
84 const f = (n: number) => {
85 const x = (n + k * 12) % 12
86 return l - a * Math.max(-1, Math.min(x - 3, 9 - x, 1))
87 }
88 return rgbToHex(f(0) * 255, f(8) * 255, f(4) * 255)
89}
90
91export function hexToInt(hex: string): number {
92 const [r, g, b] = hexToRgb(hex)
93 return (r << 16) | (g << 8) | b
94}
95
96// ---------------------------------------------------------------------------
97// Numbers and text.
98
99export const clamp01 = (v: number): number => (Number.isFinite(v) ? Math.max(0, Math.min(1, v)) : 0)
100
101export function fmtTokens(n: number): string {
102 if (!Number.isFinite(n)) return '—'
103 // Each unit starts where the one below would round up to 1000 of itself.
104 if (n >= 999.5e6) return `${(n / 1e9).toFixed(1)}B`
105 if (n >= 999_500) return `${(n / 1e6).toFixed(n >= 1e7 ? 0 : 1)}M`
106 if (n >= 999.5) return `${(n / 1e3).toFixed(n >= 1e4 ? 0 : 1)}k`
107 return `${Math.round(n)}`
108}
109
110export function fmtUsd(usd: number): string {
111 if (!Number.isFinite(usd)) return '$—'
112 if (usd < 0.01 && usd > 0) return '<$0.01'
113 return usd < 100 ? `$${usd.toFixed(2)}` : `$${Math.round(usd)}`
114}
115
116/** 0:42, 3:07, 1:02:33. */
117export function fmtClock(ms: number): string {
118 const s = Math.max(0, Math.round(ms / 1000))
119 const h = Math.floor(s / 3600)
120 const m = Math.floor((s % 3600) / 60)
121 const ss = String(s % 60).padStart(2, '0')
122 return h ? `${h}:${String(m).padStart(2, '0')}:${ss}` : `${m}:${ss}`
123}
124
125/** 42s, 7m, 2h41m, 3d4h: compact durations for countdowns. */
126export function fmtSpan(ms: number): string {
127 const s = Math.max(0, Math.round(ms / 1000))
128 if (s < 60) return `${s}s`
129 const m = Math.floor(s / 60)
130 if (m < 60) return `${m}m`
131 const h = Math.floor(m / 60)
132 if (h < 48) return `${h}h${String(m % 60).padStart(2, '0')}m`
133 return `${Math.floor(h / 24)}d${h % 24}h`
134}
135
136export function fmtPct(p: number | undefined): string {
137 return p === undefined || !Number.isFinite(p) ? '—' : `${Math.round(p)}%`
138}
139
140export function clip(s: string, max: number): string {
141 const one = s.replace(/\s+/g, ' ').trim()
142 return one.length > max ? one.slice(0, Math.max(1, max - 1)) + '…' : one
143}
144
145export function padEnd(s: string, n: number): string {
146 return s.length >= n ? s.slice(0, n) : s + ' '.repeat(n - s.length)
147}
148
149export function padStart(s: string, n: number): string {
150 return s.length >= n ? s.slice(s.length - n) : ' '.repeat(n - s.length) + s
151}
152
153/** `claude-opus-5-5[1m]` → `Opus 5.5`. */
154export function modelName(id: string | undefined): string {
155 if (!id) return '—'
156 const m = /(fable|mythos|opus|sonnet|haiku)-(\d+)(?:-(\d{1,2})(?!\d))?/i.exec(id)
157 if (!m) return id.replace(/^claude-/, '').replace(/\[.*\]$/, '')
158 const fam = m[1]!
159 return `${fam.charAt(0).toUpperCase()}${fam.slice(1).toLowerCase()} ${m[2]}${m[3] ? '.' + m[3] : ''}`
160}
161
162/** Last path segment, either slash. */
163export function baseName(p: string): string {
164 const parts = p.split(/[\\/]/).filter(Boolean)
165 return parts[parts.length - 1] ?? p
166}
167
168/** A stable small hash for seeding. */
169export function hash(s: string): number {
170 let h = 2166136261
171 for (let i = 0; i < s.length; i++) {
172 h ^= s.charCodeAt(i)
173 h = Math.imul(h, 16777619)
174 }
175 return h >>> 0
176}
177
178/** Deterministic 0..1 noise from two ints. */
179export function noise(x: number, y: number): number {
180 const s = Math.sin(x * 12.9898 + y * 78.233) * 43758.5453
181 return s - Math.floor(s)
182}
183
184/** A seeded PRNG (mulberry32). */
185export function rng(seed: number): () => number {
186 let a = seed >>> 0
187 return () => {
188 a = (a + 0x6d2b79f5) >>> 0
189 let t = a
190 t = Math.imul(t ^ (t >>> 15), t | 1)
191 t ^= t + Math.imul(t ^ (t >>> 7), t | 61)
192 return ((t ^ (t >>> 14)) >>> 0) / 4294967296
193 }
194}
195
196// ---------------------------------------------------------------------------
197// Text gauges for the terminal.
198
199const EIGHTHS = ['', '▏', '▎', '▍', '▌', '▋', '▊', '▉']
200
201/** A smooth bar with eighth blocks: `█████▍ `. */
202export function bar(ratio: number, width: number, empty = '░'): string {
203 const w = Math.max(1, Math.floor(width))
204 const exact = clamp01(ratio) * w
205 const full = Math.floor(exact)
206 const part = EIGHTHS[Math.floor((exact - full) * 8)] ?? ''
207 const used = full + (part ? 1 : 0)
208 return '█'.repeat(full) + part + empty.repeat(Math.max(0, w - used))
209}
210
211/** A segmented gauge: `▰▰▰▱▱▱`. */
212export function pips(ratio: number, width: number, on = '▰', off = '▱'): string {
213 const w = Math.max(1, Math.floor(width))
214 const n = Math.round(clamp01(ratio) * w)
215 return on.repeat(n) + off.repeat(w - n)
216}
217
218const SPARK = '▁▂▃▄▅▆▇█'
219
220/** A sparkline of the last `width` values, scaled to their own max (or `max`). */
221export function sparkline(values: readonly number[], width: number, max?: number): string {
222 const tail = values.slice(-Math.max(1, width))
223 const top = max ?? Math.max(1e-9, ...tail)
224 const line = tail.map(v => SPARK[Math.min(7, Math.max(0, Math.round((v / top) * 7)))] ?? '▁').join('')
225 return line.padStart(width, ' ')
226}
227
228/** Braille line graph, 2 samples per cell, `rows` cells tall. */
229export function brailleGraph(values: readonly number[], width: number, rows: number, max?: number): string[] {
230 const samples = values.slice(-(width * 2))
231 const top = max ?? Math.max(1e-9, ...samples)
232 const dotsTall = rows * 4
233 const grid: number[][] = Array.from({ length: rows }, () => Array.from({ length: width }, () => 0))
234 const offset = width * 2 - samples.length
235 // Dot bits per column, from the bottom row of a cell up.
236 const LEFT = [0x40, 0x04, 0x02, 0x01]
237 const RIGHT = [0x80, 0x20, 0x10, 0x08]
238 samples.forEach((v, i) => {
239 const x = offset + i
240 const col = Math.floor(x / 2)
241 const isRight = x % 2 === 1
242 const h = Math.round(clamp01(v / top) * (dotsTall - 1))
243 for (let d = 0; d <= h; d++) {
244 const row = rows - 1 - Math.floor(d / 4)
245 const bits = isRight ? RIGHT : LEFT
246 const cellRow = grid[row]
247 if (cellRow && col >= 0) cellRow[col] = (cellRow[col] ?? 0) | bits[d % 4]!
248 }
249 })
250 return grid.map(r => r.map(b => String.fromCharCode(0x2800 + b)).join(''))
251}
252
253// ---------------------------------------------------------------------------
254// Raster: a grid of colored cells, packed as the engine wants it.
255
256const B64 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
257
258export function toBase64(bytes: Uint8Array): string {
259 let out = ''
260 let i = 0
261 for (; i + 2 < bytes.length; i += 3) {
262 const n = (bytes[i]! << 16) | (bytes[i + 1]! << 8) | bytes[i + 2]!
263 out += B64[(n >> 18) & 63]! + B64[(n >> 12) & 63]! + B64[(n >> 6) & 63]! + B64[n & 63]!
264 }
265 const rest = bytes.length - i
266 if (rest === 1) {
267 const n = bytes[i]! << 16
268 out += B64[(n >> 18) & 63]! + B64[(n >> 12) & 63]! + '=='
269 } else if (rest === 2) {
270 const n = (bytes[i]! << 16) | (bytes[i + 1]! << 8)
271 out += B64[(n >> 18) & 63]! + B64[(n >> 12) & 63]! + B64[(n >> 6) & 63]! + '='
272 }
273 return out
274}
275
276/** The terminal's own default color, for a cell's foreground or background. */
277export const DEFAULT_COLOR = 0x01000000
278
279export class Canvas {
280 readonly cols: number
281 readonly rows: number
282 private readonly words: Uint32Array
283
284 constructor(cols: number, rows: number) {
285 this.cols = Math.max(1, Math.min(512, Math.floor(cols)))
286 this.rows = Math.max(1, Math.min(256, Math.floor(rows)))
287 this.words = new Uint32Array(this.cols * this.rows * 3)
288 this.clear()
289 }
290
291 clear(bg: number = DEFAULT_COLOR): void {
292 for (let i = 0; i < this.cols * this.rows; i++) {
293 this.words[i * 3] = 0x20
294 this.words[i * 3 + 1] = DEFAULT_COLOR
295 this.words[i * 3 + 2] = bg
296 }
297 }
298
299 /** Puts one width-1 character; colors are '#rrggbb' or a packed int. */
300 set(x: number, y: number, ch: string, fg?: string | number, bg?: string | number): void {
301 const cx = Math.floor(x)
302 const cy = Math.floor(y)
303 if (cx < 0 || cy < 0 || cx >= this.cols || cy >= this.rows) return
304 const i = (cy * this.cols + cx) * 3
305 const code = ch.codePointAt(0) ?? 0x20
306 this.words[i] = code > 0xffff || code < 0x20 ? 0x20 : code
307 if (fg !== undefined) this.words[i + 1] = typeof fg === 'number' ? fg : hexToInt(fg)
308 if (bg !== undefined) this.words[i + 2] = typeof bg === 'number' ? bg : hexToInt(bg)
309 }
310
311 /** Writes a string left to right, clipped to the canvas. */
312 text(x: number, y: number, s: string, fg?: string | number, bg?: string | number): void {
313 let cx = x
314 for (const ch of s) {
315 this.set(cx, y, ch, fg, bg)
316 cx++
317 }
318 }
319
320 /** Paints a cell's background only, keeping its character. */
321 paint(x: number, y: number, bg: string | number): void {
322 const cx = Math.floor(x)
323 const cy = Math.floor(y)
324 if (cx < 0 || cy < 0 || cx >= this.cols || cy >= this.rows) return
325 this.words[(cy * this.cols + cx) * 3 + 2] = typeof bg === 'number' ? bg : hexToInt(bg)
326 }
327
328 /** Two vertical pixels per cell with the upper-half block: `py` is in half-cells. */
329 pixel(x: number, py: number, color: string): void {
330 const cx = Math.floor(x)
331 const cy = Math.floor(py / 2)
332 if (cx < 0 || cy < 0 || cx >= this.cols || cy >= this.rows) return
333 const i = (cy * this.cols + cx) * 3
334 const c = hexToInt(color)
335 const isTop = Math.floor(py) % 2 === 0
336 if (this.words[i] !== 0x2580) {
337 this.words[i] = 0x2580
338 this.words[i + 1] = DEFAULT_COLOR
339 this.words[i + 2] = DEFAULT_COLOR
340 }
341 if (isTop) this.words[i + 1] = c
342 else this.words[i + 2] = c
343 }
344
345 /** The `cells` prop of a Raster. */
346 encode(): string {
347 return toBase64(new Uint8Array(this.words.buffer))
348 }
349}
350
351// ---------------------------------------------------------------------------
352// SVG for the desktop: one drawing per row (the desktop wraps siblings).
353
354export const FONT = "-apple-system,BlinkMacSystemFont,'Segoe UI',Inter,sans-serif"
355export const MONO = "ui-monospace,'Cascadia Code','SF Mono',Consolas,monospace"
356
357const XML_ESC: Record<string, string> = { '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }
358
359export function xml(s: string): string {
360 return s.replace(/[&<>"']/g, c => XML_ESC[c]!)
361}
362
363/** Theme-aware classes every KOZMOS drawing shares: t text, s secondary, m muted, k track, p panel. */
364export const SVG_BASE_CSS = `
365.t{fill:#1f1f1f}.s{fill:#5f5f5c}.m{fill:#8e8e8a}.k{fill:#e7e5e0}.p{fill:#f5f4f1}.ln{stroke:#e1dfda}
366@media (prefers-color-scheme: dark){.t{fill:#ededed}.s{fill:#b4b4b0}.m{fill:#7c7c78}.k{fill:#2d2d2b}.p{fill:#232322}.ln{stroke:#363634}}
367.pulse{animation:kzp 1.6s ease-in-out infinite}@keyframes kzp{50%{opacity:.35}}
368.spin{transform-box:fill-box;transform-origin:center;animation:kzs 2s linear infinite}@keyframes kzs{to{transform:rotate(360deg)}}
369@media (prefers-reduced-motion: reduce){*{animation:none!important}}
370`
371
372export function svg(width: number, height: number, body: string, css = ''): string {
373 return `<svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="${height}" viewBox="0 0 ${width} ${height}"><style>${SVG_BASE_CSS}${css}</style>${body}</svg>`
374}
375
376/** Rough width of UI text in px, for fitting labels. */
377export function textWidth(s: string, size: number): number {
378 let w = 0
379 for (const ch of s) w += (/[\s.,:;'|!il1()[\]]/.test(ch) ? 0.3 : /[A-Z@%MWmw]/.test(ch) ? 0.72 : 0.56) * size
380 return w
381}
382
383export function fitText(s: string, size: number, maxW: number): string {
384 if (textWidth(s, size) <= maxW) return s
385 let out = ''
386 for (const ch of s) {
387 if (textWidth(out + ch + '…', size) > maxW) break
388 out += ch
389 }
390 return out + '…'
391}
392
393/** A rounded progress bar as SVG markup. */
394export function svgBar(x: number, y: number, w: number, h: number, ratio: number, color: string): string {
395 const fw = Math.max(0, Math.min(w, w * clamp01(ratio)))
396 return `<rect class="k" x="${x}" y="${y}" width="${w}" height="${h}" rx="${h / 2}"/>` +
397 (fw > 0 ? `<rect x="${x}" y="${y}" width="${Math.max(h, fw)}" height="${h}" rx="${h / 2}" fill="${color}"/>` : '')
398}
399
400/** SVG text helper. */
401export function svgText(x: number, y: number, s: string, opts: { cls?: string; size?: number; weight?: number; anchor?: 'start' | 'middle' | 'end'; fill?: string; mono?: boolean } = {}): string {
402 const { cls = 't', size = 12, weight = 400, anchor = 'start', fill, mono = false } = opts
403 return `<text ${fill ? `fill="${fill}"` : `class="${cls}"`} x="${x}" y="${y}" font-family="${mono ? MONO : FONT}" font-size="${size}" font-weight="${weight}" text-anchor="${anchor}" font-variant-numeric="tabular-nums">${xml(s)}</text>`
404}
405
406/** Pixel width a desktop pane or band gives a drawing for `columns` reported columns. */
407export function pxOf(columns: number | undefined, fallback = 60, slack = 8): number {
408 return Math.max(200, Math.min(1600, (columns || fallback) * 8 - slack))
409}
410
411// ---------------------------------------------------------------------------
412// Prices, USD per million tokens: input, output, cache read, cache write (5 min).
413// Anthropic first-party rates as of 2026-10. Used only where the engine reports
414// tokens and not money (a subagent's own spend); the session total comes from
415// $.session.usage().cost, which is the engine's.
416
417const PRICES: [RegExp, [number, number, number, number]][] = [
418 [/fable|mythos/i, [10, 50, 0.25, 12.5]],
419 [/opus-5-5/i, [4, 20, 0.2, 5]],
420 [/opus/i, [5, 25, 0.5, 6.25]],
421 [/sonnet-5/i, [2, 10, 0.2, 2.5]],
422 [/sonnet/i, [3, 15, 0.3, 3.75]],
423 [/haiku-5/i, [0.1, 0.5, 0.01, 0.125]],
424 [/haiku/i, [1, 5, 0.1, 1.25]],
425]
426
427export type Usage = {
428 input_tokens?: number
429 output_tokens?: number
430 cache_read_input_tokens?: number
431 cache_creation_input_tokens?: number
432}
433
434export function priceOf(model: string): [number, number, number, number] {
435 return PRICES.find(([re]) => re.test(model))?.[1] ?? [4, 20, 0.2, 5]
436}
437
438export function costOf(model: string, u: Usage | null | undefined): number {
439 if (!u) return 0
440 const [i, o, r, w] = priceOf(model)
441 return ((u.input_tokens ?? 0) * i + (u.output_tokens ?? 0) * o + (u.cache_read_input_tokens ?? 0) * r + (u.cache_creation_input_tokens ?? 0) * w) / 1e6
442}
443
444export function tokensOf(u: Usage | null | undefined): number {
445 if (!u) return 0
446 return (u.input_tokens ?? 0) + (u.output_tokens ?? 0) + (u.cache_read_input_tokens ?? 0) + (u.cache_creation_input_tokens ?? 0)
447}
448
449/** The context a request filled: everything it read plus what it wrote. */
450export function contextOf(u: Usage | null | undefined): number {
451 return tokensOf(u)
452}
453
454export function windowOf(model: string): number {
455 return /haiku-4/i.test(model) ? 200_000 : 1_000_000
456}
457
458// ---------------------------------------------------------------------------
459// Rate limits.
460
461export type Limit = { kind: string; percentUsed: number; resetsAt?: string }
462
463export function limitLabel(kind: string): string {
464 if (kind === 'five_hour') return '5h'
465 if (kind === 'seven_day') return '7d'
466 if (kind === 'spend_limit') return '$'
467 return kind.replace(/_/g, ' ')
468}
469
470/** Milliseconds until a window resets, or undefined. */
471export function untilReset(l: Limit, now: number): number | undefined {
472 if (!l.resetsAt) return undefined
473 const t = Date.parse(l.resetsAt)
474 return Number.isFinite(t) ? Math.max(0, t - now) : undefined
475}
476
477/** The length of a window in ms, for burn-rate math. */
478export function windowMs(kind: string): number | undefined {
479 if (kind === 'five_hour') return 5 * 3600_000
480 if (kind === 'seven_day') return 7 * 24 * 3600_000
481 return undefined
482}
483
484// ---------------------------------------------------------------------------
485// Tool calls, described in a few words.
486
487/** What a tool call is about: the command, the file, the pattern, the agent's task. */
488export function toolDetail(tool: string, input: unknown): string {
489 const e = (input ?? {}) as Record<string, unknown>
490 const s = (k: string) => (typeof e[k] === 'string' ? (e[k] as string) : '')
491 const t = String(tool)
492 if (t === 'Bash' || t === 'PowerShell') return clip(s('description') || s('command'), 60)
493 if (s('file_path')) return baseName(s('file_path'))
494 if (s('notebook_path')) return baseName(s('notebook_path'))
495 if (t === 'Agent') return clip(s('description') || s('subagent_type'), 60)
496 if (s('pattern')) return clip(s('pattern'), 60)
497 if (s('url')) return clip(s('url').replace(/^https?:\/\//, ''), 60)
498 if (s('query')) return clip(s('query'), 60)
499 if (s('subject')) return clip(s('subject'), 60)
500 if (Array.isArray(e.todos)) return `${(e.todos as unknown[]).length} todos`
501 if (t.startsWith('mcp__')) return t.split('__').slice(1).join(' · ')
502 return ''
503}
504
505/** `mcp__server__tool` → `server·tool`; built-ins unchanged. */
506export function toolName(tool: string): string {
507 const t = String(tool)
508 return t.startsWith('mcp__') ? t.split('__').slice(1).join('·') : t
509}
510types/index.d.ts 28 lines1/** One tool family's count in a turn, with a representative tool name for its glyph and color. */
2export type StampChip = { family: string; tool: string; n: number }
3
4/** What one finished main-loop turn did. */
5export type StampReceipt = {
6 turnId: string
7 /** turn.complete's wall-clock length, used to find the turn's TurnDuration line. */
8 durationMs: number
9 /** When the turn ended, in $.clock.now() ms. */
10 endedAt: number
11 reason: string
12 tools: number
13 chips: StampChip[]
14 /** Fresh input: uncached input plus cache writes. */
15 inTokens?: number
16 outTokens?: number
17 cacheRead?: number
18 costUsd?: number
19 ctxPercent?: number
20 ctxDelta?: number
21}
22
23declare module 'claude-code' {
24 interface PluginState {
25 stamp: { receipts: StampReceipt[]; isOn: boolean }
26 }
27}
28