SLOPSHOPPER

buddy

The Claude Code Buddy cat, back above the prompt as a mod. Needs CLAUDE_CODE_ENABLE_FUNCTION_HOOKS=1.

panebandcommandtimer
v0.2.0MITupdated 2026-10-17catsby/claude-code-buddy
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · buddy
│ ┃ buddy ✕ › 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 │ ┃ Gristle ⏺ 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 │ │ › /buddy │ ⎿ buddy: Gristle is already here. │ │ [___] /\_/\ ( ✦ ✦) ( ω ) (")_(") Gristle ⟨Claude Code's own drawing⟩ ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Band
[___] /\_/\ ( ✦ ✦) ( ω ) (")_(") Gristle ⟨Claude Code's own drawing⟩
Pane · buddy
[___] /\_/\ ( ✦ ✦) ( ω ) (")_(") Gristle
README

buddy

Gristle, the Claude Code Buddy cat, back above the prompt as a mod.

 [___]
 /\_/\
( ✦   ✦)
(  ω  )
(")_(")
 Gristle

Anthropic shipped /buddy in April 2026 and removed it a few weeks later. Several projects brought it back through MCP servers, status lines, shell hooks or by patching the binary. This one uses mods, the function-hook plugin API, so the cat is drawn by Claude Code's own renderer in the band above the prompt.

What is here: the sprite and its idle poses, all eighteen species, /buddy pet, /buddy roll and /buddy name. No speech, no reactions to the conversation, no stat card yet.

docs/scope.md inventories what the original /buddy did and decides each part: what is restored, what is planned, and what is deliberately left out. The short version is that this restores the pet, not the observer — nothing here reads your conversation or spends tokens.

Running it

Needs Claude Code 2.1.287 or later:

claude --plugin-dir /path/to/this/repo

/buddy off hides the buddy, /buddy on (or bare /buddy) brings it back, and the choice persists across sessions. /buddy pet floats three hearts on the row above the hat for about two seconds and answers petted Gristle, as the original did. Sprite color, heart color and both cadence values are /config rows under this plugin.

/buddy roll gives the buddy new looks by the original's odds (rarity, species, eyes, and a hat above common), keeping its name. /buddy roll back undoes the last roll, once. /buddy name <name> renames the buddy (1 to 12 characters; a longer or blank name is refused, not cut).

Built against Claude Code 2.1.285; checked on 2.1.287. The mod API is early access and changes between releases.

Where it draws

The original drew the buddy in the right-hand gutter, level with the input. This build has fourteen hookable render sites and none of them is that gutter, so it sits right-aligned in the band directly above the prompt instead: one row off, same silhouette. docs/placement.md has the reasoning, how the band is shared with other mods, and how to verify a drawing landed.

Ctrl+X Ctrl+A collapses the band and hides the buddy. That is Claude Code's control, not this plugin's.

The animation

The cat cycles rest, tail flick, rest, ear twitch. Only one row changes per pose, so the timer fires on the change rather than at a frame rate and the engine repaints the single cell.

The hat, face and ear twitch were read frame by frame off a screen recording of the original. The tail flick never fires in those 6.7 seconds, but a screenshot of the same buddy taken days later shows it plainly. Both are kept out of the repo. The cadence is still ours, though the original's has since been measured off a longer recording: a blink and both flicks on a 7.5-second cycle.

Development

node --experimental-strip-types --test 'hooks/*.spec.ts'
claude plugin test .

Sprite geometry and cadence live in hooks/sprite.ts as pure functions so they can be tested without an engine. claude plugin test runs tests/ against the engine's own $: the commands, the store, the pose and heart timers, and the tree the band draws. What actually reached the terminal is checked by running the real thing — scripts/drive.exp spawns a session under a PTY and captures it.

To typecheck, use the declarations the engine writes to .claude-plugin/types/ when it loads the plugin. They are pinned to a version and gitignored:

npx -p typescript tsc --noEmit
claude plugin validate ./.claude-plugin/plugin.json
claude plugin validate . --strict

The first validate covers the plugin and reports what the engine sees the hooks module hooking and calling; the second covers the marketplace manifest. The first is not run with --strict because the validator warns about CLAUDE.md at the plugin root, which is this repo's own instructions rather than context shipped to whoever installs the plugin.

Credits

The sprite table in cpaczek/any-buddy (WTFPL) carried the tail-flick pose before a screenshot of the original turned up, and is where the other seventeen species come from: the whole table is vendored into hooks/species.ts from commit b5e7eb0. Its cat matches the one we measured off the recording glyph for glyph, in all three frames — the tests check it, so the two readings stay honest about each other. Its roll (src/generation/roll.ts) is where hooks/roll.ts takes the rarity weights and the hat rule from.

rjwittams/katzensteg is the reference for hooking AbovePrompt without stomping on whatever else draws there.

/buddy itself was Anthropic's, and this is an affectionate reconstruction of it, not a copy of its code.

License

MIT. See LICENSE.

