SLOPSHOPPER

kiko

Kiko boxes every turn above your prompt: Knowledge In, Knowledge Out, K.O.!

bandspinnerguardcommandtimer
v0.2.0MITupdated 2026-10-10kikostefanov-lab/claude-code-mods/kiko
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · kiko
› 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 › /kiko ⎿ kiko: Kiko is on · 0-0 | streak 0. Try /kiko stats, /kiko off. ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts
README

Claude Code mods

CI

Experiments with Claude Code mods: plugins of function hooks that add live panes, bands, status lines, toasts, tools and hooks inside Claude Code (terminal CLI and the desktop Code tab), and hot-reload while you build them.

The mods API is early access and changes between releases. Everything here was built and tested against Claude Code 2.1.286. Run /whiteboard doctor if something looks off.

ModWhat it does
whiteboard/Gives Claude a draw tool: Mermaid, D2 and PlantUML diagrams rendered locally and shown in a side pane, with history, versions, export, copy and share.
kiko/Knowledge In, Knowledge Out: a TUI boxer works the bag every turn above your prompt, grabbing what Claude reads, punching with what it writes, and finishing with a K.O.

Whiteboard

Ask Claude for a diagram ("show me the auth flow as a sequence diagram", "draw the class structure of this module") or run /whiteboard arch, and it appears in a Whiteboard pane beside the conversation. Rendering is local: nothing leaves your machine unless you press Share.

◀  3/5  ▶   Checkout sequence   ‹ v2/3 ›
[Export] [Copy] [Copy MD] [Share] [Open]
┌──────────────────────────────────────────────────────────┐
│  desktop / VS Code / mobile: the rendered SVG            │
│  Ghostty / kitty: the rendered PNG                       │
│  other terminals: the source in a code block             │
└──────────────────────────────────────────────────────────┘
 Ask Claude to change this diagram…                  send

Features

  • draw tool for Claude: { title, source, language? } with language one of mermaid (default), d2, plantuml. Rendering happens before the tool returns, so a syntax error goes straight back to Claude, which fixes it and redraws in the same turn.
  • Starter commands: /whiteboard arch (architecture), /whiteboard flow <file or area> (control flow), /whiteboard schema (data model). Each asks Claude to draw.
  • History per project: the last 20 diagrams, kept across sessions. ◀ ▶ buttons, or h / l while the pane has focus.
  • Versions: redrawing a title keeps the earlier versions; ‹ v2/3 › steps between them.
  • Ask Claude to change this: type a request under the diagram; Claude gets it with the current source and redraws.
  • Export writes diagrams/<title>.<mmd|d2|puml> and .svg into the working directory, never overwriting.
  • Copy (source), Copy MD (a fenced block that renders in GitHub, GitLab and Notion), Open (o, the SVG in your default app).
  • Share creates a secret GitHub gist after asking you first, and copies the link. Needs the GitHub CLI.
  • Themes: default, neutral, dark, forest, plus an optional Mermaid config file for team colours.
  • /whiteboard doctor checks Claude Code's version, each renderer, a test render, the GitHub CLI and terminal images, and says what to fix.

Where it works

SurfaceWhat you see
Desktop Code tab, VS CodeRendered SVG and everything above
MobileRendered SVG and buttons (no text field yet)
Terminal, Ghostty or kittyRendered PNG inline
Other terminals (iTerm2, Terminal.app, …)Source + Open to view the SVG in your browser

macOS, Linux and Windows are supported (open / xdg-open / start, zsh / bash / where). In the terminal a pane opens by itself only in the fullscreen layout at 144 or more columns; otherwise run /whiteboard.

Install

  1. Renderers. Mermaid is required, the others are optional:
   npm i -g @mermaid-js/mermaid-cli
   brew install d2 plantuml

The mod finds them through your login shell, then nvm's and Homebrew's folders, so they work even when the desktop app's PATH doesn't include them. If it can't find mmdc, set the plugin option mmdcPath.

  1. The plugin. Clone this repo, then either load it for every session (CLI and desktop) by adding it to the env block of ~/.claude/settings.json:
   {
     "env": {
       "CLAUDE_CODE_PLUGIN_DIRS": "/path/to/claude-code-mods/whiteboard"
     }
   }

or try it for one session:

   claude --plugin-dir /path/to/claude-code-mods/whiteboard

The repo is also a plugin marketplace (.claude-plugin/marketplace.json). Whether your Claude Code build loads function-hook mods from installed plugins depends on the build; the two options above always work.

  1. Check. Run /whiteboard doctor.

Options

OptionDefaultWhat it does
mmdcPathemptyAbsolute path to mmdc when it can't be found automatically
themedefaultdefault, neutral, dark or forest
mermaidConfigemptyAbsolute path to a Mermaid JSON config, for example team colours and fonts

Set them in Claude Code's config menu, or under pluginConfigs.whiteboard in your settings.

How it works

sequenceDiagram
  participant C as Claude
  participant W as whiteboard
  participant R as renderer (mmdc / d2 / plantuml)
  participant P as Pane
  C->>W: draw {title, source, language}
  W->>R: <id>.<ext> → <id>.svg (spawned; interrupt stops it)
  alt syntax error
    R-->>W: exit 1 + parse error
    W-->>C: error → Claude fixes and redraws
  else rendered
    W->>W: add to history, save for the project
    W->>P: open pane
    W-->>C: Drawn 'title' (n/total)
  end
  • Rendered files live in ~/.claude/whiteboard/<project>/; history is saved per project. Diagrams pushed out of the last 20 have their files removed.
  • Diagram text only ever goes into a file, never onto a command line; renderers run by argv, without a shell.
  • Renders time out after 20 s, and stop when you interrupt Claude.
  • --no-font-embed keeps Mermaid SVGs small: mermaid-cli 12 otherwise inlines ~160 KB of web fonts, past the 128 KB the pane draws inline. Text falls back to Arial.

