SLOPSHOPPER

marquee

KOZMOS Marquee: a status-line ticker. Model and effort, context fill, 5-hour and weekly limits with the reset countdown, session cost, git branch with ahead…

guardcommandstatusprocesstimer
★ 15v0.1.0MITupdated 2026-10-10ersinkoc/claude-mods/mods/marquee
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · marquee
› fix the failing auth test and add an audit log call ⏺ Read(src/auth.ts) ⎿ Read 6 lines ⏺ Update(src/auth.ts) ⎿ Added 2 lines, removed 1 line ⏺ Bash(bun test) ⎿ 3 pass, 1 fail ● Done. refresh now rejects expired claims and logs an audit event. ✻ Worked for 42s · done 4:20 PM › /marquee ⎿ marquee: Marquee off. ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts
README

KOZMOS Marquee

A ticker in the status line under the prompt, refreshed every second:

◆ Opus 5.5·xhigh │ ctx 42% │ 5h 23% ↻2h41m │ 7d 41% │ $3.21 │ ⎇ main ↑2 ●3 │ ▶ Bash npm test 0:12
  • model: model and effort. ctx: context fill. limits: each rate-limit window, the 5-hour one with its reset countdown. cost: session cost. git: branch, ahead/behind and the count of changed files (read every 10 s, and again after a Bash or edit). tool: the tool running in the main loop and for how long.
  • When the line is longer than width it scrolls like a marquee: a window rotating over the segment loop, with ◆ between laps. Otherwise it stays still.
  • /marquee turns it off (the status line is cleared) and on again; the choice is kept across sessions.

Settings: width (default 110), segments (default model,ctx,limits,cost,git,tool: which segments, in which order).

Türkçe

İstem satırının altındaki durum satırında her saniye yenilenen bir kayan yazı:

◆ Opus 5.5·xhigh │ ctx 42% │ 5h 23% ↻2h41m │ 7d 41% │ $3.21 │ ⎇ main ↑2 ●3 │ ▶ Bash npm test 0:12
  • model: model ve efor. ctx: bağlam doluluğu. limits: her kullanım limiti penceresi; 5 saatlik olan sıfırlanma geri sayımıyla. cost: oturum maliyeti. git: dal, ileri/geri ve değişen dosya sayısı (10 saniyede bir, ayrıca bir Bash ya da düzenlemeden sonra okunur). tool: ana döngüde çalışan araç ve ne kadar süredir çalıştığı.
  • Satır width değerinden uzunsa kayan yazı gibi kayar: segment döngüsü üzerinde dönen bir pencere, turlar arasında ◆. Değilse sabit kalır.
  • /marquee kapatır (durum satırı temizlenir) ve yeniden açar; tercih oturumlar arasında saklanır.

Ayarlar: width (varsayılan 110), segments (varsayılan model,ctx,limits,cost,git,tool: hangi segmentler, hangi sırayla).

