SLOPSHOPPER

clawd-buddy

Clawd, the Claude Code mascot, dancing above the prompt, with a small buddy at a laptop for each subagent, saying what it is doing

panebandguardcommandtoastprompt
★ 2v0.14.0no licenseupdated 2026-10-22zGreenCat/pet-claudy
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · clawd-buddy
│ ┃ Clawd Invaders ✕ › fix the failing auth test and add an audit log call │ ┃ ▣ client module ./game-client.tsx │ ⏺ 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 │ │ › /clawd-play │ │ * + ▄ ▄ ▄ > < ▄ ▄ ¡listo! ▄ ▝▝ ▘▘ ▄ ⟨Claude Code's own drawing⟩ ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Band
* + ▄ ▄ ▄ > < ▄ ▄ ¡listo! ▄ ▝▝ ▘▘ ▄ ⟨Claude Code's own drawing⟩
Pane · Clawd Invaders
▣ client module ./game-client.tsx
README

clawd-buddy

Clawd, the Claude Code mascot, above the prompt. It reacts to what Claude is doing:

  • quieto: waits, blinks and sways.
  • baila: dances while a turn runs.
  • cocina: tosses code in a pan ("cocinando código").
  • fuma: takes a smoke break now and then when idle.
  • duerme: falls asleep after 3 minutes idle.
  • celebra: cheers with confetti when a turn ends.
  • agentes: each subagent walks out of Clawd with its own laptop, shows what it is doing in a bubble, and walks back in when it finishes.

Clawd Invaders

A small shooter for long tasks. /clawd-play opens a pane (docked beside the transcript in fullscreen from 110 columns, inline above the prompt otherwise) where Clawd flies a ship against waves of bugs. The ship fires on its own; you only steer.

  • ← → or a d: move. Enter or Space: start or resume. p: pause. r or Enter after game over: restart.
  • The pane opens without the keyboard and plays a demo on autopilot. Click it to give it the keyboard and play; Esc hands it back to the prompt. The engine tells the game nothing when a click's keyboard goes back, so twelve seconds without a key, or a resize, pause your game until you click and press a key.
  • The board takes the pane's whole height and at most 44 columns, centered; it needs at least 26 columns and 16 rows. A taller pane brings more rows of bugs, faster bombs and longer drops.
  • Three lives, a short invulnerability after a hit, harder waves. The status line shows whether Claude is working or done.
  • Closing the pane ends the game. The engine decides the pane width and side; the game asks for about a third.

Install

In a Claude Code terminal session:

/plugin install clawd-buddy --marketplace zGreenCat/pet-claudy

Answer y to add the marketplace, then pick a scope (user, to have it in every session).

Preview

See every mood without running a session (Node 23.6 or newer):

node scripts/preview.ts ?        # list the moods
node scripts/preview.ts cocina   # play one
node scripts/preview.ts todos    # play them in turn

Develop

Clawd shares the area above the prompt with other plugins, including image-preview. It preserves their rendered content and reserves four rows for its scene when passing the remaining row budget along. With fewer than four available rows or a survey, Clawd steps aside.

claude plugin validate .
claude plugin test .

The hooks module is hooks/register.tsx; the poses are in hooks/clawd.ts and the subagent scene in hooks/desks.ts.

