SLOPSHOPPER

chronicle

KOZMOS Chronicle: the session as a timeline. Prompts, turn ends with duration, tool count and spend, subagents spawned and finished, commits and pushes, failed…

paneguardcommandpromptagents
★ 15v0.1.0MITupdated 2026-10-10ersinkoc/claude-mods/mods/chronicle
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · chronicle
│ ┃ KOZMOS · Chronicle ✕ › fix the failing auth test and add an audit log call │ ┃ ❯ 1 prompts ◈ 0 agents ◉ 0 commits ✖ 1 e… │ ┃ █▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁ ⏺ Read(src/auth.ts) │ ┃ [ All 5 ] [ Prompts 2 ] [ Agents 0 ] [ Git 1 ⎿ Read 6 lines │ ┃ 08:53:20 ◆ turn · 0:42 ⏺ Update(src/auth.ts) │ ┃ │ 9 tools ⎿ Added 2 lines, removed 1 line │ ┃ 08:53:20 ⇡ push ⏺ Bash(bun test) │ ┃ │ rm -rf build && git push --force… ⎿ 3 pass, 1 fail │ ┃ 08:53:20 ✖ Bash failed │ ┃ │ Run the test suite ● Done. refresh now rejects expired claims and logs an audit event. │ ┃ 08:53:20 ❯ fix the failing auth test and ad… │ ┃ │ ✻ Worked for 42s · done 4:20 PM │ ┃ 08:53:20 ★ session started │ ┃ /work/app › /chronicle │ ⎿ chronicle: Chronicle open. │ │ ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Pane · KOZMOS · Chronicle
❯ 1 prompts ◈ 0 agents ◉ 0 commits ✖ 1 errors █▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁ [ All 5 ] [ Prompts 2 ] [ Agents 0 ] [ Git 1 ] [ Errors 1 ] 08:53:20 ◆ turn · 0:42 │ 9 tools 08:53:20 ⇡ push │ rm -rf build && git push --force origin main 08:53:20 ✖ Bash failed │ Run the test suite 08:53:20 ❯ fix the failing auth test and add an audit log c… │ 08:53:20 ★ session started /work/app
README

KOZMOS Chronicle

The session as a timeline in a sidebar, newest first, each event stamped with its local time (HH:MM:SS) and drawn with its own icon and color:

EventWhat is recorded
❯ promptthe first 80 characters of each prompt you submit
◆ turnits duration, the tools it called and the spend it added
◈ / ◇ agenta subagent spawned, and finished or failed with its run time
◉ commit, ⇡ pusha successful git commit / git push through Bash, with sha, branch and message
✖ failed toolany tool call that errored or was denied
⇊ compactionmanual or automatic, with tokens before → after
▲ limit, ◔ contextcrossing 50, 80 and 95 % of a rate-limit window or of the context

Up to 300 events are kept. Filter buttons (hotkeys 1–5) narrow the view to All, Prompts, Agents, Git or Errors. A ribbon above squeezes the whole session into one row, each slice colored by its loudest event.

On the desktop the header carries counters and the ribbon, and the timeline is one SVG with a gradient rail, colored dots and a ripple on the newest event.

  • /chronicle toggles the sidebar; autoOpen (default off) opens it at start.

Türkçe

Oturumu kenar çubuğunda bir zaman çizelgesi olarak gösterir; en yeni en üstte, her olay yerel saatiyle (SS:DD:ss) ve kendi simgesi ve rengiyle:

OlayKaydedilen
❯ istemgönderdiğin her istemin ilk 80 karakteri
◆ tursüresi, çağırdığı araç sayısı ve eklediği maliyet
◈ / ◇ ajanbaşlatılan alt ajan; bitişi ya da hatası ve çalışma süresi
◉ commit, ⇡ pushBash ile başarılı git commit / git push; sha, dal ve mesaj
✖ başarısız araçhata veren ya da reddedilen her araç çağrısı
⇊ sıkıştırmaelle ya da otomatik; önce → sonra token
▲ limit, ◔ bağlambir kullanım penceresinin ya da bağlamın yüzde 50, 80 ve 95 eşiğini geçmek

En fazla 300 olay tutulur. Süzgeç düğmeleri (kısayol 1–5) görünümü Tümü, İstemler, Ajanlar, Git ya da Hatalar ile daraltır. Üstteki şerit tüm oturumu tek satıra sıkıştırır; her dilim en önemli olayının rengini alır.

Masaüstünde başlıkta sayaçlar ve şerit, zaman çizelgesi ise renk geçişli bir ray, renkli noktalar ve en yeni olayda bir dalga ile tek bir SVG'dir.

  • /chronicle kenar çubuğunu açar/kapatır; autoOpen (varsayılan kapalı) başlangıçta açar.
Source 3 files
hooks/register.tsx 444 lines
1import { atom, read, update } from 'claude-code'
2import type { Elements, EngineInterface, Register } from 'claude-code'
3
4import type { ChronEvent, ChronFilter, ChronKind, ChronSnap } from '../types'
5import { Canvas, KZ, clip, fitText, fmtClock, fmtTokens, fmtUsd, limitLabel, pxOf, svg, svgText, toolDetail, toolName } from './lib/kz.ts'
6
7const PANE = 'kz-chronicle'
8const TITLE = 'KOZMOS · Chronicle'
9const MAX_EVENTS = 300
10const MILESTONES = [50, 80, 95]
11
12const snapAtom = atom({ plugin: 'chronicle', key: 'snap' } as const, null)
13const filterAtom = atom({ plugin: 'chronicle', key: 'filter' } as const, 'all')
14
15type KindStyle = { icon: string; color: string; rank: number }
16
17const KIND: Record<ChronKind, KindStyle> = {
18  session: { icon: '★', color: KZ.mist, rank: 0 },
19  prompt: { icon: '❯', color: KZ.cyan, rank: 2 },
20  turn: { icon: '◆', color: KZ.violet, rank: 1 },
21  'agent-start': { icon: '◈', color: KZ.magenta, rank: 3 },
22  'agent-end': { icon: '◇', color: KZ.magenta, rank: 3 },
23  commit: { icon: '◉', color: KZ.green, rank: 5 },
24  push: { icon: '⇡', color: KZ.teal, rank: 5 },
25  'tool-fail': { icon: '✖', color: KZ.red, rank: 6 },
26  compact: { icon: '⇊', color: KZ.blue, rank: 4 },
27  limit: { icon: '▲', color: KZ.amber, rank: 4 },
28  context: { icon: '◔', color: KZ.yellow, rank: 4 },
29}
30
31const FILTERS: { id: ChronFilter; label: string; hotkey: string }[] = [
32  { id: 'all', label: 'All', hotkey: '1' },
33  { id: 'prompts', label: 'Prompts', hotkey: '2' },
34  { id: 'agents', label: 'Agents', hotkey: '3' },
35  { id: 'git', label: 'Git', hotkey: '4' },
36  { id: 'errors', label: 'Errors', hotkey: '5' },
37]
38
39function passes(f: ChronFilter, ev: ChronEvent): boolean {
40  if (f === 'all') return true
41  if (f === 'prompts') return ev.kind === 'prompt' || ev.kind === 'turn'
42  if (f === 'agents') return ev.kind === 'agent-start' || ev.kind === 'agent-end'
43  if (f === 'git') return ev.kind === 'commit' || ev.kind === 'push'
44  return ev.isError === true || ev.kind === 'tool-fail'
45}
46
47const colorOf = (ev: ChronEvent) => (ev.isError ? KZ.red : KIND[ev.kind].color)
48
49// ---------------------------------------------------------------------------
50// The record. Module state starts over on a reload.
51
52let events: ChronEvent[] = []
53let startedAt = 0
54let nextId = 1
55let lastPublished = ''
56let pubSeq = 0
57// Turn bookkeeping for the main loop.
58let turnTools = 0
59let turnCost: number | undefined
60let lastCost: number | undefined
61// Subagents by id: what they are and when they began.
62let agents = new Map<string, { type: string; description: string; at: number }>()
63// Milestones already announced, per rate-limit kind and for the context.
64let armed = new Map<string, number>()
65let isSeeded = false
66
67function hhmmss(at: number): string {
68  const d = new Date(at)
69  const p = (n: number) => String(n).padStart(2, '0')
70  return `${p(d.getHours())}:${p(d.getMinutes())}:${p(d.getSeconds())}`
71}
72
73function record(at: number, kind: ChronKind, title: string, detail?: string, isError?: boolean): void {
74  events = [...events, { id: nextId++, at, kind, title, ...(detail ? { detail } : {}), ...(isError ? { isError } : {}) }].slice(-MAX_EVENTS)
75}
76
77async function publish($: EngineInterface): Promise<void> {
78  const seq = ++pubSeq
79  const snap: ChronSnap = { events, startedAt }
80  const key = JSON.stringify(snap)
81  if (key === lastPublished) return
82  await Promise.resolve()
83  if (seq !== pubSeq) return
84  lastPublished = key
85  await update($, snapAtom, () => snap)
86}
87
88/** Crossing 50, 80 and 95 %; a fall below re-arms the levels it fell under. */
89function milestone(key: string, percent: number | undefined, at: number, announce: (level: number) => void): void {
90  if (percent === undefined || !Number.isFinite(percent)) return
91  const level = MILESTONES.filter(m => percent >= m).pop() ?? 0
92  const had = armed.get(key) ?? 0
93  if (level > had && isSeeded) announce(level)
94  if (level !== had) armed.set(key, level)
95}
96
97/** Whether some part of a command line (`a && b | c`) is `git [options] <verb>` that is not a dry run. */
98function runsGit(cmd: string, verb: 'commit' | 'push'): boolean {
99  const re = new RegExp(`^(\\w+=\\S* )*git(\\s+-\\S+(\\s+\\S+)?)*\\s+${verb}(?![\\w-])`)
100  const dry = verb === 'push' ? /\s(--dry-run|-[a-zA-Z]*n[a-zA-Z]*)(?=\s|$)/ : /\s--dry-run(?=\s|$)/
101  return cmd.split(/&&|\|\||[;&|\n]/).map(p => p.replace(/\s+/g, ' ').trim()).some(p => re.test(p) && !dry.test(p))
102}
103
104function commitMessage(cmd: string): string {
105  // A HEREDOC body is the message (Claude Code's own form): its first line is the subject.
106  const doc = /<<-?\s*(['"]?)(\w+)\1[^\n]*\n([\s\S]*?)\n[ \t]*\2\b/.exec(cmd)
107  const subject = doc?.[3]?.split('\n').find(l => l.trim())
108  // -m, a cluster ending in m (-am), --message, with a space, "=" or nothing before the text.
109  const m = /\s(?:-[a-zA-Z]*m|--message)(?:\s+|=)?(?:"((?:[^"\\]|\\.)*)"|'([^']*)'|(\S+))/.exec(cmd)
110  const raw = subject ?? m?.[1] ?? m?.[2] ?? m?.[3] ?? ''
111  return clip(raw.replace(/\\n/g, ' '), 72)
112}
113
114async function toggle($: EngineInterface): Promise<boolean> {
115  if ((await $.ui.panes()).some(p => p.id === PANE)) {
116    await $.ui.close({ id: PANE })
117    return false
118  }
119  await $.ui.open({ id: PANE, title: TITLE })
120  return true
121}
122
123async function costNow($: EngineInterface): Promise<number | undefined> {
124  try {
125    return (await $.session.usage()).cost?.usd
126  } catch {
127    return lastCost
128  }
129}
130
131export const register: Register = (on, options) => {
132  on('session.start', async ($, e, next) => {
133    const started = await next(e)
134    startedAt = await $.clock.now()
135    events = []
136    nextId = 1
137    lastPublished = ''
138    turnTools = 0
139    turnCost = undefined
140    lastCost = undefined
141    agents = new Map()
142    armed = new Map()
143    isSeeded = false
144    record(startedAt, 'session', 'session started', e.cwd ? clip(e.cwd, 60) : undefined)
145    await $.command.register({ name: 'chronicle', description: 'KOZMOS: toggle the Chronicle timeline sidebar', immediate: true })
146    await publish($)
147    if (options.autoOpen === true) void $.ui.open({ id: PANE, title: TITLE })
148    return started
149  })
150
151  on('command.run', { command: 'chronicle' }, async $ => ({
152    text: (await toggle($)) ? 'Chronicle open.' : 'Chronicle closed.',
153  }))
154
155  on('prompt.submit', async ($, e, next) => {
156    const r = await next(e)
157    // The person's own prompts: not task notifications, peers or triggers.
158    const isPerson = e.origin.kind === 'composer' || e.origin.kind === 'bridge' || e.origin.kind === 'sdk'
159    if (r.drop === undefined && isPerson && (r.text || e.text).trim()) {
160      record(await $.clock.now(), 'prompt', clip(r.text || e.text, 80))
161      await publish($)
162    }
163    return r
164  }).catch(($, e, next) => next(e))
165
166  on('turn.start', async ($, e, next) => {
167    turnTools = 0
168    turnCost = lastCost ?? (await costNow($))
169    return next(e)
170  })
171
172  on('turn.complete', async ($, e, next) => {
173    const at = await $.clock.now()
174    if (e.agentId === undefined) {
175      const cost = await costNow($)
176      if (cost !== undefined) lastCost = cost
177      const delta = cost !== undefined && turnCost !== undefined ? cost - turnCost : undefined
178      const how = e.reason === 'answer' ? 'turn' : e.reason === 'aborted' ? 'turn interrupted' : e.reason === 'refusal' ? 'turn refused' : 'turn failed'
179      const bits = [`${turnTools} tool${turnTools === 1 ? '' : 's'}`, delta !== undefined && delta > 0 ? `+${fmtUsd(delta)}` : '']
180      record(at, 'turn', `${how} · ${fmtClock(e.durationMs)}`, bits.filter(Boolean).join(' · '), e.reason === 'error' || e.reason === 'refusal')
181      turnCost = cost
182    } else {
183      const a = agents.get(e.agentId)
184      if (a) {
185        const ok = e.reason === 'answer'
186        record(at, 'agent-end', `${a.type} ${ok ? 'finished' : e.reason === 'aborted' ? 'stopped' : 'failed'} · ${fmtClock(at - a.at)}`, a.description, !ok)
187      }
188    }
189    await publish($)
190    return next(e)
191  })
192
193  on('agent.spawn', async ($, e, next) => {
194    const r = await next(e)
195    if (r.deny === undefined && r.agentId) {
196      const at = await $.clock.now()
197      agents.set(r.agentId, { type: e.subagentType || 'agent', description: e.description, at })
198      record(at, 'agent-start', `${e.subagentType || 'agent'} spawned${e.background ? ' (background)' : ''}`, e.description)
199      await publish($)
200    }
201    return r
202  }).catch(($, e, next) => next(e))
203
204  on('tool.call', async ($, e, next) => {
205    if (e.agentId === undefined) turnTools++
206    const ran = await next(e)
207    const at = await $.clock.now()
208    const failed = ran.isError === true || ran.deny !== undefined
209    const name = String(e.tool)
210    if (failed) {
211      const who = e.agentId === undefined ? '' : ` in ${agents.get(e.agentId)?.type ?? 'agent'}`
212      record(at, 'tool-fail', `${toolName(name)} ${ran.deny !== undefined ? 'denied' : 'failed'}${who}`, toolDetail(name, e) || undefined, true)
213      await publish($)
214    } else if (e.tool === 'Bash') {
215      const cmd = e.command
216      const res = ran.result as { interrupted?: boolean; gitOperation?: { commit?: { sha?: string; kind?: string; branch?: string }; push?: { branch?: string } } } | undefined
217      const op = res?.gitOperation
218      if (res?.interrupted !== true && (op?.commit || runsGit(cmd, 'commit'))) {
219        const sha = op?.commit?.sha ? op.commit.sha.slice(0, 7) : ''
220        const verb = op?.commit?.kind === 'amended' ? 'amend' : 'commit'
221        record(at, 'commit', `${verb}${sha ? ` ${sha}` : ''}${op?.commit?.branch ? ` on ${op.commit.branch}` : ''}`, commitMessage(cmd) || undefined)
222        await publish($)
223      }
224      if (res?.interrupted !== true && (op?.push || runsGit(cmd, 'push'))) {
225        record(at, 'push', `push${op?.push?.branch ? ` → ${op.push.branch}` : ''}`, clip(cmd, 72))
226        await publish($)
227      }
228    }
229    return ran
230  }).catch(($, e, next) => next(e))
231
232  on('session.compact', async ($, e, next) => {
233    const r = await next(e)
234    if (e.trigger !== 'precompute' && r.skip === undefined) {
235      const at = await $.clock.now()
236      const span = r.tokensBefore !== undefined && r.tokensAfter !== undefined ? `${fmtTokens(r.tokensBefore)} → ${fmtTokens(r.tokensAfter)}` : undefined
237      const who = e.agentId === undefined ? '' : ` (${agents.get(e.agentId)?.type ?? 'agent'})`
238      record(at, 'compact', `compacted · ${e.trigger}${who}`, span)
239      // The context fell: its milestones can fire again.
240      if (e.agentId === undefined) armed.delete('context')
241      await publish($)
242    }
243    return r
244  }).catch(($, e, next) => next(e))
245
246  on('session.measure', async ($, e, next) => {
247    const at = await $.clock.now()
248    if (e.cost) lastCost = e.cost.usd
249    for (const l of e.rateLimits) {
250      milestone(`limit:${l.kind}`, l.percentUsed, at, level =>
251        record(at, 'limit', `${limitLabel(l.kind)} limit past ${level}%`, `${Math.round(l.percentUsed)}% used`, level >= 95))
252    }
253    milestone('context', e.context.percent, at, level =>
254      record(at, 'context', `context past ${level}%`, e.context.tokens !== undefined ? `${fmtTokens(e.context.tokens)} of ${fmtTokens(e.context.window)}` : undefined, level >= 95))
255    isSeeded = true
256    await publish($)
257    return next(e)
258  }).catch(($, e, next) => next(e))
259
260  on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
261    const snap = (await read($, snapAtom)) ?? { events, startedAt }
262    const filter = await read($, filterAtom)
263    const ui = $.ui.resolve(e)
264    const { Box, Text, Button } = ui
265    const shown = snap.events.filter(ev => passes(filter, ev)).reverse()
266    const buttons = (
267      <Box key="filters" flexDirection="row" gap={1} flexWrap="wrap">
268        {FILTERS.map(f => (
269          <Button
270            key={`f-${f.id}`}
271            label={`${f.label} ${snap.events.filter(ev => passes(f.id, ev)).length}`}
272            hotkey={f.hotkey}
273            variant={f.id === filter ? 'primary' : undefined}
274            dimColor={f.id !== filter}
275            onPress={() => void update($, filterAtom, () => f.id)}
276          />
277        ))}
278      </Box>
279    )
280
281    if ('Svg' in ui && e.surface !== 'terminal') {
282      const { Svg } = ui
283      const W = pxOf(e.props.bodyColumns, 48)
284      const head = headerSvg(snap, W)
285      const line = timelineSvg(shown.slice(0, 60), W)
286      return (
287        <Box flexDirection="column">
288          <Svg source={head.source} alt={altHeader(snap)} width={W} height={head.height} />
289          {buttons}
290          <Svg source={line.source} alt={shown.slice(0, 12).map(ev => `${hhmmss(ev.at)} ${ev.title}`).join('; ') || 'no events'} width={W} height={line.height} />
291        </Box>
292      )
293    }
294
295    // Only the terminal is left, and it always has Raster.
296    const { Raster } = ui as Elements['terminal']
297    const cols = Math.max(30, e.props.bodyColumns || 44)
298    const t = tally(snap)
299    const ribbonW = Math.max(8, cols - 2)
300    return (
301      <Box flexDirection="column">
302        <Text wrap="truncate-end">
303          <Text color={KZ.cyan}>❯ {t.prompts}</Text><Text dimColor> prompts  </Text>
304          <Text color={KZ.magenta}>◈ {t.agents}</Text><Text dimColor> agents  </Text>
305          <Text color={KZ.green}>◉ {t.commits}</Text><Text dimColor> commits  </Text>
306          <Text color={t.errors ? KZ.red : KZ.mist}>✖ {t.errors}</Text><Text dimColor> errors</Text>
307        </Text>
308        <Raster key="ribbon" columns={ribbonW} rows={1} cells={ribbon(snap, ribbonW)} />
309        {buttons}
310        {shown.length === 0 ? <Text dimColor>  nothing here yet</Text> : null}
311        {shown.slice(0, 80).map((ev, i) => {
312          const c = colorOf(ev)
313          const isLast = i === Math.min(shown.length, 80) - 1
314          return (
315            <Box key={`ev-${ev.id}`} flexDirection="column">
316              <Text wrap="truncate-end">
317                <Text dimColor>{hhmmss(ev.at)} </Text>
318                <Text color={c} bold>{KIND[ev.kind].icon} </Text>
319                <Text bold={ev.kind === 'prompt' || ev.kind === 'commit'} color={ev.isError ? KZ.red : undefined}>{ev.title}</Text>
320              </Text>
321              {ev.detail || !isLast
322                ? (
323                    <Text wrap="truncate-end">
324                      <Text dimColor>{'         '}</Text>
325                      <Text color={c} dimColor>{isLast ? ' ' : '│'} </Text>
326                      {ev.detail ? <Text dimColor>{ev.detail}</Text> : null}
327                    </Text>
328                  )
329                : null}
330            </Box>
331          )
332        })}
333      </Box>
334    )
335  })
336}
337
338// ---------------------------------------------------------------------------
339
340function tally(s: ChronSnap): { prompts: number; agents: number; commits: number; errors: number } {
341  const t = { prompts: 0, agents: 0, commits: 0, errors: 0 }
342  for (const ev of s.events) {
343    if (ev.kind === 'prompt') t.prompts++
344    else if (ev.kind === 'agent-start') t.agents++
345    else if (ev.kind === 'commit') t.commits++
346    if (ev.isError) t.errors++
347  }
348  return t
349}
350
351/** The session squeezed into `w` slices, each painted by its loudest event. */
352function slices(s: ChronSnap, w: number): (ChronEvent | undefined)[] {
353  const out: (ChronEvent | undefined)[] = Array.from({ length: w }, () => undefined)
354  const last = s.events[s.events.length - 1]?.at ?? s.startedAt
355  const span = Math.max(60_000, last - s.startedAt)
356  for (const ev of s.events) {
357    const i = Math.min(w - 1, Math.max(0, Math.floor(((ev.at - s.startedAt) / span) * w)))
358    const cur = out[i]
359    const rank = (x: ChronEvent) => (x.isError ? 9 : KIND[x.kind].rank)
360    if (!cur || rank(ev) >= rank(cur)) out[i] = ev
361  }
362  return out
363}
364
365function ribbon(s: ChronSnap, w: number): string {
366  const cv = new Canvas(w, 1)
367  slices(s, w).forEach((ev, x) => {
368    if (ev) cv.set(x, 0, ev.kind === 'session' ? '▏' : '█', colorOf(ev))
369    else cv.set(x, 0, '▁', '#3f3f46')
370  })
371  return cv.encode()
372}
373
374// ---------------------------------------------------------------------------
375// Desktop.
376
377const CSS = `
378.ring{animation:chr 2s ease-out infinite;transform-box:fill-box;transform-origin:center}
379@keyframes chr{0%{opacity:.6;transform:scale(.7)}100%{opacity:0;transform:scale(2.2)}}
380`
381
382function altHeader(s: ChronSnap): string {
383  const t = tally(s)
384  return `${s.events.length} events: ${t.prompts} prompts, ${t.agents} agents, ${t.commits} commits, ${t.errors} errors`
385}
386
387function headerSvg(s: ChronSnap, W: number): { source: string; height: number } {
388  const t = tally(s)
389  const p: string[] = []
390  const H = 70
391  p.push(`<rect class="p" x="0" y="0" width="${W}" height="${H}" rx="12"/>`)
392  const chips: [string, number, string][] = [['prompts', t.prompts, KZ.cyan], ['agents', t.agents, KZ.magenta], ['commits', t.commits, KZ.green], ['errors', t.errors, t.errors ? KZ.red : KZ.mist]]
393  const cw = (W - 24) / chips.length
394  chips.forEach(([label, n, c], i) => {
395    const x = 12 + i * cw
396    p.push(svgText(x, 26, String(n), { size: 17, weight: 750, fill: c }))
397    p.push(svgText(x + String(n).length * 10.5 + 5, 26, label, { cls: 's', size: 10.5 }))
398  })
399  // The ribbon: the whole session left to right.
400  const rw = W - 24
401  const n = Math.max(10, Math.min(120, Math.floor(rw / 4)))
402  const sw = rw / n
403  p.push(`<rect class="k" x="12" y="40" width="${rw}" height="14" rx="4"/>`)
404  slices(s, n).forEach((ev, i) => {
405    if (ev && ev.kind !== 'session') p.push(`<rect x="${(12 + i * sw + 0.5).toFixed(1)}" y="41" width="${Math.max(1, sw - 1).toFixed(1)}" height="12" rx="1.5" fill="${colorOf(ev)}"/>`)
406  })
407  const last = s.events[s.events.length - 1]?.at ?? s.startedAt
408  p.push(svgText(12, 65, hhmmss(s.startedAt), { cls: 'm', size: 9, mono: true }))
409  p.push(svgText(W - 12, 65, hhmmss(last), { cls: 'm', size: 9, mono: true, anchor: 'end' }))
410  return { source: svg(W, H + 4, p.join(''), CSS), height: H + 4 }
411}
412
413function timelineSvg(list: ChronEvent[], W: number): { source: string; height: number } {
414  const p: string[] = []
415  const lineX = 74
416  let y = 16
417  const ys: number[] = []
418  list.forEach((ev, i) => {
419    const c = colorOf(ev)
420    const h = ev.detail ? 38 : 26
421    ys.push(y)
422    p.push(svgText(12, y + 4, hhmmss(ev.at), { cls: 'm', size: 10, mono: true }))
423    if (i === 0) p.push(`<circle cx="${lineX}" cy="${y}" r="6" fill="${c}" class="ring"/>`)
424    p.push(`<circle cx="${lineX}" cy="${y}" r="${ev.kind === 'prompt' || ev.kind === 'commit' || ev.isError ? 5 : 4}" fill="${c}"/>`)
425    if (ev.kind === 'turn' || ev.kind === 'agent-end') p.push(`<circle cx="${lineX}" cy="${y}" r="1.8" class="p"/>`)
426    const tx = lineX + 14
427    p.push(svgText(tx, y + 4, fitText(ev.title, 12, W - tx - 12), { size: 12, weight: ev.kind === 'prompt' || ev.kind === 'commit' ? 650 : 500, fill: ev.isError ? KZ.red : undefined }))
428    if (ev.detail) p.push(svgText(tx, y + 19, fitText(ev.detail, 10.5, W - tx - 12), { cls: 's', size: 10.5, mono: ev.kind === 'commit' || ev.kind === 'push' || ev.kind === 'tool-fail' }))
429    y += h
430  })
431  if (list.length === 0) {
432    p.push(svgText(W / 2, 22, 'Nothing here yet.', { cls: 'm', size: 11, anchor: 'middle' }))
433    y = 36
434  }
435  const height = Math.max(36, y - 6)
436  const top = ys[0] ?? 0
437  const bottom = ys[ys.length - 1] ?? 0
438  const rail = list.length > 1
439    ? `<defs><linearGradient id="chG" x1="0" y1="0" x2="0" y2="1"><stop offset="0" stop-color="${KZ.violet}"/><stop offset=".6" stop-color="${KZ.cyan}" stop-opacity=".7"/><stop offset="1" stop-color="${KZ.cyan}" stop-opacity=".1"/></linearGradient></defs>` +
440      `<rect x="${lineX - 1}" y="${top}" width="2" height="${bottom - top}" rx="1" fill="url(#chG)"/>`
441    : ''
442  return { source: svg(W, height, `<rect class="p" x="0" y="0" width="${W}" height="${height}" rx="12"/>${rail}${p.join('')}`, CSS), height }
443}
444
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
types/index.d.ts 37 lines
1export type ChronKind =
2  | 'session'
3  | 'prompt'
4  | 'turn'
5  | 'agent-start'
6  | 'agent-end'
7  | 'commit'
8  | 'push'
9  | 'tool-fail'
10  | 'compact'
11  | 'limit'
12  | 'context'
13
14export type ChronEvent = {
15  id: number
16  at: number
17  kind: ChronKind
18  title: string
19  detail?: string
20  /** Drawn red, and kept by the Errors filter. */
21  isError?: boolean
22}
23
24export type ChronFilter = 'all' | 'prompts' | 'agents' | 'git' | 'errors'
25
26export type ChronSnap = {
27  /** Oldest first, at most 300. */
28  events: ChronEvent[]
29  startedAt: number
30}
31
32declare module 'claude-code' {
33  interface PluginState {
34    chronicle: { snap: ChronSnap | null; filter: ChronFilter }
35  }
36}
37