Source 5 files
hooks/register.tsx 160 lines
1import type { EngineInterface, Register } from 'claude-code'
2
3import { toolDetail } from './lib/kz.ts'
4import { GIT_HEAD, GIT_STATUS, parseGitStatus } from './lib/probe.ts'
5import { buildSegments, parseSegments, scrolls, windowAt } from './ticker.ts'
6import type { SegmentName, TickerData, TickerGit } from './ticker.ts'
7
8const TICK_MS = 1000
9const GIT_MS = 10_000
10/** Characters the line moves per tick while it scrolls. */
11const SCROLL_STEP = 2
12const STORE_KEY = 'enabled'
13
14let live: TickerData = { limits: [], now: 0 }
15let isEnabled = true
16let order: SegmentName[] = []
17let width = 110
18let tick = 0
19let lastText: string | undefined
20let gitAt = -Infinity
21let isGitBusy = false
22
23// ---------------------------------------------------------------------------
24// The git probe, wrapped as bridge does: $.process.run in try/catch, the text
25// handed to lib/probe.ts.
26
27async function sh($: EngineInterface, argv: readonly string[], timeoutMs: number, cwd?: string): Promise<string | undefined> {
28  try {
29    const r = await $.process.run(argv, cwd ? { timeoutMs, cwd } : { timeoutMs })
30    return r.exitCode === 0 ? r.stdout : undefined
31  } catch {
32    return undefined
33  }
34}
35
36async function readGit($: EngineInterface, cwd: string): Promise<TickerGit | undefined> {
37  const status = await sh($, GIT_STATUS, 5000, cwd)
38  if (status === undefined) return undefined
39  const g = parseGitStatus(status, (await sh($, GIT_HEAD, 3000, cwd)) ?? '')
40  return { branch: g.branch, ahead: g.ahead, behind: g.behind, dirty: g.staged + g.unstaged + g.untracked + g.conflicts }
41}
42
43async function refreshGit($: EngineInterface): Promise<void> {
44  if (isGitBusy) return
45  isGitBusy = true
46  try {
47    live.git = await readGit($, await $.session.cwd())
48  } finally {
49    isGitBusy = false
50  }
51}
52
53// ---------------------------------------------------------------------------
54
55/** One beat: read what moved, build the line, show it when it changed. */
56async function beat($: EngineInterface): Promise<void> {
57  if (!isEnabled) return
58  const now = await $.clock.now()
59  live.now = now
60  try {
61    const usage = await $.session.usage()
62    live.ctxPercent = usage.context.percent
63    live.limits = usage.rateLimits.map(l => ({ kind: l.kind, percentUsed: l.percentUsed, resetsAt: l.resetsAt }))
64    live.costUsd = usage.cost?.usd
65  } catch {
66    // Kept as it was.
67  }
68  try {
69    live.model = (await $.session.model()) || live.model
70  } catch {
71    // Kept as it was.
72  }
73  if (order.includes('git') && now - gitAt >= GIT_MS) {
74    gitAt = now
75    void refreshGit($).catch(() => undefined)
76  }
77  show($)
78}
79
80function show($: EngineInterface): void {
81  if (!isEnabled) return
82  const segments = buildSegments(live, order)
83  const text = segments.length ? windowAt(segments, width, tick, SCROLL_STEP) : undefined
84  if (segments.length && scrolls(segments, width)) tick++
85  else tick = 0
86  if (text === lastText) return
87  lastText = text
88  $.ui.status(text)
89}
90
91async function toggle($: EngineInterface): Promise<boolean> {
92  isEnabled = !isEnabled
93  await $.store.set(STORE_KEY, isEnabled)
94  if (isEnabled) {
95    lastText = undefined
96    gitAt = -Infinity
97    await beat($)
98  } else {
99    lastText = undefined
100    $.ui.status(undefined)
101  }
102  return isEnabled
103}
104
105export const register: Register = (on, options) => {
106  // The engine checks the options against plugin.json and fills in its
107  // defaults: `segments` is always a string, `width` a finite number.
108  order = parseSegments(String(options.segments))
109  width = Math.max(20, Number(options.width))
110
111  on('session.start', async ($, e, next) => {
112    const started = await next(e)
113    live = { limits: [], now: await $.clock.now() }
114    tick = 0
115    lastText = undefined
116    gitAt = -Infinity
117    isGitBusy = false
118    try {
119      isEnabled = (await $.store.get(STORE_KEY)) !== false
120    } catch {
121      isEnabled = true
122    }
123    await $.command.register({ name: 'marquee', description: 'KOZMOS: toggle the Marquee status-line ticker', immediate: true })
124    $.clock.every(TICK_MS, () => void beat($).catch(() => undefined))
125    await beat($).catch(() => undefined)
126    return started
127  })
128
129  on('command.run', { command: 'marquee' }, async $ => ({
130    text: (await toggle($)) ? 'Marquee on.' : 'Marquee off.',
131  }))
132
133  on('turn.step', async function* ($, e, next) {
134    if (e.agentId === undefined) {
135      if (e.effort !== undefined) live.effort = String(e.effort)
136      // The engine never starts a step without a model name.
137      live.model = e.model
138    }
139    return yield* next(e)
140  })
141
142  on('tool.call', async ($, e, next) => {
143    if (e.agentId !== undefined || !isEnabled) return next(e)
144    const name = String(e.tool)
145    const at = await $.clock.now()
146    live.tool = { name, detail: toolDetail(name, e), startedAt: at }
147    live.now = at
148    show($)
149    try {
150      return await next(e)
151    } finally {
152      if (live.tool?.startedAt === at) live.tool = undefined
153      // A Bash or an edit may have moved git: look again on the next beat.
154      if (name === 'Bash' || name === 'PowerShell' || name === 'Edit' || name === 'Write') gitAt = -Infinity
155      live.now = await $.clock.now()
156      show($)
157    }
158  }).catch(($, e, next) => next(e))
159}
160
hooks/lib/kz.ts 521 lines
1// 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
140// The cuts below count UTF-16 units; they must not land between the two halves of an emoji.
141const isHigh = (u: number): boolean => u >= 0xd800 && u <= 0xdbff
142const isLow = (u: number): boolean => u >= 0xdc00 && u <= 0xdfff
143
144export function clip(s: string, max: number): string {
145  const one = s.replace(/\s+/g, ' ').trim()
146  if (one.length <= max) return one
147  let cut = Math.max(1, max - 1)
148  if (isHigh(one.charCodeAt(cut - 1))) cut--
149  return one.slice(0, cut) + '…'
150}
151
152export function padEnd(s: string, n: number): string {
153  if (s.length < n) return s + ' '.repeat(n - s.length)
154  // A pair cut in half gives way to a space, so the result keeps its width.
155  return n > 0 && isHigh(s.charCodeAt(n - 1)) ? s.slice(0, n - 1) + ' ' : s.slice(0, n)
156}
157
158export function padStart(s: string, n: number): string {
159  if (s.length < n) return ' '.repeat(n - s.length) + s
160  const k = s.length - n
161  return k > 0 && isLow(s.charCodeAt(k)) ? ' ' + s.slice(k + 1) : s.slice(k)
162}
163
164/** `claude-opus-5-5[1m]` → `Opus 5.5`. */
165export function modelName(id: string | undefined): string {
166  if (!id) return '—'
167  const m = /(fable|mythos|opus|sonnet|haiku)-(\d+)(?:-(\d{1,2})(?!\d))?/i.exec(id)
168  if (!m) return id.replace(/^claude-/, '').replace(/\[.*\]$/, '')
169  const fam = m[1]!
170  return `${fam.charAt(0).toUpperCase()}${fam.slice(1).toLowerCase()} ${m[2]}${m[3] ? '.' + m[3] : ''}`
171}
172
173/** Last path segment, either slash. */
174export function baseName(p: string): string {
175  const parts = p.split(/[\\/]/).filter(Boolean)
176  return parts[parts.length - 1] ?? p
177}
178
179/** A stable small hash for seeding. */
180export function hash(s: string): number {
181  let h = 2166136261
182  for (let i = 0; i < s.length; i++) {
183    h ^= s.charCodeAt(i)
184    h = Math.imul(h, 16777619)
185  }
186  return h >>> 0
187}
188
189/** Deterministic 0..1 noise from two ints. */
190export function noise(x: number, y: number): number {
191  const s = Math.sin(x * 12.9898 + y * 78.233) * 43758.5453
192  return s - Math.floor(s)
193}
194
195/** A seeded PRNG (mulberry32). */
196export function rng(seed: number): () => number {
197  let a = seed >>> 0
198  return () => {
199    a = (a + 0x6d2b79f5) >>> 0
200    let t = a
201    t = Math.imul(t ^ (t >>> 15), t | 1)
202    t ^= t + Math.imul(t ^ (t >>> 7), t | 61)
203    return ((t ^ (t >>> 14)) >>> 0) / 4294967296
204  }
205}
206
207// ---------------------------------------------------------------------------
208// Text gauges for the terminal.
209
210const EIGHTHS = ['', '▏', '▎', '▍', '▌', '▋', '▊', '▉']
211
212/** A smooth bar with eighth blocks: `█████▍    `. */
213export function bar(ratio: number, width: number, empty = '░'): string {
214  const w = Math.max(1, Math.floor(width))
215  const exact = clamp01(ratio) * w
216  const full = Math.floor(exact)
217  const part = EIGHTHS[Math.floor((exact - full) * 8)] ?? ''
218  const used = full + (part ? 1 : 0)
219  return '█'.repeat(full) + part + empty.repeat(Math.max(0, w - used))
220}
221
222/** A segmented gauge: `▰▰▰▱▱▱`. */
223export function pips(ratio: number, width: number, on = '▰', off = '▱'): string {
224  const w = Math.max(1, Math.floor(width))
225  const n = Math.round(clamp01(ratio) * w)
226  return on.repeat(n) + off.repeat(w - n)
227}
228
229const SPARK = '▁▂▃▄▅▆▇█'
230
231/** A sparkline of the last `width` values, scaled to their own max (or `max`). */
232export function sparkline(values: readonly number[], width: number, max?: number): string {
233  const tail = values.slice(-Math.max(1, width))
234  const top = max ?? Math.max(1e-9, ...tail)
235  const line = tail.map(v => SPARK[Math.min(7, Math.max(0, Math.round((v / top) * 7)))] ?? '▁').join('')
236  return line.padStart(width, ' ')
237}
238
239/** Braille line graph, 2 samples per cell, `rows` cells tall. */
240export function brailleGraph(values: readonly number[], width: number, rows: number, max?: number): string[] {
241  const samples = values.slice(-(width * 2))
242  const top = max ?? Math.max(1e-9, ...samples)
243  const dotsTall = rows * 4
244  const grid: number[][] = Array.from({ length: rows }, () => Array.from({ length: width }, () => 0))
245  const offset = width * 2 - samples.length
246  // Dot bits per column, from the bottom row of a cell up.
247  const LEFT = [0x40, 0x04, 0x02, 0x01]
248  const RIGHT = [0x80, 0x20, 0x10, 0x08]
249  samples.forEach((v, i) => {
250    const x = offset + i
251    const col = Math.floor(x / 2)
252    const isRight = x % 2 === 1
253    const h = Math.round(clamp01(v / top) * (dotsTall - 1))
254    for (let d = 0; d <= h; d++) {
255      const row = rows - 1 - Math.floor(d / 4)
256      const bits = isRight ? RIGHT : LEFT
257      const cellRow = grid[row]
258      if (cellRow && col >= 0) cellRow[col] = (cellRow[col] ?? 0) | bits[d % 4]!
259    }
260  })
261  return grid.map(r => r.map(b => String.fromCharCode(0x2800 + b)).join(''))
262}
263
264// ---------------------------------------------------------------------------
265// Raster: a grid of colored cells, packed as the engine wants it.
266
267const B64 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
268
269export function toBase64(bytes: Uint8Array): string {
270  let out = ''
271  let i = 0
272  for (; i + 2 < bytes.length; i += 3) {
273    const n = (bytes[i]! << 16) | (bytes[i + 1]! << 8) | bytes[i + 2]!
274    out += B64[(n >> 18) & 63]! + B64[(n >> 12) & 63]! + B64[(n >> 6) & 63]! + B64[n & 63]!
275  }
276  const rest = bytes.length - i
277  if (rest === 1) {
278    const n = bytes[i]! << 16
279    out += B64[(n >> 18) & 63]! + B64[(n >> 12) & 63]! + '=='
280  } else if (rest === 2) {
281    const n = (bytes[i]! << 16) | (bytes[i + 1]! << 8)
282    out += B64[(n >> 18) & 63]! + B64[(n >> 12) & 63]! + B64[(n >> 6) & 63]! + '='
283  }
284  return out
285}
286
287/** The terminal's own default color, for a cell's foreground or background. */
288export const DEFAULT_COLOR = 0x01000000
289
290export class Canvas {
291  readonly cols: number
292  readonly rows: number
293  private readonly words: Uint32Array
294
295  constructor(cols: number, rows: number) {
296    this.cols = Math.max(1, Math.min(512, Math.floor(cols)))
297    this.rows = Math.max(1, Math.min(256, Math.floor(rows)))
298    this.words = new Uint32Array(this.cols * this.rows * 3)
299    this.clear()
300  }
301
302  clear(bg: number = DEFAULT_COLOR): void {
303    for (let i = 0; i < this.cols * this.rows; i++) {
304      this.words[i * 3] = 0x20
305      this.words[i * 3 + 1] = DEFAULT_COLOR
306      this.words[i * 3 + 2] = bg
307    }
308  }
309
310  /** Puts one width-1 character; colors are '#rrggbb' or a packed int. */
311  set(x: number, y: number, ch: string, fg?: string | number, bg?: string | number): void {
312    const cx = Math.floor(x)
313    const cy = Math.floor(y)
314    if (cx < 0 || cy < 0 || cx >= this.cols || cy >= this.rows) return
315    const i = (cy * this.cols + cx) * 3
316    const code = ch.codePointAt(0) ?? 0x20
317    this.words[i] = code > 0xffff || code < 0x20 ? 0x20 : code
318    if (fg !== undefined) this.words[i + 1] = typeof fg === 'number' ? fg : hexToInt(fg)
319    if (bg !== undefined) this.words[i + 2] = typeof bg === 'number' ? bg : hexToInt(bg)
320  }
321
322  /** Writes a string left to right, clipped to the canvas. */
323  text(x: number, y: number, s: string, fg?: string | number, bg?: string | number): void {
324    let cx = x
325    for (const ch of s) {
326      this.set(cx, y, ch, fg, bg)
327      cx++
328    }
329  }
330
331  /** Paints a cell's background only, keeping its character. */
332  paint(x: number, y: number, bg: string | number): void {
333    const cx = Math.floor(x)
334    const cy = Math.floor(y)
335    if (cx < 0 || cy < 0 || cx >= this.cols || cy >= this.rows) return
336    this.words[(cy * this.cols + cx) * 3 + 2] = typeof bg === 'number' ? bg : hexToInt(bg)
337  }
338
339  /** Two vertical pixels per cell with the upper-half block: `py` is in half-cells. */
340  pixel(x: number, py: number, color: string): void {
341    const cx = Math.floor(x)
342    const cy = Math.floor(py / 2)
343    if (cx < 0 || cy < 0 || cx >= this.cols || cy >= this.rows) return
344    const i = (cy * this.cols + cx) * 3
345    const c = hexToInt(color)
346    const isTop = Math.floor(py) % 2 === 0
347    if (this.words[i] !== 0x2580) {
348      this.words[i] = 0x2580
349      this.words[i + 1] = DEFAULT_COLOR
350      this.words[i + 2] = DEFAULT_COLOR
351    }
352    if (isTop) this.words[i + 1] = c
353    else this.words[i + 2] = c
354  }
355
356  /** The `cells` prop of a Raster. */
357  encode(): string {
358    return toBase64(new Uint8Array(this.words.buffer))
359  }
360}
361
362// ---------------------------------------------------------------------------
363// SVG for the desktop: one drawing per row (the desktop wraps siblings).
364
365export const FONT = "-apple-system,BlinkMacSystemFont,'Segoe UI',Inter,sans-serif"
366export const MONO = "ui-monospace,'Cascadia Code','SF Mono',Consolas,monospace"
367
368const XML_ESC: Record<string, string> = { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }
369
370export function xml(s: string): string {
371  return s.replace(/[&<>"']/g, c => XML_ESC[c]!)
372}
373
374/** Theme-aware classes every KOZMOS drawing shares: t text, s secondary, m muted, k track, p panel. */
375export const SVG_BASE_CSS = `
376.t{fill:#1f1f1f}.s{fill:#5f5f5c}.m{fill:#8e8e8a}.k{fill:#e7e5e0}.p{fill:#f5f4f1}.ln{stroke:#e1dfda}
377@media (prefers-color-scheme: dark){.t{fill:#ededed}.s{fill:#b4b4b0}.m{fill:#7c7c78}.k{fill:#2d2d2b}.p{fill:#232322}.ln{stroke:#363634}}
378.pulse{animation:kzp 1.6s ease-in-out infinite}@keyframes kzp{50%{opacity:.35}}
379.spin{transform-box:fill-box;transform-origin:center;animation:kzs 2s linear infinite}@keyframes kzs{to{transform:rotate(360deg)}}
380@media (prefers-reduced-motion: reduce){*{animation:none!important}}
381`
382
383export function svg(width: number, height: number, body: string, css = ''): string {
384  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>`
385}
386
387/** Rough width of UI text in px, for fitting labels. */
388export function textWidth(s: string, size: number): number {
389  let w = 0
390  for (const ch of s) w += (/[\s.,:;'|!il1()[\]]/.test(ch) ? 0.3 : /[A-Z@%MWmw]/.test(ch) ? 0.72 : 0.56) * size
391  return w
392}
393
394export function fitText(s: string, size: number, maxW: number): string {
395  if (textWidth(s, size) <= maxW) return s
396  let out = ''
397  for (const ch of s) {
398    if (textWidth(out + ch + '…', size) > maxW) break
399    out += ch
400  }
401  return out + '…'
402}
403
404/** A rounded progress bar as SVG markup. */
405export function svgBar(x: number, y: number, w: number, h: number, ratio: number, color: string): string {
406  const fw = Math.max(0, Math.min(w, w * clamp01(ratio)))
407  return `<rect class="k" x="${x}" y="${y}" width="${w}" height="${h}" rx="${h / 2}"/>` +
408    (fw > 0 ? `<rect x="${x}" y="${y}" width="${Math.max(h, fw)}" height="${h}" rx="${h / 2}" fill="${color}"/>` : '')
409}
410
411/** SVG text helper. */
412export function svgText(x: number, y: number, s: string, opts: { cls?: string; size?: number; weight?: number; anchor?: 'start' | 'middle' | 'end'; fill?: string; mono?: boolean } = {}): string {
413  const { cls = 't', size = 12, weight = 400, anchor = 'start', fill, mono = false } = opts
414  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>`
415}
416
417/** Pixel width a desktop pane or band gives a drawing for `columns` reported columns. */
418export function pxOf(columns: number | undefined, fallback = 60, slack = 8): number {
419  return Math.max(200, Math.min(1600, (columns || fallback) * 8 - slack))
420}
421
422// ---------------------------------------------------------------------------
423// Prices, USD per million tokens: input, output, cache read, cache write (5 min).
424// Anthropic first-party rates as of 2026-10. Used only where the engine reports
425// tokens and not money (a subagent's own spend); the session total comes from
426// $.session.usage().cost, which is the engine's.
427
428const PRICES: [RegExp, [number, number, number, number]][] = [
429  [/fable|mythos/i, [10, 50, 0.25, 12.5]],
430  [/opus-5-5/i, [4, 20, 0.2, 5]],
431  [/opus/i, [5, 25, 0.5, 6.25]],
432  [/sonnet-5/i, [2, 10, 0.2, 2.5]],
433  [/sonnet/i, [3, 15, 0.3, 3.75]],
434  [/haiku-5/i, [0.1, 0.5, 0.01, 0.125]],
435  [/haiku/i, [1, 5, 0.1, 1.25]],
436]
437
438export type Usage = {
439  input_tokens?: number
440  output_tokens?: number
441  cache_read_input_tokens?: number
442  cache_creation_input_tokens?: number
443}
444
445export function priceOf(model: string): [number, number, number, number] {
446  return PRICES.find(([re]) => re.test(model))?.[1] ?? [4, 20, 0.2, 5]
447}
448
449export function costOf(model: string, u: Usage | null | undefined): number {
450  if (!u) return 0
451  const [i, o, r, w] = priceOf(model)
452  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
453}
454
455export function tokensOf(u: Usage | null | undefined): number {
456  if (!u) return 0
457  return (u.input_tokens ?? 0) + (u.output_tokens ?? 0) + (u.cache_read_input_tokens ?? 0) + (u.cache_creation_input_tokens ?? 0)
458}
459
460/** The context a request filled: everything it read plus what it wrote. */
461export function contextOf(u: Usage | null | undefined): number {
462  return tokensOf(u)
463}
464
465export function windowOf(model: string): number {
466  return /haiku-4/i.test(model) ? 200_000 : 1_000_000
467}
468
469// ---------------------------------------------------------------------------
470// Rate limits.
471
472export type Limit = { kind: string; percentUsed: number; resetsAt?: string }
473
474export function limitLabel(kind: string): string {
475  if (kind === 'five_hour') return '5h'
476  if (kind === 'seven_day') return '7d'
477  if (kind === 'spend_limit') return '$'
478  return kind.replace(/_/g, ' ')
479}
480
481/** Milliseconds until a window resets, or undefined. */
482export function untilReset(l: Limit, now: number): number | undefined {
483  if (!l.resetsAt) return undefined
484  const t = Date.parse(l.resetsAt)
485  return Number.isFinite(t) ? Math.max(0, t - now) : undefined
486}
487
488/** The length of a window in ms, for burn-rate math. */
489export function windowMs(kind: string): number | undefined {
490  if (kind === 'five_hour') return 5 * 3600_000
491  if (kind === 'seven_day') return 7 * 24 * 3600_000
492  return undefined
493}
494
495// ---------------------------------------------------------------------------
496// Tool calls, described in a few words.
497
498/** What a tool call is about: the command, the file, the pattern, the agent's task. */
499export function toolDetail(tool: string, input: unknown): string {
500  const e = (input ?? {}) as Record<string, unknown>
501  const s = (k: string) => (typeof e[k] === 'string' ? (e[k] as string) : '')
502  const t = String(tool)
503  if (t === 'Bash' || t === 'PowerShell') return clip(s('description') || s('command'), 60)
504  if (s('file_path')) return baseName(s('file_path'))
505  if (s('notebook_path')) return baseName(s('notebook_path'))
506  if (t === 'Agent') return clip(s('description') || s('subagent_type'), 60)
507  if (s('pattern')) return clip(s('pattern'), 60)
508  if (s('url')) return clip(s('url').replace(/^https?:\/\//, ''), 60)
509  if (s('query')) return clip(s('query'), 60)
510  if (s('subject')) return clip(s('subject'), 60)
511  if (Array.isArray(e.todos)) return `${(e.todos as unknown[]).length} todos`
512  if (t.startsWith('mcp__')) return t.split('__').slice(1).join(' · ')
513  return ''
514}
515
516/** `mcp__server__tool` → `server·tool`; built-ins unchanged. */
517export function toolName(tool: string): string {
518  const t = String(tool)
519  return t.startsWith('mcp__') ? t.split('__').slice(1).join('·') : t
520}
521
hooks/lib/probe.ts 211 lines
1// GENERATED by scripts/sync-shared.mjs from shared/probe.ts. Do not edit here.
2// KOZMOS shared probes: git and the machine, as argv lists and pure parsers.
3// Source of truth: shared/probe.ts; synced into each mod as hooks/lib/probe.ts.
4//
5// The engine only lets `$` flow into functions declared in the hooks file
6// itself, never across an import. So this file never touches `$`: a mod runs
7// the argv with `$.process.run` (or reads the path with `$.fs.read`) in a
8// top-level function of its own and hands the text to a parser here:
9//
10//   async function readGit($: EngineInterface, cwd: string): Promise<GitSnap> {
11//     const st = await $.process.run(GIT_STATUS, { cwd, timeoutMs: 5000 }).catch(() => undefined)
12//     if (!st || st.exitCode !== 0) return NO_GIT
13//     const head = await $.process.run(GIT_HEAD, { cwd, timeoutMs: 3000 }).catch(() => undefined)
14//     return parseGitStatus(st.stdout, head?.exitCode === 0 ? head.stdout : '')
15//   }
16
17export type Platform = 'win' | 'mac' | 'linux'
18
19/** From `$.env.get('OS')` and, off Windows, `uname -s`. */
20export function platformFrom(osEnv: string | undefined, uname: string | undefined): Platform {
21  if (/windows/i.test(osEnv ?? '')) return 'win'
22  return /darwin/i.test(uname ?? '') ? 'mac' : 'linux'
23}
24
25// ---------------------------------------------------------------------------
26// Git.
27
28export const GIT_STATUS = ['git', 'status', '--porcelain=v2', '--branch', '--show-stash'] as const
29export const GIT_HEAD = ['git', 'log', '-1', '--format=%h%x09%s%x09%cr'] as const
30export const gitLogArgv = (n: number): string[] => ['git', 'log', `-${n}`, '--format=%h%x09%s%x09%cr%x09%an%x09%ct']
31export const GIT_NUMSTAT = ['git', 'diff', '--numstat', 'HEAD'] as const
32
33export type GitSnap = {
34  isRepo: boolean
35  branch: string
36  isDetached: boolean
37  upstream?: string
38  ahead: number
39  behind: number
40  staged: number
41  unstaged: number
42  untracked: number
43  conflicts: number
44  head?: { sha: string; subject: string; when: string }
45  stash: number
46}
47
48export const NO_GIT: GitSnap = { isRepo: false, branch: '', isDetached: false, ahead: 0, behind: 0, staged: 0, unstaged: 0, untracked: 0, conflicts: 0, stash: 0 }
49
50/** Parses `GIT_STATUS` output, and `GIT_HEAD` output when given. */
51export function parseGitStatus(status: string, headLine = ''): GitSnap {
52  const snap: GitSnap = { ...NO_GIT, isRepo: true }
53  for (const line of status.split('\n')) {
54    if (line.startsWith('# branch.head ')) {
55      const b = line.slice(14).trim()
56      snap.isDetached = b === '(detached)'
57      snap.branch = b
58    } else if (line.startsWith('# branch.upstream ')) snap.upstream = line.slice(18).trim()
59    else if (line.startsWith('# branch.ab ')) {
60      const m = /\+(\d+) -(\d+)/.exec(line)
61      snap.ahead = Number(m?.[1] ?? 0)
62      snap.behind = Number(m?.[2] ?? 0)
63    } else if (line.startsWith('# stash ')) snap.stash = Number(line.slice(8)) || 0
64    else if (line.startsWith('1 ') || line.startsWith('2 ')) {
65      const xy = line.slice(2, 4)
66      if (xy[0] !== '.') snap.staged++
67      if (xy[1] !== '.') snap.unstaged++
68    } else if (line.startsWith('u ')) snap.conflicts++
69    else if (line.startsWith('? ')) snap.untracked++
70  }
71  const h = headLine.trim()
72  if (h) {
73    const f = h.split('\t')
74    // A tab inside the subject adds fields; fold them back into it.
75    if (f.length > 3) f.splice(1, f.length - 2, f.slice(1, f.length - 1).join('\t'))
76    const [sha, subject = '', when = ''] = f as [string, ...string[]]
77    snap.head = { sha, subject, when }
78  }
79  if (snap.isDetached && snap.head) snap.branch = snap.head.sha
80  return snap
81}
82
83export type GitCommit = { sha: string; subject: string; when: string; author: string; at: number }
84
85/** Parses `gitLogArgv(n)` output. `at` is the commit time in ms. */
86export function parseGitLog(out: string): GitCommit[] {
87  return out
88    .split('\n')
89    .filter(Boolean)
90    .map(l => {
91      const f = l.split('\t')
92      // A tab inside the subject adds fields; fold them back into it.
93      if (f.length > 5) f.splice(1, f.length - 4, f.slice(1, f.length - 3).join('\t'))
94      const [sha, subject = '', when = '', author = '', ct = '0'] = f as [string, ...string[]]
95      return { sha, subject, when, author, at: Number(ct) * 1000 }
96    })
97}
98
99export type GitFileStat = { path: string; added: number; removed: number }
100
101/** Parses `GIT_NUMSTAT` output (binary files count as 0/0). */
102export function parseNumstat(out: string): GitFileStat[] {
103  return out
104    .split('\n')
105    .filter(Boolean)
106    .map(l => {
107      const [a, d = '0', ...rest] = l.split('\t') as [string, ...string[]]
108      return { path: rest.join('\t'), added: Number(a) || 0, removed: Number(d) || 0 }
109    })
110}
111
112// ---------------------------------------------------------------------------
113// The machine.
114
115export type SysSnap = {
116  cpu?: number // percent, all cores
117  memUsed?: number // bytes
118  memTotal?: number // bytes
119  diskUsed?: number
120  diskTotal?: number
121  procs?: number
122  gpu?: GpuSnap
123}
124
125export type GpuSnap = { util: number; memUsed: number; memTotal: number; temp: number; name: string }
126
127/** Windows: one PowerShell call answering CPU, memory, C: and process count as JSON. */
128export const WIN_SYS = [
129  'powershell', '-NoProfile', '-NonInteractive', '-Command',
130  '$o=Get-CimInstance Win32_OperatingSystem;' +
131    '$c=(Get-CimInstance Win32_Processor | Measure-Object -Property LoadPercentage -Average).Average;' +
132    "$d=Get-CimInstance Win32_LogicalDisk -Filter \"DeviceID='C:'\";" +
133    '$p=(Get-Process).Count;' +
134    '[pscustomobject]@{cpu=$c;free=$o.FreePhysicalMemory;total=$o.TotalVisibleMemorySize;dfree=$d.FreeSpace;dsize=$d.Size;procs=$p} | ConvertTo-Json -Compress',
135] as const
136
137export function parseWinSys(out: string): SysSnap {
138  const snap: SysSnap = {}
139  try {
140    const j = JSON.parse(out || '{}') as Record<string, number | null>
141    if (typeof j.cpu === 'number') snap.cpu = j.cpu
142    if (typeof j.total === 'number' && typeof j.free === 'number') {
143      snap.memTotal = j.total * 1024
144      snap.memUsed = (j.total - j.free) * 1024
145    }
146    if (typeof j.dsize === 'number' && typeof j.dfree === 'number') {
147      snap.diskTotal = j.dsize
148      snap.diskUsed = j.dsize - j.dfree
149    }
150    if (typeof j.procs === 'number') snap.procs = j.procs
151  } catch {
152    // Leave the fields out.
153  }
154  return snap
155}
156
157export type CpuTicks = { idle: number; total: number }
158
159/** Linux: `/proc/stat`'s first line, against the previous reading. */
160export function parseProcStat(stat: string, prev: CpuTicks | undefined): { cpu?: number; ticks: CpuTicks } {
161  const nums = stat.split('\n')[0]!.trim().split(/\s+/).slice(1).map(Number)
162  const idle = (nums[3] ?? 0) + (nums[4] ?? 0)
163  const total = nums.reduce((a, b) => a + (Number.isFinite(b) ? b : 0), 0)
164  const ticks = { idle, total }
165  if (!prev || total <= prev.total) return { ticks }
166  return { cpu: 100 * (1 - (idle - prev.idle) / (total - prev.total)), ticks }
167}
168
169/** Linux: `/proc/meminfo`. */
170export function parseMeminfo(mem: string): Pick<SysSnap, 'memUsed' | 'memTotal'> {
171  const kb = (k: string) => Number(new RegExp(`${k}:\\s+(\\d+)`).exec(mem)?.[1] ?? 0) * 1024
172  const memTotal = kb('MemTotal')
173  return memTotal ? { memTotal, memUsed: memTotal - kb('MemAvailable') } : {}
174}
175
176/** macOS: `top -l 1 -n 0` and `sysctl -n hw.memsize`. */
177export const MAC_TOP = ['top', '-l', '1', '-n', '0'] as const
178export const MAC_MEMSIZE = ['sysctl', '-n', 'hw.memsize'] as const
179
180export function parseMacTop(top: string, memsize: string): SysSnap {
181  const snap: SysSnap = {}
182  const m = /CPU usage: ([\d.]+)% user, ([\d.]+)% sys/.exec(top)
183  if (m) snap.cpu = Number(m[1]) + Number(m[2])
184  const pm = /PhysMem: ([\d.]+)([GM]) used/.exec(top)
185  if (pm) snap.memUsed = Number(pm[1]) * (pm[2] === 'G' ? 1024 ** 3 : 1024 ** 2)
186  const total = Number(memsize.trim())
187  if (total) snap.memTotal = total
188  return snap
189}
190
191/** NVIDIA GPUs, any platform. */
192export const NVIDIA_SMI = ['nvidia-smi', '--query-gpu=utilization.gpu,memory.used,memory.total,temperature.gpu,name', '--format=csv,noheader,nounits'] as const
193
194export function parseNvidia(out: string): GpuSnap | undefined {
195  const line = out.split('\n')[0]!
196  if (!line.trim()) return undefined
197  const [util, used = '0', total = '0', temp = '0', name = 'GPU'] = line.split(',').map(s => s.trim()) as [string, ...string[]]
198  // A field the GPU does not report prints as "[N/A]": count it as 0, never NaN.
199  const n = (s: string): number => Number(s) || 0
200  return { util: n(util), memUsed: n(used) * 1024 ** 2, memTotal: n(total) * 1024 ** 2, temp: n(temp), name }
201}
202
203export function fmtBytes(n: number | undefined): string {
204  if (n === undefined || !Number.isFinite(n)) return '—'
205  // Each unit starts where the one below would round up to 1024 of itself.
206  if (n >= 1023.95 * 1024 ** 3) return `${(n / 1024 ** 4).toFixed(1)}T`
207  if (n >= 1023.5 * 1024 ** 2) return `${(n / 1024 ** 3).toFixed(1)}G`
208  if (n >= 1023.5 * 1024) return `${Math.round(n / 1024 ** 2)}M`
209  return `${Math.round(n / 1024)}K`
210}
211
hooks/ticker.ts 98 lines
1// marquee's pure core: the segments of the line and the scrolling window
2// over them. No `$` here, so the tests drive it directly.
3
4import { clip, fmtClock, fmtSpan, fmtUsd, limitLabel, modelName, toolName } from './lib/kz.ts'
5
6export type TickerLimit = { kind: string; percentUsed: number; resetsAt?: string }
7export type TickerGit = { branch: string; ahead: number; behind: number; dirty: number }
8export type TickerTool = { name: string; detail: string; startedAt: number }
9
10export type TickerData = {
11  model?: string
12  effort?: string
13  ctxPercent?: number
14  limits: TickerLimit[]
15  costUsd?: number
16  git?: TickerGit
17  tool?: TickerTool
18  now: number
19}
20
21export const SEGMENTS = ['model', 'ctx', 'limits', 'cost', 'git', 'tool'] as const
22export type SegmentName = (typeof SEGMENTS)[number]
23export const DEFAULT_SEGMENTS = SEGMENTS.join(',')
24
25/** Between segments. */
26export const SEP = ' │ '
27/** Between two laps of a scrolling line. */
28export const GAP = '   ◆   '
29
30/** `"model, git ,bogus,ctx"` → `['model', 'git', 'ctx']`: known names, in order, once each. */
31export function parseSegments(spec: string | undefined): SegmentName[] {
32  const out: SegmentName[] = []
33  for (const raw of (spec ?? DEFAULT_SEGMENTS).split(',')) {
34    const name = raw.trim().toLowerCase() as SegmentName
35    if ((SEGMENTS as readonly string[]).includes(name) && !out.includes(name)) out.push(name)
36  }
37  return out
38}
39
40const pct = (n: number) => `${Math.round(n)}%`
41
42/** The text of each chosen segment, in order, the empty ones left out; `limits` gives one per window. */
43export function buildSegments(d: TickerData, order: readonly SegmentName[]): string[] {
44  const out: string[] = []
45  for (const name of order) {
46    if (name === 'model') {
47      if (d.model) out.push(`◆ ${modelName(d.model)}${d.effort ? `·${d.effort}` : ''}`)
48    } else if (name === 'ctx') {
49      if (d.ctxPercent !== undefined && Number.isFinite(d.ctxPercent)) out.push(`ctx ${pct(d.ctxPercent)}`)
50    } else if (name === 'limits') {
51      for (const l of d.limits) {
52        const t = l.resetsAt ? Date.parse(l.resetsAt) : NaN
53        const reset = l.kind === 'five_hour' && Number.isFinite(t) ? ` ↻${fmtSpan(Math.max(0, t - d.now))}` : ''
54        out.push(`${limitLabel(l.kind)} ${pct(l.percentUsed)}${reset}`)
55      }
56    } else if (name === 'cost') {
57      if (d.costUsd !== undefined) out.push(fmtUsd(d.costUsd))
58    } else if (name === 'git') {
59      const g = d.git
60      if (g && g.branch) {
61        const bits = [g.ahead ? `↑${g.ahead}` : '', g.behind ? `↓${g.behind}` : '', g.dirty ? `●${g.dirty}` : ''].filter(Boolean)
62        out.push(`⎇ ${g.branch}${bits.length ? ' ' + bits.join(' ') : ''}`)
63      }
64    } else {
65      // 'tool', the last of the SegmentNames.
66      const t = d.tool
67      if (t) out.push(`▶ ${toolName(t.name)}${t.detail ? ' ' + clip(t.detail, 28) : ''} ${fmtClock(d.now - t.startedAt)}`)
68    }
69  }
70  return out
71}
72
73export function compose(segments: readonly string[]): string {
74  return segments.join(SEP)
75}
76
77/**
78 * The line to show at `tick`: the whole line when it fits in `width`
79 * characters, else a `width`-wide window rotating over the loop of the
80 * segments and GAP, `step` characters per tick.
81 */
82export function windowAt(segments: readonly string[], width: number, tick: number, step = 1): string {
83  const text = compose(segments)
84  const chars = Array.from(text)
85  const w = Math.max(8, Math.floor(width))
86  if (chars.length <= w) return text
87  const loop = [...chars, ...Array.from(GAP)]
88  const off = (((tick * step) % loop.length) + loop.length) % loop.length
89  let out = ''
90  for (let i = 0; i < w; i++) out += loop[(off + i) % loop.length]
91  return out
92}
93
94/** Whether the line scrolls at this width. */
95export function scrolls(segments: readonly string[], width: number): boolean {
96  return Array.from(compose(segments)).length > Math.max(8, Math.floor(width))
97}
98
types/index.d.ts 12 lines
1// Marquee keeps no $.state: its one output is the status line ($.ui.status),
2// and its one persisted value is the on/off switch in $.store ('enabled').
3
4export type MarqueeSegment = 'model' | 'ctx' | 'limits' | 'cost' | 'git' | 'tool'
5
6export type MarqueeOptions = {
7  /** Characters the line may take before it scrolls (default 110). */
8  width: number
9  /** Comma-separated segment names, in order (default "model,ctx,limits,cost,git,tool"). */
10  segments: string
11}
12