SLOPSHOPPER

crab-buddy

A pixel-art Claude crab above the prompt that works, thinks, cheers and sleeps with the session, with a small crab for each subagent, dressed for its kind of…

bandtimeragents
v0.3.0MITupdated 2026-10-17ziedgithub/claude-code-mods/crab-buddy
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · crab-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 ▟▀▀▀▀▀▀▀▀▙ ▖▖ ▌ ▟ ▟ ▌ ▗▗ + ▀▀▀▀▀▀▀▀▀▀▀▀▟▀▀▀ ▞ ▞ ▚ ▚ ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Band
▟▀▀▀▀▀▀▀▀▙ ▖▖ ▌ ▟ ▟ ▌ ▗▗ + ▀▀▀▀▀▀▀▀▀▀▀▀▟▀▀▀ ▞ ▞ ▚ ▚
README

crab-buddy

A pixel-art Claude crab lives in the band above the prompt and goes through your session with you. Each subagent gets a small crab of its own, dressed for its kind of work, with a badge for the model and effort it runs on.

crab-buddy in action

Moods

The five moods, each small crab beside the big one

MoodWhenWhat it does
idlebetween turnsblinks, glances left and right
workingwhile Claude workstypes on a laptop with its logo glowing
thinkingwhile thinking streamsraises a claw beside a growing thought bubble
happyfor 5 seconds after an answerjumps with its claws up, sparks flying
sleepingafter a minute with nothing to doslumps, eyes shut, zs rising

Subagents

Every subagent gets a small crab, left of the big one, that lives through the same moods for its own agent:

  • It works and thinks while its agent runs.
  • It cheers once the agent is done, then leaves.
  • It nods off after a minute of waiting.

Up to eight are drawn, and any more are counted as +N.

When a subagent messages the main conversation, or sends back its final report, a small envelope flies in an arc from its crab to the big one. Its flap takes the color of the sender's costume.

Costumes

Each small crab is dressed for its kind of work, so you can tell at a glance what each subagent is doing. It wears its hat all the time, holds its tool at its side, and uses that tool while its agent works.

The nine costumes, idle on top and at work below

CostumeWorn byAt work
builder: yellow hard hatimplementers, developers, engineers, fixershammers
planner: white hard hatPlan, planners, architects, strategistsdraws a blueprint
explorer: explorer's helmetExplore, researchers, searchers, analystssweeps a magnifying glass
reviewer: glassesreviewers, auditors, testers, checkersticks a sheet in red
chef: chef's hatgeneral-purposestirs a pot
scholar: mortarboardclaude-code-guide, writers, guidesreads a book
wizard: wizard's hatclaudewaves a wand
mechanic: blue capstatusline-setup, setup, config, deployturns a wrench
designer: beretdesigners, UI, Figmapaints from a palette

The built-in agent types always wear the costume shown above. Any other type, such as one of your own agents or a plugin's, is dressed by the words of its name. The last word that names a kind of work wins, so spec-reviewer reviews and repo-research-analyst explores.

A type whose name says nothing about its work goes bare, in a color of its own from a spare palette. That color is remembered across sessions, so the type keeps it. A fork, a copy of the conversation, goes bare in the crab's own orange and types on a laptop like the big crab.

Model and effort

Under each small crab's feet, a badge shows what its agent runs on, with the same signs and colors as the context-bar footer:

  • ◆ takes the color of the model's family: purple for Opus, blue for Sonnet, green for Haiku, pink for Fable, grey for any other.
  • The bar after it is as tall as the effort, in its color: ▂ low (grey), ▄ medium (teal), ▆ high (yellow), ▇ xhigh (orange), █ max (red). A model without effort levels, such as Haiku, shows its ◆ alone.

The badge appears with the agent's first request and follows each one after, so it changes if the agent switches model. It stays while the crab thinks, cheers or sleeps.

The badges take one row of the band under the crabs, added with the first badge and gone with the last small crab. A band too short to spare the row draws none.

The effort also sets how fast the crab works. At low it uses its tool, or types, once a second; at medium, every three quarters of a second; at high, twice a second; at xhigh, a little faster; at max, four times a second. A model without effort levels works at full pace.

In a subagent's transcript

When you open a subagent's transcript, from the list under the prompt or from /tasks, the band shows only that agent's crab, at the main crab's size and detail. Its costume is drawn again at that size: its hat sits on its head, and its tool is at its side. It keeps working, thinking and sleeping with its agent, and it stays dressed and badged after the agent is done, its badge under it. A fork, or a type no costume fits, is the main crab itself in its own color, typing on its laptop.

The hat takes two rows over the crab. If the band doesn't have them to spare, the agent's small crab is drawn instead. Back in the main conversation, the band shows the main crab and its crew again.

On a phone

When the terminal is narrower than about 85 columns, as on a phone:

  • The crab shrinks from 16 columns to 12, and shows its glyphs over its head instead of beside it.
  • Only as many small crabs as fit are drawn, and the others are counted as +N.

The crab sits flush against the right edge, next to the [-] that collapses the band.

The crab draws in the terminal only, at the finest detail a terminal's text allows. Each cell holds four pixels, two across and two down, drawn with the quarter-block characters (▘▝▖▗▚▞▙▛▜▟). Most terminals draw these, including the ones built on xterm.js.

Install

claude plugin marketplace add ziedgithub/claude-code-mods && claude plugin install crab-buddy@zied-mods

Needs Claude Code 2.1.296 or later.

Then restart Claude Code.

See the repository README for running it from a clone.

