SLOPSHOPPER

pixel-buddy

A pixel Claude critter above the prompt that reacts to typing, working, finishing and going AFK.

bandguardcommandprompttimer
★ 1v1.2.0MITupdated 2026-10-18Bocskay-Botond/claude-code-mods/mods/pixel-buddy
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · pixel-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 ⏺ 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 ⎿ pixel-buddy: Claude buddy hidden. /buddy brings it back. ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts
README

claude-code-mods

🧩 Claude Code Mods: Make Your Terminal Come Alive

Claude Code now has mods: plugins made of TypeScript function hooks that can draw UI right inside the terminal, react to everything Claude does, and change how it works. This repo contains four mods I use every day. There's a pixel critter that lives above your prompt, a control panel for model, effort and parallel agents, a project launcher box, and a live status bar. It also has everything you need to build your own in about 10 minutes.

pixel-buddy walking, typing on its laptop and blowing bubbles above the Claude Code prompt

Claude Code TypeScript License: MIT

⚠️ Mods are early access. The function-hooks API can change between Claude Code releases. Everything here was built and tested on Claude Code 2.1.294.


⚡ Quick Start (30 seconds)

Open Claude Code in a terminal and paste:

/plugin install pixel-buddy --marketplace Bocskay-Botond/claude-code-mods

Answer y to add the marketplace, press Enter for the user scope, and you're done. A little orange critter appears above your prompt. Start typing and watch it pull out a laptop. 🧡

Want the full setup? 👉 quick-start/


🎮 What's Included

All four running together: the status bar, pixel-buddy, project-box and the Tristen's Tools menu.

statusbar, pixel-buddy, project-box and tristens-tools running together in Claude Code

ModWhat it doesCommands
🐾 pixel-buddyA 12×4 pixel Claude critter above the prompt. It types on a tiny laptop while you type, patrols while Claude works, celebrates when a turn finishes, plays when you're idle (football with a goal, dancing, jump rope, butterflies, bubbles, reading a book), reacts to greetings, thanks, commits, pushes and tool-call combos, shows how much of your 5-hour budget is left, and falls asleep after 3 minutes. Now and then a shot misses and knocks project-box apart, and the box rebuilds itself./buddy /pet
🛠️ tristens-toolsA tools menu and status line: model & effort picker, Clean View (hides tool noise and shows a simple checklist), Prompt Upgrade, Agent Dock (split each request across 1–100 helper agents and watch them live), and a Roadtrip racing minigame./tools /dock /roadtrip
📁 project-boxA folder-tree card beside the status bar listing your projects by category. Click a category, then a project, to see its note and path. pixel-buddy walks over and "types the cd" for you. On a narrow terminal it folds into one row of category buttons./projects
📊 statusbarA minimal one-line status bar: working/idle, tool count, last tool, last turn duration, turns. The simplest real mod in the repo, so read this one first.—
👋 hello-modThe tutorial example: a slash command, a toast and a band in about 35 lines./hello

What's new in 1.2

  • pixel-buddy shows your 5-hour budget: past 75% a battery appears in the corner of its stage (▰▰▱ 20%), past 90% it turns red and blinks and the critter sweats. When the budget runs out the critter goes grey and slumps like a flat battery, with a countdown to the reset (⧗1:23). When the window resets it jumps up: "recharged!". Try it with /buddy limit.
  • Fix: pixel-buddy no longer paints over project-box's left border. The box's published width now reaches the buddy, and the buddy assumes the widest card until it does.

What's new in 1.1

  • Works on narrow terminals: a half-screen window or a phone over SSH (Termius and similar). Every mod lays itself out for the width it gets.
  • pixel-buddy: football with a goal (juggle, dribble, shoot, "GOAL!"), a fixed reading pose, cute reactions (greetings, thanks, commit/push, tool combos, sneezes, /pet counter, a nightcap after 23:00).
  • project-box: stacks above the band on a narrow terminal, publishes its layout for neighbours, and falls apart and rebuilds when pixel-buddy's shot misses.
  • tristens-tools: a real Prompt Upgrade (one cheap Haiku call turns your prompt into a working brief), a model switch that sticks, and a status line that shortens on narrow terminals.

Install any of them the same way:

/plugin install <mod-name> --marketplace Bocskay-Botond/claude-code-mods

📂 Repository Structure

claude-code-mods/
├── .claude-plugin/
│   └── marketplace.json      # makes this repo a plugin marketplace
├── mods/
│   ├── pixel-buddy/          # 🐾 the critter
│   ├── tristens-tools/       # 🛠️ tools menu, Agent Dock, Roadtrip
│   ├── project-box/          # 📁 project launcher card
│   └── statusbar/            # 📊 one-line status bar
├── examples/
│   └── hello-mod/            # 👋 your first mod, fully commented
├── quick-start/              # ⚡ 5-minute setup
├── docs/
│   ├── installation.md       # every way to install & manage mods
│   ├── writing-your-own-mod.md
│   ├── api-cheatsheet.md     # events, $ nouns, UI elements
│   └── troubleshooting.md
├── mod-builder-prompt/       # 🤖 a prompt that makes Claude build mods for you
└── assets/                   # 🖼️ social preview + demo GIFs

Every mod is the same four small files:

my-mod/
├── .claude-plugin/plugin.json   # name, version, description
├── hooks/hooks.json             # { "modules": ["./register.tsx"] }
├── hooks/register.tsx           # the code
└── types/index.d.ts             # the state your mod keeps (optional)

🎯 What You'll Learn

  • What a Claude Code mod is, and how it differs from skills, slash commands and classic shell hooks
  • How the on(event, hook) / next(e) middleware chain works
  • How to draw UI in the terminal: bands above the prompt, panes, buttons, even a pixel raster at 25 fps
  • How to keep state with atoms and have the UI redraw automatically
  • How to change Claude's behaviour: swap the model per request, add system-prompt sections, react to tool calls
  • How to test a mod with claude plugin test and ship it as a GitHub marketplace

🚦 Prerequisites

  • Claude Code 2.1.294 or newer in a terminal (claude --version)
  • A Claude subscription or API key (whatever you already use with Claude Code)
  • Git if you want to clone and hack on the mods
  • Coffee ☕ (highly recommended)

No Node, no npm install, no build step. Claude Code compiles the TypeScript itself.


🔨 Build Your Own Mod

The fastest way is to ask Claude. Inside Claude Code:

Make me a mod that shows a 🍅 pomodoro timer above the prompt and plays a toast when it ends.

Claude Code has a built-in skill for this: it writes the mod, hot-reloads it into your session and tests it. For a better result, paste the prompt from mod-builder-prompt/ first.

Prefer to do it by hand? docs/writing-your-own-mod.md walks through hello-mod line by line, and docs/api-cheatsheet.md has the events and elements you'll use most.


📁 Configure project-box

project-box shows a demo list until you give it yours. Copy the example and edit it:

# macOS / Linux
cp mods/project-box/project-box.example.json ~/.claude/project-box.json

# Windows (PowerShell)
Copy-Item mods\project-box\project-box.example.json $HOME\.claude\project-box.json

Restart Claude Code (or run /reload-plugins) and your projects show up. Colors can be any terminal color name (magenta, cyan, green, yellow, blue, red). Set "live": true for a green dot.


🐛 Troubleshooting

ProblemFix
Nothing appears after installRun /reload-plugins, or restart Claude Code. Make sure you're in a terminal: /plugin isn't available in the desktop app's Code tab.
Marketplace file not foundCheck the repo name: Bocskay-Botond/claude-code-mods
A mod silently does nothingStart with claude --debug. A failing hook is skipped and logged with the reason.
Small window or phone (SSH)Every mod adapts to the terminal width. Below about 70 columns project-box stacks above the status rows, pixel-buddy gets a row of its own, and the tristens-tools line shortens.
Two bands fight for spacepixel-buddy, project-box and tristens-tools are designed to stack. Turn things off with /buddy, /projects, or /plugin → disable.

