KOZMOS Thrift: a frugal mode. /thrift on|off|auto; while on, every prompt carries a short note asking Claude to be economical (targeted reads, no broad…

A frugal mode for tight limits. /thrift on|off|auto (kept across sessions). While thrift is on, every prompt carries a short note beside it — never in it — asking Claude to be economical:
Thrift mode is on: usage limits are tight. Be economical: prefer targeted reads (specific files, line ranges) over broad searches, avoid subagents unless clearly needed, do not re-read what you already have, and keep answers concise.
auto turns thrift on by itself when the 5-hour or weekly limit passes autoAt (default 90%) and off again once that window resets.
Thrift counts the cost of every turn (each model request's usage, subagents included, priced with KOZMOS's table) as a thrift turn or a normal turn; /thrift alone prints both averages and how much less a thrift turn costs.
🪙 thrift on · 5h 92% · saving mode with a coin spinning on its edge (a Client surface module) and ✕./thrift hide|show toggles the band; thrift's mode stays as it is.The prompt.submit hook is an observer plus a rewrite of context only; its .catch passes the prompt through unchanged, so thrift can never block one.
Sıkı limitler için tutumlu mod. /thrift on|off|auto (oturumlar arasında saklanır). Thrift açıkken her istemin yanına — içine değil — Claude'dan tutumlu olmasını isteyen kısa bir not eklenir: hedefli okumalar, geniş aramalardan ve gerekmedikçe alt ajanlardan kaçınma, kısa yanıtlar.
auto, 5 saatlik ya da haftalık limit autoAt (varsayılan %90) eşiğini geçince thrift'i kendiliğinden açar, pencere sıfırlanınca kapatır.
Thrift her turun maliyetini (alt ajanlar dahil) thrift turu ya da normal tur olarak sayar; /thrift iki ortalamayı ve thrift turlarının ne kadar ucuz olduğunu gösterir.
🪙 thrift on · 5h 92% · saving mode bandı./thrift hide|show bandı gizler/gösterir.hooks/register.tsx 291 lines1import { atom, read, update } from 'claude-code'
2import type { Elements, EngineInterface, Register, RenderSurface } from 'claude-code'
3
4import type { ThriftLimit, ThriftMode, ThriftSnap, ThriftTally } from '../types'
5import type { CoinProps } from './coin.tsx'
6import { KZ, costOf, fmtPct, fmtSpan, fmtUsd, heat, limitLabel, pxOf, svg, svgBar, svgText } from './lib/kz.ts'
7
8/** What the model reads beside each prompt while thrift is on (under 50 words). */
9export const THRIFT_NOTE =
10 'Thrift mode is on: usage limits are tight. Be economical: prefer targeted reads (specific files, line ranges) over broad searches, avoid subagents unless clearly needed, do not re-read what you already have, and keep answers concise.'
11
12const blank = (mode: ThriftMode, autoAt: number): ThriftSnap => ({
13 mode,
14 isOn: mode === 'on',
15 autoAt,
16 top: null,
17 thrift: { turns: 0, cost: 0 },
18 normal: { turns: 0, cost: 0 },
19})
20
21const snapAtom = atom({ plugin: 'thrift', key: 'snap' } as const, blank('off', 90))
22const hiddenAtom = atom({ plugin: 'thrift', key: 'isHidden' } as const, false)
23
24// ---------------------------------------------------------------------------
25// The live state. Module variables start over on a reload; session.start fills them.
26
27let live: ThriftSnap = blank('off', 90)
28let limits: ThriftLimit[] = []
29let turn: { id: string; isThrift: boolean; cost: number } | null = null
30let publishedKey = ''
31
32const isMode = (v: unknown): v is ThriftMode => v === 'on' || v === 'off' || v === 'auto'
33
34/** The fullest 5h / 7d window that has not reset yet. */
35export function topLimit(all: readonly ThriftLimit[], now: number): ThriftLimit | null {
36 let top: ThriftLimit | null = null
37 for (const l of all) {
38 if (l.kind !== 'five_hour' && l.kind !== 'seven_day') continue
39 const resets = l.resetsAt ? Date.parse(l.resetsAt) : NaN
40 if (Number.isFinite(resets) && resets <= now) continue
41 if (!top || l.percentUsed > top.percentUsed) top = l
42 }
43 return top
44}
45
46async function publish($: EngineInterface): Promise<void> {
47 const key = JSON.stringify(live)
48 if (key === publishedKey) return
49 publishedKey = key
50 const copy: ThriftSnap = { ...live, top: live.top ? { ...live.top } : null, thrift: { ...live.thrift }, normal: { ...live.normal } }
51 await update($, snapAtom, () => copy)
52}
53
54/** Works out whether thrift is on, and says so when auto flips it. */
55async function evaluate($: EngineInterface): Promise<void> {
56 const now = await $.clock.now()
57 live.top = topLimit(limits, now)
58 const wasOn = live.isOn
59 if (live.mode === 'on') live.isOn = true
60 else if (live.mode === 'off') live.isOn = false
61 else live.isOn = live.top !== null && live.top.percentUsed >= live.autoAt
62 if (live.mode === 'auto' && wasOn !== live.isOn) {
63 $.ui.toast(live.isOn && live.top
64 ? `🪙 thrift on (auto): ${limitLabel(live.top.kind)} at ${fmtPct(live.top.percentUsed)}`
65 : '🪙 thrift off (auto): the window reset', { timeoutMs: 6000 })
66 }
67 await publish($)
68}
69
70async function readLimits($: EngineInterface): Promise<void> {
71 try {
72 const u = await $.session.usage()
73 limits = u.rateLimits.map(l => ({ kind: l.kind, percentUsed: l.percentUsed, resetsAt: l.resetsAt }))
74 } catch {
75 // Keep the last reading.
76 }
77 await evaluate($)
78}
79
80async function setMode($: EngineInterface, mode: ThriftMode): Promise<void> {
81 live.mode = mode
82 try {
83 await $.store.set('mode', mode)
84 } catch {
85 // For this session at least.
86 }
87 await evaluate($)
88}
89
90async function setHidden($: EngineInterface, isHidden: boolean): Promise<void> {
91 await update($, hiddenAtom, () => isHidden)
92 try {
93 await $.store.set('isHidden', isHidden)
94 } catch {
95 // Hidden for this session at least.
96 }
97}
98
99async function loadStored($: EngineInterface): Promise<void> {
100 try {
101 const m = await $.store.get('mode')
102 if (isMode(m)) live.mode = m
103 const h = await $.store.get('isHidden')
104 if (typeof h === 'boolean') await update($, hiddenAtom, () => h)
105 } catch {
106 // Nothing stored yet.
107 }
108}
109
110async function endTurn($: EngineInterface, done: { isThrift: boolean; cost: number }): Promise<void> {
111 const tally: ThriftTally = done.isThrift ? live.thrift : live.normal
112 tally.turns++
113 tally.cost += done.cost
114 turn = null
115 await readLimits($)
116}
117
118const avg = (t: ThriftTally): number | undefined => (t.turns ? t.cost / t.turns : undefined)
119
120/** `thrift turns cost 61% less on average`, or undefined until both kinds ran. */
121export function comparison(s: Pick<ThriftSnap, 'thrift' | 'normal'>): string | undefined {
122 const a = avg(s.thrift)
123 const b = avg(s.normal)
124 if (a === undefined || b === undefined || b <= 0) return undefined
125 const d = Math.round((1 - a / b) * 100)
126 return d >= 0 ? `thrift turns cost ${d}% less on average` : `thrift turns cost ${-d}% more on average`
127}
128
129async function report($: EngineInterface): Promise<string> {
130 await readLimits($)
131 const s = live
132 const now = await $.clock.now()
133 const top = s.top
134 const reset = top?.resetsAt ? Date.parse(top.resetsAt) - now : NaN
135 const state = s.isOn ? 'ON' : 'off'
136 const avgOf = (t: ThriftTally) => {
137 const a = avg(t)
138 return a !== undefined ? fmtUsd(a) : '—'
139 }
140 const lines = [
141 `🪙 KOZMOS thrift · mode ${s.mode}${s.mode === 'auto' ? ` (on at ${s.autoAt}%)` : ''} · now ${state}${top ? ` · ${limitLabel(top.kind)} ${fmtPct(top.percentUsed)}${Number.isFinite(reset) ? `, resets in ${fmtSpan(reset)}` : ''}` : ''}`,
142 '',
143 'This session:',
144 ` thrift turns ${String(s.thrift.turns).padStart(3)} · avg ${avgOf(s.thrift)}`,
145 ` normal turns ${String(s.normal.turns).padStart(3)} · avg ${avgOf(s.normal)}`,
146 ]
147 const cmp = comparison(s)
148 lines.push(cmp ? ` → ${cmp}` : ' (the comparison appears once both kinds of turn have run)')
149 lines.push('', '/thrift on · off · auto · hide · show')
150 return lines.join('\n')
151}
152
153export const register: Register = (on, options) => {
154 // userConfig gives autoAt a number (90 unless set); 0 reads as the default too.
155 const autoAt = Math.max(1, Math.min(100, Number(options.autoAt) || 90))
156
157 on('session.start', async ($, e, next) => {
158 const started = await next(e)
159 live = blank('off', autoAt)
160 limits = []
161 turn = null
162 publishedKey = ''
163 await $.command.register({ name: 'thrift', description: 'KOZMOS: frugal mode — /thrift on|off|auto; /thrift alone compares thrift and normal turn costs', argumentHint: '[on|off|auto|hide|show]', immediate: true })
164 await loadStored($)
165 await readLimits($)
166 // A window resets on its own clock: look again every minute.
167 $.clock.every(60_000, () => void evaluate($).catch(() => undefined))
168 return started
169 })
170
171 on('command.run', { command: 'thrift' }, async ($, e) => {
172 const arg = e.args.trim().toLowerCase()
173 if (isMode(arg)) {
174 await setMode($, arg)
175 const why = arg === 'auto' ? ` It turns on when the 5h or 7d limit passes ${autoAt}%${live.isOn ? ' — and it is on now' : ''}.` : ''
176 return { text: `🪙 thrift ${arg}.${why}` }
177 }
178 if (arg === 'hide' || arg === 'show') {
179 await setHidden($, arg === 'hide')
180 return { text: arg === 'hide' ? 'thrift band hidden (thrift itself keeps its mode).' : 'thrift band shown.' }
181 }
182 return { text: await report($) }
183 })
184
185 // Observer plus rewrite: the note rides beside the prompt, never in it.
186 on('prompt.submit', async ($, e, next) => {
187 if (!live.isOn) return next(e)
188 return next({ ...e, context: [...(e.context ?? []), THRIFT_NOTE] })
189 }).catch(($, e, next) => next(e))
190
191 on('session.measure', async ($, e, next) => {
192 const r = await next(e)
193 if (e.changed.includes('rateLimits')) {
194 limits = e.rateLimits.map(l => ({ kind: l.kind, percentUsed: l.percentUsed, resetsAt: l.resetsAt }))
195 await evaluate($)
196 }
197 return r
198 }).catch(($, e, next) => next(e))
199
200 on('turn.start', async ($, e, next) => {
201 turn = { id: e.turnId, isThrift: live.isOn, cost: 0 }
202 return next(e)
203 })
204
205 // Every model request while a main turn runs, its subagents' included.
206 on('turn.step', async function* ($, e, next) {
207 const r = yield* next(e)
208 if (turn && r.usage) turn.cost += costOf(r.usage.model || e.model, r.usage)
209 return r
210 })
211
212 on('turn.complete', async ($, e, next) => {
213 const r = await next(e)
214 if (e.agentId === undefined && turn && turn.id === e.turnId) await endTurn($, turn)
215 return r
216 })
217
218 on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
219 const drawn = await next(e)
220 if (e.props.hasSurvey || (await read($, hiddenAtom))) return drawn
221 const s = await read($, snapAtom)
222 if (!s.isOn) return drawn
223 const cols = Math.max(30, e.props.bodyColumns || 80)
224 const lim = s.top ? `${limitLabel(s.top.kind)} ${fmtPct(s.top.percentUsed)}` : 'no limit reading'
225 const cmp = comparison(s)
226
227 if (e.surface === 'terminal') {
228 const { Box, Button, Client, Text } = $.ui.resolve(e)
229 const coin: CoinProps = { isOn: true }
230 return (
231 <Box flexDirection="column">
232 {drawn}
233 <Box key="thrift" flexDirection="row" justifyContent="space-between">
234 <Box flexDirection="row">
235 <Client key="thrift-coin" module="./coin.tsx" width={2} height={1} props={coin} />
236 <Text wrap="truncate-end">
237 <Text bold color={KZ.yellow}>thrift on</Text>
238 <Text dimColor> · </Text>
239 <Text color={s.top ? heat(s.top.percentUsed / 100) : KZ.mist}>{lim}</Text>
240 <Text dimColor> · saving mode{s.mode === 'auto' ? ' (auto)' : ''}</Text>
241 {cmp && cols > 70 ? <Text color={KZ.green}> · {cmp}</Text> : ''}
242 </Text>
243 </Box>
244 <Button key="thrift-hide" label="✕" plain dimColor role="dismiss" onPress={() => void setHidden($, true)} />
245 </Box>
246 </Box>
247 )
248 }
249
250 // Every surface but the terminal draws Svg.
251 const { Box, Button, Svg } = $.ui.resolve(e) as Elements[Exclude<RenderSurface, 'terminal'>]
252 const W = Math.max(240, pxOf(cols) - 40)
253 return (
254 <Box flexDirection="column">
255 {drawn}
256 <Box key="thrift" flexDirection="row" alignItems="center">
257 <Svg source={bandSvg(W, s, lim, cmp)} alt={`thrift on · ${lim} · saving mode${cmp ? ` · ${cmp}` : ''}`} width={W} height={44} />
258 <Button key="thrift-hide" label="✕" plain dimColor role="dismiss" onPress={() => void setHidden($, true)} />
259 </Box>
260 </Box>
261 )
262 })
263}
264
265/** The desktop band: a coin flipping on its edge, the limit gauge, the saving. */
266function bandSvg(W: number, s: ThriftSnap, lim: string, cmp: string | undefined): string {
267 const gold = '#facc15'
268 const deep = '#d97706'
269 const gaugeW = Math.min(180, Math.max(90, W * 0.22))
270 const gx = W - gaugeW - 14
271 const css = `.flip{transform-box:fill-box;transform-origin:center;animation:tflip 1.8s ease-in-out infinite}
272@keyframes tflip{0%,100%{transform:scaleX(1)}25%{transform:scaleX(.08)}50%{transform:scaleX(-1)}75%{transform:scaleX(.08)}}
273.shine{animation:tshine 1.8s ease-in-out infinite}@keyframes tshine{0%,100%{opacity:.9}25%,75%{opacity:.2}50%{opacity:.6}}
274.drop{animation:tdrop 2.4s ease-in infinite}@keyframes tdrop{0%{transform:translateY(-8px);opacity:0}30%{opacity:1}100%{transform:translateY(10px);opacity:0}}`
275 const ratio = s.top ? s.top.percentUsed / 100 : 0
276 const body = `<rect class="p" x="0" y="0" width="${W}" height="44" rx="12"/>
277<rect x="0" y="0" width="4" height="44" rx="2" fill="${gold}"/>
278<g transform="translate(26 22)"><g class="flip"><circle r="12" fill="${gold}" stroke="${deep}" stroke-width="2"/><circle r="8.2" fill="none" stroke="${deep}" stroke-width="1.2" opacity=".7"/>
279<text x="0" y="4.5" text-anchor="middle" font-family="ui-monospace,Consolas,monospace" font-size="12" font-weight="800" fill="${deep}">¢</text>
280<path class="shine" d="M-7 -6a10 10 0 0 1 6-4" stroke="#fff" stroke-width="2" stroke-linecap="round" fill="none"/></g></g>
281<circle class="drop" cx="46" cy="14" r="2.2" fill="${gold}" opacity=".8"/>
282${svgText(54, 19, 'thrift on', { size: 13.5, weight: 750, fill: deep })}
283${svgText(54 + 68, 19, `· ${lim} · saving mode${s.mode === 'auto' ? ' (auto)' : ''}`, { cls: 't', size: 12.5, weight: 600 })}
284${svgText(54, 36, cmp ?? `${s.thrift.turns} thrift turn${s.thrift.turns === 1 ? '' : 's'} so far · targeted reads, no broad searches, concise answers`, { size: 10.5, ...(cmp ? { fill: KZ.green } : { cls: 'm' }) })}
285${s.top ? svgText(gx, 16, `${limitLabel(s.top.kind)} window`, { cls: 's', size: 10, weight: 600 }) : ''}
286${s.top ? svgText(gx + gaugeW, 16, fmtPct(s.top.percentUsed), { size: 11, weight: 700, anchor: 'end' }) : ''}
287${s.top ? svgBar(gx, 22, gaugeW, 7, ratio, heat(ratio)) : ''}
288${s.top ? `<line x1="${gx + gaugeW * (s.autoAt / 100)}" x2="${gx + gaugeW * (s.autoAt / 100)}" y1="19" y2="32" stroke="${KZ.red}" stroke-width="1.4" stroke-dasharray="2 2"/>` : ''}`
289 return svg(W, 44, body, css)
290}
291hooks/coin.tsx 31 lines1// Thrift's terminal coin: a Client surface module that spins a gold coin
2// edge-on and back, about eight frames a second. No `$` here.
3import type { ClientModule } from 'claude-code'
4
5export type CoinProps = { isOn: boolean }
6
7type CoinState = { f: number }
8
9/** The coin seen turning: face, narrowing, edge, widening, the other face. */
10export const FRAMES: readonly [string, string][] = [
11 ['●', '#facc15'],
12 ['◗', '#fbbf24'],
13 ['▐', '#f59e0b'],
14 ['│', '#d97706'],
15 ['▌', '#f59e0b'],
16 ['◖', '#fbbf24'],
17]
18
19const Coin: ClientModule<CoinProps, CoinState> = (props, surface) => {
20 if (surface.state === undefined) {
21 surface.setState({ f: 0 })
22 surface.every(125, () => surface.setState({ f: ((surface.state?.f ?? 0) + 1) % FRAMES.length }))
23 }
24 const { Text } = surface.elements
25 // `f` stays within FRAMES: the timer wraps it.
26 const [ch, color] = FRAMES[surface.state?.f ?? 0]!
27 return <Text bold color={props.isOn ? color : '#9ca3af'}>{ch}</Text>
28}
29
30export default Coin
31hooks/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 24 lines1export type ThriftMode = 'on' | 'off' | 'auto'
2
3export type ThriftLimit = { kind: string; percentUsed: number; resetsAt?: string }
4
5export type ThriftTally = { turns: number; cost: number }
6
7export type ThriftSnap = {
8 mode: ThriftMode
9 /** Whether prompts carry the economy note now. */
10 isOn: boolean
11 autoAt: number
12 /** The fullest 5h / 7d window, as the band shows it. */
13 top: ThriftLimit | null
14 /** Turns of this session run with and without the note, and what they cost. */
15 thrift: ThriftTally
16 normal: ThriftTally
17}
18
19declare module 'claude-code' {
20 interface PluginState {
21 thrift: { snap: ThriftSnap; isHidden: boolean }
22 }
23}
24