Source 6 files
hooks/register.tsx 339 lines
1import type { EngineInterface, Register, Timer } from 'claude-code'
2import {
3  FRAME_OF_POSE,
4  clampCadence,
5  holdMs,
6  nameLine,
7  poseAt,
8  type Cadence,
9} from './sprite.ts'
10import { HEART_STEPS, heartHoldMs, heartRow } from './hearts.ts'
11import { SPECIES_WIDTH, spriteLines } from './species.ts'
12import {
13  GRISTLE,
14  IDENTITY_KEY,
15  NAME_MAX,
16  PREVIOUS_KEY,
17  bonesOf,
18  cleanName,
19  identityFrom,
20  type Identity,
21} from './identity.ts'
22import { describe, roll } from './roll.ts'
23
24/**
25 * The pane's id, and the store key for where the buddy lives. 'band' is the
26 * strip above the prompt; 'pane' is the docked sidebar, which costs width
27 * instead of rows. Only a docked pane yields the band: an inline one (a narrow
28 * terminal) is a framed region above the prompt, no better than the band.
29 */
30const PANE = 'buddy'
31const LAYOUT_KEY = 'layout'
32type Layout = 'band' | 'pane'
33
34let step = 0
35let hidden = false
36let identity: Identity = GRISTLE
37let layout: Layout = 'band'
38/** True while the pane is open and docked beside the transcript. */
39let docked = false
40/** Set once an inline pane has been sent away, so one arrival closes it once. */
41let inlineClosed = false
42let armed = false
43/** The one store read, shared by every caller that arrives while it is in flight. */
44let loading: Promise<void> | null = null
45let cadence: Cadence = clampCadence(undefined, undefined)
46
47/** Which heart state a pet is showing, or null when nobody is being petted. */
48let petStep: number | null = null
49let petTimer: Timer | null = null
50
51/**
52 * Only two cells change between poses, so the timer fires on the change rather
53 * than at a frame rate: four redraws a cycle, and the engine repaints the cells.
54 */
55function armPoses($: EngineInterface) {
56  $.clock.after(holdMs(poseAt(step), cadence), () => {
57    step += 1
58    if (!hidden) $.ui.invalidate('ui.render')
59    armPoses($)
60  })
61}
62
63function endPet() {
64  petTimer?.cancel()
65  petTimer = null
66  petStep = null
67}
68
69/**
70 * The heart states are held for different lengths, so the timer chains on each
71 * one's hold rather than running at a rate, as the poses do. The last hop sets
72 * `petStep` to null and still redraws, which is what clears the row.
73 */
74function advancePet($: EngineInterface) {
75  if (petStep === null) return
76  petTimer = $.clock.after(heartHoldMs(petStep), () => {
77    petTimer = null
78    petStep = petStep === null || petStep + 1 >= HEART_STEPS ? null : petStep + 1
79    $.ui.invalidate('ui.render')
80    advancePet($)
81  })
82}
83
84function startPet($: EngineInterface) {
85  petTimer?.cancel()
86  petStep = 0
87  $.ui.invalidate('ui.render')
88  advancePet($)
89}
90
91/**
92 * A hot reload drops the pending timer with the old environment and resets
93 * every module variable. 2.1.287 raises `session.start` again afterwards, which
94 * is what normally restarts the poses and reloads stored state; reaching this
95 * from the render hook and the command as well is a safety net that picks both
96 * up on the next draw or the next /buddy.
97 */
98async function ensureRunning($: EngineInterface) {
99  loading ??= Promise.all([
100    $.store.get('hidden').catch(() => undefined),
101    $.store.get(IDENTITY_KEY).catch(() => undefined),
102    $.store.get(LAYOUT_KEY).catch(() => undefined),
103  ]).then(async ([storedHidden, storedIdentity, storedLayout]) => {
104    hidden = storedHidden === true
105    identity = identityFrom(storedIdentity)
106    layout = storedLayout === 'pane' ? 'pane' : 'band'
107    // A reload leaves the pane open and the module blank: ask the engine.
108    if (layout === 'pane') {
109      const panes = await $.ui.panes().catch(() => [])
110      docked = panes.some((pane) => pane.id === PANE && pane.isPlaced)
111    }
112  })
113  await loading
114  if (!armed) {
115    armed = true
116    armPoses($)
117  }
118}
119
120/**
121 * Opens the pane when the buddy lives there and is here. A command opening it
122 * is placed from 110 columns; the plugin opening it unasked needs 144, and
123 * until then it waits undrawn and the band keeps the buddy.
124 */
125async function openPane($: EngineInterface) {
126  if (layout !== 'pane' || hidden) return
127  inlineClosed = false
128  const opened = await $.ui
129    .open({ id: PANE, title: identity.name, columns: SPECIES_WIDTH + 2 })
130    .catch(() => ({ isPlaced: false as const }))
131  docked = opened.isPlaced
132  $.ui.invalidate('ui.render')
133}
134
135async function closePane($: EngineInterface) {
136  docked = false
137  await $.ui.close({ id: PANE }).catch(() => {})
138  $.ui.invalidate('ui.render')
139}
140
141type Elements = Awaited<ReturnType<EngineInterface['ui']['resolve']>>
142
143/** The rows of the buddy, hearts first: one drawing for the band and the pane. */
144function buddyRows(
145  { Text }: Elements,
146  hearts: string | null,
147  options: Parameters<Register>[1],
148) {
149  const color =
150    identity.color ?? (typeof options?.color === 'string' ? options.color : '#7acf7a')
151  const heartColor = typeof options?.heartColor === 'string' ? options.heartColor : '#a7a6fd'
152  const showName = options?.showName !== false
153  return [
154    hearts ? (
155      <Text key="sprite:hearts" color={heartColor} wrap="truncate-end">
156        {hearts}
157      </Text>
158    ) : null,
159    // Every row, the hearts' included, is SPECIES_WIDTH wide, so the sprite
160    // keeps its column whether or not the heart row is drawn.
161    ...spriteLines(bonesOf(identity), FRAME_OF_POSE[poseAt(step)]).map((line, i) => (
162      <Text key={`sprite:${i}`} color={color} wrap="truncate-end">
163        {line}
164      </Text>
165    )),
166    showName ? (
167      <Text key="sprite:name" dimColor italic wrap="truncate-end">
168        {nameLine(identity.name)}
169      </Text>
170    ) : null,
171  ]
172}
173
174export const register: Register = (on, options) => {
175  cadence = clampCadence(options?.restMs, options?.flickMs)
176
177  on('session.start', async ($, e, next) => {
178    const r = await next(e)
179    await $.command
180      .register({
181        name: 'buddy',
182        description: 'Show, hide, pet, or reroll the buddy above the prompt',
183        argumentHint: 'on | off | pet | pane | band | roll | roll back',
184        immediate: true,
185      })
186      .catch(() => {})
187    // Off the session.start path: the store read would hold the first prompt.
188    $.clock.after(0, () => {
189      ensureRunning($).then(() => openPane($)).catch(() => {})
190    })
191    return r
192  })
193
194  on('command.run', { command: 'buddy' }, async ($, e) => {
195    await ensureRunning($)
196    const name = identity.name
197    const verb = e.args.trim().toLowerCase().split(/\s+/).join(' ')
198    if (verb === 'pet') {
199      // Nothing to pet, and no timer to leave running, while the buddy is away.
200      if (hidden) return { text: `${name} is not here. /buddy on brings ${name} back.` }
201      startPet($)
202      // The line the original printed, verbatim.
203      return { text: `petted ${name}` }
204    }
205    if (verb === 'off') {
206      hidden = true
207      endPet()
208      await $.store.set('hidden', true)
209      await closePane($)
210      $.ui.invalidate('ui.render')
211      return { text: `${name} wanders off. /buddy on brings ${name} back.` }
212    }
213    if (verb === 'on' || verb === '') {
214      const wasHidden = hidden
215      hidden = false
216      await $.store.set('hidden', false)
217      await openPane($)
218      $.ui.invalidate('ui.render')
219      return { text: wasHidden ? `${name} pads back in.` : `${name} is already here.` }
220    }
221    if (verb === 'pane') {
222      layout = 'pane'
223      hidden = false
224      await $.store.set(LAYOUT_KEY, 'pane')
225      await $.store.set('hidden', false)
226      await openPane($)
227      return {
228        text: docked
229          ? `${name} moves to the side.`
230          : `${name} stays in the band: the terminal is too narrow for a side pane (110 columns).`,
231      }
232    }
233    if (verb === 'band') {
234      layout = 'band'
235      await $.store.set(LAYOUT_KEY, 'band')
236      await closePane($)
237      return { text: `${name} is back above the prompt.` }
238    }
239    const rename = /^name(?:\s+(.*))?$/is.exec(e.args.trim())
240    if (rename) {
241      const next = cleanName(rename[1])
242      if (next === undefined) {
243        return { text: `A name is 1 to ${NAME_MAX} characters (got "${(rename[1] ?? '').trim()}"). ${name} keeps the name.` }
244      }
245      identity = identityFrom({ ...identity, name: next })
246      await $.store.set(IDENTITY_KEY, identity)
247      $.ui.invalidate('ui.render')
248      return { text: `${name} is now called ${next}.` }
249    }
250    if (verb === 'roll') {
251      const before = identity
252      const rolled = roll(Math.random)
253      // Only the looks are rolled: the name and any color the person set stay.
254      identity = identityFrom({ ...before, ...rolled })
255      await $.store.set(PREVIOUS_KEY, before)
256      await $.store.set(IDENTITY_KEY, identity)
257      $.ui.invalidate('ui.render')
258      return { text: `${name} is now ${describe(rolled)}. /buddy roll back undoes it.` }
259    }
260    if (verb === 'roll back') {
261      const previous = await $.store.get(PREVIOUS_KEY).catch(() => undefined)
262      if (previous === undefined) return { text: 'Nothing to roll back to.' }
263      identity = identityFrom(previous)
264      await $.store.set(IDENTITY_KEY, identity)
265      // One undo, not a history: a second roll back finds nothing.
266      await $.store.delete(PREVIOUS_KEY)
267      $.ui.invalidate('ui.render')
268      return { text: `${identity.name} is back as before.` }
269    }
270    return { text: `/buddy takes on, off, pet, pane, band, name <name>, roll or roll back (got "${e.args.trim()}").` }
271  })
272
273  on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
274    // The band is terminal-only, and a survey holding it outranks a cat.
275    await ensureRunning($)
276    if (hidden || docked || e.surface !== 'terminal' || e.props.hasSurvey) return next(e)
277    // Six rows of sprite plus whatever else draws; below that, yield the band.
278    if (e.props.maxRows < 6 || e.props.bodyColumns < SPECIES_WIDTH) {
279      return next(e)
280    }
281
282    const elements = await $.ui.resolve(e)
283    const { Box } = elements
284    // A seventh row has to fit before the hearts can have one of their own.
285    const hearts = petStep === null || e.props.maxRows < 7 ? null : heartRow(petStep)
286
287    return (
288      <Box flexDirection="column">
289        <Box flexDirection="row" justifyContent="flex-end">
290          {/* The inner column is what gets pushed right, so the rows keep
291              their relative offsets instead of each shearing to the edge. */}
292          <Box flexDirection="column">
293            {buddyRows(elements, hearts, options)}
294          </Box>
295        </Box>
296        {await next(e)}
297      </Box>
298    )
299  })
300
301  // The side pane: drawn only while the buddy lives there. An inline pane (the
302  // terminal is too narrow to dock) is a frame above the prompt, which is the
303  // band's cost with a border, so it is closed and the band keeps the buddy.
304  on('ui.render', { component: 'Pane' }, async ($, e, next) => {
305    if (e.requestId !== PANE) return next(e)
306    await ensureRunning($)
307    if (e.props.placement === 'inline') {
308      docked = false
309      if (!inlineClosed) {
310        inlineClosed = true
311        $.clock.after(0, () => { closePane($).catch(() => {}) })
312      }
313      return next(e)
314    }
315    docked = true
316    const elements = await $.ui.resolve(e)
317    const { Box } = elements
318    const hearts = petStep === null ? null : heartRow(petStep)
319    return (
320      <Box flexDirection="row" justifyContent="center">
321        <Box flexDirection="column">{buddyRows(elements, hearts, options)}</Box>
322      </Box>
323    )
324  })
325
326  // The person's own close mark is the same as /buddy off, or the stored
327  // hidden flag and the pane would disagree after a restart.
328  on('ui.close', async ($, e, next) => {
329    if (e.id === PANE && e.origin.kind === 'person') {
330      hidden = true
331      docked = false
332      endPet()
333      await $.store.set('hidden', true)
334      $.ui.invalidate('ui.render')
335    }
336    return next(e)
337  })
338}
339
hooks/sprite.ts 91 lines
1// The sprite as the April 2026 build drew it.
2//
3// The hat, the face and the ear twitch were read back frame by frame off a
4// 6.7-second screen recording of the original. The third pose, the tail flick,
5// never fires in that footage, and for a while it rested on the sprite table in
6// cpaczek/any-buddy (WTFPL), whose other two cat frames match the recording
7// glyph for glyph. It no longer has to: a screenshot of the same buddy, taken
8// days later, shows `(")_(")~` outright. Both are kept out of the repo.
9//
10// The cadence is ours. The original's was measured later (CLAUDE.md, "Sprite
11// provenance") and differs: a blink as well as both flicks, on 500ms steps.
12//
13// The band no longer draws `bodyLines`: it draws the vendored table in
14// species.ts, which is 12 columns wide and holds every species. These eight
15// columns stay as the measured reading, and species.spec.ts asserts the table's
16// cat is this drawing.
17
18import { CAT_INSET, SPECIES_WIDTH } from './species.ts'
19
20/** The measured drawing's width: the cat's ink, tail flick included. */
21export const SPRITE_WIDTH = 8
22
23export type Pose = 'rest' | 'tail' | 'ears'
24
25/** The table frame each pose draws. The table's frames are in this order. */
26export const FRAME_OF_POSE: Readonly<Record<Pose, number>> = { rest: 0, tail: 1, ears: 2 }
27
28/** any-buddy calls this one the top hat; their crown is `\^^^/`. */
29const TOP_HAT = ' [___]'
30const EARS: Record<Pose, string> = {
31  rest: ' /\\_/\\',
32  tail: ' /\\_/\\',
33  ears: ' /\\-/\\',
34}
35const EYES = '( ✦   ✦)'
36const MOUTH = '(  ω  )'
37const FEET: Record<Pose, string> = {
38  rest: '(")_(")',
39  tail: '(")_(")~',
40  ears: '(")_(")',
41}
42
43/**
44 * Rest between flicks, and alternate which end moves: a cat that twitched the
45 * same ear on a fixed beat would read as a spinner.
46 */
47export const CYCLE: readonly Pose[] = ['rest', 'tail', 'rest', 'ears']
48
49export function poseAt(step: number): Pose {
50  return CYCLE[((step % CYCLE.length) + CYCLE.length) % CYCLE.length]!
51}
52
53const pad = (line: string) => line.padEnd(SPRITE_WIDTH, ' ')
54
55/** The five sprite rows for a pose, each padded to SPRITE_WIDTH. */
56export function bodyLines(pose: Pose): string[] {
57  return [TOP_HAT, EARS[pose], EYES, MOUTH, FEET[pose]].map(pad)
58}
59
60/**
61 * The dim name row under the sprite, `SPECIES_WIDTH` wide. The recording puts
62 * the name at the cat's own column 0, so it is inset to match; a name too long
63 * for that gives up the inset before it gives up letters. Past the full width
64 * it is cut, but identity.ts never hands this one: a name over NAME_MAX is
65 * rejected before it is drawn.
66 */
67export function nameLine(name: string): string {
68  const inset = Math.max(0, Math.min(CAT_INSET, SPECIES_WIDTH - name.length))
69  return (' '.repeat(inset) + name).slice(0, SPECIES_WIDTH).padEnd(SPECIES_WIDTH, ' ')
70}
71
72export type Cadence = { restMs: number; flickMs: number }
73
74/** How long the current pose is held before the next one. */
75export function holdMs(pose: Pose, cadence: Cadence): number {
76  return pose === 'rest' ? cadence.restMs : cadence.flickMs
77}
78
79/**
80 * A cadence the engine will accept: a timer under a tick is refused, and a
81 * rest under a second reads as a stutter rather than a cat.
82 */
83export function clampCadence(restMs: unknown, flickMs: unknown): Cadence {
84  const num = (v: unknown, fallback: number) =>
85    typeof v === 'number' && Number.isFinite(v) ? v : fallback
86  return {
87    restMs: Math.max(1000, num(restMs, 2600)),
88    flickMs: Math.max(80, num(flickMs, 400)),
89  }
90}
91
hooks/hearts.ts 65 lines
1// The hearts `/buddy pet` floated, as the April 2026 build drew them.
2//
3// Measured off gristle_snark.mov, a screen recording of the original (kept out
4// of the repo). The file is variable-frame-rate: it holds 41 frames for 6.7
5// seconds, and a frame exists only where the screen actually repainted, so the
6// frame timestamps are repaint times rather than samples. That is where the
7// holds below come from — they are measured, not guessed.
8//
9// Columns are sprite-relative, read against the hat's `[` and `]`, which are
10// four cells apart and so fix the cell width at 11px. Three hearts in every
11// state. They start inside the sprite and drift outward, reaching a column
12// past it on each side before fading.
13//
14// One frame is deliberately not a state here. At t=2.205 the row appears with
15// hearts at columns 1 and 6 and a third that never resolved, and it is replaced
16// 52ms later — a tenth of every other hold, with a glyph missing. That reads as
17// a torn first paint rather than a pose, so the animation starts at t=2.257.
18//
19// The blogs say the original ran 2.5s. These holds total 2.06s, and the clear
20// lands somewhere in (3.800, 4.315], so the true figure is 2.06s or a little
21// more. Close enough to the blogs that the earlier 1.8s reading was simply the
22// cost of sampling at 5fps.
23
24import { CAT_INSET, SPECIES_WIDTH } from './species.ts'
25
26const HEART = '♡'
27const FADED = '·'
28
29type HeartState = {
30  /** Columns relative to the cat's left edge; outside 0..7 reaches past it. */
31  cols: readonly number[]
32  glyph: string
33  holdMs: number
34}
35
36/** t = 2.257, 2.777, 3.280 and 3.800 in the recording. */
37const STATES: readonly HeartState[] = [
38  { cols: [0, 3, 7], glyph: HEART, holdMs: 520 },
39  { cols: [-1, 3, 6], glyph: HEART, holdMs: 503 },
40  { cols: [-2, 1, 8], glyph: HEART, holdMs: 520 },
41  { cols: [-2, 3, 7], glyph: FADED, holdMs: 515 },
42]
43
44export const HEART_STEPS = STATES.length
45
46/** How long state `step` is held before the next one. */
47export function heartHoldMs(step: number): number {
48  return STATES[step]?.holdMs ?? 0
49}
50
51/**
52 * The heart row for a state, `SPECIES_WIDTH` wide, or null once the
53 * pet has run out of states and the row should go away.
54 */
55export function heartRow(step: number): string | null {
56  const state = STATES[step]
57  if (!state) return null
58  const cells = Array<string>(SPECIES_WIDTH).fill(' ')
59  for (const col of state.cols) {
60    // Measured against the cat, which the table draws CAT_INSET columns in.
61    cells[col + CAT_INSET] = state.glyph
62  }
63  return cells.join('')
64}
65
hooks/species.ts 230 lines
1// The eighteen species the original `/buddy` could roll, and the hats and eyes
2// that dress them.
3//
4// Vendored from cpaczek/any-buddy (WTFPL), `src/sprites/data.ts` and
5// `src/constants.ts` at commit b5e7eb083bb5b36b808cda87eac3f3a88f5f1a61
6// (2026-04-14). Transcribed there from the shipped build; the table is
7// reproduced here byte for byte rather than retyped.
8//
9// It is not a second opinion about the cat. Our cat was measured off a
10// recording of the original, and `species.spec.ts` asserts the two agree:
11// every `sprite.ts` pose equals this table's cat wearing the tophat, with the
12// eye filled in, trimmed to the eight columns `bodyLines` measured. That is also
13// where `sprite.ts`'s TOP_HAT comes from — the table leaves row 0 blank and
14// lets the hat land there, so our baked-in ` [___]` is `HAT_LINES.tophat`.
15//
16// This module is data and geometry only. Nothing here decides which species a
17// session gets (identity.ts holds that), and nothing here draws; register.tsx
18// draws these rows as they are.
19
20export type Species =
21  | 'duck'
22  | 'goose'
23  | 'blob'
24  | 'cat'
25  | 'dragon'
26  | 'octopus'
27  | 'owl'
28  | 'penguin'
29  | 'turtle'
30  | 'snail'
31  | 'ghost'
32  | 'axolotl'
33  | 'capybara'
34  | 'cactus'
35  | 'robot'
36  | 'rabbit'
37  | 'mushroom'
38  | 'chonk'
39
40export type Hat =
41  | 'none'
42  | 'crown'
43  | 'tophat'
44  | 'propeller'
45  | 'halo'
46  | 'wizard'
47  | 'beanie'
48  | 'tinyduck'
49
50/** The six eyes a buddy can be rolled with. */
51export type Eye = '·' | '✦' | '×' | '◉' | '@' | '°'
52
53export const SPECIES: readonly Species[] = [
54  'duck',
55  'goose',
56  'blob',
57  'cat',
58  'dragon',
59  'octopus',
60  'owl',
61  'penguin',
62  'turtle',
63  'snail',
64  'ghost',
65  'axolotl',
66  'capybara',
67  'cactus',
68  'robot',
69  'rabbit',
70  'mushroom',
71  'chonk',
72]
73
74export const EYES: readonly Eye[] = ['·', '✦', '×', '◉', '@', '°']
75
76/** Where an eye goes before one is chosen. Three characters, one cell. */
77export const EYE_SLOT = '{E}'
78
79/**
80 * Three frames of five rows per species, each row `SPECIES_WIDTH` wide once the
81 * eye slots are filled. Row 0 is blank unless the species draws something
82 * above itself in that frame; see `spriteLines`.
83 */
84export const BODIES: Record<Species, readonly (readonly string[])[]> = {
85  duck: [
86    ['            ', '    __      ', '  <({E} )___  ', '   (  ._>   ', '    `--´    '],
87    ['            ', '    __      ', '  <({E} )___  ', '   (  ._>   ', '    `--´~   '],
88    ['            ', '    __      ', '  <({E} )___  ', '   (  .__>  ', '    `--´    '],
89  ],
90  goose: [
91    ['            ', '     ({E}>    ', '     ||     ', '   _(__)_   ', '    ^^^^    '],
92    ['            ', '    ({E}>     ', '     ||     ', '   _(__)_   ', '    ^^^^    '],
93    ['            ', '     ({E}>>   ', '     ||     ', '   _(__)_   ', '    ^^^^    '],
94  ],
95  blob: [
96    ['            ', '   .----.   ', '  ( {E}  {E} )  ', '  (      )  ', '   `----´   '],
97    ['            ', '  .------.  ', ' (  {E}  {E}  ) ', ' (        ) ', '  `------´  '],
98    ['            ', '    .--.    ', '   ({E}  {E})   ', '   (    )   ', '    `--´    '],
99  ],
100  cat: [
101    ['            ', '   /\\_/\\    ', '  ( {E}   {E})  ', '  (  ω  )   ', '  (")_(")   '],
102    ['            ', '   /\\_/\\    ', '  ( {E}   {E})  ', '  (  ω  )   ', '  (")_(")~  '],
103    ['            ', '   /\\-/\\    ', '  ( {E}   {E})  ', '  (  ω  )   ', '  (")_(")   '],
104  ],
105  dragon: [
106    ['            ', '  /^\\  /^\\  ', ' <  {E}  {E}  > ', ' (   ~~   ) ', '  `-vvvv-´  '],
107    ['            ', '  /^\\  /^\\  ', ' <  {E}  {E}  > ', ' (        ) ', '  `-vvvv-´  '],
108    ['   ~    ~   ', '  /^\\  /^\\  ', ' <  {E}  {E}  > ', ' (   ~~   ) ', '  `-vvvv-´  '],
109  ],
110  octopus: [
111    ['            ', '   .----.   ', '  ( {E}  {E} )  ', '  (______)  ', '  /\\/\\/\\/\\  '],
112    ['            ', '   .----.   ', '  ( {E}  {E} )  ', '  (______)  ', '  \\/\\/\\/\\/  '],
113    ['     o      ', '   .----.   ', '  ( {E}  {E} )  ', '  (______)  ', '  /\\/\\/\\/\\  '],
114  ],
115  owl: [
116    ['            ', '   /\\  /\\   ', '  (({E})({E}))  ', '  (  ><  )  ', '   `----´   '],
117    ['            ', '   /\\  /\\   ', '  (({E})({E}))  ', '  (  ><  )  ', '   .----.   '],
118    ['            ', '   /\\  /\\   ', '  (({E})(-))  ', '  (  ><  )  ', '   `----´   '],
119  ],
120  penguin: [
121    ['            ', '  .---.     ', '  ({E}>{E})     ', ' /(   )\\    ', '  `---´     '],
122    ['            ', '  .---.     ', '  ({E}>{E})     ', ' |(   )|    ', '  `---´     '],
123    ['  .---.     ', '  ({E}>{E})     ', ' /(   )\\    ', '  `---´     ', '   ~ ~      '],
124  ],
125  turtle: [
126    ['            ', '   _,--._   ', '  ( {E}  {E} )  ', ' /[______]\\ ', '  ``    ``  '],
127    ['            ', '   _,--._   ', '  ( {E}  {E} )  ', ' /[______]\\ ', '   ``  ``   '],
128    ['            ', '   _,--._   ', '  ( {E}  {E} )  ', ' /[======]\\ ', '  ``    ``  '],
129  ],
130  snail: [
131    ['            ', ' {E}    .--.  ', '  \\  ( @ )  ', '   \\_`--´   ', '  ~~~~~~~   '],
132    ['            ', '  {E}   .--.  ', '  |  ( @ )  ', '   \\_`--´   ', '  ~~~~~~~   '],
133    ['            ', ' {E}    .--.  ', '  \\  ( @  ) ', '   \\_`--´   ', '   ~~~~~~   '],
134  ],
135  ghost: [
136    ['            ', '   .----.   ', '  / {E}  {E} \\  ', '  |      |  ', '  ~`~``~`~  '],
137    ['            ', '   .----.   ', '  / {E}  {E} \\  ', '  |      |  ', '  `~`~~`~`  '],
138    ['    ~  ~    ', '   .----.   ', '  / {E}  {E} \\  ', '  |      |  ', '  ~~`~~`~~  '],
139  ],
140  axolotl: [
141    ['            ', '}~(______)~{', '}~({E} .. {E})~{', '  ( .--. )  ', '  (_/  \\_)  '],
142    ['            ', '~}(______){~', '~}({E} .. {E}){~', '  ( .--. )  ', '  (_/  \\_)  '],
143    ['            ', '}~(______)~{', '}~({E} .. {E})~{', '  (  --  )  ', '  ~_/  \\_~  '],
144  ],
145  capybara: [
146    ['            ', '  n______n  ', ' ( {E}    {E} ) ', ' (   oo   ) ', '  `------´  '],
147    ['            ', '  n______n  ', ' ( {E}    {E} ) ', ' (   Oo   ) ', '  `------´  '],
148    ['    ~  ~    ', '  u______n  ', ' ( {E}    {E} ) ', ' (   oo   ) ', '  `------´  '],
149  ],
150  cactus: [
151    ['            ', ' n  ____  n ', ' | |{E}  {E}| | ', ' |_|    |_| ', '   |    |   '],
152    ['            ', '    ____    ', ' n |{E}  {E}| n ', ' |_|    |_| ', '   |    |   '],
153    [' n        n ', ' |  ____  | ', ' | |{E}  {E}| | ', ' |_|    |_| ', '   |    |   '],
154  ],
155  robot: [
156    ['            ', '   .[||].   ', '  [ {E}  {E} ]  ', '  [ ==== ]  ', '  `------´  '],
157    ['            ', '   .[||].   ', '  [ {E}  {E} ]  ', '  [ -==- ]  ', '  `------´  '],
158    ['     *      ', '   .[||].   ', '  [ {E}  {E} ]  ', '  [ ==== ]  ', '  `------´  '],
159  ],
160  rabbit: [
161    ['            ', '   (\\__/)   ', '  ( {E}  {E} )  ', ' =(  ..  )= ', '  (")__(")  '],
162    ['            ', '   (|__/)   ', '  ( {E}  {E} )  ', ' =(  ..  )= ', '  (")__(")  '],
163    ['            ', '   (\\__/)   ', '  ( {E}  {E} )  ', ' =( .  . )= ', '  (")__(")  '],
164  ],
165  mushroom: [
166    ['            ', ' .-o-OO-o-. ', '(__________)', '   |{E}  {E}|   ', '   |____|   '],
167    ['            ', ' .-O-oo-O-. ', '(__________)', '   |{E}  {E}|   ', '   |____|   '],
168    ['   . o  .   ', ' .-o-OO-o-. ', '(__________)', '   |{E}  {E}|   ', '   |____|   '],
169  ],
170  chonk: [
171    ['            ', '  /\\    /\\  ', ' ( {E}    {E} ) ', ' (   ..   ) ', '  `------´  '],
172    ['            ', '  /\\    /|  ', ' ( {E}    {E} ) ', ' (   ..   ) ', '  `------´  '],
173    ['            ', '  /\\    /\\  ', ' ( {E}    {E} ) ', ' (   ..   ) ', '  `------´~ '],
174  ],
175}
176
177/** Hat art, drawn on row 0. `none` is the empty string, never drawn. */
178export const HAT_LINES: Record<Hat, string> = {
179  none: '',
180  crown: '   \\^^^/    ',
181  tophat: '   [___]    ',
182  propeller: '    -+-     ',
183  halo: '   (   )    ',
184  wizard: '    /^\\     ',
185  beanie: '   (___)    ',
186  tinyduck: '    ,>      ',
187}
188
189/** Every row is this wide once its eye slots are filled. */
190export const SPECIES_WIDTH = 12
191
192/**
193 * Where the measured cat's column 0 lands in a table row: the table stores the
194 * cat two columns in. Everything measured off the recording against the cat
195 * (the hearts, the name row) is shifted by this to sit on the table's grid.
196 */
197export const CAT_INSET = 2
198
199/** How many frames a species cycles through. Three, for all eighteen. */
200export function frameCount(species: Species): number {
201  return BODIES[species].length
202}
203
204export type Bones = {
205  species: Species
206  hat: Hat
207  eye: Eye | '-'
208}
209
210/**
211 * The five rows for one frame of a buddy, each `SPECIES_WIDTH` wide.
212 *
213 * The hat only lands when the frame leaves row 0 free. Eight species draw
214 * something up there in at least one frame — dragon's smoke, octopus's
215 * bubble — and in those frames the hat is simply not shown, which is what
216 * any-buddy's renderer does and the only behaviour the table can support.
217 *
218 * Unlike that renderer this always returns five rows: it never drops a blank
219 * row 0, because the band above the prompt draws a fixed block and a sprite
220 * that changed height between frames would make the cat hop.
221 */
222export function spriteLines({ species, hat, eye }: Bones, frame: number): string[] {
223  const frames = BODIES[species]
224  const rows = frames[((frame % frames.length) + frames.length) % frames.length]!.map((row) =>
225    row.replaceAll(EYE_SLOT, eye),
226  )
227  if (hat !== 'none' && !rows[0]!.trim()) rows[0] = HAT_LINES[hat]
228  return rows
229}
230
hooks/identity.ts 74 lines
1// Who the buddy is: written down, and the person's to change.
2//
3// The original derived species, hat and eyes from the user's ID every session
4// and never stored them, precisely so that an edited config could not change
5// what you got. Here the traits are stored and the store is the authority:
6// nothing recomputes them behind your back (docs/scope.md).
7//
8// Reading is forgiving field by field. A trait the table does not know falls
9// back to Gristle's for that trait alone, so a typo in one field draws a cat
10// with the wrong hat rather than no buddy at all. That is not policing: any
11// value the table can draw is kept, whatever produced it.
12
13import { EYES, HAT_LINES, SPECIES, SPECIES_WIDTH, type Bones, type Eye, type Hat, type Species } from './species.ts'
14
15export type Identity = {
16  species: Species
17  hat: Hat
18  eye: Eye
19  name: string
20  /** The sprite's color. Unset, the `/config` color row decides. */
21  color?: string
22}
23
24/** The `$.store` key the identity lives under. */
25export const IDENTITY_KEY = 'identity'
26
27/** The `$.store` key the buddy before the last roll lives under: one undo. */
28export const PREVIOUS_KEY = 'previous'
29
30/**
31 * The longest name the band draws whole: one table row. Anything that writes a
32 * name rejects a longer one rather than store a name that would be cut off.
33 */
34export const NAME_MAX = SPECIES_WIDTH
35
36/**
37 * A name as it would be stored: trimmed, or undefined when it is blank or too
38 * long to draw whole. Names are rejected, never cut.
39 */
40export const cleanName = (raw: unknown): string | undefined => {
41  const trimmed = typeof raw === 'string' ? raw.trim() : ''
42  return trimmed && trimmed.length <= NAME_MAX ? trimmed : undefined
43}
44
45/** The buddy before anyone has changed anything. */
46export const GRISTLE: Identity = { species: 'cat', hat: 'tophat', eye: '✦', name: 'Gristle' }
47
48const oneOf = <T extends string>(allowed: readonly T[], v: unknown, fallback: T): T =>
49  typeof v === 'string' && (allowed as readonly string[]).includes(v) ? (v as T) : fallback
50
51const HATS = Object.keys(HAT_LINES) as Hat[]
52
53/**
54 * The identity a stored value describes, each field it gets wrong replaced by
55 * Gristle's. Nothing stored at all is Gristle.
56 */
57export function identityFrom(stored: unknown): Identity {
58  const s = (typeof stored === 'object' && stored !== null ? stored : {}) as Record<string, unknown>
59  const name = cleanName(s.name) ?? GRISTLE.name
60  const identity: Identity = {
61    species: oneOf(SPECIES, s.species, GRISTLE.species),
62    hat: oneOf(HATS, s.hat, GRISTLE.hat),
63    eye: oneOf(EYES, s.eye, GRISTLE.eye),
64    name,
65  }
66  if (typeof s.color === 'string' && s.color.trim()) identity.color = s.color.trim()
67  return identity
68}
69
70/** What the species table needs to draw an identity. */
71export function bonesOf({ species, hat, eye }: Identity): Bones {
72  return { species, hat, eye }
73}
74
hooks/roll.ts 78 lines
1// A fresh buddy at random, by the original's odds.
2//
3// The rarity weights and the hat rule follow `src/generation/roll.ts` in
4// cpaczek/any-buddy (WTFPL) at commit b5e7eb0, a transcription of the shipped
5// build's roll: rarity by weight, then species and eye uniformly, and a hat only
6// above common, drawn uniformly from all eight (so `none` can still come up).
7// The blogs describe each rarity unlocking its own hats; the code does not, and
8// the code is the better witness.
9//
10// Rarity is rolled for the hat rule and the line a roll answers with, and is
11// not stored: with a free re-roll it would only be a number to farm. The
12// identity keeps the looks that came of it.
13//
14// What any-buddy also rolls and this does not: stats (nothing draws them until
15// the card) and shiny (nothing draws it yet). The name is never rolled; the
16// buddy keeps the one it has.
17
18import { EYES, HAT_LINES, SPECIES, type Eye, type Hat, type Species } from './species.ts'
19
20export type Rarity = 'common' | 'uncommon' | 'rare' | 'epic' | 'legendary'
21
22export const RARITIES: readonly Rarity[] = ['common', 'uncommon', 'rare', 'epic', 'legendary']
23
24/** Out of 100. */
25export const RARITY_WEIGHTS: Readonly<Record<Rarity, number>> = {
26  common: 60,
27  uncommon: 25,
28  rare: 10,
29  epic: 4,
30  legendary: 1,
31}
32
33const HATS = Object.keys(HAT_LINES) as Hat[]
34
35export type Rolled = { species: Species; hat: Hat; eye: Eye; rarity: Rarity }
36
37/** A uniform draw in [0, 1), as `Math.random` gives. */
38export type Rng = () => number
39
40const pick = <T>(rng: Rng, from: readonly T[]): T =>
41  from[Math.min(from.length - 1, Math.floor(rng() * from.length))]!
42
43export function rollRarity(rng: Rng): Rarity {
44  let roll = rng() * 100
45  for (const rarity of RARITIES) {
46    roll -= RARITY_WEIGHTS[rarity]
47    if (roll < 0) return rarity
48  }
49  return 'common'
50}
51
52/** One roll: rarity first, then species, eye and hat, in the original's order. */
53export function roll(rng: Rng): Rolled {
54  const rarity = rollRarity(rng)
55  const species = pick(rng, SPECIES)
56  const eye = pick(rng, EYES)
57  const hat = rarity === 'common' ? 'none' : pick(rng, HATS)
58  return { species, hat, eye, rarity }
59}
60
61const HAT_WORDS: Readonly<Record<Hat, string>> = {
62  none: 'no hat',
63  crown: 'a crown',
64  tophat: 'a top hat',
65  propeller: 'a propeller hat',
66  halo: 'a halo',
67  wizard: 'a wizard hat',
68  beanie: 'a beanie',
69  tinyduck: 'a tiny duck',
70}
71
72/** "an uncommon duck in a wizard hat", for the line a roll answers with. */
73export function describe({ species, hat, rarity }: Rolled): string {
74  const article = rarity === 'uncommon' || rarity === 'epic' ? 'an' : 'a'
75  const wearing = hat === 'none' ? 'with no hat' : `in ${HAT_WORDS[hat]}`
76  return `${article} ${rarity} ${species} ${wearing}`
77}
78