Source 9 files
hooks/register.tsx 284 lines
1import { atom, read, update } from 'claude-code'
2import type { AgentStatus, Register } from 'claude-code'
3
4import type { Tick } from '../types'
5import {
6  CELEBRATE_TICKS,
7  ERRORS_TO_DIZZY,
8  READING_LINGER_TICKS,
9  READS_TO_START,
10  READS_WINDOW_TICKS,
11  SUPER_WINDOW_TICKS,
12  TICK_MS,
13  WIDTH,
14  cueOf,
15  isRead,
16  isThanks,
17  view,
18  viewKey,
19} from './clawd'
20import type { Frame, Moment, Mood } from './clawd'
21import { START_X, describe, oneLine, scene, solo, summary, walk } from './desks'
22import type { Agent, Segment } from './desks'
23import { registerGame, registerGameCommand, trackPrompt, trackTurn } from './game-register'
24import { registerMoodCommand, registerMoods } from './mood-register'
25
26// The view key last drawn. The timer only writes it when what Clawd shows
27// changes, so a still Clawd costs no redraws.
28const tick = atom({ plugin: 'clawd-buddy', key: 'tick' } as const, 0 as Tick)
29
30// What a finished agent's buddy says when its loop ended without a SubagentStop
31const ENDED: Partial<Record<AgentStatus, string>> = { completed: 'listo', failed: '✗ falló', killed: '✗ detenido' }
32// Ticks between checks of the agent list, and how old an agent must be to be checked
33const RECONCILE_TICKS = 8
34// Failed ticks before Clawd says so, once a session: one alone is let pass
35const FAILURES_TO_REPORT = 5
36
37export const register: Register = (on, options) => {
38  registerGame(on, options)
39  registerMoods(on, options)
40
41  // Module state: the clock, and what the last draw saw of the band
42  let t = 0
43  let idleTicks = 0
44  let isWorking = false
45  let bodyColumns = 80
46  let lastKey = ''
47  // The tick the main loop's last turn ended; far back, so none to celebrate
48  let finishedAt = -CELEBRATE_TICKS
49  // The subagents at their desks, in seat order
50  let agents: Agent[] = []
51  let failures = 0
52  // The moment Clawd is having and the tick it began
53  let cue: { mood: Mood; at: number } | undefined
54
55  const now = (): Moment | undefined => (cue ? { mood: cue.mood, since: t - cue.at } : undefined)
56  // The ticks of the main loop's recent reads, and the tick it sat down to read
57  let reads: number[] = []
58  let readingFrom: number | undefined
59  const readingFor = () => (readingFrom === undefined ? undefined : t - readingFrom)
60  // Commands the main loop has running, and the tick the first of them began
61  let running = 0
62  let runningFrom: number | undefined
63  const runningFor = () => (runningFrom === undefined ? undefined : t - runningFrom)
64  // The ticks recent subagents were spawned
65  let spawns: number[] = []
66  // The main loop's tool calls that failed in a row
67  let errors = 0
68
69  const isBusy = () => isWorking || agents.some(a => a.doneAt === undefined)
70
71  function drawKey(): string {
72    if (agents.length === 0) {
73      return viewKey(view(t, idleTicks, isWorking, bodyColumns, t - finishedAt, now(), readingFor(), runningFor()))
74    }
75    return `T${JSON.stringify(desksScene())}`
76  }
77
78  function soloScene(): Segment[][] {
79    const v = view(t, idleTicks, isWorking, bodyColumns, t - finishedAt, now(), readingFor(), runningFor())
80    return solo(v.frame, v.marks, v.x, v.line, v.isWorking, bodyColumns)
81  }
82
83  function desksScene() {
84    // Clawd alone, not what it holds: the desks start right beside it
85    const frame = view(t, idleTicks, isBusy(), bodyColumns, undefined, now()).frame.map(r => r.slice(0, WIDTH)) as Frame
86    return scene(t, agents, frame, isWorking ? 'dirigiendo' : 'esperando', bodyColumns)
87  }
88
89  function seat(id: string, type: string, task: string) {
90    if (!agents.some(a => a.id === id)) {
91      agents = [...agents, { id, type, activity: task, x: START_X, bornAt: t }]
92    }
93  }
94
95  function finish(id: string, result: string) {
96    agents = agents.map(a => (a.id === id && a.doneAt === undefined ? { ...a, doneAt: t, result } : a))
97  }
98
99  on('session.start', async ($, e, next) => {
100    // The clock must outlive a bad tick: a period that fails would end the
101    // interval, and Clawd would freeze on whatever it last drew
102    $.clock.every(TICK_MS, async () => {
103      try {
104        t += 1
105        idleTicks = isBusy() ? 0 : idleTicks + 1
106        if (readingFrom !== undefined && t - (reads[reads.length - 1] ?? t) > READING_LINGER_TICKS) readingFrom = undefined
107        agents = walk(agents, t, bodyColumns)
108
109        // An agent whose loop ended without a SubagentStop still leaves its desk
110        const waiting = agents.filter(a => a.doneAt === undefined && t - a.bornAt >= RECONCILE_TICKS)
111        if (waiting.length > 0 && t % RECONCILE_TICKS === 0) {
112          const list = await $.agent.list()
113          for (const a of waiting) {
114            const info = list.find(i => i.id === a.id)
115            if (!info) finish(a.id, 'listo')
116            else if (ENDED[info.status]) {
117              finish(a.id, ENDED[info.status]!)
118              // A subagent that failed or was stopped leaves Clawd dizzy
119              if (info.status !== 'completed') cue = { mood: 'dizzy', at: t }
120            }
121          }
122        }
123
124        const key = drawKey()
125        if (key !== lastKey) {
126          lastKey = key
127          await update($, tick, n => n + 1)
128        }
129      } catch (err) {
130        // The next tick draws again; a run of failures is said, not hidden
131        failures += 1
132        if (failures === FAILURES_TO_REPORT) {
133          const reason = err instanceof Error ? err.message : String(err)
134          $.ui.toast(`clawd-buddy: el reloj está fallando (${reason})`)
135        }
136      }
137    })
138
139    try {
140      await registerGameCommand($)
141    } catch (err) {
142      const reason = err instanceof Error ? err.message : String(err)
143      $.ui.toast(`clawd-buddy: /clawd-play no está disponible (${reason})`)
144    }
145    try {
146      await registerMoodCommand($)
147    } catch (err) {
148      const reason = err instanceof Error ? err.message : String(err)
149      $.ui.toast(`clawd-buddy: /clawd-mood no está disponible (${reason})`)
150    }
151
152    return next(e)
153  })
154
155  // These hooks only watch: one that fails passes the event on untouched
156  // (a `next` already called replays its answer)
157
158  // A subagent sits down when it starts, its task as its first words. Only the
159  // spawn seats one: SubagentStart can fire for loops no agent list names
160  // (a workflow's), which the check of the list would send off as done
161  on('agent.spawn', async ($, e, next) => {
162    const started = await next(e)
163    if (started.agentId && !e.workflow) {
164      seat(started.agentId, e.subagentType, oneLine(e.description))
165      // Two or more at once: Clawd suits up
166      spawns = [...spawns.filter(s => t - s < SUPER_WINDOW_TICKS), t]
167      if (spawns.length >= 2 && cue?.mood !== 'super') cue = { mood: 'super', at: t }
168    }
169    return started
170  }).catch(($, e, next) => next(e))
171
172  // Its bubble follows its tool calls; a call that went well can give Clawd a
173  // moment (passing tests, a commit, a plan)
174  on('tool.call', async ($, e, next) => {
175    const input = e as unknown as Record<string, unknown>
176    const a = e.agentId === undefined ? undefined : agents.find(x => x.id === e.agentId)
177    if (a && a.doneAt === undefined) {
178      const activity = describe(e.tool, input)
179      agents = agents.map(x => (x === a ? { ...x, activity } : x))
180    }
181    // The main loop reading one thing after another sits down to read
182    if (e.agentId === undefined && isRead(e.tool)) {
183      reads = [...reads.filter(r => t - r < READS_WINDOW_TICKS), t]
184      if (readingFrom === undefined && reads.length >= READS_TO_START) readingFrom = t
185    }
186    // While the main loop waits on a command, the headphones go on
187    const isCommand = e.agentId === undefined && e.tool === 'Bash'
188    if (isCommand) {
189      running += 1
190      runningFrom ??= t
191    }
192    let answer
193    try {
194      answer = await next(e)
195    } finally {
196      if (isCommand) {
197        running -= 1
198        if (running === 0) runningFrom = undefined
199      }
200    }
201    const isOk = answer.deny === undefined && answer.isError !== true
202    const mood = cueOf(e.tool, input, isOk)
203    if (mood) cue = { mood, at: t }
204    // Failure after failure leaves it dizzy
205    if (e.agentId === undefined) {
206      errors = isOk ? 0 : errors + 1
207      if (errors === ERRORS_TO_DIZZY) cue = { mood: 'dizzy', at: t }
208    }
209    return answer
210  }).catch(($, e, next) => next(e))
211
212  // A turn of the main loop that answered: Clawd cheers; a new prompt cuts it short
213  on('turn.complete', async ($, e, next) => {
214    if (e.agentId === undefined && e.reason === 'answer') {
215      finishedAt = t
216      isWorking = false
217      idleTicks = 0
218      reads = []
219      readingFrom = undefined
220    }
221    await trackTurn($, e)
222    return next(e)
223  }).catch(($, e, next) => next(e))
224
225  on('prompt.submit', async ($, e, next) => {
226    finishedAt = -CELEBRATE_TICKS
227    cue = isThanks(e.text) ? { mood: 'love', at: t } : undefined
228    await trackPrompt($, e)
229    return next(e)
230  }).catch(($, e, next) => next(e))
231
232  on('classic.SubagentStop', ($, e, next) => {
233    finish(e.agent_id, summary(e.last_assistant_message))
234    return next(e)
235  }).catch(($, e, next) => next(e))
236
237  on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
238    if (e.props.hasSurvey || e.props.maxRows < 4) {
239      return next(e)
240    }
241
242    // AbovePrompt is shared. Keep the rest of the render chain alive and
243    // give downstream plugins the space left after our four-row scene.
244    const below = await next({ ...e, props: { ...e.props, maxRows: e.props.maxRows - 4 } })
245
246    // Read so a write of the key redraws this band
247    await read($, tick)
248    if (e.props.isWorking) idleTicks = 0
249    isWorking = e.props.isWorking
250    bodyColumns = e.props.bodyColumns
251
252    const { Box, Text } = $.ui.resolve(e)
253    lastKey = drawKey()
254
255    const rows = agents.length > 0 ? desksScene() : soloScene()
256
257    return (
258      <Box flexDirection="column">
259        {rows.map((row, i) => (
260          <Text key={`r${i}`} wrap="truncate">
261            {row.map(({ text, style }, j) =>
262              Object.keys(style).length === 0 ? (
263                text
264              ) : (
265                <Text
266                  key={`s${j}`}
267                  {...(style.bg ? { backgroundColor: style.bg } : {})}
268                  {...(style.fg ? { color: style.fg } : {})}
269                  {...(style.dim ? { dimColor: true } : {})}
270                  {...(style.italic ? { italic: true } : {})}
271                  {...(style.bold ? { bold: true } : {})}
272                >
273                  {text}
274                </Text>
275              ),
276            )}
277          </Text>
278        ))}
279        {below}
280      </Box>
281    )
282  })
283}
284
hooks/clawd.ts 487 lines
1// Clawd's poses: dancing, cooking code in a pan, a smoke break, asleep.
2// Pure functions of the tick, so the timer can tell whether the drawing
3// changed and the tests can drive it.
4
5import type { Mark } from './desks'
6
7export const TICK_MS = 250
8export const WIDTH = 8
9// After this long idle Clawd falls asleep and stops animating
10export const SLEEP_AFTER_TICKS = (3 * 60 * 1000) / TICK_MS
11// Idle this long, Clawd takes a smoke break now and then: the last
12// SMOKE_TICKS of every SMOKE_EVERY
13const SMOKE_FROM_TICKS = 60
14const SMOKE_EVERY = 240
15const SMOKE_TICKS = 40
16
17// Clawd as the Claude Code logo draws it: a square body, an eye in each upper
18// corner, short arms at the chest and two pairs of legs at its sides. Three
19// rows, each WIDTH cells; the body is painted with the cell's background
20// rather than block glyphs, which leave a dark seam between rows in fonts
21// whose glyphs don't fill the line height. Only the thin parts (arms, legs)
22// are glyphs, half a cell or a quarter.
23//   O  orange cell
24//   L  orange cell, a dark eye in its lower left quarter; R the lower right
25//   -  orange cell with a closed eye (▁)
26//   > <  eyes squeezed with joy; ┓ ┏ half shut, at ease.
27//   s  sunglasses' band, the cell's lower half; S a lens, its upper half;
28//      l and r a lens's inner edge, the upper left or right quarter
29//   p  an eye looking up (°); w an eye wide open (●); @ an eye spinning, dizzy
30//   y z  a leg sticking up, upside down, left or right
31//   m  an eye shut tight (━), for a face sunk half a cell
32//   1 2 3  a book held low at its side, in front of its arm and body: a small light L of pages (1 their top,
33//        2 their edge with the cover's spine beside it) inside the long blue
34//        L of its cover (3); 4 a page turning. Over the body, the pages'
35//        top (5) and a turning page (6) keep the orange behind them
36//   n  a red collar along the top of the body; u a red cape showing below
37//      the body, hanging half a cell past its legs; j J a leg in front of it,
38//      left or right; k K the cape's edge stepping out a quarter, left or
39//      right; e the cape blown up between the legs, its upper half
40//   x X  a square mug, one cell high and two wide, coffee in the middle of
41//        its top row; N its handle, toward Clawd
42//   [ ]  a headphone's ear cup, left or right
43//        Each eye is ASCII or a box-drawing glyph: terminals draw those
44//        themselves, so they read the same whatever the font
45//   ^  an arm at rest, the cell's upper half; v an arm raised, its lower half
46//   a  a leg in the cell's upper left quarter; b the upper right
47//   .  empty
48// What it holds runs on past WIDTH: h a pan's handle, P the pan, c a
49// cigarette, C its ember, Y the ember drawn on.
50const HEAD = '.OLOORO.'
51const HEAD_BLINK = '.O-OO-O.'
52const HEAD_ARMS_UP = 'vOLOOROv'
53const BODY = '^OOOOOO^'
54const BODY_ARMS_UP = '.OOOOOO.'
55const LEGS = '.aa..bb.'
56// The legs shuffled inward, still under the body
57const LEGS_STEP = '.bb..aa.'
58// The right pair tapping: one leg in, one out
59const LEGS_TAP = '.aa..ab.'
60// An arm out to a pan
61const BODY_PAN = '^OOOOOO^hhPPPP'
62// A thin cigarette at the mouth, its ember dim, then drawn on with the eyes shut
63const HEAD_SMOKE = '.O┓OO┏OcccC'
64const HEAD_DRAW = '.O-OO-OcccY'
65// Cheering: eyes squeezed with joy, the arms going up and down
66const HEAD_CHEER = 'vO>OO<Ov'
67const HEAD_JOY = '.O>OO<O.'
68// Cool: one arm lifts a little, sweeps down over the face, and the glasses
69// are on: a dark band across the face and two wide lenses below it
70const HEAD_ARM_LIFTED = '.OLOOROv'
71const BODY_ARM_LIFTED = '^OOOOOO.'
72const HEAD_COOL_SWEEP = '.ssssssv'
73const BODY_COOL_SWEEP = '^OSlrSO.'
74const HEAD_COOL = '.ssssss.'
75const BODY_COOL = '^OSlrSO^'
76// Love: a deep breath, the head sinking half a cell over legs that stay put,
77// eyes shut; then eyes squeezed with joy. The rows run on blank past Clawd to
78// leave room for the heart beside it
79const ROOM = '.....'
80const HEAD_BREATH = '.vvvvvv.' + ROOM
81const BODY_BREATH = 'vOmOOmOv' + ROOM
82// Reading: a book held low at its side, in front of its arm and body, and
83// its eyes on it
84const HEAD_READ = '.OROORO.'
85const BODY_BOOK_OPEN = '^OOOOO52'
86const BODY_BOOK_TURN = '^OOOOO62'
87const LEGS_BOOK = '.aa..b33'
88// Super Clawd: a collar, and a cape behind it showing below its body and
89// hanging past its legs, its edges stepping out a little; then a fist up
90// while the cape flaps in a wave. Each column of it either hangs down or is
91// blown up: between the legs it shows its upper half, behind a leg it hides
92const BODY_SUPER = '^nnnnnn^'
93const BODY_SUPER_FIST = '^nnnnnn.'
94const CAPE_DOWN = 'kjjuuJJK'
95const CAPE_UP = 'kaaeebbK'
96// A coffee break: a square mug in hand, the coffee showing in the middle of
97// its top row, lifted to the mouth for a sip, eyes shut
98const BODY_MUG = '^OOOOOO^NxX'
99const HEAD_SIP = '.O-OO-OvNxX'
100// Music: headphones on, the cups at its sides and the band arching clear of
101// its head; eyes shut, a foot tapping
102const HEAD_MUSIC = '[OmOOmO]'
103// Magic: the rows run on blank past Clawd, room for the wand and its sparks
104const SPELL_ROOM = '............'
105// An idea: eyes up at the bulb, then wide open at the thought
106const HEAD_LOOK_UP = '.OpOOpO.'
107const HEAD_WIDE = '.OwOOwO.'
108// Dizzy: eyes spinning; losing its balance, sunk half a cell; then fallen
109// upside down, legs kicking in the air and its head on the ground
110const HEAD_DIZZY = '.O@OO@O.'
111const BODY_SINKING = 'vO@OO@Ov'
112const FALLEN: Frame = ['.yy..zz.', 'vOOOOOOv', HEAD_DIZZY]
113const FALLEN_KICK: Frame = ['.zz..yy.', 'vOOOOOOv', HEAD_DIZZY]
114
115export type Frame = [string, string, string]
116
117const DANCE: Frame[] = [
118  [HEAD, BODY, LEGS],
119  [HEAD_ARMS_UP, BODY_ARMS_UP, LEGS_STEP],
120  [HEAD, BODY, LEGS_STEP],
121  [HEAD_ARMS_UP, BODY_ARMS_UP, LEGS],
122  [HEAD_ARMS_UP, BODY_ARMS_UP, LEGS_STEP],
123  [HEAD, BODY, LEGS],
124]
125
126const IDLE: Frame = [HEAD, BODY, LEGS]
127const BLINK: Frame = [HEAD_BLINK, BODY, LEGS]
128const COOK: Frame = [HEAD, BODY_PAN, LEGS]
129
130const FOOD = ['{}', '()', '<>', '[]']
131const FOOD_COLOR = '#F2C14E'
132const PAN_COLOR = '#6B7280'
133const SMOKE_COLOR = '#B8BCC4'
134// The food's row over a toss: in the pan, up in the air, back down
135const TOSS = [2, 2, 1, 0, 0, 1, 2, 2]
136// A puff's way up from the ember, a cell or two to the right each step
137const PUFF: Mark[] = [
138  { row: 1, x: 12, text: '·', fg: SMOKE_COLOR },
139  { row: 0, x: 11, text: '∘', fg: SMOKE_COLOR },
140  { row: 0, x: 12, text: 'o', fg: SMOKE_COLOR },
141  { row: 0, x: 14, text: '°', fg: SMOKE_COLOR },
142]
143
144const WORKING_LINES = ['pensando', 'trabajando', 'bailando', 'cocinando código']
145const IDLE_LINES = ['esperándote', 'listo', 'aquí estoy']
146
147// Back and forth across `span` cells
148function bounce(t: number, span: number): number {
149  if (span <= 0) return 0
150  const period = span * 2
151  const p = t % period
152  return p < span ? p : period - p
153}
154
155// Where a working Clawd `width` cells wide stands at tick `t`: one cell every
156// other tick, back and forth within the band
157function walked(t: number, width: number, bodyColumns: number): number {
158  return bounce(Math.floor(t / 2), Math.min(40, bodyColumns - width - 22))
159}
160
161export type View = { frame: Frame; marks: Mark[]; x: number; line: string; isWorking: boolean }
162
163// Tossing code in a pan: the food flies up and lands, sizzling in between
164function cooking(t: number): { frame: Frame; marks: Mark[] } {
165  const row = TOSS[t % TOSS.length]!
166  const food = FOOD[Math.floor(t / TOSS.length) % FOOD.length]!
167  const marks: Mark[] = [{ row, x: 11, text: food, fg: FOOD_COLOR, ...(row === 2 ? { bg: PAN_COLOR } : {}) }]
168  if (row === 2) marks.push({ row: 1, x: t % 2 ? 10 : 13, text: '~', fg: SMOKE_COLOR })
169  return { frame: COOK, marks }
170}
171
172// A turn is done: Clawd cheers this many ticks, then settles back
173export const CELEBRATE_TICKS = 28
174const SPARKLE = '#F2C14E'
175const CONFETTI = [
176  { x: 19, ch: '▄', fg: '#E58FD0' },
177  { x: 22, ch: '▄', fg: '#F2C14E' },
178  { x: 25, ch: '▄', fg: '#7FD1E8' },
179  { x: 28, ch: '▄', fg: '#8DB360' },
180  { x: 31, ch: '▄', fg: '#E07A5F' },
181  { x: 34, ch: '▄', fg: '#6A9BCC' },
182]
183
184// Cheering at a finished turn: hopping with arms up, sparkles over its head and
185// confetti falling beside it, then standing still with the check
186function celebrating(since: number): { frame: Frame; marks: Mark[]; line: string } {
187  const isUp = since % 4 < 2
188  const isSettling = since >= CELEBRATE_TICKS - 8
189  if (isSettling) return { frame: IDLE, marks: [], line: '✓ listo' }
190  const marks: Mark[] = [
191    { row: 0, x: 0, text: isUp ? '*' : '+', fg: SPARKLE },
192    { row: 0, x: 7, text: isUp ? '+' : '*', fg: SPARKLE },
193  ]
194  // Each piece falls one row a tick and starts over from above the band
195  CONFETTI.forEach((c, k) => {
196    const row = (since + k * 3) % 5
197    if (row < 4) marks.push({ row, x: c.x, text: c.ch, fg: c.fg })
198  })
199  const frame: Frame = isUp ? [HEAD_CHEER, BODY_ARMS_UP, LEGS_STEP] : [HEAD_JOY, BODY, LEGS]
200  return { frame, marks, line: '¡listo!' }
201}
202
203// A smoke break: a draw every two seconds, two puffs on their way up
204function smoking(t: number): { frame: Frame; marks: Mark[] } {
205  const isDrawing = t % 8 < 2
206  const marks = [0, 4].map(k => PUFF[Math.floor(((t + k) % 8) / 2)]!)
207  return { frame: [isDrawing ? HEAD_DRAW : HEAD_SMOKE, BODY, LEGS], marks }
208}
209
210// A moment: something went well, someone said thanks, a plan came together.
211// It shows for a few seconds over whatever Clawd was doing, then lets go
212export type Mood = 'cool' | 'love' | 'idea' | 'magic' | 'super' | 'dizzy'
213export type Moment = { mood: Mood; since: number }
214export const MOMENT_TICKS: Record<Mood, number> = { cool: 24, love: 20, idea: 16, magic: 16, super: 24, dizzy: 32 }
215const HEART = '#E5484D'
216const BULB = '#F2C14E'
217// A wooden wand with a white tip
218const WAND = '#A07A5A'
219const WAND_TIP = '#FFFFFF'
220const STEAM = '#B8BCC4'
221
222const PHONES = '#2E6FD0'
223// Notes off the headphones, drawn in quarter blocks: a head and a stem
224const NOTE = '▟'
225const NOTE_COLORS = ['#7FD1E8', '#E58FD0']
226// Sparks a flicked wand throws: where each starts past the wand's tip and its
227// color; they drift away and twinkle
228const SPARKS = [
229  { row: 1, dx: 0, text: '*', fg: '#F2C14E' },
230  { row: 0, dx: 2, text: '+', fg: '#F2C14E' },
231  { row: 2, dx: 3, text: '*', fg: '#E58FD0' },
232  { row: 3, dx: 1, text: '·', fg: '#F2C14E' },
233  { row: 1, dx: 5, text: '·', fg: '#7FD1E8' },
234]
235const BULB_OFF = '#B8BCC4'
236
237// A cell's quarters as a glyph, by the quarters lit: 1 upper left, 2 upper
238// right, 4 lower left, 8 lower right
239const QUARTERS = ' ▘▝▀▖▌▞▛▗▚▐▜▄▙▟█'
240
241// A picture in quarter blocks: two pixel rows and two pixel columns to a
242// cell, X lit; each row of cells is a mark's text
243function quarters(pixels: string[]): string[] {
244  const rows: string[] = []
245  for (let r = 0; r < pixels.length; r += 2) {
246    let row = ''
247    const width = Math.max(...pixels.map(p => p.length))
248    for (let c = 0; c < width; c += 2) {
249      const lit = [pixels[r]?.[c], pixels[r]?.[c + 1], pixels[r + 1]?.[c], pixels[r + 1]?.[c + 1]]
250      row += QUARTERS[lit.reduce((m, p, k) => (p === 'X' ? m | (1 << k) : m), 0)]
251    }
252    rows.push(row)
253  }
254  return rows
255}
256
257// A big heart, Clawd's height, and the same heart a beat smaller
258const HEART_BIG = quarters(['.XX.XX..', 'XXXXXXX.', 'XXXXXXX.', '.XXXXX..', '..XXX...', '...X....'])
259const HEART_SMALL = quarters(['........', '.XX.XX..', '.XXXXX..', '..XXX...', '...X....', '........'])
260const HEART_X = 9
261
262function heart(picture: string[]): Mark[] {
263  return picture.map((text, i) => ({ row: 1 + i, x: HEART_X, text, fg: HEART }))
264}
265
266// Each moment is a short scene Clawd acts out
267function moment(m: Moment): { frame: Frame; marks: Mark[]; line: string; dx?: number } {
268  const s = m.since
269  switch (m.mood) {
270    case 'cool':
271      // An arm lifts a little, sweeps down over the face, and the glasses are
272      // on; then it taps a foot
273      if (s < 3) return { frame: [HEAD_ARM_LIFTED, BODY_ARM_LIFTED, LEGS], marks: [], line: 'momento…' }
274      if (s < 5) return { frame: [HEAD_COOL_SWEEP, BODY_COOL_SWEEP, LEGS], marks: [], line: 'momento…' }
275      return { frame: [HEAD_COOL, BODY_COOL, s % 8 < 4 ? LEGS : LEGS_TAP], marks: [], line: 'todo en verde' }
276    case 'love': {
277      // It stays put: a deep breath with its eyes shut, then eyes squeezed
278      // with joy while a heart pops up beside it and beats
279      if (s < 2) return { frame: [HEAD + ROOM, BODY, LEGS], marks: [], line: '…' }
280      if (s < 6) return { frame: [HEAD_BREATH, BODY_BREATH, LEGS], marks: [], line: '…' }
281      const head: Frame = [HEAD_JOY + ROOM, BODY, LEGS]
282      if (s < 8) return { frame: head, marks: [{ row: 2, x: HEART_X + 1, text: '♥', fg: HEART }], line: '¡de nada!' }
283      return { frame: head, marks: heart(s % 4 < 2 ? HEART_BIG : HEART_SMALL), line: '¡de nada!' }
284    }
285    case 'idea': {
286      // The bulb shows up dim; it looks up at it and the bulb lights; then it
287      // looks ahead with its eyes wide at the thought, the rays coming and going
288      const isLit = s >= 4
289      const bulb: Mark = { row: 0, x: 4, text: '●', fg: isLit ? BULB : BULB_OFF }
290      const rays: Mark[] = s >= 6 && (s - 6) % 4 < 2 ? [{ row: 0, x: 3, text: '\\', fg: BULB }, { row: 0, x: 5, text: '/', fg: BULB }] : []
291      if (s < 2) return { frame: IDLE, marks: [bulb], line: 'mmm…' }
292      if (s < 6) return { frame: [HEAD_LOOK_UP, BODY, LEGS], marks: [bulb], line: isLit ? '¡oh!' : 'mmm…' }
293      return { frame: [s < 10 ? HEAD_WIDE : HEAD, BODY, LEGS], marks: [bulb, ...rays], line: '¡idea!' }
294    }
295    case 'magic': {
296      // An arm lifts the wand, its tip glints; a flick down, eyes squeezed,
297      // and sparks fly off the tip and drift away twinkling
298      const room = (frame: Frame): Frame => [frame[0] + SPELL_ROOM, frame[1] + SPELL_ROOM, frame[2] + SPELL_ROOM]
299      // As thin as the cigarette, a quarter of a cell: two cells up from the
300      // hand, then three along the arm, the last one its white tip
301      const wandUp: Mark[] = [
302        { row: 1, x: 8, text: '▎', fg: WAND },
303        { row: 0, x: 8, text: '▎', fg: WAND_TIP },
304      ]
305      if (s < 2) return { frame: room([HEAD_ARM_LIFTED, BODY_ARM_LIFTED, LEGS]), marks: wandUp, line: 'abra…' }
306      if (s < 4) {
307        return { frame: room([HEAD_ARM_LIFTED, BODY_ARM_LIFTED, LEGS]), marks: [...wandUp, { row: 0, x: 9, text: '*', fg: BULB }], line: 'abra…' }
308      }
309      const wand: Mark[] = [
310        { row: 1, x: 8, text: '▂▂', fg: WAND },
311        { row: 1, x: 10, text: '▂', fg: WAND_TIP },
312      ]
313      const drift = Math.floor((s - 4) / 3)
314      const sparks = SPARKS.filter((_, k) => (s + k) % 3 !== 0).map(p => ({ row: p.row, x: 12 + p.dx + drift, text: p.text, fg: p.fg }))
315      if (s < 6) return { frame: room([HEAD_JOY, BODY, LEGS]), marks: [...wand, ...sparks], line: '¡cadabra!' }
316      return { frame: room(IDLE), marks: [...wand, ...sparks], line: '¡magia!' }
317    }
318    case 'super':
319      // The cape and collar come on; then a fist goes up and the cape flaps
320      if (s < 4) return { frame: [HEAD, BODY_SUPER, CAPE_DOWN], marks: [], line: '¡súper!' }
321      return { frame: [HEAD_ARM_LIFTED, BODY_SUPER_FIST, capeWave(Math.floor(s / 2))], marks: [], line: '¡súper Clawd!' }
322    case 'dizzy': {
323      // A start, eyes wide; then eyes spinning while it sways side to side
324      // under circling stars; it loses its balance and falls upside down, legs
325      // kicking; then it gets up, blinks, and shakes it off
326      const stars: Mark[] = [
327        { row: 0, x: 1 + (s % 6), text: '*', fg: BULB },
328        { row: 0, x: 1 + ((s + 3) % 6), text: '·', fg: BULB },
329      ]
330      if (s < 2) return { frame: [HEAD_WIDE, BODY, LEGS], marks: [], line: '¿eh?' }
331      if (s < 12) {
332        const sway = Math.floor(s / 2) % 2
333        return { frame: [HEAD_DIZZY, BODY, sway ? LEGS_STEP : LEGS], marks: stars, line: 'mareado…', dx: sway }
334      }
335      if (s < 14) return { frame: [HEAD_BREATH.slice(0, 8), BODY_SINKING, LEGS], marks: stars, line: '¡uy!', dx: 1 }
336      if (s < 24) return { frame: (s - 14) % 4 < 2 ? FALLEN : FALLEN_KICK, marks: stars, line: 'ay…' }
337      if (s < 28) return { frame: [s < 26 ? HEAD_BLINK : HEAD, BODY, LEGS], marks: [], line: 'uf…', dx: s % 2 }
338      return { frame: IDLE, marks: [], line: 'uf…' }
339    }
340  }
341}
342
343// Reading, `since` ticks into it: its eyes on the book, a blink now and then,
344// and every so often a page turns
345function reading(since: number): { frame: Frame; marks: Mark[]; line: string } {
346  const head = since % 16 === 11 ? HEAD_BLINK : HEAD_READ
347  const body = since % 16 >= 14 ? BODY_BOOK_TURN : BODY_BOOK_OPEN
348  return { frame: [head, body, LEGS_BOOK], marks: [], line: 'leyendo…' }
349}
350
351// The cape in a wave, `phase` steps along: each column hangs down or is blown
352// up, in runs of two that travel across it
353function capeWave(phase: number): string {
354  return [...CAPE_DOWN].map((down, c) => ((c + phase) % 4 < 2 ? down : CAPE_UP[c]!)).join('')
355}
356
357// Headphones on while a long command runs: the band over its head, notes
358// drifting up off it, and a foot tapping to the beat
359function listening(since: number): { frame: Frame; marks: Mark[]; line: string } {
360  const band: Mark = { row: 0, x: 0, text: '╭──────╮', fg: PHONES }
361  const k = Math.floor(since / 4)
362  const note: Mark = { row: since % 4 < 2 ? 1 : 0, x: 9 + (since % 4 < 2 ? 0 : 1) + (k % 2) * 2, text: NOTE, fg: NOTE_COLORS[k % NOTE_COLORS.length]! }
363  return { frame: [HEAD_MUSIC, BODY, since % 4 < 2 ? LEGS : LEGS_TAP], marks: [band, note], line: 'musiquita…' }
364}
365
366// A coffee break: steam curling up off the mug, and every so often a sip
367function coffee(t: number): { frame: Frame; marks: Mark[] } {
368  if (t % 16 < 3) return { frame: [HEAD_SIP, BODY_ARM_LIFTED, LEGS], marks: [] }
369  const marks: Mark[] = [{ row: 1, x: t % 4 < 2 ? 9 : 10, text: '~', fg: STEAM }]
370  return { frame: [HEAD, BODY_MUG, LEGS], marks }
371}
372
373// Which break an idle Clawd is on: they take turns, a smoke then a coffee
374function isCoffeeBreak(idleTicks: number): boolean {
375  return Math.floor(idleTicks / SMOKE_EVERY) % 2 === 1
376}
377
378// Tools that read: enough of them in a row and Clawd sits down to read
379const READS = new Set(['Read', 'Grep', 'Glob', 'WebFetch', 'WebSearch'])
380// How many reads, within how many ticks, start it; how long without one ends it
381export const READS_TO_START = 3
382export const READS_WINDOW_TICKS = 20
383export const READING_LINGER_TICKS = 12
384// How long a command must run before the headphones go on
385export const MUSIC_AFTER_TICKS = 8
386// Subagents spawned within this many ticks of each other make Clawd super
387export const SUPER_WINDOW_TICKS = 8
388// Tool calls of the main loop that fail in a row before Clawd gets dizzy
389export const ERRORS_TO_DIZZY = 3
390
391export function isRead(tool: string): boolean {
392  return READS.has(tool)
393}
394
395const THANKS = /\b(gracias|grax|thanks|thank you|thx)\b|<3|❤|♥/i
396// A command that runs a test suite, not one that only names a tests folder
397const TESTS = /\b(npm|pnpm|yarn|bun)\s+(run\s+)?test\b|\b(go|cargo|deno|bun|plugin|make)\s+test\b|\b(vitest|jest|pytest|mocha|rspec|phpunit)\b/
398const COMMIT = /\bgit\s+(commit|push)\b/
399
400// Whether a prompt thanks Claude
401export function isThanks(text: string): boolean {
402  return THANKS.test(text)
403}
404
405// The moment a finished tool call earns, if any: tests that pass or a commit
406// that lands, cool; a plan just made (ExitPlanMode, or a todo list with
407// nothing started yet), an idea; a skill, magic
408export function cueOf(tool: string, input: Record<string, unknown>, isOk: boolean): Mood | undefined {
409  if (!isOk) return undefined
410  if (tool === 'Bash' && typeof input.command === 'string') {
411    return TESTS.test(input.command) || COMMIT.test(input.command) ? 'cool' : undefined
412  }
413  if (tool === 'ExitPlanMode') return 'idea'
414  if (tool === 'Skill') return 'magic'
415  if (tool === 'TodoWrite' && Array.isArray(input.todos) && input.todos.length > 0) {
416    const isFresh = input.todos.every(t => typeof t === 'object' && t !== null && (t as { status?: unknown }).status === 'pending')
417    return isFresh ? 'idea' : undefined
418  }
419  return undefined
420}
421
422export function isSmoking(idleTicks: number): boolean {
423  return (
424    idleTicks >= SMOKE_FROM_TICKS &&
425    idleTicks < SLEEP_AFTER_TICKS &&
426    idleTicks % SMOKE_EVERY >= SMOKE_EVERY - SMOKE_TICKS
427  )
428}
429
430// What Clawd shows at tick `t`, given how long the session has been idle,
431// when a turn just ended how many ticks ago, the moment it is having, how
432// many ticks it has been reading, and how long a command has been running
433export function view(
434  t: number,
435  idleTicks: number,
436  isWorking: boolean,
437  bodyColumns: number,
438  since?: number,
439  now?: Moment,
440  readingFor?: number,
441  runningFor?: number,
442): View {
443  if (since !== undefined && since >= 0 && since < CELEBRATE_TICKS) {
444    return { ...celebrating(since), x: 0, isWorking: true }
445  }
446  if (now && now.since >= 0 && now.since < MOMENT_TICKS[now.mood]) {
447    // It stops where it stood when the moment began, and walks on from there
448    const x = isWorking ? walked(Math.max(0, t - now.since), WIDTH, bodyColumns) : 0
449    const { dx = 0, ...scene } = moment(now)
450    return { ...scene, x: x + dx, isWorking }
451  }
452  if (isWorking && readingFor !== undefined && readingFor >= 0) {
453    // It stops where it stood to read, and walks on from there after
454    return { ...reading(readingFor), x: walked(Math.max(0, t - readingFor), WIDTH, bodyColumns), isWorking }
455  }
456  if (isWorking && runningFor !== undefined && runningFor >= MUSIC_AFTER_TICKS) {
457    const listened = runningFor - MUSIC_AFTER_TICKS
458    return { ...listening(listened), x: walked(Math.max(0, t - listened), WIDTH, bodyColumns), isWorking }
459  }
460  if (isWorking) {
461    const line = WORKING_LINES[Math.floor(t / 24) % WORKING_LINES.length]!
462    const pose = line.startsWith('cocinando') ? cooking(t) : { frame: DANCE[t % DANCE.length]!, marks: [] }
463    const dots = '.'.repeat((Math.floor(t / 2) % 3) + 1)
464    const width = Math.max(...pose.frame.map(r => r.length))
465    return { ...pose, x: walked(t, width, bodyColumns), line: line + dots, isWorking }
466  }
467  if (idleTicks >= SLEEP_AFTER_TICKS) {
468    return { frame: BLINK, marks: [], x: 0, line: 'zzz', isWorking }
469  }
470  if (isSmoking(idleTicks)) {
471    if (isCoffeeBreak(idleTicks)) return { ...coffee(t), x: 0, line: 'un cafecito', isWorking }
472    return { ...smoking(t), x: 0, line: 'en mi break', isWorking }
473  }
474  // Blink once every ~4s, sway every second
475  return {
476    frame: t % 16 === 15 ? BLINK : IDLE,
477    marks: [],
478    x: Math.floor(t / 4) % 2,
479    line: IDLE_LINES[Math.floor(t / 40) % IDLE_LINES.length]!,
480    isWorking,
481  }
482}
483
484export function viewKey(v: View): string {
485  return `${v.frame.join('|')}#${v.x}#${v.line}#${JSON.stringify(v.marks)}`
486}
487
hooks/desks.ts 477 lines
1// The desks scene: while subagents run, each one shows up beside Clawd as a
2// small buddy typing at its own laptop, code marks floating over its head and
3// a bubble saying what that agent is doing. Pure functions of the tick and the
4// agent list, so the timer can tell whether the drawing changed and the tests
5// can drive it.
6
7export type Agent = {
8  id: string
9  type: string
10  // What its last tool call was doing; the Agent call's description until then
11  activity: string
12  // Where it stands now, cells from the first desk's left end
13  x: number
14  bornAt: number
15  // The tick its loop finished, and what it came back with
16  doneAt?: number
17  result?: string
18}
19
20export type Style = { bg?: string; fg?: string; dim?: boolean; italic?: boolean; bold?: boolean }
21export type Segment = { text: string; style: Style }
22
23export const ROWS = 4
24// Clawd's 8 cells and a gap
25const DESKS_X = 11
26// A buddy at its laptop, in cells
27const SPRITE = 10
28// Where the buddy's body starts inside that, so a walking one lines up with it
29const BODY_X = 5
30// Where a new buddy starts: stepping out of Clawd
31export const START_X = 4 - DESKS_X - BODY_X
32// A desk: the sprite and a small gap to the next
33const SLOT = 13
34// Cells a buddy walks per tick
35const STEP = 2
36// Each working buddy holds the floor this long
37const SPEAK_TICKS = 12
38// A finished buddy shows its result this long, then walks off
39const RESULT_TICKS = 16
40
41const EYE_COLOR = '#1A1A1A'
42const BOOK_COLOR = '#3E3A7A'
43const PAGE_COLOR = '#E4DCCB'
44const CAPE_COLOR = '#C8323C'
45const MUG_COLOR = '#9AA0A8'
46const COFFEE_COLOR = '#6B4430'
47const PHONES_COLOR = '#2E6FD0'
48const DONE_COLOR = '#8DB360'
49const PALETTE = ['#6A9BCC', '#8DB360', '#C77DBB', '#D4A23C', '#5FB3A9', '#E07A5F']
50const MARKS = ['=>', '++', '{}', '</>', '()', '&&', ';;', '#!']
51const MARK_COLORS = ['#E58FD0', '#F2C14E', '#7FD1E8']
52
53// Pixel colors: O Clawd, K eye, G laptop; . nothing
54const PIXEL: Record<string, string> = { O: 'claude', K: EYE_COLOR, G: '#6B7280' }
55
56// Sprites are four pixel rows of two pixels a cell, drawn in quarter blocks
57// as fine as the big Clawd: a small one with an eye in each upper corner,
58// short arms and its legs in pairs. The laptop leans on its left.
59// At the laptop, two frames of typing: the hand down on a key, then up.
60const TYPING = [
61  ['..G........OOOOOOOO.', '..G........OKOOOOKO.', '...G.....OOOOOOOOOOO', '...GGGGG...O.O..O.O.'],
62  ['..G........OOOOOOOO.', '..G......O.OKOOOOKO.', '...G......OOOOOOOOOO', '...GGGGG...O.O..O.O.'],
63]
64// Done: the laptop shut, the arm resting
65const DONE = ['...........OOOOOOOO.', '...........OKOOOOKO.', '..........OOOOOOOOOO', '...GGGGG...O.O..O.O.']
66// Walking, no laptop: two steps
67const WALKING = [
68  ['.OOOOOOOO.', '.OKOOOOKO.', 'OOOOOOOOOO', '.O.O..O.O.'],
69  ['.OOOOOOOO.', '.OKOOOOKO.', 'OOOOOOOOOO', '..O.O.O.O.'],
70]
71
72function blink(sprite: string[]): string[] {
73  return sprite.map(row => row.replace(/K/g, 'O'))
74}
75
76// One color per agent type, the same every session
77export function colorOf(type: string): string {
78  let h = 0
79  for (const c of type) h = (h * 31 + c.charCodeAt(0)) >>> 0
80  return PALETTE[h % PALETTE.length]!
81}
82
83export function oneLine(s: string): string {
84  return s.replace(/\s+/g, ' ').trim()
85}
86
87// A command's secrets masked before it shows on screen: a secret flag's value,
88// an auth header, a query parameter or variable named like a key, and long
89// runs of letters and digits that read as a token
90export function redact(command: string): string {
91  return command
92    .replace(/(--?(?:token|password|passwd|secret|api[-_]?key|auth)[= ]+)[^\s'"]+/gi, '$1***')
93    .replace(/(authorization:\s*(?:bearer|basic|token)?\s*)[^\s'"]+/gi, '$1***')
94    .replace(/([?&](?:token|access_token|api_key|key|secret|password)=)[^&\s'"]+/gi, '$1***')
95    .replace(/\b([A-Z0-9_]*(?:KEY|TOKEN|SECRET|PASSWORD)[A-Z0-9_]*=)[^\s'"]+/g, '$1***')
96    .replace(/[A-Za-z0-9_\-+=]{32,}/g, run => (/\d/.test(run) && /[A-Za-z]/.test(run) ? '***' : run))
97}
98
99function baseName(p: string): string {
100  return p.split(/[\\/]/).filter(Boolean).pop() ?? p
101}
102
103// A few words for a tool call, from its name and arguments
104export function describe(tool: string, input: Record<string, unknown>): string {
105  const s = (k: string) => (typeof input[k] === 'string' ? oneLine(input[k] as string) : '')
106  switch (tool) {
107    case 'Read':
108      return `leyendo ${baseName(s('file_path'))}`
109    case 'Edit':
110    case 'MultiEdit':
111      return `editando ${baseName(s('file_path'))}`
112    case 'NotebookEdit':
113      return `editando ${baseName(s('notebook_path'))}`
114    case 'Write':
115      return `escribiendo ${baseName(s('file_path'))}`
116    case 'Grep':
117      return `buscando "${s('pattern')}"`
118    case 'Glob':
119      return `buscando ${s('pattern')}`
120    case 'Bash':
121    case 'PowerShell':
122      return s('description') || `$ ${redact(s('command'))}`
123    case 'WebSearch':
124      return `googleando "${s('query')}"`
125    case 'WebFetch': {
126      const m = /^[a-z]+:\/\/([^/]+)/i.exec(s('url'))
127      return `leyendo ${m ? m[1] : 'la web'}`
128    }
129    case 'Agent':
130      return `delegando: ${s('description')}`
131    case 'TodoWrite':
132      return 'planeando'
133    default:
134      return tool.startsWith('mcp__') ? tool.split('__').pop()! : tool
135  }
136}
137
138// The first line of a subagent's last message, without markdown marks
139export function summary(message: string | undefined): string {
140  const line = (message ?? '').split('\n').map(l => l.replace(/^[\s#>*`-]+/, '').trim()).find(Boolean)
141  return line ? line.replace(/[*`]/g, '') : 'listo'
142}
143
144type Seats = { slot: number; shown: Agent[]; more: number }
145
146function seats(agents: Agent[], bodyColumns: number): Seats {
147  const room = Math.max(SLOT, bodyColumns - DESKS_X - 1)
148  // Too many for the room: keep four cells at the end for the count
149  const usable = agents.length > Math.floor(room / SLOT) ? room - 4 : room
150  const shown = agents.slice(0, Math.max(1, Math.floor(usable / SLOT)))
151  return { slot: SLOT, shown, more: agents.length - shown.length }
152}
153
154function isLeaving(a: Agent, t: number): boolean {
155  return a.doneAt !== undefined && t - a.doneAt >= RESULT_TICKS
156}
157
158// One tick of walking: each buddy steps toward its desk, a leaving one back
159// into Clawd, the way it came, where it is dropped
160export function walk(agents: Agent[], t: number, bodyColumns: number): Agent[] {
161  const { slot, shown } = seats(agents, bodyColumns)
162  const out: Agent[] = []
163  agents.forEach((a, i) => {
164    if (i >= shown.length) return out.push(a)
165    const target = isLeaving(a, t) ? START_X : i * slot
166    const x = a.x < target ? Math.min(target, a.x + STEP) : Math.max(target, a.x - STEP)
167    if (isLeaving(a, t) && x <= START_X) return
168    out.push(x === a.x ? a : { ...a, x })
169  })
170  return out
171}
172
173type Cell = { ch: string; style: Style }
174
175const NONE: Style = {}
176const BLANK: Cell = { ch: ' ', style: NONE }
177
178// Cells a code point takes in a terminal: none for joiners, variation
179// selectors, skin tones and combining marks; two for wide East Asian and emoji
180function cellWidth(cp: number): number {
181  if (
182    cp === 0x200d ||
183    (cp >= 0x0300 && cp <= 0x036f) ||
184    (cp >= 0xfe00 && cp <= 0xfe0f) ||
185    (cp >= 0x1f3fb && cp <= 0x1f3ff)
186  ) {
187    return 0
188  }
189  if (
190    (cp >= 0x1100 && cp <= 0x115f) ||
191    (cp >= 0x2e80 && cp <= 0xa4cf) ||
192    (cp >= 0xac00 && cp <= 0xd7a3) ||
193    (cp >= 0xf900 && cp <= 0xfaff) ||
194    (cp >= 0xfe30 && cp <= 0xfe4f) ||
195    (cp >= 0xff00 && cp <= 0xff60) ||
196    (cp >= 0xffe0 && cp <= 0xffe6) ||
197    (cp >= 0x1f300 && cp <= 0x1faff) ||
198    (cp >= 0x20000 && cp <= 0x3fffd)
199  ) {
200    return 2
201  }
202  return 1
203}
204
205// Each code point and the cells it takes; one after a joiner is drawn into
206// the glyph before it
207function glyphs(text: string): { ch: string; cells: number }[] {
208  const out: { ch: string; cells: number }[] = []
209  let isJoined = false
210  for (const ch of text) {
211    const cp = ch.codePointAt(0)!
212    out.push({ ch, cells: isJoined ? 0 : cellWidth(cp) })
213    isJoined = cp === 0x200d
214  }
215  return out
216}
217
218// How many terminal columns `text` takes
219export function columns(text: string): number {
220  return glyphs(text).reduce((n, g) => n + g.cells, 0)
221}
222
223// A wide glyph is its cell and an empty one after it. Clearing either half
224// clears the other, so a glyph drawn over it never leaves half a wide one
225function clear(row: Cell[], x: number) {
226  if (row[x]!.ch === '' && x > 0) row[x - 1] = BLANK
227  else if (row[x + 1]?.ch === '') row[x + 1] = BLANK
228  row[x] = BLANK
229}
230
231function put(row: Cell[], x: number, text: string, style: Style) {
232  let last = -1
233  for (const { ch, cells } of glyphs(text)) {
234    if (cells === 0) {
235      if (last >= 0) row[last] = { ch: row[last]!.ch + ch, style }
236      continue
237    }
238    if (x >= 0 && x + cells <= row.length) {
239      for (let k = 0; k < cells; k++) clear(row, x + k)
240      row[x] = { ch, style }
241      for (let k = 1; k < cells; k++) row[x + k] = { ch: '', style }
242      last = x
243    } else {
244      last = -1
245    }
246    x += cells
247  }
248}
249
250// Clawd's own sprite, a cell per pixel, and what it holds; . is empty
251const CELL: Record<string, Cell> = {
252  // Orange cell; one with a dark eye in a lower quarter; one with a closed eye
253  O: { ch: ' ', style: { bg: 'claude', fg: EYE_COLOR } },
254  L: { ch: '▖', style: { bg: 'claude', fg: EYE_COLOR } },
255  R: { ch: '▗', style: { bg: 'claude', fg: EYE_COLOR } },
256  '-': { ch: '▁', style: { bg: 'claude', fg: EYE_COLOR } },
257  // Eyes of a mood, each its own glyph on the orange
258  ...Object.fromEntries([...'><┓┏'].map(ch => [ch, { ch, style: { bg: 'claude', fg: EYE_COLOR, bold: true } }])),
259  // Sunglasses: the band, a lens, and each lens's inner edge
260  s: { ch: '▄', style: { bg: 'claude', fg: EYE_COLOR } },
261  S: { ch: '▀', style: { bg: 'claude', fg: EYE_COLOR } },
262  l: { ch: '▘', style: { bg: 'claude', fg: EYE_COLOR } },
263  r: { ch: '▝', style: { bg: 'claude', fg: EYE_COLOR } },
264  // Eyes looking up, and eyes wide open
265  p: { ch: '°', style: { bg: 'claude', fg: EYE_COLOR, bold: true } },
266  w: { ch: '●', style: { bg: 'claude', fg: EYE_COLOR } },
267  '@': { ch: '@', style: { bg: 'claude', fg: EYE_COLOR, bold: true } },
268  // A leg sticking up, upside down
269  y: { ch: '▖', style: { fg: 'claude' } },
270  z: { ch: '▗', style: { fg: 'claude' } },
271  // An eye shut tight
272  m: { ch: '━', style: { bg: 'claude', fg: EYE_COLOR, bold: true } },
273  // A book: the pages' top, their edge against the spine, the cover, a page turning
274  '1': { ch: '▄', style: { fg: PAGE_COLOR } },
275  '2': { ch: '▐', style: { bg: PAGE_COLOR, fg: BOOK_COLOR } },
276  '3': { ch: ' ', style: { bg: BOOK_COLOR } },
277  '4': { ch: '▟', style: { fg: PAGE_COLOR } },
278  '5': { ch: '▄', style: { bg: 'claude', fg: PAGE_COLOR } },
279  '6': { ch: '▟', style: { bg: 'claude', fg: PAGE_COLOR } },
280  // Super Clawd: a collar, the cape, a leg over it, its edges stepping out, the cape blown up
281  n: { ch: '▔', style: { bg: 'claude', fg: CAPE_COLOR } },
282  u: { ch: ' ', style: { bg: CAPE_COLOR } },
283  j: { ch: '▘', style: { bg: CAPE_COLOR, fg: 'claude' } },
284  J: { ch: '▝', style: { bg: CAPE_COLOR, fg: 'claude' } },
285  k: { ch: '▝', style: { fg: CAPE_COLOR } },
286  K: { ch: '▘', style: { fg: CAPE_COLOR } },
287  e: { ch: '▀', style: { fg: CAPE_COLOR } },
288  // Coffee over a mug, the mug, its handle toward Clawd; a headphone's ear cups
289  x: { ch: '▝', style: { bg: MUG_COLOR, fg: COFFEE_COLOR } },
290  X: { ch: '▘', style: { bg: MUG_COLOR, fg: COFFEE_COLOR } },
291  N: { ch: '(', style: { fg: MUG_COLOR } },
292  '[': { ch: '▐', style: { fg: PHONES_COLOR } },
293  ']': { ch: '▌', style: { fg: PHONES_COLOR } },
294  // An arm at rest and raised, and a leg at either side of its cell
295  '^': { ch: '▀', style: { fg: 'claude' } },
296  v: { ch: '▄', style: { fg: 'claude' } },
297  a: { ch: '▘', style: { fg: 'claude' } },
298  b: { ch: '▝', style: { fg: 'claude' } },
299  // A pan's handle, thin and level with the arm that holds it, and its pan
300  h: { ch: '▀', style: { fg: '#8B5A2B' } },
301  P: { ch: ' ', style: { bg: '#6B7280' } },
302  // A cigarette, thin as a line, and its ember dim and drawn on
303  c: { ch: '▂', style: { fg: '#EDEDED' } },
304  C: { ch: '▂', style: { fg: '#C2410C' } },
305  Y: { ch: '▂', style: { fg: '#FFB347' } },
306}
307
308function paintCells(row: Cell[], x: number, sprite: string) {
309  ;[...sprite].forEach((kind, i) => {
310    const cell = CELL[kind]
311    if (cell && x + i >= 0 && x + i < row.length) row[x + i] = cell
312  })
313}
314
315// A cell's quarters as a glyph, by the quarters set: 1 upper left, 2 upper
316// right, 4 lower left, 8 lower right
317const QUARTERS = ' ▘▝▀▖▌▞▛▗▚▐▜▄▙▟█'
318const PIXEL_ORDER = Object.values(PIXEL)
319
320// A sprite of two pixel rows and two pixel columns per cell. A cell all one
321// color is its background, so whole cells leave no seam; a full cell of two
322// is the commoner one behind a glyph of the other; a cell with empty pixels
323// is a glyph alone, in its rarest color
324function paintQuarters(rows: Cell[][], top: number, x: number, sprite: string[]) {
325  const width = Math.ceil(Math.max(...sprite.map(s => s.length)) / 2)
326  for (let r = 0; r * 2 < sprite.length; r++) {
327    const row = rows[top + r]!
328    const upper = sprite[r * 2]!
329    const lower = sprite[r * 2 + 1] ?? ''
330    for (let i = 0; i < width; i++) {
331      if (x + i < 0 || x + i >= row.length) continue
332      const px = [upper[i * 2], upper[i * 2 + 1], lower[i * 2], lower[i * 2 + 1]].map(p => PIXEL[p ?? '.'])
333      const mask = (c: string | undefined) => px.reduce((m, p, k) => (p === c ? m | (1 << k) : m), 0)
334      const count = (c: string) => px.filter(p => p === c).length
335      // Rarest first; a tie goes to the later color in PIXEL
336      const colors = PIXEL_ORDER.filter(c => count(c) > 0).sort(
337        (a, b) => count(a) - count(b) || PIXEL_ORDER.indexOf(b) - PIXEL_ORDER.indexOf(a),
338      )
339      if (colors.length === 0) continue
340      const isFull = px.every(p => p !== undefined)
341      if (colors.length === 1 && isFull) {
342        row[x + i] = { ch: ' ', style: { bg: colors[0]! } }
343      } else if (isFull) {
344        const bg = colors[colors.length - 1]!
345        row[x + i] = { ch: QUARTERS[15 - mask(bg)]!, style: { fg: colors[0]!, bg } }
346      } else {
347        row[x + i] = { ch: QUARTERS[15 - mask(undefined)]!, style: { fg: colors[0]! } }
348      }
349    }
350  }
351}
352
353function sameStyle(a: Style, b: Style): boolean {
354  return a.bg === b.bg && a.fg === b.fg && a.dim === b.dim && a.italic === b.italic && a.bold === b.bold
355}
356
357// Consecutive cells of one style as one segment, trailing blanks dropped
358function segments(row: Cell[]): Segment[] {
359  let end = row.length
360  while (end > 0 && row[end - 1]!.ch === ' ' && row[end - 1]!.style === NONE) end -= 1
361  const out: Segment[] = []
362  for (const cell of row.slice(0, end)) {
363    const last = out[out.length - 1]
364    if (last && sameStyle(last.style, cell.style)) last.text += cell.ch
365    else out.push({ text: cell.ch, style: cell.style })
366  }
367  return out
368}
369
370function fit(text: string, width: number): string {
371  if (columns(text) <= width) return text
372  let out = ''
373  let used = 0
374  for (const { ch, cells } of glyphs(text)) {
375    if (used + cells > width - 1) break
376    out += ch
377    used += cells
378  }
379  return out + '…'
380}
381
382// The drawing at tick `t`: ROWS rows of styled segments
383export function scene(
384  t: number,
385  agents: Agent[],
386  clawd: [string, string, string],
387  line: string,
388  bodyColumns: number,
389): Segment[][] {
390  const width = Math.max(DESKS_X + SLOT, bodyColumns)
391  const rows: Cell[][] = Array.from({ length: ROWS }, () =>
392    Array.from({ length: width }, () => ({ ch: ' ', style: NONE })),
393  )
394  const { slot, shown, more } = seats(agents, bodyColumns)
395
396  if (more > 0) put(rows[3]!, DESKS_X + shown.length * slot, `+${more}`, { dim: true })
397
398  // Working buddies take turns holding the floor
399  const working = shown.filter((a, i) => a.doneAt === undefined && a.x === i * slot)
400  const speaker = working.length ? working[Math.floor(t / SPEAK_TICKS) % working.length] : undefined
401
402  shown.forEach((a, i) => {
403    const x = DESKS_X + a.x
404    const isSeated = a.x === i * slot
405    const isDone = a.doneAt !== undefined
406    const blinks = (t + i * 5) % 16 === 15
407
408    if (!isSeated) {
409      const step = WALKING[(t + i) % 2]!
410      paintQuarters(rows, 2, x + BODY_X, blinks ? blink(step) : step)
411      return
412    }
413
414    if (isDone) {
415      paintQuarters(rows, 2, x, DONE)
416      put(rows[1]!, x + BODY_X + 2, '✓', { fg: DONE_COLOR, bold: true })
417    } else {
418      const typing = TYPING[(Math.floor(t / 2) + i) % 2]!
419      paintQuarters(rows, 2, x, blinks ? blink(typing) : typing)
420      // Code marks pop up over its head, two beats in three
421      const beat = Math.floor(t / 3) + i * 7
422      if (beat % 3 !== 2) {
423        const mark = MARKS[beat % MARKS.length]!
424        put(rows[1]!, x + BODY_X + (beat % 3) * 2, mark, { fg: MARK_COLORS[beat % MARK_COLORS.length]! })
425      }
426    }
427  })
428
429  // Bubbles: each fits its desk, but the speaker's runs on as far as the band
430  // goes, and the neighbors it runs over keep quiet meanwhile
431  let spokenTo = 0
432  if (speaker) {
433    const x = DESKS_X + speaker.x
434    const text = fit(speaker.activity, width - x)
435    put(rows[0]!, x, text, { fg: colorOf(speaker.type), bold: true })
436    spokenTo = x + columns(text) + 1
437  }
438  shown.forEach((a, i) => {
439    const x = DESKS_X + a.x
440    if (a === speaker || a.x !== i * slot || (x < spokenTo && x > DESKS_X + (speaker?.x ?? 0))) return
441    const isDone = a.doneAt !== undefined
442    const text = isDone ? `✓ ${a.result ?? 'listo'}` : a.activity
443    put(rows[0]!, x, fit(text, slot - 1), { fg: colorOf(a.type), dim: !isDone })
444  })
445
446  // Clawd on the left, its own line above it, in front of a buddy walking in
447  // or out of it
448  put(rows[0]!, 0, fit(line, DESKS_X - 1), { fg: 'claude', dim: true, italic: true })
449  clawd.forEach((sprite, i) => paintCells(rows[i + 1]!, 0, sprite))
450
451  return rows.map(segments)
452}
453
454// Something drawn over Clawd's scene as text: food in the air, smoke
455export type Mark = { row: number; x: number; text: string; fg: string; bg?: string }
456
457// Clawd alone: a row of air for marks, its three sprite rows `x` cells in,
458// and its line beside them
459export function solo(
460  frame: string[],
461  marks: Mark[],
462  x: number,
463  line: string,
464  isWorking: boolean,
465  bodyColumns: number,
466): Segment[][] {
467  const width = Math.max(1, bodyColumns)
468  const rows: Cell[][] = Array.from({ length: ROWS }, () =>
469    Array.from({ length: width }, () => ({ ch: ' ', style: NONE })),
470  )
471  frame.forEach((sprite, i) => paintCells(rows[i + 1]!, x, sprite))
472  for (const m of marks) put(rows[m.row]!, x + m.x, m.text, { fg: m.fg, ...(m.bg ? { bg: m.bg } : {}) })
473  const spriteWidth = Math.max(...frame.map(r => r.length))
474  put(rows[2]!, x + spriteWidth + 1, line, { fg: 'claude', dim: !isWorking, italic: true })
475  return rows.map(segments)
476}
477
hooks/game-register.tsx 69 lines
1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, PromptSubmitInput, Register, TurnCompleteInput } from 'claude-code'
3
4import type { ClaudeState } from '../types'
5import { MIN_W } from './game'
6
7const PANE = 'clawd-play'
8const COMMAND = 'clawd-play'
9// Rows asked of the pane when it sits inline above the prompt
10const INLINE_ROWS = 18
11// The cap on an inline board, whatever room the layout spares
12const MAX_INLINE_ROWS = 20
13
14const claude = atom({ plugin: 'clawd-buddy', key: 'claude' } as const, 'idle' as ClaudeState)
15
16// The pieces below ride on hooks the mascot's module already has: one module
17// cannot register the same event twice
18
19export async function registerGameCommand($: EngineInterface) {
20  await $.command.register({
21    name: COMMAND,
22    description: 'Juega Clawd Invaders en un panel mientras Claude trabaja',
23  })
24}
25
26// A slash command is no turn for Claude: only a prompt starts the work. A
27// prompt that opens with a path, like /home/x/foo.ts, is still a prompt.
28const isSlashCommand = (text: string) => /^\/[\w:-]+(\s|$)/.test(text)
29
30export async function trackPrompt($: EngineInterface, e: PromptSubmitInput) {
31  if (!isSlashCommand(e.text)) await update($, claude, () => 'working')
32}
33
34// Only a turn that answered ends the work, as for the mascot: other turns of
35// the main loop leave the state as it was
36export async function trackTurn($: EngineInterface, e: TurnCompleteInput) {
37  if (e.agentId === undefined && e.reason === 'answer') await update($, claude, () => 'done')
38}
39
40export const registerGame: Register = on => {
41  on('command.run', { command: COMMAND }, async ($, e) => {
42    const columns = Math.max(MIN_W + 2, Math.round(e.presentation.columns / 3))
43    const opened = await $.ui.open({ id: PANE, title: 'Clawd Invaders', focus: true, rows: INLINE_ROWS, columns })
44    return opened.isPlaced ? {} : { text: `Clawd Invaders no cabe aquí: ${opened.reason}` }
45  }).catch(($, e, next) => {
46    // The error crosses from the engine as a plain object, not an Error
47    const err: unknown = next.error
48    const reason = typeof err === 'object' && err !== null && 'message' in err ? String(err.message) : String(err)
49    return { text: `Clawd Invaders no pudo abrirse: ${reason}` }
50  })
51
52  on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
53    const { Client } = $.ui.resolve(e)
54    const state = await read($, claude)
55    const height =
56      e.props.placement === 'inline' ? Math.min(e.props.scroll.bodyRows, MAX_INLINE_ROWS) : e.props.scroll.bodyRows
57
58    return (
59      <Client
60        key="game"
61        module="./game-client.tsx"
62        props={{ isFocused: e.props.isFocused, claude: state }}
63        width="100%"
64        height={height}
65      />
66    )
67  })
68}
69
hooks/mood-register.tsx 77 lines
1// Choosing Clawd's moods: the `/clawd-mood` command over the plugin's own
2// `userConfig` fields. The engine hands their values to `register` and reloads
3// the plugin when one changes, so a choice written here is read back as
4// options on the next load, not kept in this module.
5
6import type { EngineInterface, PluginOptions, Register } from 'claude-code'
7
8const COMMAND = 'clawd-mood'
9
10// A slot of moods the person chooses among: its userConfig field, its name in
11// the command, and its values with how each is shown and typed
12type Slot = {
13  field: string
14  name: string
15  values: readonly { id: string; label: string; aliases?: readonly string[] }[]
16}
17
18const SLOTS: readonly Slot[] = [
19  {
20    field: 'breakMood',
21    name: 'break',
22    values: [
23      { id: 'rotar', label: 'rotar' },
24      { id: 'azar', label: 'azar' },
25      { id: 'cigarro', label: 'cigarro' },
26      { id: 'cafe', label: 'café', aliases: ['café'] },
27    ],
28  },
29]
30
31const configKey = (slot: Slot) => `clawd-buddy.${slot.field}`
32const labelOf = (slot: Slot, id: string) => slot.values.find(v => v.id === id)?.label ?? id
33const choices = (slot: Slot) => slot.values.map(v => v.label).join(', ')
34
35function current(options: PluginOptions, slot: Slot): string {
36  const value = options[slot.field]
37  return typeof value === 'string' ? value : slot.values[0]!.id
38}
39
40export function describe(options: PluginOptions): string {
41  const lines = SLOTS.map(slot => `${slot.name}: ${labelOf(slot, current(options, slot))} (${choices(slot)})`)
42  return [...lines, `Cambia uno con /${COMMAND} <espacio> <variante>.`].join('\n')
43}
44
45export async function registerMoodCommand($: EngineInterface) {
46  await $.command.register({
47    name: COMMAND,
48    description: 'Elige qué moods usa Clawd en cada momento',
49    argumentHint: '[espacio variante]',
50    immediate: true,
51  })
52}
53
54export const registerMoods: Register = (on, options) => {
55  on('command.run', { command: COMMAND }, async ($, e) => {
56    const [name, value, ...rest] = e.args.trim().split(/\s+/).filter(Boolean)
57    if (name === undefined) return { text: describe(options) }
58
59    const slot = SLOTS.find(s => s.name === name)
60    if (!slot) return { text: `No hay un espacio "${name}". Espacios: ${SLOTS.map(s => s.name).join(', ')}.` }
61    if (value === undefined || rest.length > 0) {
62      return { text: `Uso: /${COMMAND} ${slot.name} <variante>. Variantes: ${choices(slot)}.` }
63    }
64    const typed = value.toLowerCase()
65    const chosen = slot.values.find(v => v.id === typed || v.aliases?.includes(typed))
66    if (!chosen) return { text: `"${value}" no es una variante de ${slot.name}. Variantes: ${choices(slot)}.` }
67
68    const result = await $.config.set({ key: configKey(slot), value: chosen.id })
69    if (result.deny !== undefined) return { text: `No se pudo guardar ${slot.name}: ${result.deny}` }
70    return { text: `${slot.name}: ${chosen.label}. Clawd se recarga para usarlo.` }
71  }).catch(($, e, next) => {
72    const err: unknown = next.error
73    const reason = typeof err === 'object' && err !== null && 'message' in err ? String(err.message) : String(err)
74    return { text: `/${COMMAND} falló: ${reason}` }
75  })
76}
77
hooks/game.ts 293 lines
1// Clawd Invaders: the rules, as pure functions of the game and an explicit
2// tick. Time and input come in as arguments and chance from a seed in the
3// state, so the client can drive it and the tests can replay it.
4
5export type Vec = { x: number; y: number }
6// An enemy's top left cell; it takes ENEMY_W by ENEMY_H cells
7export type Enemy = { x: number; y: number; row: number }
8export type Spark = { x: number; y: number; life: number }
9export type Status = 'playing' | 'over'
10export type Cause = 'lives' | 'invaded'
11
12export type Game = {
13  w: number
14  h: number
15  // The ship's left cell; it takes the last SHIP_H rows
16  ship: number
17  lives: number
18  score: number
19  wave: number
20  enemies: Enemy[]
21  // Rows the wave started with: a bug's worth comes from its row in them
22  rows: number
23  dir: 1 | -1
24  shots: Vec[]
25  bombs: Vec[]
26  sparks: Spark[]
27  t: number
28  cooldown: number
29  invuln: number
30  // Ticks left of the cheer between waves; the next wave arrives at zero
31  celebrate: number
32  status: Status
33  cause?: Cause
34  seed: number
35}
36
37export const SHIP_W = 5
38export const SHIP_H = 2
39export const ENEMY_W = 4
40export const ENEMY_H = 2
41// An enemy and the gap to the next, across and down
42const PITCH_X = ENEMY_W + 2
43const PITCH_Y = ENEMY_H + 1
44const MAX_COLS = 6
45const MAX_ROWS = 6
46export const MIN_W = 24
47export const MIN_H = 12
48export const LIVES = 3
49export const INVULN_TICKS = 14
50export const CELEBRATE_TICKS = 12
51const SPARK_TICKS = 3
52const FIRE_EVERY = 5
53const KILL_SCORE = 10
54const WAVE_SCORE = 50
55// Ticks of warning the autopilot wants before a bomb reaches the ship
56const DODGE_TICKS = 10
57// Board rows per extra row a bumping wave descends, so a tall board keeps
58// the pace of a short one
59const ROWS_PER_DROP = 24
60
61// Ticks between enemy steps, and between bombs: harder each wave, to a floor
62export const enemyEvery = (wave: number) => Math.max(2, 7 - wave)
63export const bombEvery = (wave: number) => Math.max(8, 24 - 2 * wave)
64
65export const fits = (w: number, h: number) => w >= MIN_W && h >= MIN_H
66
67// On a tall board bombs fall a row a tick, on a short one every other tick
68export const bombFallEvery = (h: number) => (h >= 30 ? 1 : 2)
69export const dropRows = (h: number) => 1 + Math.floor(h / ROWS_PER_DROP)
70
71// The ship's top row, and the last row an enemy may reach before it invades
72const shipTop = (h: number) => h - SHIP_H
73const defense = (h: number) => shipTop(h) - 1
74const bottomOf = (e: Enemy) => e.y + ENEMY_H - 1
75
76// mulberry32: the next value in [0, 1) and the seed after it
77function roll(seed: number): [number, number] {
78  const s = (seed + 0x6d2b79f5) >>> 0
79  let r = Math.imul(s ^ (s >>> 15), 1 | s)
80  r = (r + Math.imul(r ^ (r >>> 7), 61 | r)) ^ r
81  return [((r ^ (r >>> 14)) >>> 0) / 4294967296, s]
82}
83
84const formationCols = (w: number) => Math.min(MAX_COLS, Math.floor((w + 2) / PITCH_X))
85// The rows of bugs a board holds: about its upper third, never so many that a
86// wave has no room to descend
87const maxRows = (h: number) =>
88  Math.min(MAX_ROWS, Math.floor((h - 6) / PITCH_Y), Math.max(2, Math.floor((h / 3 + 1) / PITCH_Y)))
89// Two rows short of the board's fill on the first wave, one more every other
90export const formationRows = (h: number, wave: number) =>
91  Math.min(maxRows(h), Math.max(2, maxRows(h) - 2 + Math.ceil(wave / 2)))
92
93function formation(w: number, h: number, wave: number): Enemy[] {
94  const cols = formationCols(w)
95  const rows = formationRows(h, wave)
96  const x0 = Math.floor((w - (cols * PITCH_X - 2)) / 2)
97  const enemies: Enemy[] = []
98  for (let row = 0; row < rows; row++) {
99    for (let c = 0; c < cols; c++) enemies.push({ x: x0 + c * PITCH_X, y: 1 + row * PITCH_Y, row })
100  }
101  return enemies
102}
103
104export function newGame(w: number, h: number, seed: number): Game {
105  if (!fits(w, h)) throw new Error(`board ${w}x${h} is under the minimum ${MIN_W}x${MIN_H}`)
106  return {
107    w,
108    h,
109    ship: Math.floor((w - SHIP_W) / 2),
110    lives: LIVES,
111    score: 0,
112    wave: 1,
113    enemies: formation(w, h, 1),
114    rows: formationRows(h, 1),
115    dir: 1,
116    shots: [],
117    bombs: [],
118    sparks: [],
119    t: 0,
120    cooldown: 0,
121    invuln: 0,
122    celebrate: 0,
123    status: 'playing',
124    seed: seed >>> 0,
125  }
126}
127
128// The living bugs moved as one block just enough to fit the board and stay
129// above the defense line. A block too big for the board, from a wider one, is
130// laid out again as a fresh formation of at most as many bugs, bottom rows
131// first gone: shrinking the pane never adds a bug.
132function refit(enemies: Enemy[], w: number, h: number, wave: number): Enemy[] {
133  if (enemies.length === 0) return enemies
134  const left = Math.min(...enemies.map(e => e.x))
135  const right = Math.max(...enemies.map(e => e.x + ENEMY_W - 1))
136  const top = Math.min(...enemies.map(e => e.y))
137  const bottom = Math.max(...enemies.map(bottomOf))
138  const dx = Math.min(0, w - 1 - right)
139  const dy = Math.min(0, defense(h) - 1 - bottom)
140  if (left + dx >= 0 && top + dy >= 1) return enemies.map(e => ({ ...e, x: e.x + dx, y: e.y + dy }))
141  return formation(w, h, wave).slice(0, enemies.length)
142}
143
144// The same game on a new board: score, lives, wave and the living bugs kept;
145// what flew is gone
146export function resize(g: Game, w: number, h: number): Game {
147  if (!fits(w, h)) throw new Error(`board ${w}x${h} is under the minimum ${MIN_W}x${MIN_H}`)
148  return {
149    ...g,
150    w,
151    h,
152    ship: Math.min(g.ship, w - SHIP_W),
153    enemies: refit(g.enemies, w, h, g.wave),
154    shots: [],
155    bombs: [],
156    sparks: [],
157  }
158}
159
160export function move(g: Game, dx: number): Game {
161  if (g.status !== 'playing') return g
162  return { ...g, ship: Math.max(0, Math.min(g.w - SHIP_W, g.ship + dx)) }
163}
164
165// The demo's pilot: a cell a tick away from a bomb coming down on the ship,
166// otherwise toward the nearest bug, to fire under it
167export function autopilot(g: Game): -1 | 0 | 1 {
168  const center = g.ship + Math.floor(SHIP_W / 2)
169  const watch = Math.ceil(DODGE_TICKS / bombFallEvery(g.h))
170  const near = g.bombs.filter(b => b.y >= shipTop(g.h) - watch && b.x >= g.ship - 1 && b.x <= g.ship + SHIP_W)
171  if (near.length > 0) {
172    const away = near[0]!.x >= center ? -1 : 1
173    const blocked = (away === -1 && g.ship === 0) || (away === 1 && g.ship === g.w - SHIP_W)
174    return blocked ? (-away as -1 | 1) : away
175  }
176  if (g.enemies.length === 0) return 0
177  const target = g.enemies.reduce((best, e) => {
178    const d = Math.abs(e.x + 1 - center)
179    const bestD = Math.abs(best.x + 1 - center)
180    return d < bestD || (d === bestD && e.y > best.y) ? e : best
181  })
182  const to = target.x + 1
183  return to === center ? 0 : to > center ? 1 : -1
184}
185
186const covers = (e: Enemy, s: Vec) => s.y >= e.y && s.y <= bottomOf(e) && s.x >= e.x && s.x < e.x + ENEMY_W
187
188// Each shot kills the first enemy it meets and is spent: it scores once
189function collide(g: Game): Game {
190  if (g.shots.length === 0 || g.enemies.length === 0) return g
191  let enemies = g.enemies
192  let score = g.score
193  const shots: Vec[] = []
194  const sparks = [...g.sparks]
195  for (const s of g.shots) {
196    const hit = enemies.find(e => covers(e, s))
197    if (!hit) {
198      shots.push(s)
199      continue
200    }
201    enemies = enemies.filter(e => e !== hit)
202    score += KILL_SCORE * Math.max(1, g.rows - hit.row)
203    sparks.push({ x: hit.x + 1, y: hit.y, life: SPARK_TICKS })
204  }
205  return { ...g, enemies, shots, sparks, score }
206}
207
208function marchEnemies(g: Game): Game {
209  if (g.enemies.length === 0 || g.t % enemyEvery(g.wave) !== 0) return g
210  const left = Math.min(...g.enemies.map(e => e.x))
211  const right = Math.max(...g.enemies.map(e => e.x + ENEMY_W - 1))
212  const bumps = (g.dir === 1 && right + 1 > g.w - 1) || (g.dir === -1 && left - 1 < 0)
213  const drop = dropRows(g.h)
214  const enemies = g.enemies.map(e => (bumps ? { ...e, y: e.y + drop } : { ...e, x: e.x + g.dir }))
215  const dir = bumps ? (-g.dir as 1 | -1) : g.dir
216  return { ...g, enemies, dir }
217}
218
219function dropBomb(g: Game): Game {
220  if (g.enemies.length === 0 || g.t % bombEvery(g.wave) !== 0) return g
221  const lowest = new Map<number, Enemy>()
222  for (const e of g.enemies) {
223    const low = lowest.get(e.x)
224    if (!low || e.y > low.y) lowest.set(e.x, e)
225  }
226  const shooters = [...lowest.values()]
227  const [r, seed] = roll(g.seed)
228  const from = shooters[Math.floor(r * shooters.length)]!
229  // From under one of its two middle cells, the seed's low bit choosing
230  return { ...g, seed, bombs: [...g.bombs, { x: from.x + 1 + (seed & 1), y: bottomOf(from) + 1 }] }
231}
232
233// Bombs fall and the ship takes the ones that land on it; one hit leaves it
234// invulnerable for a while, so one impact costs one life
235function fall(g: Game): Game {
236  const top = shipTop(g.h)
237  const falling = g.t % bombFallEvery(g.h) === 0
238  let lives = g.lives
239  let invuln = g.invuln
240  const sparks = [...g.sparks]
241  const bombs: Vec[] = []
242  for (const b of g.bombs) {
243    const at = falling ? { ...b, y: b.y + 1 } : b
244    if (at.y < top) {
245      bombs.push(at)
246      continue
247    }
248    if (at.y > g.h - 1) continue
249    const onShip = at.x >= g.ship && at.x < g.ship + SHIP_W
250    if (onShip && invuln === 0) {
251      lives -= 1
252      invuln = INVULN_TICKS
253      sparks.push({ x: at.x, y: top, life: SPARK_TICKS })
254    } else if (!onShip) {
255      bombs.push(at)
256    }
257  }
258  return { ...g, bombs, lives, invuln, sparks }
259}
260
261function judge(g: Game): Game {
262  if (g.lives <= 0) return { ...g, lives: 0, status: 'over', cause: 'lives' }
263  if (g.enemies.some(e => bottomOf(e) >= defense(g.h))) return { ...g, status: 'over', cause: 'invaded' }
264  if (g.enemies.length === 0 && g.celebrate === 0) {
265    return { ...g, wave: g.wave + 1, score: g.score + WAVE_SCORE, shots: [], bombs: [], celebrate: CELEBRATE_TICKS }
266  }
267  return g
268}
269
270export function step(g: Game): Game {
271  if (g.status !== 'playing') return g
272  let n: Game = {
273    ...g,
274    t: g.t + 1,
275    cooldown: Math.max(0, g.cooldown - 1),
276    invuln: Math.max(0, g.invuln - 1),
277    sparks: g.sparks.map(s => ({ ...s, life: s.life - 1 })).filter(s => s.life > 0),
278  }
279
280  if (n.celebrate > 0) {
281    const celebrate = n.celebrate - 1
282    if (celebrate > 0) return { ...n, celebrate }
283    return { ...n, celebrate, enemies: formation(n.w, n.h, n.wave), rows: formationRows(n.h, n.wave), dir: 1 }
284  }
285
286  const muzzle = { x: n.ship + Math.floor(SHIP_W / 2), y: shipTop(n.h) - 1 }
287  if (n.cooldown === 0) n = { ...n, cooldown: FIRE_EVERY, shots: [...n.shots, muzzle] }
288  n = collide({ ...n, shots: n.shots.map(s => ({ ...s, y: s.y - 1 })).filter(s => s.y >= 0) })
289  n = collide(marchEnemies(n))
290  n = fall(dropBomb(n))
291  return judge(n)
292}
293
hooks/game-client.tsx 248 lines
1// Clawd Invaders' surface module: it keeps the games, the key and pointer
2// listeners and the one clock of the instance, and draws the board. Without
3// the keyboard the pane plays a demo on autopilot, so it shows what it is;
4// with it, the player's game runs.
5//
6// Two things hand the game the keyboard: the pane's own focus (ctrl+x tab, or
7// the open asking for it) and a click on the game, which gives this Client the
8// keys while the pane's isFocused stays false. No event says when a click's
9// focus ends (Escape returns it unseen), so a game that hears no key for a
10// while pauses itself, and playing again is explicit.
11
12import type { ClientSurface } from 'claude-code'
13
14import type { ClaudeState } from '../types'
15import { LIVES, autopilot, fits, move, newGame, resize, step } from './game'
16import type { Game } from './game'
17import { FLAME, ORANGE, frame, overlay, paint, runs } from './game-sprites'
18import type { Line, Run } from './game-sprites'
19
20export const STEP_MS = 90
21// Cells a key press moves the ship
22const KEY_STEP = 2
23// Rows the HUD, the board's two borders and the status line take
24const FRAME_ROWS = 4
25// The board takes the pane's whole height, the room a shooter wants, but
26// stays this narrow at most, centered in a wider pane
27const MAX_W = 44
28// Ticks the demo shows its lost game before it plays another
29const DEMO_RESTART_TICKS = 20
30// Ticks of play without a key before the game takes the keyboard for gone
31export const IDLE_PAUSE_TICKS = Math.round(12_000 / STEP_MS)
32const HEART = '#E5484D'
33
34export type Props = { isFocused: boolean; claude: ClaudeState }
35
36export type Local = {
37  props: Props
38  // The player's game, from the first time the pane has the keyboard
39  play?: Game
40  demo?: Game
41  demoOverFor: number
42  isPaused: boolean
43  // The board size the games were last laid out for
44  size: { w: number; h: number }
45  // True from a click on the game or a key it heard, until it hears none for
46  // IDLE_PAUSE_TICKS
47  hasKeys: boolean
48  idleTicks: number
49}
50
51const CLAUDE_LINE: Record<ClaudeState, string> = {
52  idle: 'Claude: en espera',
53  working: 'Claude: trabajando…',
54  done: 'Claude: terminó',
55}
56
57const seed = () => Math.floor(Math.random() * 4294967296)
58
59const hasKeyboard = (s: Local) => s.props.isFocused || s.hasKeys
60
61// The demo plays whenever the game has no keyboard and no game of the
62// player's is waiting on it
63const isDemo = (s: Local) => !hasKeyboard(s) && s.play?.status !== 'playing'
64
65const shouldRun = (s: Local) => {
66  if (!fits(s.size.w, s.size.h)) return false
67  if (isDemo(s)) return s.demo !== undefined
68  return hasKeyboard(s) && !s.isPaused && s.play?.status === 'playing'
69}
70
71export function advance(s: Local) {
72  if (isDemo(s) && s.demo) {
73    if (s.demo.status === 'over') {
74      s.demoOverFor += 1
75      if (s.demoOverFor >= DEMO_RESTART_TICKS) {
76        s.demo = newGame(s.size.w, s.size.h, seed())
77        s.demoOverFor = 0
78      }
79    } else {
80      s.demo = step(move(s.demo, autopilot(s.demo)))
81    }
82  } else if (s.play) {
83    s.play = step(s.play)
84    s.idleTicks += 1
85    if (s.idleTicks >= IDLE_PAUSE_TICKS) {
86      s.hasKeys = false
87      s.isPaused = true
88    }
89  }
90}
91
92// What to say over the player's board, if anything
93function message(s: Local, g: Game): Line[] {
94  if (g.status === 'over') {
95    return [
96      { text: g.cause === 'invaded' ? '¡Los bugs llegaron!' : '¡Sin vidas!', fg: HEART, bold: true },
97      { text: `Puntos: ${g.score}` },
98      { text: hasKeyboard(s) ? 'Enter: otra vez' : 'Clic para jugar otra' },
99    ]
100  }
101  if (!hasKeyboard(s)) return [{ text: 'Pausa', bold: true }, { text: 'Clic para seguir' }]
102  if (s.isPaused && g.t === 0) {
103    return [
104      { text: 'CLAWD INVADERS', fg: ORANGE, bold: true },
105      { text: 'Enter: jugar' },
106      { text: '←/→ o a/d: mover · dispara sola' },
107    ]
108  }
109  if (s.isPaused) return [{ text: 'Pausa', bold: true }, { text: 'Enter: seguir · p: pausa' }]
110  if (g.celebrate > 0) return [{ text: `¡Oleada ${g.wave - 1} limpia!`, fg: FLAME, bold: true }]
111  return []
112}
113
114export default function GameClient(props: Props, surface: ClientSurface<Local>) {
115  const { Box, Text } = surface.elements
116  const first = surface.state === undefined
117  const s: Local =
118    surface.state ?? { props, demoOverFor: 0, isPaused: true, size: { w: 0, h: 0 }, hasKeys: false, idleTicks: 0 }
119  s.props = props
120  if (!hasKeyboard(s)) {
121    s.isPaused = true
122    if (s.play?.status === 'over') s.play = undefined
123  }
124
125  // Not w and h: the JSX factory is h
126  const width = Math.min(MAX_W, surface.columns - 2)
127  const height = surface.rows - FRAME_ROWS
128  if (width > 0 && height > 0 && (width !== s.size.w || height !== s.size.h)) {
129    s.size = { w: width, h: height }
130    if (fits(width, height)) {
131      if (s.play) s.play = resize(s.play, width, height)
132      s.demo = s.demo ? resize(s.demo, width, height) : newGame(width, height, seed())
133    }
134    s.isPaused = true
135  }
136  const ensurePlay = () => {
137    if (s.play || !fits(s.size.w, s.size.h)) return
138    s.play = newGame(s.size.w, s.size.h, seed())
139    s.isPaused = true
140  }
141  if (hasKeyboard(s)) ensurePlay()
142
143  if (first) {
144    surface.setState(s)
145    const redraw = () => surface.setState(s)
146
147    // One clock for the instance, started once as the engine asks; a paused
148    // game's tick does nothing and draws nothing
149    surface.every(STEP_MS, () => {
150      if (!shouldRun(s)) return
151      advance(s)
152      redraw()
153    })
154
155    surface.onPointer(({ type }) => {
156      if (type !== 'down' || s.hasKeys) return
157      s.hasKeys = true
158      s.idleTicks = 0
159      ensurePlay()
160      redraw()
161    })
162
163    surface.onKey(({ key, ctrl, meta }) => {
164      if (ctrl || meta) return
165      s.hasKeys = true
166      s.idleTicks = 0
167      ensurePlay()
168      const g = s.play
169      if (!g || !fits(s.size.w, s.size.h)) return redraw()
170      if (g.status === 'over') {
171        if (key !== 'return' && key !== ' ' && key !== 'r') return redraw()
172        s.play = newGame(s.size.w, s.size.h, seed())
173        s.isPaused = false
174      } else if (key === 'p') {
175        s.isPaused = !s.isPaused
176      } else if (key === 'left' || key === 'a') {
177        s.play = move(g, -KEY_STEP)
178        s.isPaused = false
179      } else if (key === 'right' || key === 'd') {
180        s.play = move(g, KEY_STEP)
181        s.isPaused = false
182      } else if (key === 'return' || key === ' ') {
183        s.isPaused = false
184      }
185      redraw()
186    })
187  }
188
189  if (s.size.w <= 0 || s.size.h <= 0) return <Text dimColor>Clawd Invaders…</Text>
190
191  if (!fits(s.size.w, s.size.h) || !s.demo) {
192    return (
193      <Box flexDirection="column">
194        <Text>Panel muy pequeño para Clawd Invaders.</Text>
195        <Text dimColor>Ensánchalo o usa un terminal más grande.</Text>
196      </Box>
197    )
198  }
199
200  const demo = isDemo(s)
201  const g = demo ? s.demo : s.play!
202  const lines = demo ? [] : message(s, g)
203  const board = frame(lines.length > 0 ? overlay(paint(g), lines) : paint(g)).map(runs)
204
205  const margin = ' '.repeat(Math.max(0, Math.floor((surface.columns - (s.size.w + 2)) / 2)))
206  const hint = hasKeyboard(s) ? 'Esc: prompt · p: pausa' : 'clic: jugar'
207  const styled = (run: Run, key: string) => (
208    <Text
209      key={key}
210      {...(run.fg ? { color: run.fg } : {})}
211      {...(run.bg ? { backgroundColor: run.bg } : {})}
212      {...(run.bold ? { bold: true } : {})}
213    >
214      {run.text}
215    </Text>
216  )
217
218  return (
219    <Box flexDirection="column">
220      {demo ? (
221        <Text wrap="truncate">
222          {margin}
223          <Text color={ORANGE} bold>
224            DEMO
225          </Text>
226          <Text dimColor>{'  haz clic para jugar'}</Text>
227        </Text>
228      ) : (
229        <Text wrap="truncate">
230          {margin}
231          <Text color={HEART}>{'♥'.repeat(g.lives) + '♡'.repeat(Math.max(0, LIVES - g.lives))}</Text>
232          <Text bold>{`  PUNTOS ${g.score}`}</Text>
233          <Text dimColor>{`  OLEADA ${g.wave}`}</Text>
234        </Text>
235      )}
236      {board.map((row, i) => (
237        <Text key={`r${i}`} wrap="truncate">
238          {margin}
239          {row.map((run, j) => styled(run, `s${j}`))}
240        </Text>
241      ))}
242      <Text dimColor wrap="truncate">
243        {`${margin}${CLAUDE_LINE[props.claude]} · ${hint}`}
244      </Text>
245    </Box>
246  )
247}
248
hooks/game-sprites.ts 147 lines
1// Clawd Invaders' look: the board as a grid of cells, painted like the
2// mascot's scenes (a background color per cell for bodies, thin parts as
3// half or quarter glyphs), then merged into runs of one style for the terminal.
4
5import { SHIP_H } from './game'
6import type { Game } from './game'
7
8export type Cell = { ch: string; fg?: string; bg?: string; bold?: boolean }
9export type Run = { text: string; fg?: string; bg?: string; bold?: boolean }
10// A line of a message laid over the board
11export type Line = { text: string; fg?: string; bold?: boolean }
12
13export const ORANGE = '#D97757'
14const ORANGE_HIT = '#8C4A33'
15const EYE = '#1A1A1A'
16export const FLAME = '#F2C14E'
17const BOMB = '#E5484D'
18const BORDER = '#5A5670'
19const PANEL = '#24212E'
20const BUGS = ['#C77DBB', '#6A9BCC', '#8DB360', '#D4A23C']
21
22const BLANK: Cell = { ch: ' ' }
23
24function put(grid: Cell[][], x: number, y: number, cells: Cell[]) {
25  const row = grid[y]
26  if (!row) return
27  cells.forEach((c, i) => {
28    if (x + i >= 0 && x + i < row.length) row[x + i] = c
29  })
30}
31
32// A sprite's rows in letters, as the mascot's are; . is empty
33//   B  body cell; e f  the eyes over it, left and right
34//   a b  a leg in the cell's upper left or right quarter
35//   w  a wing, the cell's lower half
36//   L R  a body cell with an eye in its lower left or right quarter
37//   F  the thruster's flame, the cell's upper half
38function sprite(rows: string[], body: string, eyes: [string, string], flame = FLAME): Cell[][] {
39  const glyph: Record<string, Cell> = {
40    B: { ch: ' ', bg: body },
41    e: { ch: eyes[0], fg: EYE, bg: body, bold: true },
42    f: { ch: eyes[1], fg: EYE, bg: body, bold: true },
43    L: { ch: '▖', fg: EYE, bg: body },
44    R: { ch: '▗', fg: EYE, bg: body },
45    a: { ch: '▘', fg: body },
46    b: { ch: '▝', fg: body },
47    w: { ch: '▄', fg: body },
48    F: { ch: '▀', fg: flame },
49  }
50  return rows.map(r => [...r].map(k => glyph[k] ?? BLANK))
51}
52
53// Clawd at the helm: the logo's square orange body with an eye in each lower
54// corner, short wings at its sides, its legs under it and a flame between
55// them that flickers. Dizzy eyes after a hit, joyful ones between waves.
56function ship(g: Game): Cell[][] {
57  const body = g.invuln > 0 && g.t % 2 === 0 ? ORANGE_HIT : ORANGE
58  const flame = g.t % 2 === 0 ? FLAME : BOMB
59  if (g.celebrate > 0) return sprite(['weBfw', '.aFb.'], body, ['>', '<'], flame)
60  if (g.invuln > 0) return sprite(['weBfw', '.aFb.'], body, ['@', '@'], flame)
61  return sprite(['wLBRw', '.aFb.'], body, [' ', ' '], flame)
62}
63
64// A bug: a colored body with a face of its own per row, and legs that step
65// out and in as it marches
66const BUG_EYES: [string, string][] = [
67  ['\\', '/'],
68  ['°', '°'],
69  ['●', '●'],
70  ['o', 'o'],
71]
72
73function bug(row: number, phase: number): Cell[][] {
74  const body = BUGS[row % BUGS.length]!
75  const eyes = BUG_EYES[row % BUG_EYES.length]!
76  return sprite(['BefB', phase % 2 === 0 ? 'a..b' : 'b..a'], body, eyes)
77}
78
79export function paint(g: Game): Cell[][] {
80  const grid: Cell[][] = Array.from({ length: g.h }, () => Array.from({ length: g.w }, () => BLANK))
81  // Bugs step with each march, every few ticks
82  const phase = Math.floor(g.t / 4)
83  for (const e of g.enemies) bug(e.row, phase).forEach((cells, dy) => put(grid, e.x, e.y + dy, cells))
84  for (const b of g.bombs) put(grid, b.x, b.y, [{ ch: '●', fg: BOMB }])
85  for (const s of g.shots) put(grid, s.x, s.y, [{ ch: '┃', fg: FLAME, bold: true }])
86  for (const s of g.sparks) {
87    const bright = s.life > 1
88    put(grid, s.x, s.y, [
89      { ch: bright ? '*' : '·', fg: FLAME, bold: true },
90      { ch: bright ? '+' : '·', fg: BOMB, bold: true },
91    ])
92  }
93  ship(g).forEach((cells, dy) => put(grid, g.ship, g.h - SHIP_H + dy, cells))
94  return grid
95}
96
97// A box of text over the middle of the board, on a panel of its own color so
98// it reads over whatever is under it
99export function overlay(grid: Cell[][], lines: Line[]): Cell[][] {
100  const out = grid.map(r => [...r])
101  const width = out[0]?.length ?? 0
102  const inner = Math.min(width, Math.max(...lines.map(l => l.text.length)) + 4)
103  const rows = [{ text: '' }, ...lines, { text: '' }]
104  const top = Math.max(0, Math.floor((out.length - rows.length) / 2))
105  const left = Math.floor((width - inner) / 2)
106  rows.forEach((line, i) => {
107    const text = [...line.text].slice(0, inner)
108    const pad = Math.floor((inner - text.length) / 2)
109    const cells = Array.from({ length: inner }, (_, k): Cell => {
110      const ch = text[k - pad]
111      if (ch === undefined) return { ch: ' ', bg: PANEL }
112      return { ch, bg: PANEL, fg: line.fg ?? FLAME, ...(line.bold ? { bold: true } : {}) }
113    })
114    put(out, left, top + i, cells)
115  })
116  return out
117}
118
119// The board inside a rounded border
120export function frame(grid: Cell[][]): Cell[][] {
121  const width = grid[0]?.length ?? 0
122  const edge = (l: string, r: string): Cell[] => [
123    { ch: l, fg: BORDER },
124    ...Array.from({ length: width }, (): Cell => ({ ch: '─', fg: BORDER })),
125    { ch: r, fg: BORDER },
126  ]
127  const side: Cell = { ch: '│', fg: BORDER }
128  return [edge('╭', '╮'), ...grid.map(r => [side, ...r, side]), edge('╰', '╯')]
129}
130
131export function runs(row: Cell[]): Run[] {
132  const out: Run[] = []
133  for (const c of row) {
134    const last = out[out.length - 1]
135    if (last && last.fg === c.fg && last.bg === c.bg && last.bold === c.bold) last.text += c.ch
136    else {
137      out.push({
138        text: c.ch,
139        ...(c.fg ? { fg: c.fg } : {}),
140        ...(c.bg ? { bg: c.bg } : {}),
141        ...(c.bold ? { bold: true } : {}),
142      })
143    }
144  }
145  return out
146}
147
types/index.d.ts 9 lines
1export type Tick = number
2export type ClaudeState = 'idle' | 'working' | 'done'
3
4declare module 'claude-code' {
5  interface PluginState {
6    'clawd-buddy': { tick: Tick; claude: ClaudeState }
7  }
8}
9