More: docs/troubleshooting.md


🤝 Contributing

Built a cool mod? PRs are welcome!

  1. Fork the repo
  2. Add your mod under mods/<your-mod>/ (four files, see above)
  3. Make sure claude plugin validate mods/<your-mod> and claude plugin test mods/<your-mod> pass
  4. Add it to .claude-plugin/marketplace.json and to the table in this README
  5. Open a PR with a screenshot or GIF 📸

📄 License

MIT. Do whatever you want, just don't blame me if your critter falls asleep on the job. 😴


🙏 Acknowledgments


☕ Support

If this made your terminal a little more fun, ⭐ star the repo and share it with someone who lives in Claude Code.

Now go build a mod. Your terminal has been boring for long enough. 🚀

Source 2 files
hooks/register.tsx 957 lines
1import { atom, read, update } from 'claude-code'
2import type { Register } from 'claude-code'
3
4import type { Bump } from '../types'
5
6// A 12x4 pixel critter drawn with quadrant blocks (one cell = 2x2 pixels, so
7// a leg is one pixel: half a column), on a stage of `width` columns, 4 rows.
8const isShown = atom({ plugin: 'pixel-buddy', key: 'isShown' } as const, true)
9// A missed shot that hits the project box: project-box reads this and draws
10// its card shaken, scattered, then rebuilding row by row (step 0..10).
11const bump = atom({ plugin: 'pixel-buddy', key: 'bump' } as const, { phase: 'none', step: 0 } as Bump)
12
13// The project-box box beside the status bar: read (never written) so the
14// critter can walk up to it and react when it opens, picks or hides.
15const projCat = atom({ plugin: 'project-box', key: 'openCat' } as const, '')
16const projPick = atom({ plugin: 'project-box', key: 'openProject' } as const, '')
17const projHidden = atom({ plugin: 'project-box', key: 'isHidden' } as const, false)
18// its card widths (closed / open cap, stack threshold), as project-box
19// publishes them; zeros until it has (see the render for the fallback)
20const projLayout = atom({ plugin: 'project-box', key: 'layout' } as const, { narrow: 0, wide: 0, stack: 0 })
21type ProjEvent = 'open' | 'close' | 'pick' | 'hide' | 'show'
22const PROJ_LEN: Record<ProjEvent, number> = { open: 3800, close: 2500, pick: 5500, hide: 2500, show: 3200 }
23
24const ORANGE = 0xd97757
25const EYE = 0x1c1c1c
26const GOLD = 0xf5c26b
27const SLEEPY = 0x8ea4d2
28const PINK = 0xe0607e
29const GREEN = 0x2fd27a
30const DIM = 0x8a8a8a
31const LID = 0x5d6169
32const KEYS = 0xa7adb5
33const SCREEN = 0x6fa8dc
34const SCREEN_LIT = 0xcfe8ff
35const BALL = 0xf2f2f2
36const POST = 0xf2f2f2
37const NET = 0x6f7378
38const ROPE = 0xd8d8d8
39const PAGE = 0xf4efe6
40const FOLD = 0xc9bfae
41const WING_A = 0xf5c26b
42const WING_B = 0xe0607e
43const BUBBLE = 0x9fd3ff
44const CAP = 0x4a6fd1
45const POMPOM = 0xf2f2f2
46const SWEAT = 0x9fd3ff
47const RED = 0xe0605e
48const YELLOW = 0xf2d14b
49// out of the 5-hour budget: the critter goes dull, like a flat battery
50const DRAINED = 0x8f7f79
51const NONE = 0x01000000
52
53// Short one-off reactions layered over whatever the critter is doing.
54type Emote = 'hello' | 'thanks' | 'night' | 'oops' | 'commit' | 'push' | 'combo' | 'sneeze' | 'hiccup' | 'love' | 'drained' | 'charged'
55const EMOTE_LEN: Record<Emote, number> = {
56  hello: 2500, thanks: 3000, night: 2500, oops: 1400, commit: 2400, push: 2200, combo: 1600, sneeze: 1400, hiccup: 900, love: 3500, drained: 2200, charged: 3200,
57}
58const COMBOS = [10, 25, 50, 100]
59const hourOf = (now: number) => new Date(now).getHours()
60const isNightAt = (now: number) => hourOf(now) >= 23 || hourOf(now) < 5
61
62// What a prompt says to the critter, if anything: a greeting, thanks, good night.
63const greetingOf = (text: string): Emote | undefined => {
64  const t = ` ${text.toLowerCase().replace(/[!?.,:;()'"]/g, ' ')} `
65  const has = (...words: string[]) => words.some(w => t.includes(` ${w} `))
66  if (has('jó éjt', 'jo ejt', 'jóéjt', 'jó éjszakát', 'good night', 'gn')) return 'night'
67  if (has('köszi', 'köszike', 'köszönöm', 'kösz', 'koszi', 'thanks', 'thx', 'ty', 'thank you')) return 'thanks'
68  if (has('szia', 'sziasztok', 'helló', 'hello', 'hali', 'hi', 'hey', 'csá', 'cső', 'jó reggelt')) return 'hello'
69  return undefined
70}
71
72const ROWS = 4
73const PH = ROWS * 2
74const SPRITE_W = 12
75const SPRITE_H = 4
76const TICK = 100 // animation cadence (blinks, beats, walking speeds are per tick)
77const FRAME_MS = 40 // repaint rate: 25 fps
78const PLAY_MS = 20_000 // quiet this long: start playing
79const PLAY_LEN = 12_000 // each game lasts this long
80const SLEEP_MS = 180_000 // quiet this long: fall asleep
81const PLAYS = ['football', 'dance', 'rope', 'butterfly', 'read', 'bubbles', 'visit'] as const
82
83type Eyes = 'center' | 'left' | 'right' | 'closed'
84type Arms = 'down' | 'up' | 'waveL' | 'waveR' | 'tapL' | 'tapR' | 'hold'
85type Pose = { eyes: Eyes; arms: Arms; legs: 0 | 1; squash: boolean; cap?: boolean; blush?: boolean; body?: number }
86// isOver: drawn over pixels too (text that must stay whole, like a tool name)
87type Label = { x: number; row: number; text: string; color: number; isOver?: boolean }
88type Dot = { x: number; y: number; color: number }
89
90// ---- animation state (module-local: a reload just restarts the critter) ----
91const s = {
92  width: 32,
93  requestId: '',
94  x: 4,
95  dir: 1 as 1 | -1,
96  target: 4,
97  isWorking: false,
98  tools: 0,
99  toolName: '',
100  toolAt: 0,
101  lastKey: 0,
102  keys: 0,
103  lastActive: 0,
104  wokeAt: 0,
105  doneAt: 0,
106  petAt: 0,
107  submitAt: 0,
108  lastFrame: '',
109  typeStart: 0,
110  typed: [] as { ch: string; at: number; dx: number }[],
111  now: 0,
112  isProjSeen: false,
113  projCat: '',
114  projPick: '',
115  projHidden: false,
116  // the box sits beside the stage (not hidden, not stacked above on a narrow terminal)
117  isBoxBeside: true,
118  projEvent: 'open' as ProjEvent,
119  projArg: '',
120  projAt: -1e9,
121  projUntil: 0,
122  // the run to (or from) the project box: eased from `from` to `to`
123  trip: { at: -1, from: 0, to: 0, start: 0, dur: 0 },
124  prevNow: 0,
125  bumpWant: { phase: 'none', step: 0 } as Bump,
126  bumpSent: 'none:0',
127  fbKey: -1,
128  fbFrom: 0,
129  isFbMiss: false,
130  emote: { kind: 'hello' as Emote, at: -1e9, arg: '' },
131  sleepAfterTurn: false,
132  petStreak: 0,
133  pets: 0,
134  seed: 0,
135  helloAt: 0,
136  // the 5-hour rate-limit window: percent used (-1 = no reading yet), when it
137  // resets (epoch ms, 0 = unknown), and whether the budget ran out
138  five: -1,
139  fiveReset: 0,
140  isLimited: false,
141}
142
143// A reading of the 5-hour window (session.start, session.measure): past 100%
144// the budget is gone; a later reading under it means it came back.
145const readFive = (limits: { kind: string; percentUsed: number; resetsAt?: string }[], now: number) => {
146  const w = limits.find(l => l.kind === 'five_hour')
147  if (w === undefined) return
148  s.five = w.percentUsed
149  const at = w.resetsAt === undefined ? NaN : Date.parse(w.resetsAt)
150  if (!Number.isNaN(at)) s.fiveReset = at
151  if (w.percentUsed >= 100 && !s.isLimited) {
152    s.isLimited = true
153    s.emote = { kind: 'drained', at: now, arg: '' }
154  } else if (w.percentUsed < 100 && s.isLimited) {
155    recharge(now)
156  }
157}
158const recharge = (now: number) => {
159  s.isLimited = false
160  s.emote = { kind: 'charged', at: now, arg: '' }
161}
162const untilReset = (now: number) => {
163  if (s.fiveReset <= now) return ''
164  const m = Math.ceil((s.fiveReset - now) / 60000)
165  return m >= 60 ? `${Math.floor(m / 60)}:${String(m % 60).padStart(2, '0')}` : `${m}m`
166}
167
168// ---- pixels ----
169const B64 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
170const toBase64 = (bytes: Uint8Array) => {
171  let out = ''
172  for (let i = 0; i < bytes.length; i += 3) {
173    const a = bytes[i] ?? 0, b = bytes[i + 1], c = bytes[i + 2]
174    const n = (a << 16) | ((b ?? 0) << 8) | (c ?? 0)
175    out += B64.charAt((n >> 18) & 63) + B64.charAt((n >> 12) & 63)
176    out += b === undefined ? '=' : B64.charAt((n >> 6) & 63)
177    out += c === undefined ? '=' : B64.charAt(n & 63)
178  }
179  return out
180}
181
182// quadrant glyph by mask: top-left 1, top-right 2, bottom-left 4, bottom-right 8
183const QUAD = [0x20, 0x2598, 0x259d, 0x2580, 0x2596, 0x258c, 0x259e, 0x259b, 0x2597, 0x259a, 0x2590, 0x259c, 0x2584, 0x2599, 0x259f, 0x2588]
184
185const putter = (px: Uint32Array, pw: number, ox: number, oy: number) => (x: number, y: number, color: number) => {
186  const X = ox + x, Y = oy + y
187  if (X >= 0 && X < pw && Y >= 0 && Y < PH) px[Y * pw + X] = color
188}
189
190// Laptop in side view to the critter's right: the keyboard deck on the ground,
191// the lid hinged at its far end, `lid` pixels raised (0 = shut, 3 = open and
192// tilted back), its screen glowing toward the critter.
193const drawLaptop = (px: Uint32Array, pw: number, ox: number, oy: number, lid: number, isLit: boolean, isTapDown: boolean) => {
194  const put = putter(px, pw, ox, oy)
195  for (let x = 12; x <= 17; x++) put(x, 3, KEYS)
196  for (let y = 4 - Math.min(lid, 3); y <= 3; y++) put(18, y, LID)
197  if (lid >= 3) {
198    put(19, 0, LID)
199    put(17, 0, isLit ? SCREEN_LIT : SCREEN)
200    put(17, 1, isLit ? SCREEN_LIT : SCREEN)
201  }
202  if (isTapDown) put(12, 2, ORANGE)
203}
204
205const drawCritter = (px: Uint32Array, pw: number, ox: number, oy: number, p: Pose) => {
206  const put = putter(px, pw, ox, oy)
207  const C = p.body ?? ORANGE
208  const top = p.squash ? 1 : 0
209  for (let y = top; y <= 2; y++) for (let x = 2; x <= 9; x++) put(x, y, C)
210  const [left, right] = {
211    down: [1, 1], up: [0, 0], waveL: [0, 1], waveR: [1, 0], tapL: [1, 2], tapR: [1, 1], hold: [2, 2],
212  }[p.arms] as [number, number]
213  // a raised arm points up and out from the shoulder, its hand above the head,
214  // so it never lines up with the top of the head
215  const arm = (inner: number, outer: number, y: number) => {
216    if (y === 0) {
217      put(inner, top, C)
218      put(outer, top - 1, C)
219    } else {
220      const ay = Math.min(2, y + top)
221      put(inner, ay, C)
222      put(outer, ay, C)
223    }
224  }
225  arm(1, 0, left)
226  arm(10, 11, right)
227  if (p.eyes !== 'closed') {
228    const [l, r] = p.eyes === 'left' ? [2, 7] : p.eyes === 'right' ? [4, 9] : [3, 8]
229    put(l, 1, EYE)
230    put(r, 1, EYE)
231  }
232  for (const lx of p.legs === 0 ? [2, 4, 7, 9] : [3, 5, 6, 8]) put(lx, 3, C)
233  if (p.blush && p.eyes === 'closed') {
234    put(2, 1, PINK)
235    put(9, 1, PINK)
236  }
237  if (p.cap) {
238    // a floppy nightcap, its tip and pompom drooping to the right
239    for (let x = 3; x <= 8; x++) put(x, top - 1, CAP)
240    for (let x = 5; x <= 9; x++) put(x, top - 2, CAP)
241    put(10, top - 3, POMPOM)
242  }
243}
244
245const render = (w: number, px: Uint32Array, labels: Label[]) => {
246  const pw = w * 2
247  const words = new Uint32Array(w * ROWS * 3)
248  for (let r = 0; r < ROWS; r++) {
249    for (let cx = 0; cx < w; cx++) {
250      const quad = [
251        px[2 * r * pw + 2 * cx] ?? 0, px[2 * r * pw + 2 * cx + 1] ?? 0,
252        px[(2 * r + 1) * pw + 2 * cx] ?? 0, px[(2 * r + 1) * pw + 2 * cx + 1] ?? 0,
253      ]
254      const counts = new Map<number, number>()
255      for (const c of quad) if (c !== 0) counts.set(c, (counts.get(c) ?? 0) + 1)
256      const ranked = [...counts.entries()].sort((a, b) => b[1] - a[1]).map(([c]) => c)
257      const fg = ranked[0]
258      const i = (r * w + cx) * 3
259      if (fg === undefined) {
260        words.set([0x20, NONE, NONE], i)
261        continue
262      }
263      // a cell holds two colors: the commonest is drawn, the next fills the rest
264      const mask = quad.reduce((m, c, k) => (c === fg ? m | (1 << k) : m), 0)
265      words.set([QUAD[mask] ?? 0x2588, fg, ranked[1] ?? NONE], i)
266    }
267  }
268  for (const l of labels) {
269    for (let k = 0; k < l.text.length; k++) {
270      const x = l.x + k
271      if (x < 0 || x >= w || l.row < 0 || l.row >= ROWS) continue
272      const i = (l.row * w + x) * 3
273      if (!l.isOver && words[i] !== 0x20) continue
274      words.set([l.text.charCodeAt(k), l.color, NONE], i)
275    }
276  }
277  return toBase64(new Uint8Array(words.buffer))
278}
279
280// ---- behaviour ----
281const modeAt = (now: number) => {
282  if (now - s.doneAt < 2500) return 'done' as const
283  if (s.isWorking) return s.tools === 0 ? ('think' as const) : ('work' as const)
284  if (now - s.lastKey < 1900) return 'type' as const
285  if (s.isLimited) return 'limit' as const
286  if (s.trip.at !== s.projAt ? now - s.projAt < 5000 : now < s.projUntil) return 'proj' as const
287  if (now - s.lastActive > SLEEP_MS) return 'sleep' as const
288  if (now - s.lastActive > SLEEP_MS - 5000) return 'yawn' as const
289  if (now - s.lastActive > PLAY_MS) return 'play' as const
290  return 'idle' as const
291}
292
293const frame = (now: number) => {
294  const w = s.width
295  const pw = w * 2
296  const px = new Uint32Array(pw * PH)
297  const labels: Label[] = []
298  const mode = modeAt(now)
299  const tick = Math.floor(now / TICK)
300  const maxX = Math.max(0, pw - SPRITE_W - 8)
301  const pose: Pose = { eyes: 'center', arms: 'down', legs: 0, squash: false }
302  let lift = 0
303  let laptop = -1
304  let isLit = false
305  let isTapDown = false
306  let shift = 0
307  const dots: Dot[] = []
308  // only a missed shot (football, below) drives the project box
309  s.bumpWant = { phase: 'none', step: 0 }
310  const ox = Math.round(s.x)
311  const cx = () => Math.round(s.x / 2)
312  const right = () => cx() + SPRITE_W / 2
313
314  // speeds are per tick; frames come every FRAME_MS, so move by elapsed time
315  const step = Math.min(3, Math.max(0, now - s.prevNow) / TICK)
316  s.prevNow = Math.max(s.prevNow, now)
317  const dash = (min: number, ticks: number) => Math.min(4, Math.max(min, Math.abs(s.target - s.x) / ticks))
318  const walk = (speed: number) => {
319    if (Math.abs(s.target - s.x) <= speed * step) {
320      s.x = s.target
321      return false
322    }
323    s.dir = s.target > s.x ? 1 : -1
324    s.x += s.dir * speed * step
325    pose.legs = tick % 2 === 0 ? 0 : 1
326    pose.eyes = s.dir > 0 ? 'right' : 'left'
327    return true
328  }
329
330  if (s.isLimited && s.fiveReset > 0 && now >= s.fiveReset) {
331    s.five = 0
332    recharge(now)
333  }
334
335  if (mode === 'limit') {
336    // out of the 5-hour budget: slumped, dull, a flat battery over its head
337    // and the time until the window resets
338    pose.squash = true
339    pose.eyes = Math.floor(now / 3000) % 4 === 0 ? 'center' : 'closed'
340    pose.body = DRAINED
341    const blink = Math.floor(now / 500) % 2 === 0
342    labels.push({ x: right(), row: 1, text: blink ? '▱▱▱' : '   ', color: RED })
343    const left = untilReset(now)
344    if (left !== '') labels.push({ x: right(), row: 2, text: `⧗${left}`, color: DIM })
345    if (now % 8000 < 1500) labels.push({ x: Math.max(0, cx() - 1), row: 0, text: 'out of juice…', color: DIM })
346  } else if (mode === 'yawn') {
347    // a big stretch and a yawn just before dozing off
348    const t = now - s.lastActive - (SLEEP_MS - 5000)
349    pose.arms = t < 2500 ? 'up' : 'down'
350    pose.eyes = 'closed'
351    lift = t < 1200 ? 1 : 0
352    labels.push({ x: right(), row: 1, text: t < 2500 ? 'yawn' : '…', color: SLEEPY })
353  } else if (mode === 'sleep') {
354    pose.squash = true
355    pose.eyes = 'closed'
356    const phase = Math.floor(now / 600) % 4
357    if (phase >= 1) labels.push({ x: right(), row: 2, text: 'z', color: SLEEPY })
358    if (phase >= 2) labels.push({ x: right() + 1, row: 1, text: 'z', color: SLEEPY })
359    if (phase >= 3) labels.push({ x: right() + 2, row: 0, text: 'Z', color: SLEEPY })
360  } else if (mode === 'type') {
361    // pull the laptop out, lift the lid, tap away; shut it after a pause
362    const opening = Math.min(1, (now - s.typeStart) / 450)
363    const closing = Math.max(0, Math.min(1, (now - s.lastKey - 1500) / 400))
364    laptop = Math.round(3 * opening * (1 - closing))
365    const isTyping = closing === 0 && opening === 1
366    pose.eyes = 'right'
367    pose.arms = isTyping ? (s.keys % 2 === 0 ? 'tapL' : 'tapR') : 'down'
368    isTapDown = isTyping && s.keys % 2 === 0
369    isLit = now - s.lastKey < 120
370    for (const t of s.typed) {
371      const age = now - t.at
372      if (age > 900) continue
373      labels.push({ x: cx() + 6 + (t.dx % 3), row: age < 450 ? 1 : 0, text: t.ch, color: age < 450 ? GOLD : DIM })
374    }
375  } else if (mode === 'think') {
376    pose.arms = Math.floor(now / 700) % 2 === 0 ? 'down' : 'waveR'
377    pose.eyes = Math.floor(now / 1400) % 2 === 0 ? 'right' : 'center'
378    const dots = '.'.repeat(1 + (Math.floor(now / 400) % 3))
379    labels.push({ x: right(), row: 1, text: dots, color: DIM })
380    labels.push({ x: right() - 1, row: 0, text: '?', color: GOLD })
381  } else if (mode === 'work') {
382    if (now - s.submitAt > 45_000) {
383      // a long one: a sweat drop rolls off, and now and then a sigh
384      const ph = (now % 1200) / 1200
385      dots.push({ x: ox - 1, y: PH - SPRITE_H + Math.floor(ph * 3), color: SWEAT })
386      if (now - s.submitAt > 120_000 && now % 6000 < 1200) labels.push({ x: right(), row: 2, text: 'phew', color: DIM })
387    }
388    const patrol = Math.min(maxX, 56)
389    if (s.target === s.x || s.target > patrol) s.target = s.x < patrol / 2 ? patrol : 0
390    walk(1)
391    pose.arms = tick % 4 < 2 ? 'waveL' : 'waveR'
392    lift = tick % 4 === 0 ? 1 : 0
393    const back = s.dir > 0 ? cx() - 1 : right()
394    if (tick % 3 === 0) labels.push({ x: back, row: 3, text: '✦', color: GOLD })
395    else if (tick % 3 === 1) labels.push({ x: back, row: 3, text: '·', color: DIM })
396    if (now - s.toolAt < 1500 && s.toolName !== '') {
397      // top row: raised hands and hops reach row 1 and would cut the word
398      labels.push({ x: Math.max(0, Math.min(w - s.toolName.length, cx())), row: 0, text: s.toolName, color: GOLD, isOver: true })
399    }
400  } else if (mode === 'done') {
401    const t = (now - s.doneAt) / 1000
402    lift = Math.max(0, Math.round(Math.sin(t * Math.PI * 2.4) * 3))
403    pose.arms = 'up'
404    labels.push({ x: right(), row: 1, text: '✓', color: GREEN })
405    if (tick % 4 < 2) labels.push({ x: cx() - 1, row: 1, text: '✦', color: GOLD })
406    else labels.push({ x: right() + 1, row: 0, text: '✦', color: GOLD })
407  } else if (mode === 'play') {
408    const k = now - s.lastActive - PLAY_MS
409    const picked = PLAYS[(s.seed + Math.floor(k / PLAY_LEN)) % PLAYS.length] ?? 'dance'
410    const play = picked === 'visit' && !s.isBoxBeside ? 'dance' : picked
411    const t = k % PLAY_LEN
412    if (play === 'football') {
413      // juggle, dribble up to the goal and shoot: a goal, or now and then a
414      // shot over the bar that crashes into the project box
415      const key = Math.floor(k / PLAY_LEN)
416      if (s.fbKey !== key) {
417        s.fbKey = key
418        s.fbFrom = s.x
419        s.isFbMiss = s.isBoxBeside && Math.random() < 0.4
420      }
421      const gx = pw - 16
422      const xk = Math.max(0, Math.min(maxX, gx - 30))
423      const oyG = PH - SPRITE_H
424      const ease = (u: number) => 0.5 - Math.cos(Math.PI * Math.max(0, Math.min(1, u))) / 2
425      const arc = (x0: number, y0: number, x1: number, y1: number, top: number, u: number) =>
426        ({ x: Math.round(x0 + (x1 - x0) * u), y: Math.round(y0 + (y1 - y0) * u - top * 4 * u * (1 - u)), color: BALL })
427      // the goal: front post, crossbar, net at the back (gone once a missed
428      // shot sends the critter running past it to the box)
429      if (!(s.isFbMiss && t >= 9800)) {
430        for (let y = PH - 4; y < PH; y++) dots.push({ x: gx, y, color: POST })
431        for (let x = gx; x <= gx + 4; x++) dots.push({ x, y: PH - 4, color: POST })
432        for (let y = PH - 3; y < PH; y++) dots.push({ x: gx + 4, y, color: NET })
433        dots.push({ x: gx + 2, y: PH - 1, color: NET })
434      }
435      const bx0 = xk + 13
436      // juggle left of the goal: standing at or past the shooting spot (a
437      // narrow window) the critter first walks back to it, ball at its feet
438      const jx = Math.min(s.fbFrom, xk)
439      if (t < 800 && s.fbFrom > jx) {
440        const prev = s.x
441        s.x = s.fbFrom + (jx - s.fbFrom) * ease(t / 800)
442        pose.eyes = 'left'
443        if (Math.abs(s.x - prev) > 0.05) pose.legs = Math.floor(now / 90) % 2 === 0 ? 0 : 1
444        dots.push({ x: Math.max(0, Math.round(s.x) - 2), y: PH - 1, color: BALL })
445      } else if (t < 5400) {
446        // keepy-uppy, counting
447        s.x = jx
448        const n = Math.floor(t / 900)
449        const ph = (t % 900) / 900
450        lift = ph < 0.12 ? 1 : 0
451        pose.arms = n % 2 === 0 ? 'waveL' : 'waveR'
452        const h = Math.round(12 * ph * (1 - ph))
453        dots.push({ x: Math.round(s.x) + 5 + (n % 2), y: Math.max(0, oyG - 1 - lift - h), color: BALL })
454        if (n >= 2) labels.push({ x: right() + 1, row: 0, text: String(n), color: DIM })
455      } else if (t < 7400) {
456        // dribble towards the goal, the ball rolling just ahead
457        const u = (t - 5400) / 2000
458        const prev = s.x
459        s.x = jx + (xk - jx) * ease(u)
460        pose.eyes = 'right'
461        if (Math.abs(s.x - prev) > 0.05) pose.legs = Math.floor(now / 90) % 2 === 0 ? 0 : 1
462        dots.push({ x: Math.round(s.x) + 13 + (Math.floor(now / 180) % 2), y: PH - 1, color: BALL })
463      } else if (t < 7900) {
464        // wind up
465        s.x = xk
466        shift = -1
467        pose.eyes = 'right'
468        pose.arms = 'waveL'
469        dots.push({ x: bx0, y: PH - 1, color: BALL })
470      } else if (t < 8900) {
471        // the shot
472        s.x = xk
473        pose.eyes = 'right'
474        pose.arms = 'up'
475        lift = t < 8100 ? 1 : 0
476        const u = (t - 7900) / 1000
477        dots.push(s.isFbMiss ? arc(bx0, PH - 1, pw - 1, 1, 4, u) : arc(bx0, PH - 1, gx + 2, PH - 2, 3, u))
478      } else if (!s.isFbMiss) {
479        // GOAL!
480        s.x = xk
481        const c = t - 8900
482        lift = Math.max(0, Math.round(Math.abs(Math.sin((c / 1000) * Math.PI * 2.4)) * 2))
483        pose.arms = 'up'
484        dots.push({ x: gx + 2 + (Math.floor(c / 300) % 2), y: PH - 1 - (c < 600 ? 1 : 0), color: BALL })
485        labels.push({ x: Math.min(w - 6, right() + 1), row: 1, text: 'GOAL!', color: GOLD })
486        if (tick % 4 < 2) labels.push({ x: cx() - 1, row: 0, text: '✦', color: GOLD })
487        else labels.push({ x: Math.min(w - 1, right() + 6), row: 0, text: '✦', color: GOLD })
488      } else {
489        // over the bar and into the box: oops, run over and fix it
490        const c = t - 8900
491        const fall = Math.min(1, c / 600)
492        dots.push(arc(pw - 1, 1, pw - 6, PH - 1, 0, fall))
493        if (c < 900) {
494          s.x = xk
495          pose.eyes = 'closed'
496          pose.arms = 'up'
497          shift = Math.floor(now / 60) % 2 === 0 ? 1 : -1
498          labels.push({ x: Math.min(w - 6, right() + 1), row: 1, text: 'oops!', color: RED })
499        } else if (c < 1700) {
500          s.x = xk + (maxX - xk) * ease((c - 900) / 800)
501          pose.eyes = 'right'
502          pose.legs = Math.floor(now / 70) % 2 === 0 ? 0 : 1
503        } else {
504          s.x = maxX
505          pose.eyes = 'right'
506          pose.arms = tick % 4 < 2 ? 'waveR' : 'down'
507          labels.push({ x: Math.max(0, cx() - 1), row: 0, text: 'sorry!', color: PINK })
508        }
509        // drive the box: a knock, the mess, then rows coming back one by one
510        s.bumpWant = c < 500 ? { phase: 'hit', step: 0 }
511          : c < 1700 ? { phase: 'scatter', step: Math.floor((c - 500) / 400) }
512          : c < 3000 ? { phase: 'rebuild', step: Math.min(10, Math.floor((c - 1700) / 120)) }
513          : { phase: 'none', step: 0 }
514      }
515    } else if (play === 'dance') {
516      const beat = Math.floor(t / 300)
517      shift = [0, 1, 0, -1][beat % 4] ?? 0
518      pose.arms = beat % 2 === 0 ? 'waveL' : 'waveR'
519      pose.legs = beat % 2 === 0 ? 0 : 1
520      pose.eyes = beat % 4 < 2 ? 'left' : 'right'
521      lift = beat % 2 === 0 ? 1 : 0
522      labels.push(beat % 4 < 2
523        ? { x: cx() - 1, row: beat % 2, text: '♪', color: GOLD }
524        : { x: right() + 1, row: beat % 2, text: '♫', color: GOLD })
525    } else if (play === 'rope') {
526      // the rope swings over the head, then under the feet as it hops
527      const ph = (t % 800) / 800
528      lift = ph > 0.55 && ph < 0.95 ? 2 : 0
529      const oy = PH - SPRITE_H - lift
530      for (let dx = -1; dx <= 12; dx++) {
531        if (ph < 0.5) {
532          const u = (dx - 5.5) / 6.5
533          dots.push({ x: ox + dx, y: Math.max(0, oy + 1 - Math.round(3 * (1 - u * u))), color: ROPE })
534        } else {
535          dots.push({ x: ox + dx, y: PH - 1, color: ROPE })
536        }
537      }
538      if (t > 2400) labels.push({ x: right() + 1, row: 0, text: String(Math.floor(t / 800)), color: DIM })
539    } else if (play === 'butterfly') {
540      // a butterfly flits about; chase it and leap when it comes close
541      const tt = t / 1000
542      const bx = Math.round(Math.max(1, Math.min(pw - 2, pw / 2 + (pw / 2 - 4) * Math.sin(tt * 0.7))))
543      const by = 1 + Math.round(1.2 * Math.sin(tt * 3.1))
544      dots.push({ x: bx, y: by, color: tick % 2 === 0 ? WING_A : WING_B })
545      s.target = Math.max(0, Math.min(maxX, bx - 6))
546      walk(dash(0.6, 15))
547      pose.eyes = bx > ox + 6 ? 'right' : 'left'
548      if (Math.abs(bx - (ox + 6)) < 3 && t % 1600 < 400) {
549        lift = 2
550        pose.arms = 'up'
551      }
552    } else if (play === 'read') {
553      // an open book held in both hands over the lower half: two rows of
554      // pages with the spine in the middle, every cell at most two colors;
555      // the eyes run along a line, jump back, and now and then a page turns
556      const oy = PH - SPRITE_H
557      pose.arms = 'hold'
558      const line = t % 1800
559      pose.eyes = line < 700 ? 'left' : line < 1400 ? 'center' : 'right'
560      for (let y = oy + 2; y <= oy + 3; y++) {
561        for (let x = 2; x <= 9; x++) dots.push({ x: ox + x, y, color: x === 5 || x === 6 ? FOLD : PAGE })
562      }
563      if (t % 5400 > 5000) dots.push({ x: ox + 6, y: oy + 1, color: PAGE }, { x: ox + 7, y: oy + 1, color: PAGE })
564      if (t % 9000 > 7600 && t % 9000 < 8400) labels.push({ x: right(), row: 1, text: '!', color: GOLD })
565    } else if (play === 'visit') {
566      // stroll over to the project box, knock, then lean in and peek
567      s.target = maxX
568      const moving = walk(dash(0.5, 25))
569      if (!moving) {
570        pose.eyes = 'right'
571        if (t % 4000 < 1600) {
572          pose.arms = t % 400 < 200 ? 'waveR' : 'down'
573          labels.push({ x: right(), row: t % 800 < 400 ? 1 : 2, text: 'tok', color: DIM })
574        } else {
575          shift = 1
576          if (t % 4000 > 3400) labels.push({ x: right(), row: 1, text: '?', color: GOLD })
577        }
578      }
579    } else {
580      // bubbles: blow a few and watch them float away
581      pose.arms = 'waveR'
582      pose.eyes = 'right'
583      const glyphs = ['°', 'o', 'O']
584      for (let i = 0; i < 3; i++) {
585        const phase = (t + i * 700) % 2100
586        const step = Math.floor(phase / 700)
587        labels.push({ x: right() + i + step, row: 2 - step, text: glyphs[step] ?? 'o', color: BUBBLE })
588      }
589    }
590  } else if (mode === 'proj') {
591    const ev = s.projEvent
592    if (s.trip.at !== s.projAt) {
593      // plan the run once per event: ~110 px/s, never longer than 2.4 s
594      const to = ev === 'open' || ev === 'pick' || ev === 'show' ? maxX : ev === 'close' ? Math.round(maxX / 2) : s.x
595      const start = s.projAt + (ev === 'close' ? 900 : 0)
596      const dur = Math.min(2400, Math.abs(to - s.x) * 9)
597      s.trip = { at: s.projAt, from: s.x, to, start, dur }
598      s.projUntil = start + dur + PROJ_LEN[ev]
599    }
600    const tr = s.trip
601    const k = tr.dur === 0 ? 1 : Math.min(1, Math.max(0, (now - tr.start) / tr.dur))
602    const moving = now >= tr.start && k < 1
603    if (now >= tr.start) s.x = tr.from + (tr.to - tr.from) * (0.5 - Math.cos(Math.PI * k) / 2)
604    s.target = s.x
605    const t = now - tr.start - tr.dur // since arrival; negative on the way
606    if (moving) {
607      // eased run: quick feet, a little hop, dust behind
608      s.dir = tr.to > tr.from ? 1 : -1
609      pose.eyes = s.dir > 0 ? 'right' : 'left'
610      pose.legs = Math.floor(now / 70) % 2 === 0 ? 0 : 1
611      pose.arms = Math.floor(now / 140) % 2 === 0 ? 'waveL' : 'waveR'
612      lift = Math.floor(now / 140) % 2
613      if (now - s.projAt < 500) labels.push({ x: right(), row: 1, text: '!', color: GOLD })
614      if (Math.floor(now / 120) % 2 === 0) labels.push({ x: s.dir > 0 ? cx() - 1 : right(), row: 3, text: '·', color: DIM })
615    } else if (ev === 'open') {
616      // point at the folder that just opened
617      pose.eyes = 'right'
618      pose.arms = t % 600 < 300 ? 'waveR' : 'down'
619      labels.push({ x: right() + (t % 600 < 300 ? 1 : 0), row: 2, text: '→', color: GOLD })
620    } else if (ev === 'pick') {
621      // open the project: laptop out, type the cd
622      laptop = 3
623      pose.eyes = 'right'
624      pose.arms = tick % 2 === 0 ? 'tapL' : 'tapR'
625      isTapDown = tick % 2 === 0
626      isLit = tick % 3 === 0
627      const cmd = `cd ${s.projArg}`.slice(0, Math.max(3, Math.floor(t / 120)))
628      labels.push({ x: Math.max(0, cx() - 2), row: 0, text: cmd, color: GOLD })
629    } else if (ev === 'close') {
630      pose.arms = 'up'
631      pose.eyes = 'left'
632      labels.push({ x: right(), row: 1, text: 'ok', color: DIM })
633    } else if (ev === 'hide') {
634      pose.eyes = 'right'
635      pose.arms = tick % 4 < 2 ? 'waveR' : 'down'
636      labels.push({ x: right(), row: 1, text: 'bye!', color: GOLD })
637    } else {
638      pose.eyes = 'right'
639      pose.arms = tick % 4 < 2 ? 'waveR' : 'up'
640      lift = t % 600 < 150 ? 1 : 0
641      labels.push({ x: right(), row: 1, text: 'hi!', color: GOLD })
642    }
643  } else {
644    // idle: wander now and then, look around, blink
645    const moving = walk(dash(0.5, 30))
646    if (!moving) {
647      const look = Math.floor(now / 2300) % 5
648      pose.eyes = look === 1 ? 'left' : look === 3 ? 'right' : 'center'
649      if (tick % 70 === 0 && (tick / 70) % 3 === 1) s.target = Math.round(Math.random() * maxX)
650      if (tick % 150 === 75 && now - s.emote.at > 5000) {
651        const r = Math.random()
652        if (r < 0.25) s.emote = { kind: 'sneeze', at: now, arg: '' }
653        else if (r < 0.45) s.emote = { kind: 'hiccup', at: now, arg: '' }
654      }
655    }
656    if (tick % 45 === 0 || tick % 45 === 2) pose.eyes = 'closed'
657  }
658
659  if (now - s.helloAt < 2500) {
660    pose.arms = tick % 4 < 2 ? 'waveL' : 'waveR'
661    const h = hourOf(now)
662    labels.push({ x: right(), row: 1, text: h >= 5 && h < 10 ? 'morning!' : h >= 22 || h < 5 ? 'evening!' : 'hi!', color: GOLD })
663  }
664  if (now - s.wokeAt < 900) {
665    labels.push({ x: right(), row: 1, text: '!', color: GOLD })
666    lift = 1
667    pose.eyes = 'center'
668    pose.squash = false
669  }
670  const em = s.emote
671  const et = now - em.at
672  if (et >= 0 && et < EMOTE_LEN[em.kind]) {
673    const hop = Math.max(0, Math.round(Math.sin((et / 1000) * Math.PI * 2.4) * 2))
674    if (em.kind === 'hello') {
675      pose.arms = tick % 4 < 2 ? 'waveL' : 'waveR'
676      labels.push({ x: right(), row: 1, text: 'szia!', color: GOLD })
677    } else if (em.kind === 'thanks' || em.kind === 'love') {
678      pose.eyes = 'closed'
679      pose.blush = true
680      pose.arms = em.kind === 'love' ? 'up' : 'down'
681      lift = em.kind === 'love' ? hop : 0
682      const k = Math.floor(et / 350)
683      labels.push({ x: right() + (k % 2), row: Math.max(0, 2 - (k % 3)), text: '♥', color: PINK })
684      labels.push({ x: cx() - 1 - (k % 2), row: Math.max(0, 2 - ((k + 1) % 3)), text: '♥', color: PINK })
685      if (em.arg !== '') labels.push({ x: Math.max(0, cx()), row: 0, text: em.arg, color: PINK })
686    } else if (em.kind === 'night') {
687      pose.arms = tick % 4 < 2 ? 'waveR' : 'down'
688      pose.eyes = 'closed'
689      labels.push({ x: right(), row: 1, text: 'night!', color: SLEEPY })
690    } else if (em.kind === 'oops') {
691      // a tool failed: wince and shake
692      shift = Math.floor(now / 60) % 2 === 0 ? 1 : -1
693      pose.eyes = 'closed'
694      pose.arms = 'up'
695      labels.push({ x: right() + 1, row: 1, text: '>_<', color: RED })
696    } else if (em.kind === 'commit') {
697      pose.arms = 'up'
698      lift = hop
699      labels.push({ x: Math.min(w - 8, right() + 1), row: 1, text: 'commit ✓', color: GREEN })
700    } else if (em.kind === 'push') {
701      // a big jump, dust where it left the ground
702      lift = Math.max(0, Math.round(Math.sin((et / EMOTE_LEN.push) * Math.PI) * 3))
703      pose.arms = 'up'
704      labels.push({ x: Math.min(w - 6, right() + 1), row: 1, text: 'push ↑', color: GOLD })
705      if (lift >= 2) labels.push({ x: cx() + 1, row: 3, text: '·  ·', color: DIM })
706    } else if (em.kind === 'combo') {
707      labels.push({ x: right(), row: 0, text: `x${em.arg}!`, color: GOLD })
708      labels.push({ x: tick % 2 === 0 ? cx() - 1 : right(), row: 1, text: '✦', color: GOLD })
709    } else if (em.kind === 'sneeze') {
710      // wind up... and out it comes
711      if (et < 500) {
712        pose.eyes = 'closed'
713        pose.squash = true
714        labels.push({ x: right(), row: 2, text: 'h…', color: DIM })
715      } else {
716        lift = et < 800 ? 1 : 0
717        shift = et < 700 ? -1 : 0
718        labels.push({ x: right(), row: 1, text: 'achoo!', color: GOLD })
719      }
720    } else if (em.kind === 'drained') {
721      // the budget just ran out: a shiver, then it sags
722      shift = et < 900 && Math.floor(now / 70) % 2 === 0 ? 1 : 0
723      pose.eyes = 'closed'
724      pose.body = Math.floor(now / 150) % 2 === 0 ? DRAINED : ORANGE
725      labels.push({ x: right(), row: 1, text: 'uh-oh…', color: RED })
726    } else if (em.kind === 'charged') {
727      // the window reset: a jolt and a happy jump
728      pose.arms = 'up'
729      lift = hop
730      labels.push({ x: Math.max(0, cx() - 1), row: 0, text: '↯', color: YELLOW, isOver: true })
731      labels.push({ x: Math.min(w - 10, right() + 1), row: 1, text: 'recharged!', color: GREEN })
732    } else {
733      lift = et < 200 ? 1 : 0
734      pose.eyes = 'center'
735      labels.push({ x: right(), row: 1, text: 'hic', color: DIM })
736    }
737  }
738  if (isNightAt(now)) pose.cap = true
739  if (now - s.petAt < 2200 && s.petStreak >= 3) {
740    // petted again and again: giggling hops
741    lift = Math.max(lift, Math.round(Math.abs(Math.sin(((now - s.petAt) / 1000) * Math.PI * 3)) * 2))
742    labels.push({ x: Math.max(0, cx()), row: 0, text: 'hehe!', color: PINK })
743  }
744  if (now - s.petAt < 2200) {
745    pose.blush = true
746    const k = Math.floor((now - s.petAt) / 300)
747    labels.push({ x: cx() + 1 + (k % 3), row: Math.max(0, 1 - Math.floor(k / 3)), text: '♥', color: PINK })
748    labels.push({ x: cx() + 4 - (k % 2), row: Math.max(0, 1 - Math.floor(k / 2)), text: '♥', color: PINK })
749    pose.eyes = 'closed'
750    pose.arms = 'up'
751  }
752
753  if (!s.isLimited && s.five >= 75) {
754    // running low on the 5-hour budget: a battery in the corner, red and
755    // blinking past 90%, and at that point the odd sweat drop
756    const left = Math.max(0, 100 - s.five)
757    const bars = left > 17 ? '▰▰▱' : left > 5 ? '▰▱▱' : '▱▱▱'
758    const isLow = s.five >= 90
759    const gauge = `${bars} ${Math.round(left)}%`
760    if (!isLow || Math.floor(now / 700) % 3 !== 0) labels.push({ x: Math.max(0, w - gauge.length), row: 0, text: gauge, color: isLow ? RED : YELLOW })
761    if (isLow && mode !== 'sleep' && now % 5000 < 1100) dots.push({ x: ox + 11, y: PH - SPRITE_H + Math.floor(((now % 5000) / 1100) * 3), color: SWEAT })
762  }
763
764  s.x = Math.max(0, Math.min(maxX, s.x))
765  drawCritter(px, pw, Math.round(s.x) + shift, PH - SPRITE_H - lift, pose)
766  for (const d of dots) if (d.x >= 0 && d.x < pw && d.y >= 0 && d.y < PH) px[d.y * pw + d.x] = d.color
767  if (laptop >= 0) drawLaptop(px, pw, Math.round(s.x), PH - SPRITE_H, laptop, isLit, isTapDown)
768  return { cells: render(w, px, labels), mode }
769}
770
771// Synchronous on purpose: prompt.edit runs on every key within a 50 ms budget,
772// so activity is stamped with the tick's clock (at most one tick old).
773const touch = () => {
774  const now = s.now
775  if (now - s.lastActive > PLAY_MS) s.wokeAt = now
776  s.lastActive = now
777  s.seed = Math.floor(Math.random() * PLAYS.length)
778  return now
779}
780
781export const register: Register = on => {
782  on('session.start', async ($, e, next) => {
783    await $.command.register({ name: 'buddy', description: 'Show or hide the Claude buddy · /buddy limit previews the out-of-budget look' })
784    await $.command.register({ name: 'pet', description: 'Pet the Claude buddy' })
785    s.now = await $.clock.now()
786    s.lastActive = s.now
787    s.helloAt = s.now
788    s.seed = Math.floor(Math.random() * PLAYS.length)
789    const u = await $.session.usage().catch(() => undefined)
790    if (u !== undefined) readFive(u.rateLimits, s.now)
791
792    $.clock.every(FRAME_MS, async () => {
793      s.now = await $.clock.now()
794      if (s.requestId === '' || !(await read($, isShown))) return
795      const { cells } = frame(s.now)
796      const want = `${s.bumpWant.phase}:${s.bumpWant.step}`
797      if (want !== s.bumpSent) {
798        s.bumpSent = want
799        const value = s.bumpWant
800        await update($, bump, () => value)
801      }
802      if (cells === s.lastFrame) return
803      s.lastFrame = cells
804      await $.ui.blit({ requestId: s.requestId, key: 'buddy', cells, columns: s.width, rows: ROWS })
805    })
806    return next(e)
807  })
808
809  on('command.run', { command: 'buddy' }, async ($, e) => {
810    if (e.args.trim() === 'limit') {
811      // a preview of running out of the 5-hour budget: drained for 12 s, then recharged
812      const real = { five: s.five, fiveReset: s.fiveReset }
813      s.isLimited = true
814      s.emote = { kind: 'drained', at: s.now, arg: '' }
815      s.fiveReset = s.now + 12_000
816      $.clock.after(13_000, () => {
817        s.five = real.five
818        s.fiveReset = real.fiveReset
819      })
820      return { text: 'Preview: the buddy runs out of the 5-hour budget, and recharges in 12 s.' }
821    }
822    const shown = await update($, isShown, v => !v)
823    return { text: shown ? 'Claude buddy is back.' : 'Claude buddy hidden. /buddy brings it back.' }
824  })
825  on('command.run', { command: 'pet' }, async $ => {
826    const now = touch()
827    s.petStreak = now - s.petAt < 4000 ? s.petStreak + 1 : 1
828    s.petAt = now
829    // pets are counted across sessions; every tenth is a little party
830    s.pets = Number((await $.store.get('pets')) ?? 0) + 1
831    await $.store.set('pets', s.pets)
832    if (s.pets % 10 === 0) s.emote = { kind: 'love', at: now, arg: `♥ x${s.pets}` }
833    return { text: `♥ (pet #${s.pets})` }
834  })
835
836  on('prompt.edit', async ($, e, next) => {
837    const prev = s.lastKey
838    const now = touch()
839    if (now - prev > 1900) s.typeStart = now
840    s.lastKey = now
841    s.keys += 1
842    const ch = e.inputText.slice(-1)
843    if (ch >= '!' && ch <= '~') {
844      s.typed = [...s.typed.filter(t => now - t.at < 900), { ch, at: now, dx: (s.keys * 5) % 6 }].slice(-4)
845    }
846    return next(e)
847  })
848  on('prompt.submit', async ($, e, next) => {
849    s.submitAt = touch()
850    s.isWorking = true
851    s.tools = 0
852    const greeting = greetingOf(e.text)
853    if (greeting !== undefined) s.emote = { kind: greeting, at: s.submitAt, arg: '' }
854    if (greeting === 'night') s.sleepAfterTurn = true
855    return next(e)
856  })
857  on('tool.call', async ($, e, next) => {
858    s.toolAt = touch()
859    s.tools += 1
860    s.toolName = e.tool.replace(/^mcp__[^_]+(_[^_]+)*__/, '').slice(0, 10)
861    if (COMBOS.includes(s.tools)) s.emote = { kind: 'combo', at: s.toolAt, arg: String(s.tools) }
862    const command = 'command' in e && typeof e.command === 'string' ? e.command : ''
863    const result = await next(e)
864    if ('isError' in result && result.isError === true) {
865      s.emote = { kind: 'oops', at: s.now, arg: '' }
866    } else if ('result' in result && /\bgit\s+push\b/.test(command)) {
867      s.emote = { kind: 'push', at: s.now, arg: '' }
868    } else if ('result' in result && /\bgit\s+commit\b/.test(command)) {
869      s.emote = { kind: 'commit', at: s.now, arg: '' }
870    }
871    return result
872  })
873  on('session.measure', async ($, e, next) => {
874    if (e.changed.includes('rateLimits')) readFive(e.rateLimits, s.now)
875    return next(e)
876  })
877
878  on('turn.complete', async ($, e, next) => {
879    s.isWorking = false
880    if (e.reason === 'error' && s.five >= 90) {
881      // an API error this close to the 5-hour cap: the budget ran out
882      touch()
883      if (!s.isLimited) {
884        s.isLimited = true
885        s.emote = { kind: 'drained', at: s.now, arg: '' }
886      }
887      return next(e)
888    }
889    // an answer came through, so the budget is there (the error was something else)
890    if (e.reason === 'answer' && s.isLimited && s.five < 100) recharge(s.now)
891    s.doneAt = touch()
892    if (s.sleepAfterTurn) {
893      // said good night: celebrate the answer, yawn, then sleep
894      s.sleepAfterTurn = false
895      s.lastActive = s.doneAt - SLEEP_MS + 5500
896    }
897    return next(e)
898  })
899
900  on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
901    if (e.surface !== 'terminal' || e.props.hasSurvey || !(await read($, isShown))) return next(e)
902    const below = await next(e)
903    const { Box, Raster } = $.ui.resolve(e)
904    s.requestId = e.requestId
905    // follow the project box: react to what changed since the last draw, and
906    // stretch the stage up to the box's left edge so the critter can reach it
907    const [cat, pick, hidden, published] = await Promise.all([read($, projCat), read($, projPick), read($, projHidden), read($, projLayout)])
908    // a box that has not published its layout yet: assume its widest closed card
909    const narrow = published.narrow > 0 ? published.narrow : 30
910    const wide = published.wide > 0 ? published.wide : 46
911    const stack = published.stack
912    const cols = e.props.bodyColumns
913    // a half-screen window or a phone over SSH: the box stacks above the band
914    // (project-box), and the critter takes a row of its own above the rest
915    const isNarrow = cols < (stack || narrow + 42)
916    if (s.isProjSeen) {
917      const happen = (ev: ProjEvent, arg = '') => {
918        s.projEvent = ev
919        s.projArg = arg
920        s.projAt = s.now
921      }
922      if (hidden !== s.projHidden) happen(hidden ? 'hide' : 'show')
923      else if (pick !== s.projPick && pick !== '') happen('pick', pick)
924      else if (cat !== s.projCat) happen(cat === '' ? 'close' : 'open', cat)
925    }
926    Object.assign(s, { isProjSeen: true, projCat: cat, projPick: pick, projHidden: hidden, isBoxBeside: !hidden && !isNarrow })
927    const box = !s.isBoxBeside ? 0 : (cat === '' ? narrow : Math.min(wide, Math.max(narrow, cols - 40))) + 2
928    s.width = Math.max(SPRITE_W + 4, cols - box - 1)
929    s.isWorking = s.isWorking || e.props.isWorking
930    const { cells } = frame(s.now)
931    s.lastFrame = cells
932    if (isNarrow) {
933      return (
934        <Box flexDirection="column">
935          <Raster key="buddy" columns={s.width} rows={ROWS} cells={cells} />
936          {below}
937        </Box>
938      )
939    }
940    // The critter floats bottom-left, just above the band's last row (the
941    // status line), so a tall neighbour (a box beside the status bar) never
942    // pushes it up and away, whichever plugin wraps whom. An empty strut keeps
943    // the band tall enough for it; the engine's rows sit bottom-aligned beside.
944    return (
945      <Box flexDirection="row" alignItems="flex-end">
946        <Box width={0} height={ROWS + 1} />
947        <Box flexDirection="column" flexGrow={1} flexShrink={1}>
948          {below}
949        </Box>
950        <Box position="absolute" left={0} bottom={1}>
951          <Raster key="buddy" columns={s.width} rows={ROWS} cells={cells} />
952        </Box>
953      </Box>
954    )
955  })
956}
957
types/index.d.ts 20 lines
1export type Shown = boolean
2/** A shot into the project box: 'hit', 'scatter' (step = frame), 'rebuild' (step 0..10 = rows back). */
3export type Bump = { phase: 'none' | 'hit' | 'scatter' | 'rebuild'; step: number }
4
5declare module 'claude-code' {
6  interface PluginState {
7    'pixel-buddy': {
8      isShown: Shown
9      bump: Bump
10    }
11    // read only: the project box the critter walks up to (project-box)
12    'project-box': {
13      isHidden: boolean
14      openCat: string
15      openProject: string
16      layout: { narrow: number; wide: number; stack: number }
17    }
18  }
19}
20