Layout

.claude-plugin/marketplace.json  the repo as a plugin marketplace
.github/workflows/ci.yml         validate, test and smoke test on every push
whiteboard/
  .claude-plugin/plugin.json     manifest and options
  hooks/register.tsx             engine wiring: tool, command, pane, buttons
  hooks/history.ts               pure history logic
  hooks/render.ts                pure rendering, platform and version helpers
  hooks/actions.ts               pure pane, command and doctor helpers
  hooks/*.test.ts(x)             claude plugin test suites
  hooks/testkit.ts               fake host for the tests
  types/index.d.ts               session-state contract
  scripts/smoke-mmdc.sh          renders with the real mmdc

Development

claude plugin validate whiteboard   # what the engine will load, call and refuse
claude plugin test whiteboard       # 85 tests across terminal, desktop and mobile
claude plugin test kiko             # 43 tests: round logic, sprites, the band on every surface
whiteboard/scripts/smoke-mmdc.sh    # real mmdc: SVG size limit, PNG, syntax errors

See CONTRIBUTING.md and CHANGELOG.md.

Known limitations

  • Mermaid's state-diagram grammar is lenient: some typos render as odd states instead of failing.
  • Sources longer than about 9,800 characters show truncated in the source view; Copy and Export still give the full text.
  • Windows support is written and unit-tested but has not been run on a Windows machine yet.

Kiko

K-I-K-O: Knowledge In, Knowledge Out. While Claude works, Kiko boxes your problem in a band above the prompt. Every turn is a round; what Claude reads is Knowledge In, what it writes is Knowledge Out, and the end of the turn is the K.O.

 ROUND 3 ── KIKO vs. THE FLAKY AUTH TEST ─────────────── 0:42
 KI █████████░░░ 12.4k                     KO ████████░░░░ 2.1k
                .---.                                  ┌┴┐
   [app.ts]›››▄█(>.<)==█▄          {fix.ts}            │░│
                 /  \                       ‹ jab!     └─┘
 > reading app.ts
  • Rounds: "ROUND n ── FIGHT!" when a turn starts; the opponent is named from your prompt.
  • Moves: swirly eyes while Claude thinks, talking while it replies, a grab ([file]›››, gloves open) for every read, search or fetch, a punch ({file} into the bag, which flashes and swings) for every edit or write, a dodge for other tools.
  • Bars: KI is new input tokens, KO is output tokens (log scale).
  • K.O.: a 3-row card for 5 seconds, plus a K.O. ▸ … notice in the transcript (the terminal shows it; the desktop doesn't display notices yet).
  • Career record across sessions: /kiko stats (wins, streak, fastest and biggest K.O., last opponents).
  • Spinner words while Claude thinks or replies: "Kikonsidering", "Winding up the KO", "Trash-talking"…
  • /kiko off and /kiko on (saved; the record still counts while off). Interrupted or failed turns end quietly.

Kiko only watches: every hook passes the turn, its stream and each tool call through unchanged, and never calls a model.

Install: add :/path/to/claude-code-mods/kiko to CLAUDE_CODE_PLUGIN_DIRS (see the whiteboard's install above), or claude --plugin-dir /path/to/claude-code-mods/kiko.

SurfaceWhat Kiko shows
TerminalThe band as text rows, spinner words, the K.O. line in the transcript
Desktop Code tabThe band as one fixed-width code block, spinner words while Claude thinks or replies
VS Code, mobileNothing yet: the engine only raises the band and spinner on the terminal and desktop

Notes on the mods API (learned the hard way)

Useful if you're writing your own mod. These are things the type declarations don't spell out up front:

  • $ can only be passed to functions declared at the top level of the same file. Helpers in other files must be pure; the engine refuses to load the module otherwise.
  • Never name a variable h. JSX compiles to bare h(...) calls, and a local h shadows the factory.
  • Text, Svg and Markdown drop a key prop. Tests find them by type and text; Buttons and Inputs keep their keys.
  • The terminal's element table includes an Svg that draws nothing. Pick the body by e.surface, not by 'Svg' in elements.
  • Relative $.fs paths resolve against the engine's cwd, not necessarily the session's: build paths from $.session.cwd().
  • A slash command can't call $.prompt.submit directly: the command holds the turn the prompt would wait for. Submit from a timer ($.clock.after(0, …)) or a later event.
  • $.process.spawn kills its child when the dispatch is abandoned, so a render started from a tool call stops when the user interrupts. $.process.run has a timeout but no abort.
  • The desktop app (2.1.286) can't run Client surface modules: any module, even ten lines with no imports, is torn down with "did not load within 10s" (in ~/Library/Logs/Claude/claude.ai-web.log). Animate from the hooks module instead: a $.clock.every started in session.start writing a frame counter to $.state, with the band drawing rows (Text on the terminal, Code elsewhere for fixed-width columns). The test kit runs Client modules fine, so it won't catch this.
  • Desktop panes show one at a time; only the visible pane runs its content. Keep that in mind when probing with several panes.
  • Timers only outlive the dispatch that starts them from session.start. A $.clock.after set inside turn.complete never fires.
  • VS Code's element table lists a Client that draws nothing, like the terminal's Svg.
  • On the desktop, a running tool sets the spinner's message ("Running tools…"), so a spinner rewrite that respects message only shows while Claude thinks or replies.
  • In claude plugin test:
  • The test's $ carries only engine events (tool.call, ui.mount, session.start, command.run…), not plugin calls (fs, env, process), so test through the plugin's own tools, commands and panes.
  • tool.register / command.register have no implementation there and must be stubbed.
  • Stubs answer { value } or { deny }; one that throws is skipped, not rejected.
  • A process.spawn stub is an async generator that yields chunks and returns { value: { code, signal } }.
  • mock.clock holds timers until the test calls advance.
  • Inline test plugins are written to a temp folder, so they can't name a surface module of the plugin under test.
  • The CLI's runner (2.1.284) can't hook or observe session.append; check appended notices live.

Design docs

The spec and the implementation plan for 0.1 are in docs/superpowers/.

License

MIT

Source 7 files
hooks/register.tsx 215 lines
1// Kiko's hooks: the round's life on the engine, /kiko, and the band and spinner. Everything
2// that takes `$` lives in this file, since the engine follows `$` into a function declared
3// here but never across an import; the pure rules come from round, record, words and layout.
4import { atom, read, update } from 'claude-code'
5import type { EngineInterface, Register, TurnCompleteInput } from 'claude-code'
6
7import type { KikoRecord, Mode } from '../types'
8import { bandRows } from './layout'
9import { EMPTY_RECORD, isKikoRecord, recordLine, updateRecord } from './record'
10import {
11  IDLE, TICK_MS, afterTool, beatFor, classifyTool, freshSession, isFighting, knockOut, opponentName, startFight, stopFight, tick,
12  withMode, withUsage,
13} from './round'
14import type { Usage } from './round'
15import { koLine, spinnerKind, spinnerWord, statsText } from './words'
16
17const round = atom({ plugin: 'kiko', key: 'round' } as const, IDLE)
18const enabled = atom({ plugin: 'kiko', key: 'enabled' } as const, true)
19
20const RECORD_KEY = 'kiko:record'
21const ENABLED_KEY = 'kiko:enabled'
22
23const KIKO_COMMAND = {
24  name: 'kiko',
25  description: 'Kiko, your KIKO fighter: Knowledge In, Knowledge Out',
26  argumentHint: '[on | off | stats]',
27  immediate: true,
28} as const
29
30// A subagent's loop carries its agentId; its turns and tool calls aren't Kiko's fight.
31const isSub = (e: object): boolean => 'agentId' in e && Boolean(e.agentId)
32
33// The saved record, and whether it may be written back: a failed read or a value that isn't
34// a record is shown as a fresh one but never overwritten.
35async function loadRecord($: EngineInterface): Promise<{ rec: KikoRecord; isWritable: boolean }> {
36  let saved: unknown
37  try {
38    saved = await $.store.get(RECORD_KEY)
39  } catch {
40    return { rec: EMPTY_RECORD, isWritable: false }
41  }
42  if (saved === undefined) return { rec: EMPTY_RECORD, isWritable: true }
43  return isKikoRecord(saved) ? { rec: saved, isWritable: true } : { rec: EMPTY_RECORD, isWritable: false }
44}
45
46async function setEnabled($: EngineInterface, value: boolean): Promise<void> {
47  await update($, enabled, () => value)
48  await $.store.set(ENABLED_KEY, value)
49}
50
51async function openSession($: EngineInterface): Promise<void> {
52  // Kiko is on unless it was switched off; a failed read leaves it on.
53  const saved = await $.store.get(ENABLED_KEY).catch(() => undefined)
54  await update($, enabled, () => saved !== false)
55  const { rec } = await loadRecord($)
56  await update($, round, r => freshSession(r, recordLine(rec)))
57}
58
59async function startRound($: EngineInterface, text: string, turnId: string): Promise<void> {
60  // The same turn again is a no-op; a different one starts a new round even if the last
61  // turn's turn.complete never came.
62  if (isFighting(await read($, round), turnId)) return
63  const { rec } = await loadRecord($)
64  const now = await $.clock.now()
65  await update($, round, r => startFight(r, { turnId, opponent: opponentName(text), now, record: recordLine(rec) }))
66}
67
68async function setMode($: EngineInterface, turnId: string, mode: Mode): Promise<void> {
69  await update($, round, r => withMode(r, turnId, mode))
70}
71
72async function addUsage($: EngineInterface, turnId: string, usage: Usage): Promise<void> {
73  await update($, round, r => withUsage(r, turnId, usage))
74}
75
76// Plays the tool's beat; false when no round is on, so the call is left alone after.
77async function toolBeat($: EngineInterface, tool: string, input: unknown): Promise<boolean> {
78  if (!isFighting(await read($, round))) return false
79  const { kind, label } = classifyTool(tool, input)
80  await update($, round, r => beatFor(r, kind, label, tool))
81  return true
82}
83
84async function finishRound($: EngineInterface, e: TurnCompleteInput): Promise<void> {
85  const r = await read($, round)
86  if (!isFighting(r, e.turnId)) return
87  if (e.reason !== 'answer' || e.isAborted) {
88    await update($, round, stopFight)
89    return
90  }
91  const saved = await loadRecord($)
92  const rec = updateRecord(saved.rec, { ms: e.durationMs, tokens: r.tokensIn + r.tokensOut, opponent: r.opponent })
93  if (saved.isWritable) await $.store.set(RECORD_KEY, rec)
94  const done = knockOut(r, await $.clock.now(), recordLine(rec))
95  await update($, round, () => done)
96  if (await read($, enabled)) {
97    await $.session.append({ message: { type: 'system', content: [{ type: 'text', text: koLine(done, rec) }] } }).catch(() => undefined)
98  }
99}
100
101// The band's clock. Timers only outlive the dispatch that starts them from session.start,
102// and the desktop can't run a Client surface module, so the band animates from here: each
103// tick advances a fight's frame or ends a stale K.O. card, and writes nothing while idle.
104async function tickRound($: EngineInterface): Promise<void> {
105  const r = await read($, round)
106  if (r.phase === 'idle') return
107  const now = await $.clock.now()
108  if (tick(r, now)) await update($, round, x => tick(x, now) ?? x)
109}
110
111async function kikoCommand($: EngineInterface, args: string): Promise<string> {
112  const word = args.trim().toLowerCase()
113  if (word === 'on') {
114    await setEnabled($, true)
115    return 'Kiko is on. Ding ding!'
116  }
117  if (word === 'off') {
118    await setEnabled($, false)
119    return 'Kiko is off. The record still counts; /kiko on to bring Kiko back.'
120  }
121  const { rec } = await loadRecord($)
122  if (word === 'stats') return statsText(rec)
123  if (word === '') return `Kiko is ${(await read($, enabled)) ? 'on' : 'off'} · ${recordLine(rec)}. Try /kiko stats, /kiko off.`
124  return 'Usage: /kiko on, /kiko off, /kiko stats'
125}
126
127export const register: Register = on => {
128  on('session.start', async ($, e, next) => {
129    try {
130      await $.command.register(KIKO_COMMAND)
131      await openSession($)
132      $.clock.every(TICK_MS, () => void tickRound($).catch(() => undefined))
133    } catch {
134      // Kiko never stops a session from starting.
135    }
136    return next(e)
137  })
138
139  on('turn.start', async ($, e, next) => {
140    if (!isSub(e)) await startRound($, e.text, e.turnId).catch(() => undefined)
141    return next(e)
142  })
143
144  on('turn.step', async function* ($, e, next) {
145    const stream = next(e)
146    const r = isSub(e) ? undefined : await read($, round).catch(() => undefined)
147    if (!r || !isFighting(r, e.turnId)) return yield* stream
148    let mode: Mode | undefined
149    for (;;) {
150      const item = await stream.next()
151      if (item.done) return item.value
152      const chunk = item.value
153      try {
154        if (chunk.kind === 'thinking' || chunk.kind === 'text') {
155          const now = chunk.kind === 'thinking' ? 'thinking' : 'responding'
156          if (now !== mode) {
157            mode = now
158            await setMode($, e.turnId, now)
159          }
160        } else if (chunk.kind === 'stop' && chunk.usage) {
161          await addUsage($, e.turnId, chunk.usage)
162        }
163      } catch {
164        // Watching the stream never changes it.
165      }
166      yield chunk
167    }
168  })
169
170  on('tool.call', async ($, e, next) => {
171    const isOurs = isSub(e) ? false : await toolBeat($, e.tool, e).catch(() => false)
172    const result = await next(e)
173    // The tool's result goes back unchanged either way.
174    if (isOurs) await update($, round, afterTool).catch(() => undefined)
175    return result
176  })
177
178  on('turn.complete', async ($, e, next) => {
179    try {
180      return await next(e)
181    } finally {
182      // The K.O. lands whether or not the chain beneath finished cleanly; its error, if any,
183      // still reaches the engine.
184      if (!isSub(e)) await finishRound($, e).catch(() => undefined)
185    }
186  })
187
188  on('command.run', { command: 'kiko' }, async ($, e) => ({ text: await kikoCommand($, e.args ?? '') }))
189
190  on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
191    const r = await read($, round)
192    if (!(await read($, enabled)) || r.phase === 'idle' || e.props.hasSurvey) return next(e)
193    const rows = bandRows(r, await $.clock.now(), Math.max(20, e.props.bodyColumns), e.props.maxRows)
194    const els = $.ui.resolve(e)
195    // The terminal draws Text in its own fixed-width cells; elsewhere one Code block keeps
196    // the columns straight.
197    if (e.surface === 'terminal') {
198      const { Box, Text } = els
199      return (
200        <Box flexDirection="column">
201          {rows.map(row => <Text wrap="truncate">{row}</Text>)}
202        </Box>
203      )
204    }
205    const { Code } = els
206    return <Code source={rows.join('\n')} />
207  })
208
209  on('ui.render', { component: 'Spinner' }, async ($, e, next) => {
210    const r = await read($, round)
211    if (!(await read($, enabled)) || r.phase !== 'fight' || e.props.message) return next(e)
212    return next({ ...e, props: { ...e.props, word: spinnerWord(spinnerKind(e.props.mode, r), r.n) } })
213  })
214}
215
hooks/layout.ts 104 lines
1// The band's rows: header, KI and KO bars, the arena and the status line, or the K.O. card,
2// each padded or cut to the band's width.
3import type { Round } from '../types'
4import { beatStepOf } from './round'
5import { BAG, KO_LETTERS, SPRITES } from './sprites'
6import type { Frame } from './sprites'
7import { fmtTokens, mmss } from './words'
8
9export type View = { frame: number; beatStep: number | null; now: number }
10
11export function fitRow(text: string, columns: number): string {
12  return text.length >= columns ? text.slice(0, columns) : text + ' '.repeat(columns - text.length)
13}
14
15const FULL = 200_000
16
17export function bar(value: number, width: number): string {
18  const fraction = Math.min(1, Math.log10(1 + Math.max(0, value)) / Math.log10(1 + FULL))
19  const filled = Math.round(fraction * width)
20  return '█'.repeat(filled) + '░'.repeat(width - filled)
21}
22
23function header(round: Round, view: View, columns: number): string {
24  const isBell = round.beat?.kind === 'bell' && view.beatStep !== null
25  const left = isBell ? ` ROUND ${round.n} ── FIGHT! ` : ` ROUND ${round.n} ── KIKO vs. ${round.opponent} `
26  const clock = ` ${mmss((round.endedAt ?? view.now) - round.startedAt)} `
27  const fill = Math.max(1, columns - left.length - clock.length)
28  return fitRow(left + '─'.repeat(fill) + clock, columns)
29}
30
31function bars(round: Round, columns: number): string {
32  const label = (name: string, value: number, width: number) => `${name} ${bar(value, width)} ${fmtTokens(value)}`
33  const width = Math.max(4, Math.min(12, Math.floor((columns - 24) / 2)))
34  const left = ` ${label('KI', round.tokensIn, width)}`
35  const right = `${label('KO', round.tokensOut, width)} `
36  return fitRow(left + ' '.repeat(Math.max(2, columns - left.length - right.length)) + right, columns)
37}
38
39function kikoFrame(round: Round, view: View): Frame {
40  const step = view.beatStep
41  const beat = round.beat && step !== null ? round.beat.kind : null
42  if (beat === 'chomp') return SPRITES.chomp[Math.min(step! >> 1, 3)]!
43  if (beat === 'punch') return SPRITES.punch[Math.min(step! >> 1, 2)]!
44  if (beat === 'dodge') return SPRITES.dodge[step! % 2]!
45  const loop = round.mode === 'thinking' ? SPRITES.thinking : round.mode === 'responding' ? SPRITES.responding : SPRITES.guard
46  return loop[view.frame % loop.length]!
47}
48
49function bagFrame(round: Round, view: View): Frame {
50  const step = view.beatStep
51  const isHit = round.beat?.kind === 'punch' && step !== null && step >= 3
52  return isHit ? BAG.hit[Math.min(step! - 3, BAG.hit.length - 1)]! : BAG.idle[(view.frame >> 2) % BAG.idle.length]!
53}
54
55function arena(round: Round, view: View, columns: number): string[] {
56  const hasBag = columns >= 60
57  const LEFT = 14
58  const me = kikoFrame(round, view)
59  const them = bagFrame(round, view)
60  const step = view.beatStep
61  const gap = Math.max(4, columns - LEFT - me[0].length - (hasBag ? them[0].length + 2 : 0))
62  const lanes = [' '.repeat(LEFT), ' '.repeat(LEFT), ' '.repeat(LEFT)]
63  const mid = [' '.repeat(gap), ' '.repeat(gap), ' '.repeat(gap)]
64  const put = (row: string, at: number, text: string) => (row.slice(0, at) + text + row.slice(at + text.length)).slice(0, row.length)
65
66  if (round.beat?.kind === 'chomp' && step !== null && step < 4) {
67    const item = `[${round.beat.label}]›››`.slice(0, LEFT)
68    lanes[1] = put(lanes[1]!, Math.min(step * 3, LEFT - item.length), item)
69  }
70  if (round.beat?.kind === 'punch' && step !== null && step >= 1 && step < 4) {
71    const item = `{${round.beat.label}}`.slice(0, gap)
72    mid[1] = put(mid[1]!, Math.min((step - 1) * Math.floor(gap / 3), gap - item.length), item)
73    if (step === 3) mid[2] = put(mid[2]!, Math.max(0, gap - 7), '‹ jab!')
74  }
75  if (round.mode === 'responding' && step === null) {
76    const letters = 'k i k o'
77    mid[1] = put(mid[1]!, (view.frame * 2) % Math.max(1, gap - letters.length), letters)
78  }
79  return [0, 1, 2].map(i => fitRow(`${lanes[i]}${me[i]}${mid[i]}${hasBag ? `${them[i]}  ` : ''}`, columns))
80}
81
82export function layout(round: Round, view: View, columns: number, maxRows = 6): string[] {
83  const status = fitRow(` > ${round.status || (round.mode === 'thinking' ? 'thinking' : round.mode === 'responding' ? 'replying' : 'circling')}`, columns)
84  if (columns < 30) return [header(round, view, columns), status]
85  const rows = [header(round, view, columns), bars(round, columns), ...arena(round, view, columns), status]
86  return maxRows < 6 ? [rows[0]!, ...rows.slice(2)] : rows
87}
88
89export function koCard(round: Round, columns: number): string[] {
90  const took = mmss((round.endedAt ?? round.startedAt) - round.startedAt)
91  const lines = [
92    `K.O.!  Kiko beats ${round.opponent} in ${took}`,
93    `read ${round.reads} | wrote ${round.writes} | ${fmtTokens(round.tokensIn)} in / ${fmtTokens(round.tokensOut)} out`,
94    `record ${round.record}`,
95  ]
96  return lines.map((text, i) => fitRow(` ${KO_LETTERS[i]}  ${text}`, columns))
97}
98
99// What the band shows for a round that isn't idle: the K.O. card, or the fight on its frame.
100export function bandRows(round: Round, now: number, columns: number, maxRows: number): string[] {
101  if (round.phase === 'ko') return koCard(round, columns)
102  return layout(round, { frame: round.frame, beatStep: beatStepOf(round), now }, columns, maxRows)
103}
104
hooks/record.ts 27 lines
1// Kiko's career: wins, streaks and the last few opponents, saved across sessions.
2import type { KikoRecord } from '../types'
3
4export const EMPTY_RECORD: KikoRecord = { wins: 0, streak: 0, bestStreak: 0, fastestMs: null, biggestTokens: 0, recent: [] }
5
6export function updateRecord(rec: KikoRecord, fight: { ms: number; tokens: number; opponent: string }): KikoRecord {
7  const streak = rec.streak + 1
8  return {
9    wins: rec.wins + 1,
10    streak,
11    bestStreak: Math.max(rec.bestStreak, streak),
12    fastestMs: rec.fastestMs === null ? fight.ms : Math.min(rec.fastestMs, fight.ms),
13    biggestTokens: Math.max(rec.biggestTokens, fight.tokens),
14    recent: [fight.opponent, ...rec.recent].slice(0, 5),
15  }
16}
17
18export function isKikoRecord(v: unknown): v is KikoRecord {
19  const r = v as KikoRecord | undefined
20  return Boolean(r) && typeof r!.wins === 'number' && typeof r!.streak === 'number' && typeof r!.bestStreak === 'number' &&
21    typeof r!.biggestTokens === 'number' && Array.isArray(r!.recent)
22}
23
24export function recordLine(rec: KikoRecord): string {
25  return `${rec.wins}-0 | streak ${rec.streak}`
26}
27
hooks/round.ts 148 lines
1// Kiko's brain: the pure rules of a round (opponent names, knowledge in and out, the
2// band's clock and each change a turn makes to the round), with no `$`, so the tests
3// drive it directly.
4import type { BeatKind, Mode, Round } from '../types'
5import { EMPTY_RECORD, recordLine } from './record'
6
7export const IDLE: Round = {
8  phase: 'idle', n: 0, turnId: null, opponent: '', startedAt: 0, endedAt: null, mode: 'requesting', status: '',
9  tokensIn: 0, tokensOut: 0, reads: 0, writes: 0, seq: 0, beat: null, record: recordLine(EMPTY_RECORD), frame: 0, beatAt: 0,
10}
11
12const STOP = new Set(`a an and are as at be by can could do does fix for from help how i in into is it its just let lets me
13  my need now of on or our please should show so some tell than that the then this to up us want was we what when why will
14  with would you your make add build create write update change look check new get set run see find think about
15  makes give me tell explain`.split(/\s+/))
16
17const NAME_MAX = 28
18
19export function opponentName(text: string): string {
20  const words = text
21    .normalize('NFKD').replace(/[̀-ͯ]/g, '')
22    .toLowerCase()
23    .replace(/`[^`]*`/g, ' ')
24    .replace(/<\/?[a-z][\w-]*[^>]*>/g, ' ')
25    .match(/[a-z][a-z0-9'-]*/g) ?? []
26  const kept = words.filter(w => w.length > 1 && !STOP.has(w)).slice(0, 3)
27  if (kept.length === 0) return 'THE UNKNOWN BUG'
28  let name = `THE ${kept.join(' ').toUpperCase()}`
29  while (name.length > NAME_MAX && name.includes(' ', 4)) name = name.slice(0, name.lastIndexOf(' '))
30  return name.slice(0, NAME_MAX)
31}
32
33const IN_TOOLS = new Set(['Read', 'Grep', 'Glob', 'WebFetch', 'WebSearch', 'LS', 'NotebookRead'])
34const OUT_TOOLS = new Set(['Edit', 'Write', 'MultiEdit', 'NotebookEdit'])
35
36const clip = (s: string, n = 20) => (s.length > n ? s.slice(0, n) : s)
37// Labels land in fixed-width art: anything but printable ASCII becomes '?'.
38const ascii = (s: string) => s.replace(/[^\x20-\x7e]/gu, '?')
39const lastSegment = (p: string) => p.split(/[/\\]/).filter(Boolean).pop() ?? p
40
41export type ToolKind = 'in' | 'out' | 'dodge'
42
43export function classifyTool(tool: string, input: unknown): { kind: ToolKind; label: string } {
44  const args = (input ?? {}) as Record<string, unknown>
45  const str = (k: string) => (typeof args[k] === 'string' ? (args[k] as string) : '')
46  const path = str('file_path') || str('notebook_path') || str('path')
47  let host = ''
48  try { host = str('url') ? new URL(str('url')).host : '' } catch { host = '' }
49  const label = clip(ascii(path ? lastSegment(path) : str('pattern') || str('query') || host || tool))
50  if (IN_TOOLS.has(tool)) return { kind: 'in', label }
51  if (OUT_TOOLS.has(tool)) return { kind: 'out', label }
52  if (tool.startsWith('mcp__')) {
53    const short = clip(ascii(tool.slice(tool.lastIndexOf('__') + 2)))
54    if (/(read|search|get|list|fetch|query|find)/i.test(short)) return { kind: 'in', label: short }
55    if (/(write|create|update|edit|delete|send|post|set|add)/i.test(short)) return { kind: 'out', label: short }
56    return { kind: 'dodge', label: short }
57  }
58  return { kind: 'dodge', label: clip(ascii(tool)) }
59}
60
61const BEAT: Record<ToolKind, BeatKind> = { in: 'chomp', out: 'punch', dodge: 'dodge' }
62
63export function beatFor(round: Round, kind: ToolKind, label: string, tool: string): Round {
64  const seq = round.seq + 1
65  const status = kind === 'in' ? `reading ${label}` : kind === 'out' ? `editing ${label}` : `running ${tool}`
66  return {
67    ...round,
68    seq,
69    mode: 'tool',
70    status,
71    reads: round.reads + (kind === 'in' ? 1 : 0),
72    writes: round.writes + (kind === 'out' ? 1 : 0),
73    beat: { id: seq, kind: BEAT[kind], label },
74    beatAt: round.frame,
75  }
76}
77
78export const TICK_MS = 200
79export const BEAT_FRAMES = 6
80export const KO_CARD_MS = 5_000
81
82// Which frame of its move the current beat is on, or null once it has played out.
83export function beatStepOf(round: Round): number | null {
84  if (!round.beat) return null
85  const step = round.frame - round.beatAt
86  return step >= 0 && step < BEAT_FRAMES ? step : null
87}
88
89// One tick of the band's clock: the next frame of a fight, the end of a stale K.O. card,
90// or null when nothing changes (idle, or a card still showing).
91export function tick(round: Round, now: number): Round | null {
92  if (round.phase === 'fight') return { ...round, frame: round.frame + 1 }
93  if (round.phase === 'ko' && round.endedAt !== null && now - round.endedAt >= KO_CARD_MS) return { ...round, phase: 'idle' }
94  return null
95}
96
97export type Usage = { input_tokens: number; output_tokens: number; cache_read_input_tokens: number; cache_creation_input_tokens: number }
98
99const count = (x: unknown) => (typeof x === 'number' && Number.isFinite(x) ? x : 0)
100
101export function applyUsage(round: Round, usage: Usage): Round {
102  return {
103    ...round,
104    // Cache reads are the conversation re-read, not new knowledge.
105    tokensIn: round.tokensIn + count(usage.input_tokens) + count(usage.cache_creation_input_tokens),
106    tokensOut: round.tokensOut + count(usage.output_tokens),
107  }
108}
109
110// A round in progress, and when a turn is named, that turn's.
111export function isFighting(round: Round, turnId?: string): boolean {
112  return round.phase === 'fight' && (turnId === undefined || round.turnId === turnId)
113}
114
115// A new session keeps the round count and beat ids and shows the saved record.
116export function freshSession(round: Round, record: string): Round {
117  return { ...IDLE, n: round.n, seq: round.seq, record }
118}
119
120export function startFight(prev: Round, fight: { turnId: string; opponent: string; now: number; record: string }): Round {
121  const seq = prev.seq + 1
122  return {
123    ...IDLE, n: prev.n + 1, seq, turnId: fight.turnId, phase: 'fight', opponent: fight.opponent, startedAt: fight.now,
124    status: 'touching gloves', beat: { id: seq, kind: 'bell', label: '' }, record: fight.record,
125  }
126}
127
128export function withMode(round: Round, turnId: string, mode: Mode): Round {
129  return isFighting(round, turnId) && round.mode !== mode ? { ...round, mode, status: '' } : round
130}
131
132export function withUsage(round: Round, turnId: string, usage: Usage): Round {
133  return isFighting(round, turnId) ? applyUsage(round, usage) : round
134}
135
136// Back to waiting on the model once a tool has answered.
137export function afterTool(round: Round): Round {
138  return isFighting(round) ? { ...round, mode: 'requesting', status: '' } : round
139}
140
141export function knockOut(round: Round, now: number, record: string): Round {
142  return { ...round, phase: 'ko', endedAt: now, record, status: 'K.O.!' }
143}
144
145export function stopFight(round: Round): Round {
146  return { ...round, phase: 'idle' }
147}
148
hooks/words.ts 56 lines
1// What Kiko says: times and token counts, the K.O. line, /kiko stats and the spinner words.
2import type { KikoRecord, Round } from '../types'
3
4export function mmss(ms: number): string {
5  const s = Math.max(0, Math.floor(ms / 1000))
6  return `${Math.floor(s / 60)}:${String(s % 60).padStart(2, '0')}`
7}
8
9export function fmtTokens(n: number): string {
10  if (n < 1000) return String(n)
11  if (n < 1_000_000) return `${(n / 1000).toFixed(1)}k`
12  return `${(n / 1_000_000).toFixed(1)}M`
13}
14
15export function koLine(round: Round, rec: KikoRecord): string {
16  const took = mmss((round.endedAt ?? round.startedAt) - round.startedAt)
17  return `K.O. ▸ Kiko beats ${round.opponent} in ${took} · read ${round.reads} · wrote ${round.writes} · ` +
18    `${fmtTokens(round.tokensIn)} in / ${fmtTokens(round.tokensOut)} out · ${rec.wins}-0`
19}
20
21export function statsText(rec: KikoRecord): string {
22  return [
23    `**Kiko's record: ${rec.wins}-0**`,
24    '',
25    `- Streak: ${rec.streak} (best ${rec.bestStreak})`,
26    `- Fastest K.O.: ${rec.fastestMs === null ? 'none yet' : mmss(rec.fastestMs)}`,
27    `- Biggest K.O.: ${fmtTokens(rec.biggestTokens)} tokens`,
28    `- Last opponents: ${rec.recent.length ? rec.recent.join(', ') : 'none yet'}`,
29  ].join('\n')
30}
31
32export type SpinnerKind = 'thinking' | 'in' | 'out' | 'responding' | 'tool' | 'requesting'
33
34export function spinnerKind(engineMode: string, round: Round): SpinnerKind {
35  if (engineMode === 'thinking') return 'thinking'
36  if (engineMode === 'responding') return 'responding'
37  if (engineMode === 'tool-use' || engineMode === 'tool-input') {
38    return round.beat?.kind === 'chomp' ? 'in' : round.beat?.kind === 'punch' ? 'out' : 'tool'
39  }
40  return 'requesting'
41}
42
43const WORDS: Record<SpinnerKind, readonly string[]> = {
44  thinking: ['Kikonsidering', 'Sizing up the opponent', 'Plotting the combo', 'Reading the ring'],
45  in: ['Chomping knowledge', 'Knowledge in', 'Studying the tape', 'Nom-nom-noting'],
46  out: ['Winding up the KO', 'Knowledge out', 'Landing the uppercut', 'Jab, jab, cross'],
47  responding: ['Trash-talking', 'Ringside commentary', 'Calling the shot', 'Talking the talk'],
48  tool: ['Bobbing and weaving', 'Footwork', 'Working the corner', 'Kiko-ing'],
49  requesting: ['Kiko-ing', 'Touching gloves', 'Circling', 'Bouncing on toes'],
50}
51
52export function spinnerWord(kind: SpinnerKind, n: number): string {
53  const words = WORDS[kind]
54  return words[Math.abs(n) % words.length]!
55}
56
hooks/sprites.ts 54 lines
1// Kiko's art: a boxer with block gloves up, a punching bag, and the K.O. letters. Every
2// frame of a figure is the same size and uses only art characters (see isArtChar).
3
4export type Frame = readonly [string, string, string]
5
6const KIKO_W = 11
7const BAG_W = 6
8const pad = (s: string, w: number) => (s.length >= w ? s.slice(0, w) : s + ' '.repeat(w - s.length))
9// `x` shifts the figure right, for bobbing and sidesteps.
10const kiko = (top: string, face: string, legs: string, x = 0): Frame => {
11  const at = ' '.repeat(x)
12  return [pad(at + top, KIKO_W), pad(at + face, KIKO_W), pad(at + legs, KIKO_W)]
13}
14const bag = (fill: string, x: number): Frame => {
15  const at = ' '.repeat(x)
16  return [pad(`${at}┌┴┐`, BAG_W), pad(`${at}│${fill}│`, BAG_W), pad(`${at}└─┘`, BAG_W)]
17}
18
19const HEAD = '  .---.'
20const STANCE = '   / \\'
21const LUNGE = '   /  \\'
22// Gloves up either side of the face; a face is five characters, `(o.o)`.
23const guard = (face: string) => `▄█${face}█▄`
24const reach = (face: string) => `▄█${face}==█▄`
25
26export const SPRITES = {
27  guard: [kiko(HEAD, guard('(o.o)'), STANCE), kiko(HEAD, guard('(o.o)'), STANCE, 1)],
28  thinking: [
29    kiko(`${HEAD} ?`, guard('(o.o)'), STANCE), kiko(`${HEAD}  ?`, guard('(@.@)'), STANCE),
30    kiko(`${HEAD} ? ?`, guard('(-.-)'), STANCE), kiko(`${HEAD}  ?`, guard('(@.@)'), STANCE),
31  ],
32  responding: [kiko(HEAD, guard('(o.o)'), STANCE), kiko(HEAD, guard('(oOo)'), STANCE), kiko(HEAD, guard('(o-o)'), STANCE)],
33  // Gloves open for the incoming file, then clamp on it.
34  chomp: [
35    kiko(HEAD, '▀█(O.O)█▀', STANCE), kiko(HEAD, '▀█(O.O)█▀', STANCE),
36    kiko(HEAD, guard('(>.<)'), STANCE), kiko(HEAD, guard('(^.^)'), STANCE),
37  ],
38  punch: [kiko(HEAD, guard('(>.<)'), STANCE), kiko(HEAD, reach('(>.<)'), LUNGE), kiko(HEAD, reach('(^.^)'), LUNGE)],
39  dodge: [kiko(HEAD, guard('(>.>)'), STANCE), kiko(HEAD, guard('(<.<)'), STANCE, 2)],
40} as const
41
42// The bag hangs still; a hit flashes it and swings it right, then it swings back.
43export const BAG = {
44  idle: [bag('█', 1)],
45  hit: [bag('░', 2), bag('█', 3), bag('█', 2)],
46} as const
47
48export const KO_LETTERS: readonly string[] = ['╦╔═ ╔═╗  ', '╠╩╗ ║ ║  ', '╩ ╩o╚═╝o ']
49
50export function isArtChar(ch: string): boolean {
51  const c = ch.codePointAt(0) ?? 0
52  return ch.length === 1 && ((c >= 0x20 && c <= 0x7e) || (c >= 0x2500 && c <= 0x259f) || c === 0x2039 || c === 0x203a)
53}
54
types/index.d.ts 42 lines
1export type Phase = 'idle' | 'fight' | 'ko'
2export type Mode = 'requesting' | 'thinking' | 'responding' | 'tool'
3export type BeatKind = 'bell' | 'chomp' | 'punch' | 'dodge'
4export type Beat = { id: number; kind: BeatKind; label: string }
5
6export type Round = {
7  phase: Phase
8  n: number
9  turnId: string | null
10  opponent: string
11  startedAt: number
12  endedAt: number | null
13  mode: Mode
14  status: string
15  tokensIn: number
16  tokensOut: number
17  reads: number
18  writes: number
19  seq: number
20  beat: Beat | null
21  record: string
22  /** The band's animation frame, advanced every tick while fighting. */
23  frame: number
24  /** The frame the current beat started on. */
25  beatAt: number
26}
27
28export type KikoRecord = {
29  wins: number
30  streak: number
31  bestStreak: number
32  fastestMs: number | null
33  biggestTokens: number
34  recent: string[]
35}
36
37declare module 'claude-code' {
38  interface PluginState {
39    kiko: { round: Round; enabled: boolean }
40  }
41}
42