Source 4 files
hooks/register.tsx 409 lines
1import type { AgentInfo, EngineInterface, Register, Timer } from 'claude-code'
2
3import { AGENT_ROWS, agentMoodFor, CHEER_FRAMES, CLAUDE_COLOR, COMPACT_BELOW, drawAgent, drawLone, drawScene, flapColorOf, FRAME_MS, IDLE, minisThatFit, moodFor } from './crab'
4import type { Activity, AgentActivity, AgentModel, Costume, Flight, Mini, MiniPhase, Scene } from './crab'
5import { tap } from './shared/stream'
6
7const PERSONA_KEY = 'persona'
8const CREW_POLL_MS = 1000
9const AGENT_COLORS_KEY = 'agentColors'
10// A width change asked for a redraw that has not come yet is asked again after this many frames
11const REDRAW_RETRY_FRAMES = 4
12// A message flies on a clock of its own, smoother than the poses', for FLIGHT_STEPS of it
13const FLIGHT_MS = 50
14const FLIGHT_STEPS = 24
15// A report delivered this soon after the agent's own send is that same message
16const SENT_RECENTLY_FRAMES = 8
17
18// The small crab of each built-in agent type is dressed for its work; a fork, a copy of the
19// conversation, goes bare in the crab's own color
20export const AGENT_COSTUMES: Readonly<Record<string, Costume | null>> = {
21  'general-purpose': 'chef',
22  Explore: 'explorer',
23  Plan: 'planner',
24  'claude-code-guide': 'scholar',
25  'statusline-setup': 'mechanic',
26  claude: 'wizard',
27  fork: null,
28}
29// Any other type is dressed by the words of its name, past a plugin's prefix: the last word
30// that names a kind of work wins, as `spec-reviewer` reviews. A word here matches the start
31// of a name's word (a word of two letters, the whole of it), the longest match winning, so
32// `devops` sets up while `developer` builds
33export const COSTUME_WORDS: Readonly<Record<Costume, readonly string[]>> = {
34  reviewer: ['review', 'audit', 'critic', 'inspect', 'verif', 'check', 'lint', 'test', 'qa', 'detect', 'guard', 'sentinel', 'secur', 'judge'],
35  designer: ['design', 'figma', 'ui', 'ux', 'style', 'css', 'brand', 'visual'],
36  planner: ['plan', 'architect', 'strateg', 'roadmap', 'spec', 'scope'],
37  explorer: ['explor', 'search', 'research', 'find', 'scout', 'investigat', 'analy', 'histor', 'discover', 'locat', 'browse', 'crawl', 'fetch'],
38  scholar: ['guide', 'doc', 'readme', 'writ', 'teach', 'explain', 'tutor', 'help', 'learn', 'summar', 'translat'],
39  mechanic: ['setup', 'config', 'install', 'deploy', 'devops', 'ops', 'infra', 'ci', 'docker', 'statusline', 'release', 'maint'],
40  builder: ['implement', 'build', 'code', 'coder', 'dev', 'engineer', 'fix', 'refactor', 'migrat', 'program', 'creat', 'generat'],
41  chef: ['cook', 'chef', 'general'],
42  wizard: ['wizard', 'magic', 'oracle', 'claude'],
43}
44// A bare small crab, of a type no word dresses, takes the first of these no type holds yet,
45// kept in the store for good
46export const SPARE_AGENT_COLORS: readonly number[] = [
47  0xff7b72, 0x56d4dd, 0xa5d65a, 0xdb61a2, 0x79c0ff, 0xd29922, 0xf0f6fc, 0x8b949e, 0x2ea043, 0x9e6a03,
48]
49
50const wordsOf = (type: string): string[] =>
51  (type.split(':').pop() ?? type)
52    .replace(/([a-z0-9])([A-Z])/g, '$1 $2')
53    .toLowerCase()
54    .split(/[^a-z0-9]+/)
55    .filter(word => word !== '')
56
57const costumeOfWord = (word: string): Costume | null => {
58  let best: Costume | null = null
59  let bestLength = 0
60  for (const [costume, stems] of Object.entries(COSTUME_WORDS) as [Costume, readonly string[]][]) {
61    for (const stem of stems) {
62      const isMatch = stem.length <= 2 ? word === stem : word.startsWith(stem)
63      if (isMatch && stem.length > bestLength) {
64        best = costume
65        bestLength = stem.length
66      }
67    }
68  }
69  return best
70}
71
72export const costumeOf = (type: string): Costume | null => {
73  if (Object.hasOwn(AGENT_COSTUMES, type)) return AGENT_COSTUMES[type] ?? null
74  for (const word of wordsOf(type).reverse()) {
75    const costume = costumeOfWord(word)
76    if (costume !== null) return costume
77  }
78  return null
79}
80
81const isColorRecord = (value: unknown): value is Record<string, number> =>
82  typeof value === 'object' && value !== null && Object.values(value).every(color => typeof color === 'number')
83
84const hashOf = (text: string): number => {
85  let hash = 0
86  for (let i = 0; i < text.length; i++) hash = (hash * 31 + text.charCodeAt(i)) >>> 0
87  return hash
88}
89
90// A fork takes the crab's own color, any other type the one kept for it, else the first spare
91// no type holds; once the spares run out, one picked by the name
92export const pickAgentColor = (type: string, kept: Readonly<Record<string, number>>): number => {
93  if (type === 'fork') return CLAUDE_COLOR
94  const known = kept[type]
95  if (known !== undefined) return known
96  const taken = new Set(Object.values(kept))
97  const free = SPARE_AGENT_COLORS.find(color => !taken.has(color))
98  return free ?? SPARE_AGENT_COLORS[hashOf(type) % SPARE_AGENT_COLORS.length] ?? CLAUDE_COLOR
99}
100
101// What an agent's status means for its small crab: walking, standing, a last hop, or gone
102export const crewPhase = (status: string): MiniPhase | null => {
103  if (status === 'pending' || status === 'running') return 'running'
104  if (status === 'waiting' || status === 'idle') return 'waiting'
105  return status === 'completed' ? 'done' : null
106}
107
108// The crab thinks from the first piece of thinking until the model writes, calls a tool or
109// stops; the stream's own bookkeeping items leave it as it was
110export const isThinkingChunk = (kind: string, wasThinking: boolean): boolean => {
111  if (kind === 'thinking') return true
112  return kind === 'engine' ? wasThinking : false
113}
114
115// The crab above the prompt is repainted in place on each frame of the clock: a blit, not
116// a redraw. Its site is known once the band is drawn, and gone while a dialog takes it
117let frameTick = 0
118let activity: Activity = IDLE
119let personaSite: string | null = null
120let paintedCells: string | null = null
121let paintedSize = ''
122let redrawAskedAt: number | null = null
123// The band's room, and the agent whose transcript is in view above it, from the subagent
124// list or `/tasks` (none: the main conversation's), known once it is drawn
125let bandColumns = Number.POSITIVE_INFINITY
126let bandRows = Number.POSITIVE_INFINITY
127let viewedAgent: string | undefined
128
129// The subagents' small crabs, in the order they started, dressed for their type's work or
130// bare in its color, and badged with the model of their last request. `isListed` once
131// `$.agent.list()` showed the agent, whose leaving the list then ends it; a workflow's agents
132// are never listed and end with their `turn.complete` alone
133type CrewMember = AgentActivity & { color: number; costume: Costume | null; model?: AgentModel; isListed: boolean }
134const crew = new Map<string, CrewMember>()
135let keptColors: Record<string, number> = {}
136
137// How each agent the session ran is dressed and badged, kept once its small crab has left, so
138// its crab is dressed while its transcript is in view after it is done; `leftAt`, the frame
139// it left
140type Dress = { color: number; costume: Costume | null; model?: AgentModel; leftAt: number | null }
141const roster = new Map<string, Dress>()
142
143// A new type's color is written at once, over what another session may have kept meanwhile
144const colorOf = async ($: EngineInterface, type: string): Promise<number> => {
145  if (type === 'fork' || keptColors[type] !== undefined) return pickAgentColor(type, keptColors)
146  const stored = await $.store.get(AGENT_COLORS_KEY)
147  if (isColorRecord(stored)) keptColors = { ...stored, ...keptColors }
148  const color = pickAgentColor(type, keptColors)
149  keptColors = { ...keptColors, [type]: color }
150  await $.store.set(AGENT_COLORS_KEY, keptColors)
151  return color
152}
153
154const enlist = async ($: EngineInterface, id: string, type: string, phase: MiniPhase, isListed: boolean): Promise<void> => {
155  const costume = costumeOf(type)
156  const color = costume === null ? await colorOf($, type) : CLAUDE_COLOR
157  if (!roster.has(id)) roster.set(id, { color, costume, leftAt: null })
158  if (!crew.has(id)) crew.set(id, { color, costume, phase, isThinking: false, since: frameTick, isListed })
159}
160
161// A small crab leaves the band; its agent stays dressed in the roster
162const dismiss = (id: string): void => {
163  crew.delete(id)
164  const dress = roster.get(id)
165  if (dress !== undefined && dress.leftAt === null) roster.set(id, { ...dress, leftAt: frameTick })
166}
167
168// An agent in view the band never drew, as one started before a reload, dressed from the
169// list and the colors the store keeps, writing none: a drawing writes nothing
170const learn = async ($: EngineInterface, agents: readonly AgentInfo[], id: string): Promise<void> => {
171  const agent = agents.find(one => one.id === id)
172  if (roster.has(id) || agent === undefined) return
173  const costume = costumeOf(agent.type)
174  if (costume === null && agent.type !== 'fork' && keptColors[agent.type] === undefined) {
175    const stored = await $.store.get(AGENT_COLORS_KEY)
176    if (isColorRecord(stored)) keptColors = { ...stored, ...keptColors }
177  }
178  const color = costume === null ? pickAgentColor(agent.type, keptColors) : CLAUDE_COLOR
179  roster.set(id, { color, costume, leftAt: crew.has(id) ? null : frameTick })
180}
181
182// The model and effort of an agent's request go on its badge, and set its pace
183const badge = (id: string, model: AgentModel): void => {
184  const member = crew.get(id)
185  if (member !== undefined) crew.set(id, { ...member, model })
186  const dress = roster.get(id)
187  if (dress !== undefined) roster.set(id, { ...dress, model })
188}
189
190// The crab of an agent in view: its small crab's mood while it has one, else at rest from
191// when it left, then asleep, as a waiting one; an agent never seen goes bare in orange
192const loneOf = (id: string): Mini => {
193  const member = crew.get(id)
194  if (member !== undefined) return { color: member.color, costume: member.costume, model: member.model, mood: agentMoodFor(member, frameTick) }
195  const dress = roster.get(id)
196  const rest: AgentActivity = { phase: 'waiting', isThinking: false, since: dress?.leftAt ?? frameTick }
197  return { color: dress?.color ?? CLAUDE_COLOR, costume: dress?.costume ?? null, model: dress?.model, mood: agentMoodFor(rest, frameTick) }
198}
199
200// The messages in the air, from the small crab of `agentId`, and when each agent last sent
201type InFlight = { agentId: string; color: number; step: number }
202let flights: InFlight[] = []
203let flightTimer: Timer | null = null
204const sentAt = new Map<string, number>()
205
206const fly = async ($: EngineInterface): Promise<void> => {
207  flights = flights.map(flight => ({ ...flight, step: flight.step + 1 })).filter(flight => flight.step <= FLIGHT_STEPS)
208  if (flights.length === 0) {
209    flightTimer?.cancel()
210    flightTimer = null
211  }
212  await paint($)
213}
214
215const launch = ($: EngineInterface, agentId: string): void => {
216  const member = crew.get(agentId)
217  if (member === undefined) return
218  sentAt.set(agentId, frameTick)
219  flights = [...flights, { agentId, color: flapColorOf(member), step: 0 }]
220  flightTimer ??= $.clock.every(FLIGHT_MS, () => void fly($))
221}
222
223// An answer is the agent's report to the main loop: unless the agent just sent it itself, it
224// flies over before the small crab cheers and leaves; an interrupted or failed agent just leaves
225const finish = ($: EngineInterface, id: string, isAnswered: boolean): void => {
226  const member = crew.get(id)
227  if (member === undefined || member.phase === 'done') return
228  if (!isAnswered) {
229    dismiss(id)
230    return
231  }
232  const sent = sentAt.get(id)
233  if (sent === undefined || frameTick - sent >= SENT_RECENTLY_FRAMES) launch($, id)
234  crew.set(id, { ...member, phase: 'done', isThinking: false, since: frameTick })
235}
236
237const moveTo = (id: string, member: CrewMember, phase: MiniPhase): void => {
238  if (member.phase !== phase) crew.set(id, { ...member, phase, isThinking: false, since: frameTick })
239}
240
241// The list says which agents still run or wait; one marked done stays done until a step of
242// its own says it runs again
243const syncCrew = async ($: EngineInterface): Promise<void> => {
244  const agents = await $.agent.list()
245  const listed = new Set(agents.map(agent => agent.id))
246  for (const agent of agents) {
247    const phase = crewPhase(agent.status)
248    const member = crew.get(agent.id)
249    if (member === undefined) {
250      if (phase === 'running' || phase === 'waiting') await enlist($, agent.id, agent.type, phase, true)
251    } else if (phase === null || phase === 'done') {
252      finish($, agent.id, phase === 'done')
253    } else if (member.phase !== 'done') {
254      const listed = { ...member, isListed: true }
255      crew.set(agent.id, listed)
256      moveTo(agent.id, listed, phase)
257    }
258  }
259  for (const [id, member] of crew) {
260    if (member.isListed && !listed.has(id) && member.phase !== 'done') dismiss(id)
261  }
262}
263
264// A narrow band, as on a phone, takes the smaller crab, and draws the small crabs it has
265// room for, counting the others
266export const sceneOf = (mood: Scene['mood'], members: readonly CrewMember[], tick: number, columns: number): Scene => {
267  const isCompact = columns < COMPACT_BELOW
268  const shown = minisThatFit(members.length, columns, isCompact)
269  return {
270    mood,
271    minis: members.slice(0, shown).map(member => ({ color: member.color, mood: agentMoodFor(member, tick), costume: member.costume, model: member.model })),
272    hidden: members.length - shown,
273    flights: [],
274    isCompact,
275  }
276}
277
278// A message whose sender's small crab has left is dropped with it; one from a small crab
279// past the `shown` ones leaves from their count
280export const flightsOf = (ids: readonly string[], inFlight: readonly InFlight[], shown: number): Flight[] =>
281  inFlight.flatMap(flight => {
282    const from = Math.min(ids.indexOf(flight.agentId), shown)
283    return from < 0 ? [] : [{ from, color: flight.color, progress: flight.step / FLIGHT_STEPS }]
284  })
285
286const currentScene = (): Scene => {
287  const scene = sceneOf(moodFor(activity, frameTick), [...crew.values()], frameTick, bandColumns)
288  return { ...scene, flights: flightsOf([...crew.keys()], flights, scene.minis.length) }
289}
290
291// What the band draws: the crab and its crew; or, while an agent's transcript is in view,
292// that agent's crab alone at the crab's own size, its outfit drawn at that size, or its
293// small crab where the band lacks the rows for its hat. Badges go under them where the band
294// has the row
295const drawBand = (): { columns: number; rows: number; cells: string } => {
296  if (viewedAgent === undefined) return drawScene(currentScene(), frameTick, bandRows)
297  const mini = loneOf(viewedAgent)
298  return mini.costume !== null && bandRows < AGENT_ROWS ? drawLone(mini, frameTick, bandRows) : drawAgent(mini, frameTick, bandRows)
299}
300
301const animate = async ($: EngineInterface): Promise<void> => {
302  frameTick++
303  for (const [id, member] of crew) {
304    if (member.phase === 'done' && frameTick - member.since >= CHEER_FRAMES) dismiss(id)
305  }
306  await paint($)
307}
308
309const paint = async ($: EngineInterface): Promise<void> => {
310  const { columns, rows, cells } = drawBand()
311  if (personaSite === null || cells === paintedCells) return
312  // A crab more or fewer changes the size, which takes a redraw rather than a blit
313  if (`${columns}x${rows}` !== paintedSize) {
314    if (redrawAskedAt === null || frameTick - redrawAskedAt >= REDRAW_RETRY_FRAMES) {
315      redrawAskedAt = frameTick
316      $.ui.invalidate('ui.render')
317    }
318    return
319  }
320  const result = await $.ui.blit({ requestId: personaSite, key: PERSONA_KEY, cells })
321  if (!('deny' in result)) paintedCells = cells
322}
323
324export const register: Register = on => {
325  on('session.start', async ($, e, next) => {
326    $.clock.every(FRAME_MS, () => void animate($))
327    $.clock.every(CREW_POLL_MS, () => void syncCrew($))
328    return next(e)
329  })
330
331  // A subagent's message flies from its small crab to the crab, unless it goes to another
332  // of the subagents
333  on('session.send', async ($, e, next) => {
334    const result = await next(e)
335    if (result.isDelivered && e.agentId !== undefined && !crew.has(e.to)) launch($, e.agentId)
336    return result
337  })
338
339  // A subagent's small crab appears as it starts, dressed for its type's work
340  on('agent.spawn', async ($, e, next) => {
341    const result = await next(e)
342    if (result.agentId !== undefined) await enlist($, result.agentId, e.subagentType, 'running', false)
343    return result
344  })
345
346  // A subagent's run raises no `turn.start`: the crab works for the main loop only
347  on('turn.start', async ($, e, next) => {
348    activity = { ...activity, isWorking: true, isThinking: false }
349    return next(e)
350  })
351
352  on('turn.complete', async ($, e, next) => {
353    if (e.agentId === undefined) {
354      activity = { isWorking: false, isThinking: false, endedAt: frameTick, isCheering: e.reason === 'answer' }
355    } else {
356      finish($, e.agentId, e.reason === 'answer')
357    }
358    return next(e)
359  })
360
361  on('turn.step', async function* ($, e, next) {
362    // A subagent's small crab works on each of its steps and thinks while its thinking
363    // streams; one the crew lacks, started before a reload, is looked up in the list. Each
364    // request names the model and effort its badge shows
365    if (e.agentId !== undefined) {
366      const id = e.agentId
367      const member = crew.get(id)
368      if (member === undefined) await syncCrew($)
369      else moveTo(id, member, 'running')
370      badge(id, { id: e.model, effort: e.effort === undefined ? null : String(e.effort) })
371      return yield* tap(next(e), async chunk => {
372        const current = crew.get(id)
373        if (current === undefined || current.phase !== 'running') return
374        const isThinking = isThinkingChunk(chunk.kind, current.isThinking)
375        if (isThinking !== current.isThinking) crew.set(id, { ...current, isThinking })
376      })
377    }
378    return yield* tap(next(e), async chunk => {
379      const isThinking = isThinkingChunk(chunk.kind, activity.isThinking)
380      if (isThinking !== activity.isThinking) activity = { ...activity, isThinking }
381    })
382  })
383
384  // The band above the prompt, empty unless a survey takes it; drawn on the right of the
385  // room the engine leaves it beside its collapse mark. The crab is drawn in the terminal only.
386  // A switch to an agent's transcript, or back, draws it again
387  on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
388    if (e.props.hasSurvey || e.surface !== 'terminal') return next(e)
389    // The crab takes the band, but the mods beneath still see it drawn: context-bar learns
390    // the agent in view from it
391    await next(e)
392    const { Box, Raster } = $.ui.resolve(e)
393    bandColumns = e.props.bodyColumns
394    bandRows = e.props.maxRows
395    viewedAgent = e.props.view?.agentId
396    if (viewedAgent !== undefined && !roster.has(viewedAgent)) await learn($, await $.agent.list(), viewedAgent)
397    const { columns, rows, cells } = drawBand()
398    personaSite = e.requestId
399    paintedCells = cells
400    paintedSize = `${columns}x${rows}`
401    redrawAskedAt = null
402    return (
403      <Box justifyContent="flex-end">
404        <Raster key={PERSONA_KEY} columns={columns} rows={rows} cells={cells} />
405      </Box>
406    )
407  })
408}
409
hooks/crab.ts 685 lines
1// The Claude Code crab drawn in block glyphs: each terminal cell holds four pixels, two
2// across and two down, in at most two colors, the finest a terminal's text can draw. The
3// crab, 16 columns by 4 rows, is shaded with a lighter top and left edge and a darker right
4// and underside. The columns past it hold the glyphs of its moods (the `z` of sleep, the
5// sparks of a finished answer, the bubble of a thought). In a narrow band, as on a phone, a
6// smaller crab of 12 columns stands in for it, its glyphs over its head to spare the
7// columns. Ahead of it stands a small crab for each subagent, dressed for its agent's kind
8// of work, living its agent's moods as the crab lives the main loop's, its glyphs over its
9// head. A badge under each small crab's feet tells the model its agent runs on and the
10// effort it asks, and that effort sets how fast the crab works. While an agent's own
11// transcript is in view, its crab stands alone at the crab's own size, its outfit drawn again
12// at that size
13import { COSTUME_COLORS, COSTUMES, FULL_COSTUMES } from './costumes'
14import type { Costume, FullOutfit, Outfit } from './costumes'
15
16export type { Costume } from './costumes'
17export type Mood = 'idle' | 'working' | 'thinking' | 'happy' | 'sleeping'
18export type Activity = { isWorking: boolean; isThinking: boolean; endedAt: number; isCheering: boolean }
19// A subagent at work, waiting for a message, or done; `since` is when it became so
20export type MiniPhase = 'running' | 'waiting' | 'done'
21export type AgentActivity = { phase: MiniPhase; isThinking: boolean; since: number }
22// The model an agent's last request named, and the effort it asked: null for a model without
23// effort levels
24export type AgentModel = { id: string; effort: string | null }
25// A small crab wears the costume of its agent's kind of work; without one, as a fork or a
26// type no costume fits, it goes bare in its own color and works at a laptop as the crab does.
27// It wears its badge once its agent's first request has gone out
28export type Mini = { color: number; mood: Mood; costume: Costume | null; model?: AgentModel }
29// A message on its way from a small crab to the crab: `from` is the sender's place among
30// the small crabs, one past the drawn ones flying from their count; `progress` runs 0 to 1
31export type Flight = { from: number; color: number; progress: number }
32// `hidden`: the small crabs past the drawn ones, counted as `+N`; `isCompact`: the smaller crab
33export type Scene = { mood: Mood; minis: readonly Mini[]; hidden: number; flights: readonly Flight[]; isCompact: boolean }
34
35export const FRAME_MS = 250
36export const PERSONA_ROWS = 4
37export const MAX_MINIS = 8
38// A band narrower than this, as on a phone, takes the smaller crab
39export const COMPACT_BELOW = 80
40// Each cell holds two pixels across and two down
41const CELL_PIXELS = 2
42// The small crab is 14 pixels wide, standing on the band's floor, the top of its head on the
43// fourth pixel row under its hat; the six pixel columns at its right hold its tool
44const MINI_BODY_PIXELS = 14
45const MINI_TOOL_PIXELS = 6
46const MINI_COLUMNS = (MINI_BODY_PIXELS + MINI_TOOL_PIXELS) / CELL_PIXELS
47const MINI_HEAD_ROW = 3
48// Its glyph shows in the top row, over its tool, clear of its hat
49const MINI_GLYPH_ROW = 0
50const MINI_GLYPH_COLUMN = MINI_BODY_PIXELS / CELL_PIXELS
51const MINI_GAP = 1
52const MINI_STEP = MINI_COLUMNS + MINI_GAP
53// Its badge sits in a row under the band's crabs, the diamond under the middle of its body:
54// added once a small crab has one, where the band has the row to spare
55const BADGE_ROWS = 1
56const MINI_BADGE_COLUMN = 3
57// Each small crab keeps its own time, so they neither blink nor type in step
58const MINI_TICK_SHIFT = 7
59const HAPPY_FRAMES = 20
60// A done subagent's small crab cheers as long as the crab does, then leaves
61export const CHEER_FRAMES = HAPPY_FRAMES
62const SLEEP_FRAMES = 240
63const BLINK_EVERY = 16
64const GLANCE_EVERY = 64
65const GLANCE_FRAMES = 8
66const Z_FRAMES = 3
67const GLOW_FRAMES = 4
68const BUBBLE_FRAMES = 2
69
70const DEFAULT_COLOR = 0x01000000
71// The `claude` color of Claude Code's theme, the one of its welcome crab
72export const CLAUDE_COLOR = 0xd77757
73const Z_COLOR = 0x8b949e
74const SPARK_COLOR = 0xe3b341
75const BUBBLE_COLOR = 0xd2a8ff
76const COUNT_COLOR = 0x8b949e
77const PAPER_COLOR = 0xf0f6fc
78// A white envelope, its flap in the sender's color
79const ENVELOPE = ['PFFFFP', 'PPFFPP']
80const ENVELOPE_PIXELS = 6
81// It leaves from over the sender's head and arcs this many pixels higher on its way
82const ENVELOPE_TOP = 2
83const FLIGHT_ARC = 2
84// An empty pixel counts as a dark terminal's background when a cell must give up a color
85const BACKDROP = 0x1e1e1e
86// The badge, as the context-bar footer shows the same: a diamond in the color of the model's
87// family, then a bar as tall as the effort, in the effort's color
88const BADGE_GLYPH = '◆'
89const FAMILY = /opus|sonnet|haiku|fable/
90const MODEL_COLORS: Readonly<Record<string, number>> = { opus: 0xbc8cff, sonnet: 0x58a6ff, haiku: 0x7ee787, fable: 0xf778ba }
91const OTHER_MODEL_COLOR = 0x8b949e
92const EFFORT_BARS: Readonly<Record<string, { glyph: string; color: number }>> = {
93  low: { glyph: '▂', color: 0x8b949e },
94  medium: { glyph: '▄', color: 0x39c5bb },
95  high: { glyph: '▆', color: 0xe3b341 },
96  xhigh: { glyph: '▇', color: 0xffa657 },
97  max: { glyph: '█', color: 0xff7b72 },
98}
99// How fast an agent's crab works, by its effort: so many steps of its tool, or of its typing,
100// in so many frames, from one a second at `low` to one a frame at `max`. Without a level, as
101// on a model without effort, it works at full pace
102const PACES: Readonly<Record<string, readonly [number, number]>> = {
103  low: [1, 4],
104  medium: [1, 3],
105  high: [1, 2],
106  xhigh: [2, 3],
107  max: [1, 1],
108}
109
110type Palette = Readonly<Record<string, number>>
111
112const mixColor = (from: number, to: number, amount: number): number => {
113  let mixed = 0
114  for (const shift of [16, 8, 0]) {
115    const a = (from >> shift) & 0xff
116    const b = (to >> shift) & 0xff
117    mixed |= Math.round(a + (b - a) * amount) << shift
118  }
119  return mixed
120}
121
122// `E` eyes, `W` their glint, `K` shut eyes, `P` blush, and the laptop: `L` lid, `G` and `N`
123// its logo's two glows, `B` base
124const FIXED: Palette = {
125  E: 0x1c1c22,
126  W: 0xffffff,
127  K: 0x4b2318,
128  P: 0xff9696,
129  L: 0x8b949e,
130  G: 0xf0f6fc,
131  N: 0x58a6ff,
132  B: 0x6e7681,
133}
134
135// `H` highlight, `O` the color itself, `S` shadow, `D` the darkest, for feet and shut eyes
136export const paletteFor = (color: number): Palette => ({
137  ...FIXED,
138  H: mixColor(color, 0xffffff, 0.28),
139  O: color,
140  S: mixColor(color, 0x000000, 0.25),
141  D: mixColor(color, 0x000000, 0.5),
142})
143
144const CRAB_PALETTE = paletteFor(CLAUDE_COLOR)
145
146// The color a small crab's messages carry on their flap: its costume's, else its own
147export const flapColorOf = (mini: Pick<Mini, 'color' | 'costume'>): number =>
148  mini.costume === null ? mini.color : COSTUMES[mini.costume].flap
149
150// Blinks now and then, and looks left, then later right, as if around the room
151type Gaze = 'ahead' | 'left' | 'right' | 'shut'
152
153type Cell = { row: number; column: number }
154
155// One size of the crab: its head and standing body around the eyes of each gaze, and its
156// whole sprite in the other poses, each as tall as the band; then where its glyphs show
157type CrabArt = {
158  columns: number
159  // The columns past it its glyphs take
160  markColumns: number
161  // A thought's bubble and sleep's `z`s, one cell after the other
162  rise: readonly Cell[]
163  // Sparks as it jumps up and as it lands, where it leaves room for them
164  sparkUp: Cell | null
165  sparkDown: Cell
166  head: readonly string[]
167  eyes: Readonly<Record<Gaze, readonly string[]>>
168  standing: readonly string[]
169  // Behind a laptop seen from the back, one claw up, the logo on its lid in one glow
170  working: (isLeftUp: boolean, glow: string) => readonly string[]
171  // One claw up at its head, eyes turned to the bubble
172  pondering: readonly string[]
173  jumping: readonly string[]
174  landed: readonly string[]
175  asleep: readonly string[]
176}
177
178// The crab, 32 pixels by 8: its head's corners rounded, eyes four pixels by two with a glint
179// in one, pincers open at the ends of its claws, four legs splayed out
180const FULL_HEAD = ['.......HHHHHHHHHHHHHHHHHS.......', '......HHOOOOOOOOOOOOOOOOSS......']
181const FULL_GLINTING_EYES = '......HOOOWEEEOOOOWEEEOOOS......'
182const FULL_EYES_AHEAD = [FULL_GLINTING_EYES, 'O.O...HOOOEEEEOOOOEEEEOOOS...O.O']
183const FULL_UNDERSIDE = '......SSSSSSSSSSSSSSSSSSSS......'
184const FULL_LEGS = ['.........S...S....S...S.........', '........S...S......S...S........']
185const FULL_STANDING = ['OOOOOOOOOOOOOOOOOOOOOOOOOSOOOOOO', FULL_UNDERSIDE, ...FULL_LEGS]
186const FULL_LID = '......LLLLLLLLLLLLLLLLLLLL......'
187
188const FULL: CrabArt = {
189  columns: 16,
190  markColumns: 3,
191  rise: [
192    { row: 2, column: 16 },
193    { row: 1, column: 17 },
194    { row: 0, column: 18 },
195  ],
196  sparkUp: { row: 0, column: 16 },
197  sparkDown: { row: 1, column: 17 },
198  head: FULL_HEAD,
199  eyes: {
200    ahead: FULL_EYES_AHEAD,
201    left: ['......HOWEEEOOOOWEEEOOOOOS......', 'O.O...HOEEEEOOOOEEEEOOOOOS...O.O'],
202    right: ['......HOOOOOWEEEOOOOWEEEOS......', 'O.O...HOOOOOEEEEOOOOEEEEOS...O.O'],
203    shut: ['......HOOOOOOOOOOOOOOOOOOS......', 'O.O...HOOOKKKKOOOOKKKKOOOS...O.O'],
204  },
205  standing: FULL_STANDING,
206  working: (isLeftUp, glow) => [
207    ...FULL_HEAD,
208    isLeftUp ? '..O.O.HOOOWEEEOOOOWEEEOOOS......' : '......HOOOWEEEOOOOWEEEOOOS.O.O..',
209    isLeftUp ? '..OOOOHOOOEEEEOOOOEEEEOOOS......' : '......HOOOEEEEOOOOEEEEOOOSOOOO..',
210    isLeftUp ? `....OOLLLLLLLLL${glow}${glow}LLLLLLLLLSSSS..` : `..OOOOLLLLLLLLL${glow}${glow}LLLLLLLLLSS....`,
211    `......LLLLLLLL${glow.repeat(4)}LLLLLLLL......`,
212    FULL_LID,
213    '....BBBBBBBBBBBBBBBBBBBBBBBB....',
214  ],
215  pondering: [
216    '.......HHHHHHHHHHHHHHHHHS.O.O...',
217    '......HHOOOOOOOOOOOOOOOOSSOO....',
218    '......HOOOOOWEEEOOOOWEEEOSOO....',
219    'O.O...HOOOOOEEEEOOOOEEEEOSSS....',
220    'OOOOOOOOOOOOOOOOOOOOOOOOOS......',
221    FULL_UNDERSIDE,
222    ...FULL_LEGS,
223  ],
224  jumping: [
225    'O.O...HHHHHHHHHHHHHHHHHHSS...O.O',
226    'OOOO..HOOOOOOOOOOOOOOOOOOS..OOOO',
227    '..OOOOHOOOWEEEOOOOWEEEOOOSOOOO..',
228    '......HOOOEEEEOOOOEEEEOOOS......',
229    '......OOPPOOOOOOOOOOOOPPOS......',
230    FULL_UNDERSIDE,
231    '.......S...S........S...S.......',
232    '................................',
233  ],
234  landed: [...FULL_HEAD, ...FULL_EYES_AHEAD, 'OOOOOOOOPPOOOOOOOOOOOOPPOSOOOOOO', FULL_UNDERSIDE, ...FULL_LEGS],
235  asleep: [
236    '................................',
237    '.......HHHHHHHHHHHHHHHHHS.......',
238    '......HHOOOOOOOOOOOOOOOOSS......',
239    '......HOOOOOOOOOOOOOOOOOOS......',
240    '......HOOOKKKKOOOOKKKKOOOS......',
241    '..OOOOHOOOOOOOOOOOOOOOOOOSOOOO..',
242    FULL_UNDERSIDE,
243    '......DDDD..DD....DD..DDDD......',
244  ],
245}
246
247// The smaller crab, 24 pixels by 6 under two empty rows: eyes a cell each, glinting, under a
248// row of forehead; its glyphs take the top row, over its head and its raised claw
249const COMPACT_HEAD = [
250  '........................',
251  '........................',
252  '.....HHHHHHHHHHHHHS.....',
253  '....HHOOOOOOOOOOOOSS....',
254]
255const COMPACT_GLINTING_EYES = 'O.O.HOOOWEOOOOWEOOOS.O.O'
256const COMPACT_UNDERSIDE = '....SSSSSSSSSSSSSSSS....'
257const COMPACT_LEGS = '......S..S....S..S......'
258const COMPACT_STANDING = [COMPACT_UNDERSIDE, COMPACT_LEGS]
259
260const COMPACT: CrabArt = {
261  columns: 12,
262  markColumns: 0,
263  rise: [
264    { row: 0, column: 9 },
265    { row: 0, column: 10 },
266    { row: 0, column: 11 },
267  ],
268  sparkUp: null,
269  sparkDown: { row: 0, column: 10 },
270  head: COMPACT_HEAD,
271  eyes: {
272    ahead: [COMPACT_GLINTING_EYES, 'OOOOHOOOEEOOOOEEOOOSOOOO'],
273    left: ['O.O.HOWEOOOOWEOOOOOS.O.O', 'OOOOHOEEOOOOEEOOOOOSOOOO'],
274    right: ['O.O.HOOOOOWEOOOOWEOS.O.O', 'OOOOHOOOOOEEOOOOEEOSOOOO'],
275    shut: ['O.O.HOOOOOOOOOOOOOOS.O.O', 'OOOOHOOOKKOOOOKKOOOSOOOO'],
276  },
277  standing: COMPACT_STANDING,
278  working: (isLeftUp, glow) => [
279    ...COMPACT_HEAD.slice(0, 3),
280    isLeftUp ? '..O.HHOOOOOOOOOOOOSS....' : '....HHOOOOOOOOOOOOSS.O..',
281    isLeftUp ? '..OOHOOOEEOOOOEEOOOS....' : '....HOOOEEOOOOEEOOOSOO..',
282    isLeftUp ? '....OOLLLLLLLLLLLLSSSS..' : '..SSOOLLLLLLLLLLLLSS....',
283    `....LLLLLL${glow.repeat(4)}LLLLLL....`,
284    '..BBBBBBBBBBBBBBBBBBBB..',
285  ],
286  pondering: [
287    '........................',
288    '........................',
289    '.....HHHHHHHHHHHHHS.O.O.',
290    '....HHOOOOOOOOOOOOSSOO..',
291    'O.O.HOOOOOEEOOOOEEOSSS..',
292    'OOOOHOOOOOOOOOOOOOOS....',
293    ...COMPACT_STANDING,
294  ],
295  jumping: [
296    'O.O..HHHHHHHHHHHHHS..O.O',
297    'OOOOHHOOOOOOOOOOOOSSOOOO',
298    '....HOOOWEOOOOWEOOOS....',
299    '....HOPPEEOOOOEEPPOS....',
300    COMPACT_UNDERSIDE,
301    COMPACT_LEGS,
302    '........................',
303    '........................',
304  ],
305  landed: [...COMPACT_HEAD, COMPACT_GLINTING_EYES, 'OOOOHOPPEEOOOOEEPPOSOOOO', ...COMPACT_STANDING],
306  asleep: [
307    '........................',
308    '........................',
309    '........................',
310    '.....HHHHHHHHHHHHHS.....',
311    '....HHOOOOOOOOOOOOSS....',
312    '....HOOOOOOOOOOOOOOS....',
313    'OOOOOOOOKKOOOOKKOOOOOOOO',
314    '....DDSSSSSSSSSSSSDD....',
315  ],
316}
317
318// The small crab, 14 by 5 at two pixels a column: eyes a cell each with a glint, claws out
319// at its sides, four thin legs. Its head's top row hides under a hat
320const MINI_TOP = '...HHHHHHHH...'
321const MINI_UNDERSIDE = '..SSSSSSSSSS..'
322const MINI_LEGS = '..S.S....S.S..'
323const MINI_GAZE: Record<Gaze, readonly string[]> = {
324  ahead: ['..OOWEOOWEOO..', 'OOOOEEOOEEOOOO'],
325  left: ['..WEOOWEOOOO..', 'OOEEOOEEOOOOOO'],
326  right: ['..OOOOWEOOWE..', 'OOOOOOEEOOEEOO'],
327  shut: ['..OOOOOOOOOO..', 'OOOOKKOOKKOOOO'],
328}
329// Peeking over a laptop seen from the back, one claw up, the logo on its lid in one glow
330const miniTyping = (isLeftUp: boolean, glow: string): readonly string[] => [
331  MINI_TOP,
332  isLeftUp ? 'OOOOEEOOEEOO..' : '..OOEEOOEEOOOO',
333  isLeftUp ? '..LLLLLLLLLLOO' : 'OOLLLLLLLLLL..',
334  `..LLLL${glow}${glow}LLLL..`,
335  '.BBBBBBBBBBBB.',
336]
337// Eyes up to its raised claw
338const MINI_PONDERING = [MINI_TOP, '..OOOOEEOOEEOO', 'OOOOOOOOOOOOO.', MINI_UNDERSIDE, MINI_LEGS]
339// Eyes shut in arcs over flushed cheeks, claws out, then up
340const MINI_LANDED = [MINI_TOP, '..OOEEOOEEOO..', 'OOPPOOOOOOPPOO', MINI_UNDERSIDE, MINI_LEGS]
341const MINI_CHEERING = [MINI_TOP, 'O.OOEEOOEEOO.O', '.OPPOOOOOOPPO.', MINI_UNDERSIDE, MINI_LEGS]
342// Sat down, eyes shut, claws on the ground
343const MINI_ASLEEP = [MINI_TOP, '..OOOOOOOOOO..', '.OOOKKOOKKOOO.', 'OOSSSSSSSSSSOO', MINI_UNDERSIDE]
344
345type Mark = { row: number; column: number; glyph: string; color: number }
346type Pose = { sprite: readonly string[]; marks: readonly Mark[] }
347
348export const IDLE: Activity = { isWorking: false, isThinking: false, endedAt: -SLEEP_FRAMES, isCheering: false }
349
350// A subagent's small crab works, thinks, cheers once done, and falls asleep after a minute
351// of waiting, as the crab does for the main loop
352export const agentMoodFor = (agent: AgentActivity, tick: number): Mood => {
353  if (agent.phase === 'running') return agent.isThinking ? 'thinking' : 'working'
354  if (agent.phase === 'done') return 'happy'
355  return tick - agent.since >= SLEEP_FRAMES ? 'sleeping' : 'idle'
356}
357
358// A finished answer cheers for a moment; a quiet session falls asleep after a minute
359export const moodFor = (activity: Activity, tick: number): Mood => {
360  if (activity.isWorking) return activity.isThinking ? 'thinking' : 'working'
361  const quiet = tick - activity.endedAt
362  if (activity.isCheering && quiet < HAPPY_FRAMES) return 'happy'
363  return quiet >= SLEEP_FRAMES ? 'sleeping' : 'idle'
364}
365
366const gazeAt = (tick: number): Gaze => {
367  if (tick % BLINK_EVERY === 0) return 'shut'
368  const glance = tick % GLANCE_EVERY
369  if (glance >= 20 && glance < 20 + GLANCE_FRAMES) return 'left'
370  return glance >= 44 && glance < 44 + GLANCE_FRAMES ? 'right' : 'ahead'
371}
372
373// A pose at `tick`; at work, at its `beat`, the step its pace has reached (the crab's own is
374// the frame's)
375type PoseAt = (tick: number, beat?: number) => Pose
376
377// The step of its work an agent's crab has reached by `tick`, at the pace of its effort
378export const beatOf = (model: AgentModel | undefined, tick: number): number => {
379  const pace = model === undefined || model.effort === null ? undefined : PACES[model.effort]
380  const [steps, frames] = pace ?? [1, 1]
381  return Math.floor((tick * steps) / frames)
382}
383
384// The badge of an agent's model, from `column` of `row`: the diamond, then the effort's bar
385// for a model with effort levels; none before its first request
386export const badgeOf = (model: AgentModel | undefined, row: number, column: number): Mark[] => {
387  if (model === undefined) return []
388  const family = FAMILY.exec(model.id.toLowerCase())?.[0]
389  const color = (family === undefined ? undefined : MODEL_COLORS[family]) ?? OTHER_MODEL_COLOR
390  const bar = model.effort === null ? undefined : EFFORT_BARS[model.effort]
391  return [{ row, column, glyph: BADGE_GLYPH, color }, ...(bar === undefined ? [] : [{ row, column: column + 1, ...bar }])]
392}
393
394// The crab's poses in one of its sizes
395const posesOf = (art: CrabArt): Record<Mood, PoseAt> => {
396  const rising = (glyphs: string, color: number): Mark[] => art.rise.map((cell, i) => ({ ...cell, glyph: glyphs.charAt(i), color }))
397  return {
398    idle: tick => ({ sprite: [...art.head, ...art.eyes[gazeAt(tick)], ...art.standing], marks: [] }),
399    // Typing, one claw up and one down in turn, the logo pulsing between two glows
400    working: (tick, beat = tick) => ({ sprite: art.working(beat % 2 === 0, Math.floor(tick / GLOW_FRAMES) % 2 === 0 ? 'G' : 'N'), marks: [] }),
401    // A bubble beside its raised claw grows one dot at a time, holds whole, then starts over
402    thinking: tick => {
403      const phase = Math.floor(tick / BUBBLE_FRAMES) % 4
404      return { sprite: art.pondering, marks: rising('.oO', BUBBLE_COLOR).slice(0, Math.min(phase, 2) + 1) }
405    },
406    // Jumps with its claws up and its cheeks flushed, sparks flying
407    happy: tick => {
408      const isUp = tick % 2 === 1
409      const spark = isUp ? art.sparkUp : art.sparkDown
410      const marks = spark === null ? [] : [{ ...spark, glyph: isUp ? '*' : '+', color: SPARK_COLOR }]
411      return { sprite: isUp ? art.jumping : art.landed, marks }
412    },
413    // Slumped, eyes shut, claws down, and a `z` rising one step at a time before the next starts low
414    sleeping: tick => {
415      const phase = Math.floor(tick / Z_FRAMES) % 4
416      return { sprite: art.asleep, marks: phase === 3 ? [] : rising('zzZ', Z_COLOR).slice(0, phase + 1) }
417    },
418  }
419}
420
421const FULL_POSES = posesOf(FULL)
422const COMPACT_POSES = posesOf(COMPACT)
423
424// The small crab's poses; its one glyph a pose shows sits in the top row
425const glyphOver = (glyph: string, color: number, column = MINI_GLYPH_COLUMN): Mark[] => [
426  { row: MINI_GLYPH_ROW, column, glyph, color },
427]
428
429const standing = (gaze: Gaze): readonly string[] => [MINI_TOP, ...MINI_GAZE[gaze], MINI_UNDERSIDE, MINI_LEGS]
430
431const MINI_POSES: Record<Mood, PoseAt> = {
432  idle: tick => ({ sprite: standing(gazeAt(tick)), marks: [] }),
433  working: (tick, beat = tick) => ({ sprite: miniTyping(beat % 2 === 0, Math.floor(tick / GLOW_FRAMES) % 2 === 0 ? 'G' : 'N'), marks: [] }),
434  thinking: tick => ({ sprite: MINI_PONDERING, marks: glyphOver('.oOO'.charAt(Math.floor(tick / BUBBLE_FRAMES) % 4), BUBBLE_COLOR) }),
435  // Claws up and down in turn, too small to leave the ground
436  happy: tick => {
437    const isUp = tick % 2 === 1
438    return { sprite: isUp ? MINI_CHEERING : MINI_LANDED, marks: glyphOver(isUp ? '*' : '+', SPARK_COLOR, MINI_GLYPH_COLUMN + (isUp ? 0 : 1)) }
439  },
440  sleeping: tick => {
441    const glyph = 'zZ'.charAt(Math.floor(tick / Z_FRAMES) % 3)
442    return { sprite: MINI_ASLEEP, marks: glyph === '' ? [] : glyphOver(glyph, Z_COLOR) }
443  },
444}
445
446// Dressed, it stands while idle, uses its tool while its agent works, its eyes on it, and in
447// its other moods holds it as it thinks, cheers or sleeps
448const dressedPose = (outfit: Outfit, mood: Mood, tick: number, beat: number): { sprite: readonly string[]; tool: readonly string[] } => {
449  if (mood === 'working') return { sprite: standing('right'), tool: outfit.work[beat % outfit.work.length] ?? outfit.tool }
450  return { sprite: MINI_POSES[mood](tick).sprite, tool: outfit.tool }
451}
452
453const countText = (hidden: number): string => (hidden > 0 ? `+${hidden}` : '')
454
455// The small crabs and their count take the left, a gap, then the crab and its glyphs
456export const sceneColumns = (minis: number, hidden: number, isCompact: boolean): number => {
457  const count = countText(hidden)
458  const crew = minis * MINI_STEP + (count === '' ? 0 : count.length + MINI_GAP)
459  const art = isCompact ? COMPACT : FULL
460  return crew + art.columns + art.markColumns
461}
462
463// As many small crabs as the band has room for beside the crab, at most MAX_MINIS, the
464// others counted
465export const minisThatFit = (members: number, bodyColumns: number, isCompact: boolean): number => {
466  for (let shown = Math.min(members, MAX_MINIS); shown > 0; shown--) {
467    if (sceneColumns(shown, members - shown, isCompact) <= bodyColumns) return shown
468  }
469  return 0
470}
471
472// `columns` counts cells; `pixels` holds two to a cell across and down, its rows as many as
473// the cells' rows take, and `marks` sit in cells
474type Canvas = { columns: number; pixels: (number | null)[][]; marks: Mark[] }
475
476const blankCanvas = (columns: number, rows: number): Canvas => ({
477  columns,
478  pixels: Array.from({ length: rows * CELL_PIXELS }, () => Array<number | null>(columns * CELL_PIXELS).fill(null)),
479  marks: [],
480})
481
482const rowsOf = (canvas: Canvas): number => canvas.pixels.length / CELL_PIXELS
483
484const stamp = (canvas: Canvas, sprite: readonly string[], palette: Palette, left: number, top: number): void => {
485  sprite.forEach((line, y) => {
486    for (let x = 0; x < line.length; x++) {
487      const color = palette[line.charAt(x)]
488      const row = canvas.pixels[top + y]
489      if (color !== undefined && row !== undefined && left + x < row.length) row[left + x] = color
490    }
491  })
492}
493
494// A bare small crab in its own color; a dressed one in its wear, its hat over the top of its
495// head, its tool at its right. Its badge under it, where the canvas has the row
496const drawMini = (canvas: Canvas, mini: Mini, tick: number, column: number): void => {
497  const left = column * CELL_PIXELS
498  const beat = beatOf(mini.model, tick)
499  const pose = MINI_POSES[mini.mood](tick, beat)
500  for (const mark of pose.marks) canvas.marks.push({ ...mark, column: column + mark.column })
501  if (rowsOf(canvas) > PERSONA_ROWS) canvas.marks.push(...badgeOf(mini.model, PERSONA_ROWS, column + MINI_BADGE_COLUMN))
502  if (mini.costume === null) {
503    stamp(canvas, pose.sprite, paletteFor(mini.color), left, MINI_HEAD_ROW)
504    return
505  }
506  const outfit = COSTUMES[mini.costume]
507  const palette = { ...paletteFor(mini.color), ...COSTUME_COLORS }
508  const { sprite, tool } = dressedPose(outfit, mini.mood, tick, beat)
509  stamp(canvas, sprite, palette, left, MINI_HEAD_ROW)
510  stamp(canvas, outfit.wear, palette, left, MINI_HEAD_ROW + 1)
511  stamp(canvas, outfit.hat, palette, left, MINI_HEAD_ROW + 1 - outfit.hat.length)
512  stamp(canvas, tool, palette, left + MINI_BODY_PIXELS, 0)
513}
514
515// The band's rows: a row for badges under the crabs once a small crab has one and the band
516// has `maxRows` to spare for it
517const badgedRows = (rows: number, minis: readonly Mini[], maxRows: number): number =>
518  minis.some(mini => mini.model !== undefined) && maxRows >= rows + BADGE_ROWS ? rows + BADGE_ROWS : rows
519
520export const composeScene = (scene: Scene, tick: number, maxRows = Number.POSITIVE_INFINITY): Canvas => {
521  const canvas = blankCanvas(sceneColumns(scene.minis.length, scene.hidden, scene.isCompact), badgedRows(PERSONA_ROWS, scene.minis, maxRows))
522  let left = 0
523  scene.minis.forEach((mini, place) => {
524    drawMini(canvas, mini, tick + place * MINI_TICK_SHIFT, left)
525    left += MINI_STEP
526  })
527  const count = countText(scene.hidden)
528  for (let i = 0; i < count.length; i++) canvas.marks.push({ row: PERSONA_ROWS - 1, column: left + i, glyph: count.charAt(i), color: COUNT_COLOR })
529  const countLeft = left
530  if (count !== '') left += count.length + MINI_GAP
531  const pose = (scene.isCompact ? COMPACT_POSES : FULL_POSES)[scene.mood](tick)
532  stamp(canvas, pose.sprite, CRAB_PALETTE, left * CELL_PIXELS, 0)
533  for (const mark of pose.marks) canvas.marks.push({ ...mark, column: left + mark.column })
534  for (const flight of scene.flights) {
535    const start = flight.from < scene.minis.length
536      ? flight.from * MINI_STEP * CELL_PIXELS + (MINI_BODY_PIXELS - ENVELOPE_PIXELS) / 2
537      : countLeft * CELL_PIXELS
538    const { column, row } = flightPoint(start, left * CELL_PIXELS, flight.progress)
539    stamp(canvas, ENVELOPE, { P: PAPER_COLOR, F: flight.color }, column, row)
540  }
541  return canvas
542}
543
544// Eased along the row so it sets off and lands gently, lifted most halfway; in pixels
545export const flightPoint = (start: number, end: number, progress: number): { column: number; row: number } => {
546  const t = Math.min(1, Math.max(0, progress))
547  const eased = t < 0.5 ? 2 * t * t : 1 - 2 * (1 - t) * (1 - t)
548  return { column: Math.round(start + (end - start) * eased), row: Math.round(ENVELOPE_TOP - FLIGHT_ARC * 4 * t * (1 - t)) }
549}
550
551// The block glyph of each set of a cell's four pixels, by bit: top left 1, top right 2,
552// bottom left 4, bottom right 8
553const QUADRANTS = [0x20, 0x2598, 0x259d, 0x2580, 0x2596, 0x258c, 0x259e, 0x259b, 0x2597, 0x259a, 0x2590, 0x259c, 0x2584, 0x2599, 0x259f, 0x2588]
554
555const distance = (a: number | null, b: number | null): number => {
556  const from = a ?? BACKDROP
557  const to = b ?? BACKDROP
558  let sum = 0
559  for (const shift of [16, 8, 0]) {
560    const step = ((from >> shift) & 0xff) - ((to >> shift) & 0xff)
561    sum += step * step
562  }
563  return sum
564}
565
566// A cell of four pixels: its glyph paints the foreground's pixels and leaves the background's,
567// an empty pixel the terminal's own. A cell of more than two colors keeps the pair that
568// draws it closest, the most used first, each other pixel taking the nearer of them
569const cellOf = (pixels: readonly (number | null)[]): [number, number, number] => {
570  const counts = new Map<number | null, number>()
571  for (const pixel of pixels) counts.set(pixel, (counts.get(pixel) ?? 0) + 1)
572  const colors = [...counts.keys()].sort((a, b) => (counts.get(b) ?? 0) - (counts.get(a) ?? 0))
573  let pair: (number | null)[] = colors.slice(0, 2)
574  if (colors.length > 2) {
575    let best = Number.POSITIVE_INFINITY
576    for (let i = 0; i < colors.length; i++) {
577      for (let j = i + 1; j < colors.length; j++) {
578        const a = colors[i] ?? null
579        const b = colors[j] ?? null
580        const cost = pixels.reduce<number>((sum, pixel) => sum + Math.min(distance(pixel, a), distance(pixel, b)), 0)
581        if (cost < best) {
582          best = cost
583          pair = [a, b]
584        }
585      }
586    }
587  }
588  const [first = null, second = null] = pair
589  const back = first === null ? first : second
590  const fore = first === null ? second : first
591  if (fore === null) return [0x20, DEFAULT_COLOR, DEFAULT_COLOR]
592  if (back === null && pair.length === 1) return [0x20, DEFAULT_COLOR, fore]
593  let set = 0
594  pixels.forEach((pixel, bit) => {
595    if (pixel === fore || (pixel !== back && distance(pixel, fore) < distance(pixel, back))) set |= 1 << bit
596  })
597  return [QUADRANTS[set] ?? 0x20, fore, back ?? DEFAULT_COLOR]
598}
599
600// The Raster's `cells`: row-major `[codePoint, foreground, background]` u32 triplets in base64
601export const encodeCanvas = (canvas: Canvas): string => {
602  const words: number[] = []
603  for (let row = 0; row < canvas.pixels.length / CELL_PIXELS; row++) {
604    const top = canvas.pixels[row * CELL_PIXELS] ?? []
605    const bottom = canvas.pixels[row * CELL_PIXELS + 1] ?? []
606    for (let column = 0; column < canvas.columns; column++) {
607      const mark = canvas.marks.find(m => m.row === row && m.column === column)
608      if (mark !== undefined) {
609        words.push(mark.glyph.charCodeAt(0), mark.color, DEFAULT_COLOR)
610      } else {
611        const x = column * CELL_PIXELS
612        words.push(...cellOf([top[x] ?? null, top[x + 1] ?? null, bottom[x] ?? null, bottom[x + 1] ?? null]))
613      }
614    }
615  }
616  return new Uint8Array(Uint32Array.from(words).buffer).toBase64()
617}
618
619export const drawScene = (scene: Scene, tick: number, maxRows = Number.POSITIVE_INFINITY): { columns: number; rows: number; cells: string } => {
620  const canvas = composeScene(scene, tick, maxRows)
621  return { columns: canvas.columns, rows: rowsOf(canvas), cells: encodeCanvas(canvas) }
622}
623
624// A dressed agent's crab at the crab's own size: its hat's four rows over its head, the
625// crab under them, its tool in the ten pixel columns right of its claw, its glyphs over its
626// right shoulder, between its hat and its tool, and its badge under it, the diamond under the
627// middle of its body
628const AGENT_HAT_PIXELS = 4
629const AGENT_TOOL_PIXELS = 10
630const AGENT_BADGE_COLUMN = 7
631export const AGENT_COLUMNS = FULL.columns + AGENT_TOOL_PIXELS / CELL_PIXELS
632export const AGENT_ROWS = PERSONA_ROWS + AGENT_HAT_PIXELS / CELL_PIXELS
633const AGENT_ART: CrabArt = {
634  ...FULL,
635  rise: [
636    { row: 1, column: 13 },
637    { row: 0, column: 14 },
638    { row: 0, column: 15 },
639  ],
640  sparkUp: { row: 0, column: 15 },
641  sparkDown: { row: 1, column: 14 },
642}
643const AGENT_POSES = posesOf(AGENT_ART)
644
645// Dressed, it stands while idle, uses its tool while its agent works, its eyes on it, and in
646// its other moods holds it as it thinks, cheers or sleeps; asleep, its head sits a row lower
647const agentPose = (outfit: FullOutfit, mood: Mood, tick: number, beat: number): { sprite: readonly string[]; tool: readonly string[]; marks: readonly Mark[]; drop: number } => {
648  if (mood === 'working') return { sprite: [...FULL_HEAD, ...FULL.eyes.right, ...FULL_STANDING], tool: outfit.work[beat % outfit.work.length] ?? outfit.tool, marks: [], drop: 0 }
649  const pose = AGENT_POSES[mood](tick)
650  return { sprite: pose.sprite, tool: outfit.tool, marks: pose.marks, drop: mood === 'sleeping' ? 1 : 0 }
651}
652
653// A small crab alone at its own size, where the band lacks the rows for its hat
654export const drawLone = (mini: Mini, tick: number, maxRows = Number.POSITIVE_INFINITY): { columns: number; rows: number; cells: string } => {
655  const canvas = blankCanvas(MINI_COLUMNS, badgedRows(PERSONA_ROWS, [mini], maxRows))
656  drawMini(canvas, mini, tick, 0)
657  return { columns: canvas.columns, rows: rowsOf(canvas), cells: encodeCanvas(canvas) }
658}
659
660// An agent's crab drawn alone at the crab's own size, as the band draws it while the agent's
661// transcript is in view. Bare, it is the crab in its agent's color, at work on its laptop;
662// dressed, it wears its outfit drawn at that size. Either works at its effort's pace
663export const drawAgent = (mini: Mini, tick: number, maxRows = Number.POSITIVE_INFINITY): { columns: number; rows: number; cells: string } => {
664  const palette = { ...paletteFor(mini.color), ...COSTUME_COLORS }
665  const beat = beatOf(mini.model, tick)
666  if (mini.costume === null) {
667    const canvas = blankCanvas(FULL.columns + FULL.markColumns, badgedRows(PERSONA_ROWS, [mini], maxRows))
668    const pose = FULL_POSES[mini.mood](tick, beat)
669    stamp(canvas, pose.sprite, palette, 0, 0)
670    canvas.marks.push(...pose.marks)
671    if (rowsOf(canvas) > PERSONA_ROWS) canvas.marks.push(...badgeOf(mini.model, PERSONA_ROWS, AGENT_BADGE_COLUMN))
672    return { columns: canvas.columns, rows: rowsOf(canvas), cells: encodeCanvas(canvas) }
673  }
674  const outfit = FULL_COSTUMES[mini.costume]
675  const canvas = blankCanvas(AGENT_COLUMNS, badgedRows(AGENT_ROWS, [mini], maxRows))
676  const { sprite, tool, marks, drop } = agentPose(outfit, mini.mood, tick, beat)
677  stamp(canvas, sprite, palette, 0, AGENT_HAT_PIXELS)
678  stamp(canvas, outfit.wear, palette, 0, AGENT_HAT_PIXELS + drop)
679  stamp(canvas, outfit.hat, palette, 0, drop)
680  stamp(canvas, tool, palette, FULL.columns * CELL_PIXELS, 0)
681  canvas.marks.push(...marks)
682  if (rowsOf(canvas) > AGENT_ROWS) canvas.marks.push(...badgeOf(mini.model, AGENT_ROWS, AGENT_BADGE_COLUMN))
683  return { columns: canvas.columns, rows: rowsOf(canvas), cells: encodeCanvas(canvas) }
684}
685
hooks/shared/stream.ts 14 lines
1// The master copy, kept at the repository's root: each mod that uses it holds a copy under
2// hooks/shared/, as a mod loads and installs on its own. Edit it here, then run
3// scripts/sync-shared.sh
4
5// Passes the response on as it streams, seeing each chunk on the way
6export async function* tap<T, R>(stream: AsyncGenerator<T, R>, see: (chunk: T) => Promise<void>): AsyncGenerator<T, R> {
7  for (;;) {
8    const step = await stream.next()
9    if (step.done === true) return step.value
10    await see(step.value)
11    yield step.value
12  }
13}
14
hooks/costumes.ts 308 lines
1// What a subagent's small crab wears for its kind of work: a hat, what it wears over its face
2// (glasses), and a tool it holds at its right and uses while its agent works.
3// All are drawn at two pixels a column, as the small crab is: a terminal cell shows four
4// pixels in at most two colors, so the art keeps to two colors in each two by two block
5export type Costume = 'builder' | 'planner' | 'explorer' | 'reviewer' | 'chef' | 'scholar' | 'wizard' | 'mechanic' | 'designer'
6
7export type Outfit = {
8  // Rows over its head, 14 pixels wide, the last over the top row of its head
9  hat: readonly string[]
10  // Rows over its face from its eyes down, 14 pixels wide, in every pose
11  wear: readonly string[]
12  // The tool, six pixels wide by the band's eight pixel rows: held, clear of the top row where
13  // the crab's glyph shows, and the frames of its use
14  tool: readonly string[]
15  work: readonly (readonly string[])[]
16  // Its color on the flap of the messages it sends
17  flap: number
18}
19
20// The costumes' own colors, in lowercase letters beside the crab's uppercase ones
21export const COSTUME_COLORS = {
22  // hats: a hard hat's yellow with its light, a white one's grey, khaki and its band, a
23  // mortarboard's black and grey, violet, gold, a cap's blue and its peak, a beret's red
24  y: 0xf5c518,
25  l: 0xfff3b0,
26  w: 0xf4f4f4,
27  x: 0xb8bcc2,
28  t: 0xc8a165,
29  r: 0x7a5a2e,
30  i: 0x3d444d,
31  a: 0x6e7681,
32  v: 0x8957e5,
33  j: 0xffd33d,
34  n: 0x2f81f7,
35  m: 0x1158c7,
36  f: 0xda3633,
37  // wear: glasses' frame and lenses
38  k: 0x1f2328,
39  q: 0x9ecbff,
40  // tools: wood and its dark, steel and its dark, paper and its ink, red ink, a blueprint, paint
41  b: 0xa0703c,
42  d: 0x6b4423,
43  g: 0xc9d1d9,
44  h: 0x8b949e,
45  p: 0xf6f8fa,
46  c: 0x57606a,
47  e: 0xe5534b,
48  u: 0x1f6feb,
49  z: 0x3fb950,
50  // shades the outfits drawn at the crab's own size add: each hat's shadow, a steel and a
51  // wood highlight, a blueprint's light lines
52  1: 0xc99a06,
53  2: 0xc9ced4,
54  3: 0x9c7a45,
55  4: 0x5f36b0,
56  5: 0x1a5fd0,
57  6: 0xa82724,
58  7: 0xf6f8fa,
59  8: 0xc48a4a,
60  9: 0x79b8ff,
61} as const
62
63const NONE = '......'
64
65// A tool drawn from a pixel row down, padded to the band's height
66const at = (top: number, ...rows: string[]): readonly string[] =>
67  Array.from({ length: 8 }, (_, row) => rows[row - top] ?? NONE)
68
69const hardHat = (shell: string, ridge: string): readonly string[] => [
70  `....${shell}${shell}${ridge}${ridge}${shell}${shell}....`,
71  `..${shell.repeat(4)}${ridge}${ridge}${shell.repeat(4)}..`,
72  `..${shell.repeat(4)}${ridge}${ridge}${shell.repeat(4)}..`,
73  shell.repeat(14),
74]
75
76// An open wrench held up on a slant
77const WRENCH = ['...g.g', '...ggg', '..gg..', '.gg...', 'gg....']
78// A sheet's line of writing, then ticked in red
79const SHEET = ['..ppcc', '..pppp']
80const TICKED = ['..pecc', '..eppp']
81// A ring of steel round a glass, its handle down to the claw
82const LENS = ['.gggg.', 'ggqqgg', 'ggqqgg', '.gggg.', '.b....', 'b.....']
83
84export const COSTUMES: Readonly<Record<Costume, Outfit>> = {
85  // A yellow hard hat, hammering
86  builder: {
87    hat: hardHat('y', 'l'),
88    wear: [],
89    tool: at(2, 'gggg..', 'hhhh..', '.bb...', '.bb...', '.bb...'),
90    work: [at(0, 'gggg..', 'hhhh..', '.bb...', '.bb...', '.bb...'), at(2, '....gg', '....gg', '....gg', 'bbbbgg')],
91    flap: COSTUME_COLORS.y,
92  },
93  // A white hard hat and a blueprint, drawn line by line
94  planner: {
95    hat: hardHat('w', 'x'),
96    wear: [],
97    tool: at(2, 'uuuuuu', 'uppppu', 'uuupuu', 'upuupu', 'upuupu', 'uuuuuu'),
98    work: [
99      at(2, 'uuuuuu', 'uuuuuu', 'uuuuuu', 'uuuuuu', 'uuuuuu', 'uuuuuu'),
100      at(2, 'uuuuuu', 'uppppu', 'uuuuuu', 'uuuuuu', 'uuuuuu', 'uuuuuu'),
101      at(2, 'uuuuuu', 'uppppu', 'uuupuu', 'uuupuu', 'uuuuuu', 'uuuuuu'),
102      at(2, 'uuuuuu', 'uppppu', 'uuupuu', 'upuupu', 'upuupu', 'uuuuuu'),
103    ],
104    flap: COSTUME_COLORS.u,
105  },
106  // A khaki explorer's helmet and a magnifying glass, sweeping up and down
107  explorer: {
108    hat: ['....tttttt....', '...tttttttt...', '..rrrrrrrrrr..', 'tttttttttttttt'],
109    wear: [],
110    tool: at(2, ...LENS),
111    work: [at(0, ...LENS), at(2, ...LENS)],
112    flap: COSTUME_COLORS.t,
113  },
114  // Glasses, ticking a sheet in red
115  reviewer: {
116    hat: [],
117    wear: ['..OkqqkkqqkO..', '..OkEEOOEEkO..'],
118    tool: at(2, ...SHEET, ...SHEET, ...SHEET),
119    work: [at(2, ...SHEET, ...SHEET, ...SHEET), at(2, ...TICKED, ...SHEET, ...SHEET), at(2, ...TICKED, ...TICKED, ...SHEET), at(2, ...TICKED, ...TICKED, ...TICKED)],
120    flap: COSTUME_COLORS.e,
121  },
122  // A chef's toque, stirring a pot
123  chef: {
124    hat: ['..ww.wwww.ww..', '.wwwwwwwwwwww.', '..wwwwwwwwww..', '..xxxxxxxxxx..'],
125    wear: [],
126    tool: at(2, '..bb..', '..bb..', '...b..', '...b..', '...b..'),
127    work: [at(2, '...b..', '...b..', '...b..', '...b..', 'gggggg', 'hhhhhh'), at(2, '..b...', '..b...', '..b...', '..b...', 'gggggg', 'hhhhhh')],
128    flap: COSTUME_COLORS.w,
129  },
130  // A mortarboard and its tassel, reading a book a page at a time
131  scholar: {
132    hat: ['....aaaaaa....', 'aaaaaaaaaaaaaa', '...iiiiiiii..j', '...iiiiiiii..j'],
133    wear: [],
134    tool: at(4, 'dddd..', 'djjd..', 'dddd..', 'pppp..'),
135    work: [at(4, 'pppppp', 'pcpcpc', 'dddddd'), at(2, '..pp..', '..pp..', 'pppppp', 'pcpcpc', 'dddddd')],
136    flap: COSTUME_COLORS.j,
137  },
138  // A starred wizard's hat, waving a wand
139  wizard: {
140    hat: ['.......vv.....', '.....vvvv.....', '....vvjvvv....', '.vvvvvvvvvvvv.'],
141    wear: [],
142    tool: at(2, '..jj..', '..jj..', '..d...', '..d...', '.d....', 'd.....'),
143    work: [at(0, '...l.j', '....j.', '...d..', '..d...', '.d....', 'd.....'), at(4, '....lj', 'ddddjj', '.....l')],
144    flap: COSTUME_COLORS.v,
145  },
146  // A blue cap, turning a wrench
147  mechanic: {
148    hat: ['..............', '...nnnnnnnn...', '..nnnnnnnnnn..', '..nnnnnnnnnnmm'],
149    wear: [],
150    tool: at(2, ...WRENCH),
151    work: [at(0, ...WRENCH), at(0, '..gg.g', '..gggg', ...WRENCH.slice(2))],
152    flap: COSTUME_COLORS.n,
153  },
154  // A red beret, painting from a palette
155  designer: {
156    hat: ['......f.......', '...ffffffff...', '.fffffffffffff'],
157    wear: [],
158    tool: at(4, 'tttttt', 'tftntz', 'tttttt'),
159    work: [at(0, '...d..', '...d..', '...f..', '...f..', 'tttttt', 'tftntz', 'tttttt'), at(0, '..d...', '..d...', '..n...', '..n...', 'tttttt', 'tftntz', 'tttttt')],
160    flap: COSTUME_COLORS.f,
161  },
162}
163
164// The same outfits drawn again for the crab's own size, as an agent's crab wears them while
165// its transcript is in view, at the crab's 32 pixels by 8: a hat of five rows, the last on
166// the top row of its head, a tassel's rows past them; wear over its face from that row; and
167// a tool ten pixels wide by the figure's twelve rows, held right of its claw
168export type FullOutfit = { hat: readonly string[]; wear: readonly string[]; tool: readonly string[]; work: readonly (readonly string[])[] }
169
170const BLANK = '..........'
171
172// A tool at the crab's size drawn from a pixel row down, padded to the figure's height
173const tall = (top: number, ...rows: string[]): readonly string[] =>
174  Array.from({ length: 12 }, (_, row) => rows[row - top] ?? BLANK)
175
176const hardHatOf = (shell: string, ridge: string, shade: string): readonly string[] => [
177  `...........${shell.repeat(4)}${ridge}${ridge}${shell.repeat(3)}${shade}...........`,
178  `.........${shell.repeat(6)}${ridge}${ridge}${shell.repeat(5)}${shade}.........`,
179  `........${shell.repeat(7)}${ridge}${ridge}${shell.repeat(6)}${shade}........`,
180  `........${shell.repeat(7)}${ridge}${ridge}${shell.repeat(6)}${shade}........`,
181  `....${shell.repeat(23)}${shade}....`,
182]
183
184// A hammer's steel head over its handle; a magnifying glass, its lens catching the light; an
185// open wrench
186const HAMMER = ['7gggggh...', 'gggggggh..', 'hhhhhhhh..', '.8b.......', '.8b.......', '.8b.......', '.8b.......', '.8b.......', '.8b.......']
187const FULL_LENS = ['..7ggg7...', '.gq99qqg..', 'gq9pqqqqg.', 'gqqqqqqqg.', 'gqqqqqqhg.', '.gqqqqhg..', '..ghhhg...', '.bb.......', 'bb........']
188const FULL_WRENCH = ['.g...g....', '.gg.gg....', '..ggg.....', '..7gh.....', '..gh......', '..gh......', '..gh......', '..gh......', '.ggg......', 'g..g......']
189// A clipboard's sheet of three lines, ticked one by one in red
190const PAD = ['ddddgddd..', 'dpppppcd..', 'dpccccpd..', 'dppppppd..', 'dpccccpd..', 'dppppppd..', 'dpccccpd..', 'dddddddd..']
191const ticked = (lines: number): readonly string[] =>
192  PAD.map((row, i) => ([2, 4, 6].slice(0, lines).includes(i) ? 'depcccpd..' : row))
193
194export const FULL_COSTUMES: Readonly<Record<Costume, FullOutfit>> = {
195  builder: {
196    hat: hardHatOf('y', 'l', '1'),
197    wear: [],
198    tool: tall(3, ...HAMMER),
199    work: [
200      tall(0, ...HAMMER),
201      tall(5, '..........', '.......7gh', '.......ggh', '8bbbbbbggh', 'bbbbbbbggh', '.......hhh'),
202    ],
203  },
204  planner: {
205    hat: hardHatOf('w', 'x', '2'),
206    wear: [],
207    tool: tall(4, 'uuuuuuuuu.', 'u999999uu.', 'uuuu9uuuu.', 'u9uu9uu9u.', 'u9uu9uu9u.', 'u9uuuuu9u.', 'u9999999u.', 'uuuuuuuuu.'),
208    work: [
209      tall(4, 'uuuuuuuuu.', 'uuuuuuuuu.', 'uuuuuuuuu.', 'uuuuuuuuu.', 'uuuuuuuuu.', 'uuuuuuuuu.', 'uuuuuuuuu.', 'uuuuuuuuu.'),
210      tall(4, 'uuuuuuuuu.', 'u999999uu.', 'uuuuuuuuu.', 'uuuuuuuuu.', 'uuuuuuuuu.', 'uuuuuuuuu.', 'uuuuuuuuu.', 'uuuuuuuuu.'),
211      tall(4, 'uuuuuuuuu.', 'u999999uu.', 'uuuu9uuuu.', 'u9uu9uuuu.', 'u9uu9uuuu.', 'u9uuuuuuu.', 'uuuuuuuuu.', 'uuuuuuuuu.'),
212      tall(4, 'uuuuuuuuu.', 'u999999uu.', 'uuuu9uuuu.', 'u9uu9uu9u.', 'u9uu9uu9u.', 'u9uuuuu9u.', 'u9999999u.', 'uuuuuuuuu.'),
213    ],
214  },
215  explorer: {
216    hat: [
217      '............tttttttt............',
218      '..........ttttttttttt3..........',
219      '.........tttttttttttttt3........',
220      '........rrrrrrrrrrrrrrrr........',
221      '...tttttttttttttttttttttttttt3..',
222    ],
223    wear: [],
224    tool: tall(2, ...FULL_LENS),
225    work: [tall(0, ...FULL_LENS), tall(3, ...FULL_LENS)],
226  },
227  reviewer: {
228    hat: [],
229    wear: ['', '.........gggggg..gggggg.........', '.........g....gggg....g.........', '.........g....g..g....g.........', '.........gggggg..gggggg.........'],
230    tool: tall(4, ...PAD),
231    work: [tall(4, ...PAD), tall(4, ...ticked(1)), tall(4, ...ticked(2)), tall(4, ...ticked(3))],
232  },
233  chef: {
234    hat: [
235      '.........wwww.wwww.wwww.........',
236      '.......wwwwwwwwwwwwwwwww2.......',
237      '........www2www2www2www2........',
238      '.........ww2www2www2ww2.........',
239      '........xxxxxxxxxxxxxxxx........',
240    ],
241    wear: [],
242    tool: tall(3, '..8b......', '.8bbb.....', '.bbbb.....', '..bb......', '..b.......', '..b.......', '..b.......', '..b.......', '..b.......'),
243    work: [
244      tall(2, '....b.....', '....b.....', '....b.....', '...b......', '...b......', 'g7gggggggh', 'ghhhhhhhhh', '.ggggggggh', '.ghhhhhhh.', '..hhhhhh..'),
245      tall(2, '..b.......', '..b.......', '..b.......', '...b......', '...b......', 'g7gggggggh', 'ghhhhhhhhh', '.ggggggggh', '.ghhhhhhh.', '..hhhhhh..'),
246    ],
247  },
248  scholar: {
249    hat: [
250      '...............jj...............',
251      '...aaaaaaaaaaaaaaaaaaaaaaaaaa...',
252      '.....aaaaaaaaaaaaaaaaaaaaaaj....',
253      '........iiiiiiiiiiiiiiii...j....',
254      '.......iiiiiiiiiiiiiiiiii..j....',
255      '...........................j....',
256      '..........................jjj...',
257    ],
258    wear: [],
259    tool: tall(5, 'ddddddd...', 'djjjjjd...', 'dddddddp..', 'dddddddp..', 'dddddddp..', 'dddddddp..', 'pppppppp..'),
260    work: [
261      tall(5, 'pppp.pppp.', 'pccp.pccp.', 'pppp.pppp.', 'pccpdpccp.', 'ppppdpppp.', 'ddddddddd.'),
262      tall(3, '....pp....', '....pcp...', '....ppp...', 'pppp.pppp.', 'pccp.pccp.', 'pppp.pppp.', 'pccpdpccp.', 'ppppdpppp.', 'ddddddddd.'),
263    ],
264  },
265  wizard: {
266    hat: [
267      '.......vvv......................',
268      '.........vvvvvv.................',
269      '..........vvvvjvvvv4............',
270      '........vvvvvvvvvvvvvvv4........',
271      '....vvvvvvvvvvvvvvvvvvvvvvv4....',
272    ],
273    wear: [],
274    tool: tall(4, '......lj..', '.....jjj..', '......j...', '.....d....', '....d.....', '...d......', '..d.......', '.d........'),
275    work: [
276      tall(0, '.......l..', '......ljl.', '.....l.l..', '....jj....', '....d.....', '...d......', '...d......', '..d.......', '.d........'),
277      tall(5, '.......l.l', '........j.', 'ddddddjjjl', '........j.', '.......l.l'),
278    ],
279  },
280  mechanic: {
281    hat: [
282      '...............mm...............',
283      '...........nnnnnnnnnn...........',
284      '.........nnnnnnnnnnnnnn5........',
285      '........nnnnnnnnnnnnnnnn5.......',
286      '.......nnnnnnnnnnnnnnnnnnmmmmmm.',
287    ],
288    wear: [],
289    tool: tall(2, ...FULL_WRENCH),
290    work: [tall(0, ...FULL_WRENCH), tall(2, 'g.g.......', '.ggg......', '..ggg.....', '...7gh....', '....gh....', '.....gh...', '......gh..', '.......gh.', '........gg')],
291  },
292  designer: {
293    hat: [
294      '................................',
295      '..............ff................',
296      '........ffffffffffffff6.........',
297      '....ffffffffffffffffffff66......',
298      '...fff66666666666666666.........',
299    ],
300    wear: [],
301    tool: tall(6, '.ttttttt..', 'ttfttnttt.', 'tttzt..tt.', 'ttyttt.tt.', '.ttttttt..'),
302    work: [
303      tall(0, '....d.....', '....d.....', '....d.....', '....d.....', '....f.....', '....f.....', '.ttttttt..', 'ttfttnttt.', 'tttzt..tt.', 'ttyttt.tt.', '.ttttttt..'),
304      tall(0, '..d.......', '..d.......', '..d.......', '..d.......', '..n.......', '..n.......', '.ttttttt..', 'ttfttnttt.', 'tttzt..tt.', 'ttyttt.tt.', '.ttttttt..'),
305    ],
306  },
307}
308