SLOPSHOPPER

dashboard

A band above the Claude Code prompt: an animated mini Claude that acts out what Claude is doing, who is working (model, effort, plan) and live ctx / 5h / 7d…

panebandspinnerguardcommandprompt
v0.4.0MITupdated 2026-10-09kyso1/claude-code-dashboard
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · dashboard
│ ┃ Mini Claude ✕ › fix the failing auth test and add an audit log call │ ┃ Mini Claude · 1/6 Paleta │ ┃ ⏺ Read(src/auth.ts) │ ┃  Opus 5.5 app $0.42 ⎿ Read 6 lines │ ┃ ✳ Thinking… pensando ⏺ Update(src/auth.ts) │ ┃ CTX ███ 51% 5H ████▏ 69% ↻ u ⎿ Added 2 lines, removed 1 line │ ┃ ⏺ Bash(bun test) │ ┃ 1: ✓ Do /theme 2: Clássico 3: Chamados 4: ⎿ 3 pass, 1 fail │ ┃ │ ┃ ●Paleta ○Cor ○Olhos ○Silhueta ○Chapéu ● Done. refresh now rejects expired claims and logs an audit event. │ ┃ ○Reações │ ┃ ✻ Worked for 42s · done 4:20 PM │ ┃ setas: prévia · Enter: escolhe · Esc: sai │ › /nome │ ⎿ dashboard: O mini Claude ainda não tem nome. Use /nome <nome>. │ │ ▐▙███▟▙▘ ▟█…█▙  Opus 5.5 app $0.42 ▝▜█████▌ ▗▝▘▝▀▀▀▘ ✳ Thinking… pensando ▘▘ ▝▝ CTX ███ 51% 5H ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Band
▐▙███▟▙▘ ▟█…█▙  Opus 5.5 app $0.42 ▝▜█████▌ ▗▝▘▝▀▀▀▘ ✳ Thinking… pensando ▘▘ ▝▝ CTX ███ 51% 5H
Pane · Mini Claude
Mini Claude · 1/6 Paleta  Opus 5.5 app $0.42 ✳ Thinking… pensando CTX ███ 51% 5H ████▏ 69% ↻ undefined Na… 1: ✓ Do /theme 2: Clássico 3: Chamados 4: Catppuccin Moch ●Paleta ○Cor ○Olhos ○Silhueta ○Chapéu ○Reações setas: prévia · Enter: escolhe · Esc: sai
README

claude-code-dashboard

Uma faixa viva acima do prompt do Claude Code: um mini Claude que encena o que o Claude está fazendo, quem está trabalhando (modelo, effort, plano) e medidores de contexto e de limite de uso que se atualizam em tempo real.

A faixa durante um turno: o mini Claude pensa, cozinha enquanto o Bash roda, constrói enquanto edita um arquivo e comemora no fim

É um mod: um plugin de function hooks que roda dentro do Claude Code e desenha na interface a 30 quadros por segundo. Uma statusline comum não chega lá, porque o Claude Code redesenha a statusLine no máximo uma vez por segundo, e nenhuma animação fica fluida assim.

O que tem na faixa

O mini Claude. É o bonequinho da tela de boas-vindas, desenhado em pixels de quadrante (2×2 por caractere). A cena muda conforme o que está acontecendo:

As oito cenas do mini Claude

CenaQuando apareceVerbos do spinner que caem nela
cozinhandoBashSautéing, Brewing, Baking, Simmering…
pensandoReadPondering, Musing, Cogitating…
construindoEdit, WriteForging, Crafting, Tinkering…
passeandoGrep, Glob, busca na webMeandering, Moseying, Zigzagging…
fazendo mágicaAgent, Skill, workflowsEnchanting, Clauding, Levitating…
dançandoescrevendo a respostaMoonwalking, Grooving, Vibing…
cultivandolistas de tarefasSprouting, Germinating, Hatching…
na ventaniaferramentas de MCPSwirling, Gusting, Thundering…
  • Os 189 verbos que o Claude Code sorteia para o spinner estão distribuídos nessas oito cenas.
  • Durante a ferramenta, a cena acompanha a ferramenta em uso. Entre uma e outra, volta para a do verbo do turno. Cada cena fica pelo menos 1,5 s na tela para não piscar.
  • Fora de trabalho, ele pisca quando está à toa, dorme depois de 90 s parado e comemora quando o turno termina.
  • /nome Kiko dá um nome a ele, e a legenda passa a dizer "Kiko está cozinhando".
  • /boneco abre um menu para vestir o mini Claude e escolher as cores da faixa, uma parte por vez (veja abaixo).

Quem está trabalhando. Modelo, effort (com os mesmos pips coloridos dos medidores), pasta, branch e custo da sessão. Em plano Pro ou Max, o custo aparece como "via API" ao lado de um selo do plano: é quanto aquela sessão custaria pagando por token, e não o que você está pagando.

Os medidores. Contexto restante, limite de 5 horas e limite semanal, cada um com o horário de reset:

Medidores de 96%, 58% e 9%, com o brilho passando

  • Cor: contínua, do verde (cheio) ao vermelho (vazio), calculada em OKLCH, então não há degraus nem faixas escuras no meio do caminho.
  • Precisão: as barras preenchem com 1/8 de célula (▏▎▍▌▋▊▉).
  • Brilho: atravessa os três medidores a cada 3 segundos.
  • Alerta: abaixo de 15%, o medidor pulsa.

Painel de subagents. Um script de subagentStatusLine deixa as linhas do painel de agentes no mesmo estilo. Cada linha mostra:

  • status animado;
  • minigráfico de quantos tokens o agente gastou a cada atualização;
  • contexto usado;
  • tempo rodando;
  • modelo e effort.

Linhas do painel de subagents

/boneco: personalize

/boneco abre um painel acima do prompt e passa por seis partes. A seta passa pelas opções e a prévia mostra cada uma animada. Enter (ou a tecla ao lado do nome) escolhe e segue para a próxima parte. A escolha fica salva e vale para as próximas sessões. Esc fecha o painel sem desfazer nada. Para abrir direto numa parte, use /boneco chapeu (ou paleta, cor, olhos, silhueta, reacoes).

ParteOpções
PaletaDo /theme (o padrão), Clássico, Chamados, Catppuccin Mocha, Dracula, Tokyo Night, Nord, Gruvbox, Rosé Pine, Synthwave, Fósforo, Âmbar, Daltonismo (rampa azul → laranja), Papel (terminal claro)
Corda paleta, fixa (8 amostras ou qualquer hex), arco-íris, pelo modelo, pela cena, pelo contexto, pelo effort; e dois tons
Olhosvazados, grandes, LED colorido, óculos escuros, visor; e bochechas
Silhuetaclássica, orelhinhas, cantos redondos, fantasminha
Chapéu14 chapéus, figurino por cena ou pelo calendário. Um chapéu põe 1 linha a mais na faixa.
Reaçõessusto quando uma ferramenta falha, aceno quando você responde a um pedido de permissão, suor com pouco contexto, ócio variado, bichinho

Chapéus, olhos e silhuetas

A faixa em cada paleta

Instalação

Você precisa de:

  • um Claude Code com suporte a mods (plugins of function hooks); testado na 2.1.295, e a API ainda é de acesso antecipado;
  • um terminal com truecolor e uma Nerd Font, para os ícones e as pontas arredondadas.

Pelo marketplace

No prompt do Claude Code:

/plugin install dashboard --marketplace kyso1/claude-code-dashboard

Responda y para adicionar o marketplace e escolha o escopo de usuário.

Pelo clone

git clone https://github.com/kyso1/claude-code-dashboard ~/.claude/mods/dashboard

Em ~/.claude/settings.json:

{
  "env": { "CLAUDE_CODE_PLUGIN_DIRS": "~/.claude/mods/dashboard" }
}

A pasta fica vigiada, então editar um arquivo recarrega o mod na hora.

Linhas de subagents (opcional)

{
  "subagentStatusLine": { "type": "command", "command": "bash ~/.claude/mods/dashboard/extras/subagent-statusline.sh" }
}

Se instalou pelo marketplace, aponte para o extras/subagent-statusline.sh dentro da pasta do plugin. Precisa de jq. A faixa já mostra o que uma statusline costuma mostrar, então dá para remover a statusLine se você usar uma.

Windows

O mod funciona no Windows nativo. Use o Windows Terminal com uma Nerd Font; o console antigo (conhost) não desenha truecolor direito.

git clone https://github.com/kyso1/claude-code-dashboard "$env:USERPROFILE\.claude\mods\dashboard"

Em %USERPROFILE%\.claude\settings.json, com barras normais nos caminhos:

{
  "env": { "CLAUDE_CODE_PLUGIN_DIRS": "C:/Users/<você>/.claude/mods/dashboard" },
  "subagentStatusLine": { "type": "command", "command": "powershell -NoProfile -ExecutionPolicy Bypass -File C:/Users/<você>/.claude/mods/dashboard/extras/subagent-statusline.ps1" }
}

O .ps1 faz o mesmo que o .sh, sem precisar de jq. No Windows, o Claude Code roda esses comandos no Git Bash se ele estiver instalado, e no PowerShell se não estiver. Com Git Bash e jq (winget install jqlang.jq), o .sh também funciona.

Personalizar

O quêOnde
Velocidade, largura e pausa do brilhoSPEED, RADIUS, PAUSE em hooks/gauges.ts
Largura das barras e limite do pulsoMAX_W, MIN_W, LOW em hooks/gauges.ts
Tempo mínimo de cada cenaHOLD_MS em hooks/clawd.ts
Qual ferramenta vira qual cenaTOOL_SCENES em hooks/clawd.ts
Quadros por segundoFPS em hooks/register.tsx
Paletas (cores, rampa dos medidores)PALETTES em hooks/palettes.ts
Chapéus (pixel a pixel)HAT_PIXELS em hooks/wardrobe.ts
Opções e textos do /bonecoOPTIONS em hooks/menu.ts

O mini Claude e o selo do modelo usam a cor claude do seu tema customizado, se ele definir uma. Sem isso, ficam no laranja do Claude.

Como funciona

hooks/
  register.tsx   eventos do Claude Code -> estado -> faixa; o painel /boneco
  band.ts        as linhas da faixa: palco + identidade, legenda e medidores
  clawd.ts       o mini Claude: cenas, reações, legenda
  wardrobe.ts    o que ele veste: cor do corpo, olhos, silhueta, chapéus
  pixels.ts      a grade de pixels de quadrante (2x2 por célula, até 2 cores)
  look.ts        as escolhas do /boneco, lidas campo a campo do $.store
  palettes.ts    as 14 paletas
  menu.ts        as partes do /boneco, o que cada tecla faz, a prévia
  gauges.ts      medidores, rampa de cor e brilho
  identity.ts    modelo, effort, pasta, branch, custo e plano
  paths.ts       pasta do usuário e caminhos no Windows
  paint.ts       cores OKLCH e a grade de células do Raster
extras/
  subagent-statusline.sh    linhas de subagents (jq)
  subagent-statusline.ps1   as mesmas, em PowerShell (Windows)
  check-ps1.sh              confere que as duas imprimem o mesmo
HookPara quê
ui.render em AbovePromptdesenha a faixa como um Raster (cada célula com glifo, cor de frente e de fundo)
$.clock.every(33ms) + $.ui.blitrepinta as células 30 vezes por segundo sem refazer a interface
ui.render em Spinnerlê o verbo e o modo do spinner, sem mudar o que ele desenha
tool.callqual ferramenta está rodando e com qual argumento
session.start, session.measurecontexto, limites de 5h/7d e custo
classic.Stop, classic.PostToolUseo effort em uso no turno
prompt.submit, turn.completecomeço e fim do turno
command.runo /nome, salvo em $.store entre sessões
classic.PostToolUseFailure, classic.PermissionRequest, classic.PermissionDeniedas reações do /boneco
command.run (boneco), ui.render em Pane, ui.focus, ui.closeo painel do /boneco e sua prévia

O plano vem de ~/.claude.json (oauthAccount.organizationType). O mod não lê o arquivo de credenciais.

Três armadilhas que custaram tempo:

  • Sprite fora da grade: um sprite em pixels de quadrante só pode andar de célula inteira em célula inteira. Um pixel fora da grade e os quadrantes se recombinam numa mancha torta.
  • Verbo do turno: o verbo do spinner é sorteado uma vez por turno. Por isso a cena segue a ferramenta, senão um turno longo teria uma animação só.
  • Onde passar $: a validação dos mods só aceita passar $ para funções declaradas no topo do arquivo.

Desenvolvimento

claude plugin validate .
claude plugin test .          # 63 testes: cenas, rosto alinhado, rampa de cor, brilho, legenda…
bash extras/check-ps1.sh   # o .ps1 imprime o mesmo que o .sh (precisa de pwsh e jq)

As imagens deste README saem do próprio código do mod. docs/render.mts desenha as grades de células num canvas e monta os GIFs com ffmpeg:

PLAYWRIGHT_FROM=/caminho/de/um/projeto/com/playwright/package.json npx -y tsx docs/render.mts docs

Licença

MIT

Source 12 files
hooks/register.tsx 343 lines
1import type { EngineInterface as Dollar, Register, SessionContextUsage, SessionRateLimit } from 'claude-code'
2
3import { composeBand } from './band'
4import { STAGE_W, direct, react, sceneFor, type Mood, type ReactEvent, type Reaction, type Scene, type Tool } from './clawd'
5import type { Gauge } from './gauges'
6import { CAVEMAN, PONYTAIL, planOf, prettyModel, type Identity } from './identity'
7import { DEFAULT_LOOK, readLook, type Look } from './look'
8import {
9  MENU_ID, OPTIONS, PREVIEW_KEY, STEPS, SUMMARY, SWATCHES, hotkey, isPicked, openAt, press, previewRows, progress, summary, title, typeHex,
10  type MenuState, type Press,
11} from './menu'
12import { CLAUDE, encode, fromHex, safe, type Paint } from './paint'
13import { baseName, homeOf, lastTwo } from './paths'
14
15// The band above the prompt (band.ts): mini Claude on the left; on the right who
16// is working (model, effort, folder, branch, cost), what it is doing, and the
17// fuel gauges. A mod, not a statusLine command: that redraws at 1 fps at best,
18// and the animations need ~30.
19const FPS = 30
20const KEY = 'dashboard'
21const NAME_MAX = 16
22const POKE_MS = 500 // how often to ask for the band back while it is not drawn
23
24export const register: Register = on => {
25  let gauges: Gauge[] = []
26  let mood: Mood = { working: false, since: Date.now() }
27  let tool: Tool | undefined
28  let accent: Paint = CLAUDE
29  let ident: Identity = { modes: [] }
30  let band: { requestId: string; columns: number; rows: number } | null = null
31  let poked = 0 // when the band was last asked back (POKE_MS)
32  let name: string | undefined // the mascot's, set with /nome; kept across sessions in $.store
33  let look: Look = DEFAULT_LOOK // what /boneco picked; kept across sessions in $.store
34  let reaction: Reaction = {} // a failed tool, a permission asked: drawn only if /boneco turned it on
35  let menu: MenuState | undefined // /boneco open: which part, what the focus is on
36  let pane: { columns: number; rows: number } | null = null // the menu's preview Raster, as last drawn
37  const director: { scene?: Scene; since: number } = { since: 0 }
38  const feel = (ev: ReactEvent) => {
39    reaction = react(reaction, ev, Date.now())
40  }
41
42  const measure = (context: SessionContextUsage, limits: SessionRateLimit[], usd?: number) => {
43    const limit = (kind: string, label: string): Gauge => {
44      const l = limits.find(r => r.kind === kind)
45      return { label, left: l ? 100 - l.percentUsed : null, resetsAt: l?.resetsAt ? Date.parse(l.resetsAt) : undefined }
46    }
47    gauges = [
48      { label: 'ctx', left: context.percent === undefined ? null : 100 - context.percent },
49      limit('five_hour', '5h'),
50      limit('seven_day', '7d'),
51    ]
52    if (usd !== undefined) ident = { ...ident, usd }
53  }
54
55  const bandState = () => ({ mood, tool, scene: director.scene, gauges, ident, themeAccent: accent, look, reaction, name })
56
57  const rows = (now: number, columns: number) => {
58    if (!mood.working) director.scene = undefined // the next turn opens on its own scene
59    const scene = mood.working ? direct(director, sceneFor(mood, tool), now) : undefined
60    return composeBand({ mood, tool, scene, gauges, ident, themeAccent: accent, look, reaction, name }, now, columns)
61  }
62
63  on('session.start', async ($, e, next) => {
64    const usage = await $.session.usage()
65    measure(usage.context, usage.rateLimits, usage.cost?.usd)
66    accent = await themeAccent($)
67    const stored = await $.store.get('name')
68    name = typeof stored === 'string' && stored ? stored : undefined
69    look = readLook(await $.store.get('look'))
70    await $.command.register({
71      name: 'nome',
72      description: 'Dá um nome ao mini Claude da faixa (sem nome: mostra o atual; "-": apaga)',
73      argumentHint: '<nome>',
74    })
75    await $.command.register({
76      name: 'boneco',
77      description: 'Personaliza o mini Claude e as cores da faixa, uma parte por vez',
78      argumentHint: '[paleta|cor|olhos|silhueta|chapeu|reacoes]',
79    })
80    const polled = await readIdentity($)
81    ident = { ...ident, ...polled, effort: ident.effort ?? polled.effort }
82
83    $.clock.every(1000 / FPS, async () => {
84      const now = Date.now()
85      if (band) {
86        const grid = rows(now, band.columns)
87        if (grid.length !== band.rows) {
88          band = null
89          $.ui.invalidate('ui.render')
90        } else {
91          const { deny } = await $.ui.blit({ requestId: band.requestId, key: KEY, cells: encode(grid, band.columns) })
92          if (deny) band = null // collapsed or unmounted; the next render brings it back
93        }
94      } else if (gauges.length && now - poked >= POKE_MS) {
95        // a dialog hides the band (a denied blit) and the engine shows it again with
96        // no render of its own: without this it stays frozen on its last frame
97        poked = now
98        $.ui.invalidate('ui.render')
99      }
100      if (menu && pane) {
101        const grid = previewRows(bandState(), menu, now, pane.columns)
102        if (grid.length !== pane.rows) {
103          pane = null // a hat came or went: the pane redraws at the new height
104          $.ui.invalidate('ui.render')
105        } else {
106          const { deny } = await $.ui.blit({ requestId: MENU_ID, key: PREVIEW_KEY, cells: encode(grid, pane.columns) })
107          if (deny) pane = null
108        }
109      }
110    })
111    // ponytail: who and where are polled every 5s, not hooked per way each can change
112    $.clock.every(5000, async () => {
113      accent = await themeAccent($)
114      const polled = await readIdentity($)
115      ident = { ...ident, ...polled, effort: ident.effort ?? polled.effort } // a reported effort wins
116    })
117    return next(e)
118  })
119
120  on('session.measure', ($, e, next) => {
121    measure(e.context, e.rateLimits, e.cost?.usd)
122    return next(e)
123  })
124
125  // the live effort, as the status line had it: carried by the turn's hook events
126  const effortOf = (e: { agent_id?: string; effort?: { level: string } }) => {
127    if (!e.agent_id && e.effort?.level) ident = { ...ident, effort: e.effort.level }
128  }
129  on('classic.PostToolUse', ($, e, next) => (effortOf(e), feel({ kind: 'settled', agentId: e.agent_id }), next(e)))
130  on('classic.Stop', ($, e, next) => (effortOf(e), next(e)))
131
132  // the reactions: a failed tool startles it; a permission answered, it waves as the band comes back
133  on('classic.PostToolUseFailure', ($, e, next) => (feel({ kind: 'failure', agentId: e.agent_id, interrupt: e.is_interrupt }), next(e)))
134  on('classic.PermissionRequest', ($, e, next) => (feel({ kind: 'permission', agentId: e.agent_id }), next(e)))
135  on('classic.PermissionDenied', ($, e, next) => (feel({ kind: 'settled', agentId: e.agent_id }), next(e)))
136
137  // what the mascot acts out: the turn, the spinner's verb and mode, the tool
138  on('prompt.submit', ($, e, next) => {
139    mood = { working: true, since: Date.now() }
140    feel({ kind: 'reset' })
141    return next(e)
142  })
143  on('ui.render', { component: 'Spinner' }, ($, e, next) => {
144    mood = { ...mood, working: true, word: e.props.word, message: e.props.message, mode: e.props.mode }
145    return next(e)
146  })
147  on('tool.call', async ($, e, next) => {
148    if (e.agentId) return next(e)
149    const id = e.tool_use_id
150    tool = { id, name: String(e.tool), detail: detail(e as unknown as Record<string, unknown>) }
151    try {
152      return await next(e)
153    } finally {
154      if (tool?.id === id) tool = undefined
155    }
156  })
157  on('turn.complete', ($, e, next) => {
158    if (!e.agentId) {
159      mood = { working: false, since: mood.since, doneAt: Date.now(), durationMs: e.durationMs }
160      feel({ kind: 'settled' })
161    }
162    tool = undefined
163    return next(e)
164  })
165
166  on('command.run', { command: 'nome' }, async ($, e) => {
167    const asked = safe(e.args.trim()).slice(0, NAME_MAX).trim()
168    if (!asked) return { text: name ? `O mini Claude se chama ${name}.` : 'O mini Claude ainda não tem nome. Use /nome <nome>.' }
169    if (asked === '-') {
170      await $.store.delete('name')
171      name = undefined
172      return { text: 'Nome apagado.' }
173    }
174    await $.store.set('name', asked)
175    name = asked
176    return { text: `Agora o mini Claude se chama ${asked}.` }
177  })
178
179  // /boneco: the menu, one part at a time; each pick is saved at once
180  on('command.run', { command: 'boneco' }, async ($, e) => {
181    look = readLook(await $.store.get('look')) // another session may have changed it
182    menu = openAt(e.args)
183    pane = null
184    const opened = await $.ui.open({ id: MENU_ID, title: 'Mini Claude', focus: true, closeOnEscape: true, holdToasts: true, rows: 18 })
185    $.ui.invalidate('ui.render') // already open: redraw it on the part asked for
186    return opened.isPlaced ? {} : { text: `O menu do mini Claude abre quando houver espaço: ${opened.reason}` }
187  })
188
189  on('ui.focus', { component: 'Pane', requestId: MENU_ID }, ($, e, next) => {
190    if (menu) menu = { ...menu, focused: e.element }
191    return next(e)
192  })
193
194  on('ui.close', { id: MENU_ID }, ($, e, next) => {
195    menu = undefined
196    pane = null
197    return next(e)
198  })
199
200  on('ui.render', { component: 'Pane', requestId: MENU_ID }, ($, e, next) => {
201    if (!menu) return next(e)
202    const s = menu
203    const step = STEPS[s.step]
204    const { Box, Text, Button, Input, Raster } = $.ui.resolve(e)
205    const columns = Math.max(STAGE_W + 2, e.props.bodyColumns)
206    const grid = previewRows(bandState(), s, Date.now(), columns)
207    pane = e.surface === 'terminal' ? { columns, rows: grid.length } : null
208    const done = (r: Press) => {
209      if (r.look !== look) {
210        look = r.look
211        void $.store.set('look', look)
212      }
213      menu = r.close ? undefined : { ...r.state, focused: undefined }
214      if (r.close) void $.ui.close({ id: MENU_ID })
215      $.ui.invalidate('ui.render')
216    }
217    const act = (key: string) => () => done(press(look, s, key))
218    const options = step && !s.sub ? OPTIONS[step.key] : []
219    return (
220      <Box flexDirection="column" gap={1}>
221        <Text bold>{title(s)}</Text>
222        {pane ? <Raster key={PREVIEW_KEY} columns={columns} rows={grid.length} cells={encode(grid, columns)} /> : null}
223        {s.step === SUMMARY ? <Text>{summary(look).join('\n')}</Text> : null}
224        {options.length ? (
225          <Box flexWrap="wrap" columnGap={2}>
226            {options.map((o, i) => (
227              <Button key={`opt:${o.value}`} hotkey={hotkey(i)} plain autoFocus={i === 0 || undefined} onPress={act(`opt:${o.value}`)}>
228                {`${step && isPicked(look, step.key, o.value) ? '✓ ' : ''}${o.name}`}
229              </Button>
230            ))}
231          </Box>
232        ) : null}
233        {s.sub ? (
234          <Box flexDirection="column">
235            <Box flexWrap="wrap" columnGap={2}>
236              {SWATCHES[s.sub].map(([hex, label], i) => (
237                <Button key={`sw:${hex}`} hotkey={hotkey(i)} plain autoFocus={i === 0 || undefined} onPress={act(`sw:${hex}`)}>
238                  <Text color={hex}>■</Text>
239                  {` ${label}`}
240                </Button>
241              ))}
242            </Box>
243            {s.sub === 'fixa' ? <Input key="hex" label="ou um hex " placeholder="#rrggbb" submitLabel="usar" onSubmit={v => done(typeHex(look, s, v))} /> : null}
244            {s.error ? <Text dimColor>{`✗ ${safe(s.error)}`}</Text> : null}
245          </Box>
246        ) : null}
247        {step?.key === 'color' && !s.sub ? (
248          <Button key="tog:duo" hotkey="t" plain onPress={act('tog:duo')}>{`Dois tons: ${look.duo ? 'ligado' : 'desligado'}`}</Button>
249        ) : null}
250        {step?.key === 'eyes' && !s.sub ? (
251          <Button key="tog:cheeks" hotkey="t" plain onPress={act('tog:cheeks')}>{`Bochechas: ${look.cheeks ? 'ligadas' : 'desligadas'}`}</Button>
252        ) : null}
253        <Text dimColor>{progress(s)}</Text>
254        <Box columnGap={2}>
255          {s.step > 0 || s.sub ? <Button key="nav:back" hotkey="v" plain onPress={act('nav:back')}>← voltar</Button> : null}
256          {step?.key === 'extras' ? <Button key="nav:next" hotkey="c" plain onPress={act('nav:next')}>Continuar</Button> : null}
257          {s.step === SUMMARY ? <Button key="nav:restart" hotkey="r" plain onPress={act('nav:restart')}>Recomeçar</Button> : null}
258          {s.step === SUMMARY ? <Button key="nav:close" hotkey="f" plain autoFocus onPress={act('nav:close')}>Fechar</Button> : null}
259          <Text dimColor>setas: prévia · Enter: escolhe · Esc: sai</Text>
260        </Box>
261      </Box>
262    )
263  })
264
265  on('ui.render', { component: 'AbovePrompt' }, ($, e, next) => {
266    if (e.surface !== 'terminal' || e.props.hasSurvey || !gauges.length) return next(e)
267    const { Box, Raster } = $.ui.resolve(e)
268    const columns = e.props.bodyColumns
269    const grid = rows(Date.now(), columns)
270    band = { requestId: e.requestId, columns, rows: grid.length }
271    feel({ kind: 'shown' })
272    return (
273      <Box marginTop={1}>
274        <Raster key={KEY} columns={columns} rows={grid.length} cells={encode(grid, columns)} />
275      </Box>
276    )
277  })
278}
279
280// Model, folder, branch, plan and modes: cheap reads. Effort only as settings have it;
281// the turn's own hook events report the live one.
282async function readIdentity($: Dollar): Promise<Omit<Identity, 'usd'>> {
283  const cwd = await $.session.cwd()
284  const home = await homeDir($)
285  const flag = (f: string) => $.fs.read(`${home}/.claude/${f}`).then(s => s.trim() !== '', () => false)
286  const [model, branch, caveman, ponytail, plan] = await Promise.all([
287    $.session.model(),
288    $.process.run(['git', '-C', cwd, 'branch', '--show-current']).then(r => r.stdout.trim(), () => ''),
289    flag('.caveman-active'),
290    flag('.ponytail-active'),
291    $.fs.read(`${home}/.claude.json`).then(s => planOf(JSON.parse(s)), () => undefined),
292  ])
293  return {
294    model: prettyModel(model),
295    effort: await settingsEffort($, home, model),
296    folder: baseName(cwd),
297    branch: branch || undefined,
298    plan,
299    modes: [...(caveman ? [CAVEMAN] : []), ...(ponytail ? [PONYTAIL] : [])],
300  }
301}
302
303// The first argument that says what a call is about: a command, a path, a query.
304function detail(args: Record<string, unknown>): string {
305  for (const k of ['command', 'file_path', 'pattern', 'url', 'query', 'description', 'skill', 'prompt']) {
306    const v = args[k]
307    if (typeof v !== 'string' || !v.trim()) continue
308    const first = v.trim().split('\n')[0] ?? ''
309    return k === 'file_path' ? lastTwo(first) : first
310  }
311  return ''
312}
313
314// Effort before the first turn reports it: the model's own setting, then the global one.
315async function settingsEffort($: Dollar, home: string, model: string): Promise<string | undefined> {
316  try {
317    const s = JSON.parse(await $.fs.read(`${home}/.claude/settings.json`))
318    return s?.modelSettings?.[model]?.effortLevel ?? s?.effortLevel
319  } catch {
320    return undefined
321  }
322}
323
324// The mascot and the model badge wear the theme's `claude` color when the theme
325// is a custom one (~/.claude/themes/<slug>.json) that sets it; orange otherwise.
326// That is palette P0 ('tema'); the other palettes bring their own (palettes.ts).
327async function themeAccent($: Dollar): Promise<Paint> {
328  try {
329    const theme = (await $.config.list()).find(r => r.key === 'theme')?.value
330    if (typeof theme !== 'string' || !theme.startsWith('custom:')) return CLAUDE
331    const home = await homeDir($)
332    const file = JSON.parse(await $.fs.read(`${home}/.claude/themes/${theme.slice('custom:'.length)}.json`))
333    return fromHex(String(file?.overrides?.claude ?? '')) ?? CLAUDE
334  } catch {
335    return CLAUDE
336  }
337}
338
339// HOME, or on Windows (where it may be unset) USERPROFILE
340async function homeDir($: Dollar): Promise<string> {
341  return homeOf(await $.env.get('HOME'), await $.env.get('USERPROFILE'))
342}
343
hooks/band.ts 47 lines
1// The band's rows, as register.tsx draws them and the /boneco preview shows a
2// palette: the stage on the left (3 rows, 4 with a hat) and, beside its last
3// three, who is working, what it is doing and the fuel gauges.
4
5import { STAGE_W, caption, stage, type Mood, type Reaction, type Scene, type Tool } from './clawd'
6import { gaugeRow, type Gauge } from './gauges'
7import { identityRow, type Identity } from './identity'
8import type { Look } from './look'
9import { paletteOf } from './palettes'
10import { CLAUDE, fit, type Cell, type Paint } from './paint'
11import { bodyColor } from './wardrobe'
12
13export type BandState = {
14  mood: Mood
15  tool?: Tool
16  scene?: Scene
17  gauges: Gauge[]
18  ident: Identity
19  themeAccent: Paint
20  look: Look
21  reaction?: Reaction
22  name?: string
23}
24
25const GAP: Cell[] = [{ ch: ' ', fg: CLAUDE }, { ch: ' ', fg: CLAUDE }]
26export const MIN_RIGHT = 60 // narrower than this beside the stage: drop the stage
27
28export function composeBand(b: BandState, now: number, columns: number): Cell[][] {
29  const pal = paletteOf(b.look.palette, b.themeAccent)
30  const o = {
31    look: b.look, palette: pal, reaction: b.reaction, model: b.ident.model, effortLevel: b.ident.effort,
32    ctxLeft: b.gauges.find(g => g.label === 'ctx')?.left ?? undefined,
33  }
34  const body = bodyColor(b.look, pal.accent, pal, now, b.mood.working ? b.scene : undefined, o)
35  const side = (w: number) => [
36    identityRow(b.ident, pal.accent, pal),
37    caption(b.mood, b.tool, now, w, body, b.scene, b.name, pal),
38    gaugeRow(b.gauges, now, now, w, pal),
39  ]
40  const right = columns - STAGE_W - GAP.length
41  if (right < MIN_RIGHT) return side(columns).map(row => fit(row, columns))
42  const rhs = side(right)
43  const st = stage(b.mood, now, pal.accent, b.scene, o)
44  const off = st.length - 3
45  return st.map((row, i) => [...row, ...GAP, ...fit(rhs[i - off] ?? [], right)])
46}
47
hooks/clawd.ts 362 lines
1// Mini Claude: the welcome screen's mascot, drawn in quadrant pixels (2x2 a
2// cell) on a 3-row stage, acting out the spinner's verb. Each of the 189 verbs
3// Claude Code samples belongs to one of eight scenes; a verb it learns later
4// falls back on the spinner's mode.
5
6import { DEFAULT_LOOK, type Extra, type Look } from './look'
7import { CLASSIC, type Palette } from './palettes'
8import { CLAUDE, FAINT, fit, lift, text, type Cell, type Paint } from './paint'
9import { STAGE_W, blankCanvas, dot, glyph, toCells, type Canvas } from './pixels'
10import { BLUSH, bodyColor, carved, face, ghostHem, hatFor, rowsFor, tones, wearHat, type BodyCtx, type Eyes, type Scene } from './wardrobe'
11
12export { STAGE_W } from './pixels'
13export type { Scene } from './wardrobe'
14
15export type Mode = 'requesting' | 'responding' | 'thinking' | 'tool-input' | 'tool-use'
16export type Mood = { working: boolean; word?: string; message?: string | null; mode?: Mode; since: number; doneAt?: number; durationMs?: number }
17export type Tool = { id: string; name: string; detail: string }
18
19export const VERBS: Record<Scene, string> = {
20  cook: 'Baking Blanching Brewing Bunning Caramelizing Churning Concocting Cooking Crunching Drizzling Fermenting Flambéing Frosting Garnishing Infusing Julienning Kneading Leavening Marinating Onioning Percolating Proofing Sautéing Seasoning Simmering Smooshing Stewing Tempering Whisking Zesting',
21  think: 'Befuddling Bloviating Calculating Cerebrating Cogitating Computing Considering Contemplating Deciphering Deliberating Determining Elucidating Envisioning Flummoxing Hashing Ideating Imagining Inferring Mulling Musing Perusing Philosophizing Pondering Pontificating Processing Puzzling Reticulating Ruminating Thinking',
22  build: 'Accomplishing Actioning Actualizing Architecting Bootstrapping Coalescing Combobulating Composing Crafting Creating Crystallizing Doing Doodling Effecting Embellishing Finagling Forging Forming Generating Gitifying Herding Mustering Newspapering Orchestrating Polishing Puttering Recombobulating Sketching Synthesizing Tinkering Working Wrangling',
23  dance: "Beboppin' Boogieing Booping Canoodling Choreographing Frolicking Gesticulating Grooving Harmonizing Honking Improvising Jitterbugging Moonwalking Razzle-dazzling Razzmatazzing Shimmying Sock-hopping Vibing",
24  walk: 'Boondoggling Burrowing Catapulting Dilly-dallying Fiddle-faddling Flibbertigibbeting Gallivanting Galloping Hullaballooing Kerfuffling Lollygagging Meandering Moseying Noodling Perambulating Pouncing Scampering Schlepping Scurrying Shenaniganing Skedaddling Slithering Spelunking Swooping Tomfoolering Topsy-turvying Waddling Wandering Whatchamacalliting Zigzagging',
25  magic: 'Beaming Channeling Clauding Discombobulating Enchanting Hyperspacing Ionizing Levitating Manifesting Metamorphosing Nucleating Orbiting Prestidigitating Quantumizing Sublimating Transfiguring Transmogrifying Transmuting Warping',
26  grow: 'Cultivating Germinating Hatching Incubating Nesting Osmosing Photosynthesizing Pollinating Propagating Roosting Sprouting Symbioting Unfurling',
27  wind: 'Billowing Cascading Ebbing Flowing Fluttering Gusting Misting Nebulizing Precipitating Spinning Swirling Thundering Twisting Undulating Unraveling Whirlpooling Whirring Wibbling',
28}
29export const LABELS: Record<Scene, string> = {
30  cook: 'cozinhando', think: 'pensando', build: 'construindo', dance: 'dançando',
31  walk: 'passeando', magic: 'fazendo mágica', grow: 'cultivando', wind: 'na ventania',
32}
33const MODE_LABELS: Record<Mode, string> = {
34  requesting: 'esperando a API', responding: 'escrevendo a resposta', thinking: 'pensando',
35  'tool-input': 'preparando a ferramenta', 'tool-use': 'usando ferramenta',
36}
37const BY_VERB = new Map(
38  (Object.keys(VERBS) as Scene[]).flatMap(s => VERBS[s].split(' ').map(v => [v.toLowerCase(), s] as const)),
39)
40
41export function sceneOf(word: string | undefined, mode?: Mode): Scene {
42  const key = (word ?? '').replace(/(…|\.\.\.)$/, '').trim().toLowerCase()
43  const hit = BY_VERB.get(key)
44  if (hit) return hit
45  return mode === 'tool-use' || mode === 'tool-input' ? 'build' : mode === 'responding' ? 'dance' : 'think'
46}
47
48// --- the mascot ----------------------------------------------------------------
49
50type Arm = 'out' | 'up' | 'down'
51type Pose = { eyes: Eyes; armL: Arm; armR: Arm; legs: 0 | 1 | 2 }
52
53// 18x5 pixels, as the welcome screen's  ▐▛███▜▌ / ▝▜█████▛▘ /   ▘▘ ▝▝
54// Drawn only on the cell grid (`cell` is a whole column, y always 0): a sprite
55// one pixel off it recombines the quadrants into a slanted blob with no eyes.
56// So motion is whole-cell steps, arms, legs, eyes and color, never half cells;
57// and the eyes only move within their own cell (front <-> up), never sideways.
58// What it wears (/boneco) comes with the canvas, drawn by wardrobe.ts.
59const ARMS: Record<Arm, number[][]> = { out: [[1, 2], [2, 2]], up: [[2, 1], [1, 0]], down: [[2, 3], [1, 4]] }
60const LEGS = [[4, 6, 11, 13], [3, 6, 11, 14], [4, 7, 10, 13]]
61
62function clawd(cv: Canvas, cell: number, pose: Pose, c: Paint) {
63  const { look, hat, t } = cv.dress
64  cv.cell = cell
65  const x0 = cell * 2
66  const [top, bot] = tones(look, c)
67  const at = (y: number) => (y < 2 ? top : bot)
68  const shape = hat && look.shape === 'orelhas' ? 'classica' : look.shape // a hat hides the ears
69  for (let y = 0; y < 4; y++) for (let x = 3; x <= 14; x++) if (!carved(shape, x, y)) dot(cv, x0 + x, y, at(y))
70  face(cv, x0, shape === 'orelhas' && pose.eyes === 'up' ? 'front' : pose.eyes, look, t) // an eye up would hole an ear
71  for (const [x = 0, y = 0] of ARMS[pose.armL]) dot(cv, x0 + x, y, at(y))
72  for (const [x = 0, y = 0] of ARMS[pose.armR]) dot(cv, x0 + 17 - x, y, at(y))
73  if (shape === 'fantasma') ghostHem(cv, x0, t, bot)
74  else for (const x of LEGS[pose.legs] ?? []) dot(cv, x0 + x, 4, bot)
75  if (look.cheeks) dot(cv, x0 + 4, 2, BLUSH), dot(cv, x0 + 13, 2, BLUSH)
76  if (hat) wearHat(cv, x0, hat, top, t)
77}
78
79const beat = (t: number, ms: number) => Math.floor(t / ms)
80const blink = (t: number, eyes: Eyes): Eyes => (t % 3700 < 130 ? 'shut' : eyes)
81const hash = (n: number) => Math.imul(n ^ 0x9e3779b9, 0x85ebca6b) >>> 0
82const glow = (c: Paint, on: boolean): Paint => (on ? lift(c, 0.1, 0.8) : c)
83
84const STEEL: Paint = [0.55, 0.02, 250]
85const STEAM: Paint = [0.88, 0.01, 250]
86const FLAME: Paint = [0.7, 0.18, 40]
87const FLAME2: Paint = [0.84, 0.16, 85]
88const GOLD: Paint = [0.88, 0.15, 95]
89const WOOD: Paint = [0.52, 0.08, 60]
90const LEAF: Paint = [0.76, 0.17, 145]
91const PINK: Paint = [0.76, 0.15, 350]
92const WATER: Paint = [0.76, 0.11, 235]
93const CLOUD: Paint = [0.82, 0.01, 250]
94const BUBBLE: Paint = [0.9, 0.02, 260]
95
96const SCENES: Record<Scene, (cv: Canvas, t: number, c: Paint) => void> = {
97  cook(cv, t, c) {
98    clawd(cv, 1, { eyes: blink(t, 'front'), armL: 'down', armR: beat(t, 380) % 2 ? 'out' : 'up', legs: 0 }, c)
99    for (let x = 21; x <= 24; x++) dot(cv, x, 3, STEEL) // handle
100    dot(cv, 25, 3, STEEL)
101    dot(cv, 35, 3, STEEL)
102    for (let x = 26; x <= 34; x++) dot(cv, x, 4, STEEL)
103    for (let x = 27; x <= 33; x += 2) dot(cv, x + (beat(t, 130) % 2), 5, (beat(t, 130) + x) % 3 ? FLAME : FLAME2)
104    const hop = Math.round(Math.abs(Math.sin((t / 560) * Math.PI)) * 3)
105    dot(cv, 29, 3 - hop, GOLD)
106    dot(cv, 30, 3 - hop, GOLD)
107    for (const k of [0, 1]) {
108      const p = (t / 1100 + k / 2) % 1
109      dot(cv, 27 + k * 5 + Math.sin(p * 6.28), 2 - Math.floor(p * 3), STEAM)
110    }
111  },
112  think(cv, t, c) {
113    // eyes up, hand to the chin; bubbles rise into a cloud with the thought in it
114    clawd(cv, 1, { eyes: blink(t, 'up'), armL: 'out', armR: 'up', legs: 0 }, c)
115    const step = beat(t, 380) % 12
116    if (step >= 1) dot(cv, 21, 3, BUBBLE)
117    if (step >= 2) dot(cv, 23, 2, BUBBLE), dot(cv, 24, 2, BUBBLE)
118    if (step >= 3) {
119      for (let x = 27; x <= 34; x++) dot(cv, x, 0, BUBBLE), dot(cv, x, 2, BUBBLE)
120      for (let x = 26; x <= 35; x++) dot(cv, x, 1, BUBBLE)
121      glyph(cv, 15, 0, ['?', '…', '!', '…'][beat(t, 600) % 4] ?? '?', [0.32, 0.04, 260], BUBBLE)
122    }
123  },
124  build(cv, t, c) {
125    const down = beat(t, 300) % 2 === 1
126    clawd(cv, 1, { eyes: blink(t, 'front'), armL: 'down', armR: down ? 'out' : 'up', legs: 0 }, c)
127    for (let x = 24; x <= 31; x++) dot(cv, x, 4, WOOD), dot(cv, x, 5, [0.42, 0.07, 60])
128    if (down) {
129      for (let x = 19; x <= 22; x++) dot(cv, x, 3, WOOD)
130      for (const [x, y] of [[23, 2], [24, 2], [23, 3], [24, 3]] as const) dot(cv, x, y, STEEL)
131      if (t % 600 < 220) glyph(cv, 13, 0, '✦', GOLD), glyph(cv, 14, 1, '·', GOLD), glyph(cv, 11, 0, '·', GOLD)
132    } else {
133      dot(cv, 19, 1, WOOD)
134      for (const [x, y] of [[20, 0], [21, 0], [20, 1], [21, 1]] as const) dot(cv, x, y, STEEL)
135    }
136  },
137  dance(cv, t, c) {
138    const b = beat(t, 260)
139    const left = b % 2 === 0
140    clawd(cv, b % 4 < 2 ? 1 : 2, { eyes: blink(t, b % 8 < 6 ? 'front' : 'up'), armL: left ? 'up' : 'out', armR: left ? 'out' : 'up', legs: left ? 1 : 2 }, glow(c, b % 4 === 0))
141    for (const k of [0, 1, 2]) {
142      const p = (t / 1500 + k / 3) % 1
143      glyph(cv, 12 + k * 3 + Math.floor(p * 2), 2 - Math.floor(p * 3), k % 2 ? '♫' : '♪', [0.8, 0.14, (t / 20 + k * 120) % 360])
144    }
145  },
146  walk(cv, t, c) {
147    const span = STAGE_W - 9 // cells of road
148    const s = beat(t, 300) % (2 * span)
149    const right = s < span
150    const cell = right ? s : 2 * span - s
151    const step = s % 2
152    clawd(cv, cell, { eyes: blink(t, 'front'), armL: step ? 'out' : 'down', armR: step ? 'down' : 'out', legs: step ? 1 : 2 }, c)
153    glyph(cv, right ? cell - 1 : cell + 9, 2, step ? '·' : ' ', FAINT)
154  },
155  magic(cv, t, c) {
156    clawd(cv, 1, { eyes: blink(t, 'up'), armL: 'up', armR: 'up', legs: 0 }, glow(c, beat(t, 400) % 2 === 0))
157    const slot = beat(t, 260)
158    for (let k = 0; k < 5; k++) {
159      const h = hash(slot * 7 + k)
160      const at = 10 + ((h >>> 3) % 12)
161      glyph(cv, at, (h >>> 8) % 3, '✦✧⋆·'[(h >>> 12) % 4] ?? '·', [0.84, 0.13, [300, 200, 90][(h >>> 14) % 3] ?? 300])
162    }
163    if (beat(t, 400) % 2 === 0) glyph(cv, 0, 0, '✧', GOLD)
164  },
165  grow(cv, t, c) {
166    const cycle = (t / 650) % 9
167    clawd(cv, 1, { eyes: blink(t, 'front'), armL: 'down', armR: 'out', legs: 0 }, c)
168    for (let x = 27; x <= 32; x++) dot(cv, x, 5, WOOD)
169    for (let x = 28; x <= 31; x++) dot(cv, x, 4, WOOD)
170    const h = Math.min(4, Math.floor(cycle))
171    for (let i = 1; i <= h; i++) dot(cv, 29, 4 - i, LEAF)
172    if (h >= 2) dot(cv, 28, 2, LEAF)
173    if (h >= 3) dot(cv, 30, 1, LEAF)
174    if (cycle >= 5) dot(cv, 28, 0, PINK), dot(cv, 30, 0, PINK), dot(cv, 29, 0, GOLD)
175    else {
176      const p = (t / 420) % 1
177      dot(cv, 20 + p * 7, 3 + Math.round(p * p * 2), WATER)
178    }
179  },
180  wind(cv, t, c) {
181    const flap = beat(t, 300) % 2
182    clawd(cv, beat(t, 900) % 2 ? 2 : 1, { eyes: blink(t, 'front'), armL: flap ? 'up' : 'out', armR: flap ? 'out' : 'up', legs: 0 }, c)
183    for (let x = 28; x <= 35; x++) dot(cv, x, 0, CLOUD)
184    for (let x = 26; x <= 37; x++) dot(cv, x, 1, CLOUD)
185    for (let k = 0; k < 4; k++) dot(cv, 27 + k * 3, 2 + Math.floor(((t / 260 + k * 0.37) % 1) * 4), WATER)
186    glyph(cv, 21 - (beat(t, 110) % 10), 2, '~', FAINT)
187  },
188}
189
190function idle(cv: Canvas, t: number, c: Paint, asleep: boolean) {
191  clawd(cv, 1, { eyes: asleep ? 'shut' : blink(t, beat(t, 5200) % 4 === 3 ? 'up' : 'front'), armL: 'out', armR: 'out', legs: 0 }, c)
192  if (asleep) {
193    const p = (t / 1600) % 1
194    glyph(cv, 10 + Math.floor(p * 2), 1 - Math.floor(p * 2), p < 0.5 ? 'z' : 'Z', FAINT)
195  }
196}
197
198function party(cv: Canvas, t: number, c: Paint) {
199  const b = beat(t, 200)
200  clawd(cv, 1, { eyes: 'front', armL: b % 2 ? 'up' : 'out', armR: b % 2 ? 'out' : 'up', legs: (b % 2) + 1 as 1 | 2 }, glow(c, b % 2 === 0))
201  for (const [cx, cy, d] of [[0, 0, 0], [10, 0, 1], [11, 2, 2], [0, 2, 3]] as const)
202    if ((beat(t, 150) + d) % 2) glyph(cv, cx, cy, '✦', GOLD)
203}
204
205// --- reactions and company (/boneco, part 6) ----------------------------------------
206
207// what just happened to the main thread: a tool failed (when), a permission waits,
208// the band came back after one (when: the dialog hides the band, so it waves then)
209export type Reaction = { sustoAt?: number; waiting?: boolean; waveAt?: number }
210export type ReactEvent = { kind: 'failure' | 'permission' | 'settled' | 'reset' | 'shown'; agentId?: string; interrupt?: boolean }
211export const SUSTO_MS = 1300
212export const ACENO_MS = 1500
213const LOW_CTX = 15 // % of context left under which it sweats
214const ERR: Paint = [0.7, 0.19, 25]
215const PET: Paint = [0.9, 0.03, 80]
216
217export function react(r: Reaction, ev: ReactEvent, now: number): Reaction {
218  if (ev.agentId) return r // a subagent's: the band is the main thread's
219  switch (ev.kind) {
220    case 'failure':
221      return { waiting: false, sustoAt: ev.interrupt ? r.sustoAt : now } // Esc is no failure
222    case 'permission':
223      return { ...r, waiting: true }
224    case 'settled':
225      return { ...r, waiting: false }
226    case 'reset':
227      return {}
228    case 'shown':
229      return r.waiting ? { ...r, waiting: false, waveAt: now } : r
230  }
231}
232
233function susto(cv: Canvas, dt: number, c: Paint) {
234  const cell = dt < 450 ? 1 + (Math.floor(dt / 70) % 2) : 1 // shakes a whole cell at a time
235  clawd(cv, cell, { eyes: 'up', armL: 'up', armR: 'up', legs: 0 }, c)
236  glyph(cv, cell + 9, 0, '!', ERR)
237}
238
239function aceno(cv: Canvas, t: number, c: Paint) {
240  clawd(cv, 1, { eyes: blink(t, 'front'), armL: 'out', armR: beat(t, 200) % 2 ? 'up' : 'out', legs: 0 }, c)
241}
242
243function ocio(cv: Canvas, t: number, c: Paint) {
244  const p = t % 9000
245  if (p < 2400) clawd(cv, 1, { eyes: beat(t, 600) % 2 ? 'up' : 'front', armL: 'out', armR: 'out', legs: 0 }, c) // looks around
246  else if (p < 3800) {
247    clawd(cv, 1, { eyes: 'shut', armL: 'up', armR: 'up', legs: 0 }, c) // yawns and stretches
248    glyph(cv, 11, 0, 'o', FAINT)
249  } else if (p < 6000) clawd(cv, 1, { eyes: blink(t, 'front'), armL: 'out', armR: 'down', legs: beat(t, 220) % 2 ? 1 : 0 }, c) // taps a foot
250  else idle(cv, t, c, false)
251}
252
253function sweat(cv: Canvas, t: number) {
254  const p = (t / 900) % 1
255  dot(cv, cv.cell * 2 + 16, Math.floor(p * 3), WATER)
256}
257
258// a two-cell companion, wagging its tail: beside the mascot, or behind it on a walk
259function pet(cv: Canvas, t: number, cell: number, tailLeft: boolean) {
260  const x0 = cell * 2
261  for (const [x, y] of [[0, 4], [0, 5], [1, 5], [2, 5], [3, 5], [3, 4]] as const) dot(cv, x0 + x, y, PET)
262  dot(cv, tailLeft ? x0 - 1 : x0 + 4, beat(t, 250) % 2 ? 4 : 5, PET)
263}
264function petFor(cv: Canvas, t: number, scene: Scene | undefined) {
265  if (scene !== 'walk') return pet(cv, t, cv.cell + 10, false)
266  const span = STAGE_W - 9
267  const right = beat(t, 300) % (2 * span) < span
268  pet(cv, t, right ? cv.cell - 4 : cv.cell + 10, right)
269}
270
271// What it acts out: the tool in use when there is one, the turn's verb between
272// tools. The verb is sampled once a turn, so a long turn would play one scene
273// throughout; the tools keep it changing.
274const TOOL_SCENES: [RegExp, Scene][] = [
275  [/^(Bash|PowerShell|Monitor)$/, 'cook'],
276  [/^(Read|NotebookRead)$/, 'think'],
277  [/^(Grep|Glob|LS|WebFetch|WebSearch|ToolSearch)$/, 'walk'],
278  [/^(Edit|MultiEdit|Write|NotebookEdit)$/, 'build'],
279  [/^(Agent|Task|Workflow|Skill|SendMessage)$/, 'magic'],
280  [/^(TodoWrite|Task(Create|Update)|Artifact)/, 'grow'],
281  [/^mcp__/, 'wind'],
282]
283export function sceneFor(m: Mood, tool?: Tool): Scene {
284  for (const [re, scene] of tool ? TOOL_SCENES : []) if (re.test(tool?.name ?? '')) return scene
285  return sceneOf(m.word, m.mode)
286}
287
288// A scene holds HOLD_MS before the next takes over, so a burst of quick tools
289// does not flicker.
290export const HOLD_MS = 1500
291export function direct(d: { scene?: Scene; since: number }, want: Scene, now: number): Scene {
292  if (d.scene === undefined || (want !== d.scene && now - d.since >= HOLD_MS)) {
293    d.scene = want
294    d.since = now
295  }
296  return d.scene
297}
298
299// --- what the band draws -------------------------------------------------------
300
301export const DONE_MS = 2500
302const SLEEP_MS = 90_000
303type Phase = 'work' | 'done' | 'idle' | 'sleep'
304
305export function phaseOf(m: Mood, now: number): Phase {
306  if (m.working) return 'work'
307  if (m.doneAt !== undefined && now - m.doneAt < DONE_MS) return 'done'
308  return now - (m.doneAt ?? m.since) > SLEEP_MS ? 'sleep' : 'idle'
309}
310
311// What /boneco picked and what the band knows, for the body color: the palette
312// (gauges' ramp, for 'effort'), context left, model and effort as shown; and
313// what just happened (a failed tool, a permission answered).
314export type StageOpts = BodyCtx & { look?: Look; palette?: Palette; month?: number; reaction?: Reaction }
315
316export function drawStage(m: Mood, t: number, accent: Paint = CLAUDE, scene?: Scene, o: StageOpts = {}): Canvas {
317  const look = o.look ?? DEFAULT_LOOK
318  const on = (x: Extra) => look.extras.includes(x)
319  const phase = phaseOf(m, t)
320  const sc = phase === 'work' ? (scene ?? sceneOf(m.word, m.mode)) : undefined
321  const cv = blankCanvas({ look, hat: hatFor(look.hat, sc, o.month ?? new Date(t).getMonth()), t }, rowsFor(look))
322  const sweating = on('suor') && (o.ctxLeft ?? 100) < LOW_CTX
323  const body = bodyColor(look, accent, o.palette ?? CLASSIC, t, sc, o)
324  const c = sweating ? lift(body, 0.03, 0.55) : body
325  const dt = o.reaction?.sustoAt === undefined ? -1 : t - o.reaction.sustoAt // since the tool failed
326  const startled = on('susto') && dt >= 0 && dt < SUSTO_MS
327  const dw = o.reaction?.waveAt === undefined ? -1 : t - o.reaction.waveAt // since the band came back
328  const waving = !startled && on('aceno') && dw >= 0 && dw < ACENO_MS
329  if (startled) susto(cv, dt, c)
330  else if (waving) aceno(cv, t, c)
331  else if (sc) SCENES[sc](cv, t, c)
332  else if (phase === 'done') party(cv, t, c)
333  else if (phase === 'idle' && on('ocio')) ocio(cv, t, c)
334  else idle(cv, t, c, phase === 'sleep')
335  if (sweating) sweat(cv, t)
336  if (on('pet')) petFor(cv, t, startled || waving ? undefined : sc)
337  return cv
338}
339
340export function stage(m: Mood, t: number, accent: Paint = CLAUDE, scene?: Scene, o: StageOpts = {}): Cell[][] {
341  return toCells(drawStage(m, t, accent, scene, o))
342}
343
344const STAR = '·✢✳✶✻✽✻✶✳✢'
345const secs = (ms: number) => (ms < 60_000 ? `${Math.round(ms / 1000)}s` : `${Math.floor(ms / 60_000)}m ${Math.round((ms % 60_000) / 1000)}s`)
346
347export function caption(m: Mood, tool: Tool | undefined, t: number, width: number, accent: Paint = CLAUDE, scene?: Scene, name?: string, pal: Palette = CLASSIC): Cell[] {
348  const phase = phaseOf(m, t)
349  const who = name ? `${name} ` : ''
350  const green: Paint = pal.dark ? [0.8, 0.15, 150] : [0.5, 0.15, 150] // darker on a light terminal
351  if (phase === 'done') return fit(text(name ? `✓ ${name} terminou em ${secs(m.durationMs ?? 0)}` : `✓ feito em ${secs(m.durationMs ?? 0)}`, green), width)
352  if (phase === 'sleep') return fit(text(`z  ${who}${name ? 'está ' : ''}dormindo`, pal.faint), width)
353  if (phase === 'idle') return fit(text(`✻ ${who}${name ? 'está ' : ''}pronto`, pal.faint), width)
354
355  const star = STAR[beat(t, 120) % STAR.length] ?? '✻'
356  const said = (m.message ?? m.word ?? 'Working').replace(/(…|\.\.\.)$/, '')
357  const label = LABELS[scene ?? sceneOf(m.word, m.mode)]
358  const mode = m.mode && MODE_LABELS[m.mode] !== label ? `   ${MODE_LABELS[m.mode]}` : '' // not "pensando  pensando"
359  const doing = tool ? [...text(`   › ${tool.name} `, pal.text), ...text(tool.detail, pal.faint)] : text(mode, pal.faint)
360  return fit([...text(`${star} ${said}…`, accent), ...text(`  ${name ? `${name} está ${label}` : label}`, pal.faint), ...doing], width)
361}
362
hooks/gauges.ts 100 lines
1// The gauge row: ctx, 5h and 7d fuel left. Each gauge is a rounded badge, a
2// rounded capsule bar (1/8-cell precision over a dark track of its own hue)
3// and its percentage, on the palette's ramp: green at 100% -> red at 0% on the
4// classic one, the same stops as the effort pips. A glint sweeps the row,
5// foreground and background; under LOW% a gauge breathes.
6
7import { CLASSIC, classicRamp, type Palette } from './palettes'
8import { CAP_L, CAP_R, type Cell, type Paint } from './paint'
9
10// tune: glint speed (columns/s), radius (columns), pause between sweeps (ms)
11export const SPEED = 80
12export const RADIUS = 2.5
13export const PAUSE = 1800
14const MAX_W = 16 // bar cells, shrunk down to MIN_W in a narrow band
15const MIN_W = 6
16const GAP = '   '
17const LOW = 15 // % left under which a gauge breathes
18const BREATH_MS = 1400
19
20export type Gauge = { label: string; left: number | null; resetsAt?: number }
21type Base = { ch: string; fg: Paint; bg?: Paint; breathe?: boolean }
22
23const WEEKDAYS = ['dom', 'seg', 'ter', 'qua', 'qui', 'sex', 'sáb']
24const clamp = (v: number) => Math.min(100, Math.max(0, v))
25
26// fuel left -> its place on the classic ramp; each palette has its own (palettes.ts)
27export const ramp = classicRamp
28
29function when(resetsAt: number | undefined, now: number): string {
30  if (resetsAt === undefined) return '--'
31  const d = new Date(resetsAt)
32  const hm = `${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}`
33  return d.toDateString() === new Date(now).toDateString() ? hm : `${WEEKDAYS[d.getDay()]} ${hm}`
34}
35
36function layout(gauges: Gauge[], now: number, columns: number, pal: Palette): Base[] {
37  const tail = (g: Gauge) => (g.label === 'ctx' ? '' : ` ↻ ${when(g.resetsAt, now)}`)
38  const fixed =
39    gauges.reduce((n, g) => n + g.label.length + 2 + 1 + 2 + 5 + tail(g).length, 0) + GAP.length * (gauges.length - 1)
40  const w = Math.max(MIN_W, Math.min(MAX_W, Math.floor((columns - fixed) / gauges.length)))
41
42  const out: Base[] = []
43  const put = (s: string, fg: Paint, bg?: Paint, breathe?: boolean) => {
44    for (const ch of s) out.push({ ch, fg, bg, breathe })
45  }
46
47  gauges.forEach((g, n) => {
48    if (n) put(GAP, pal.text)
49    const known = g.left !== null
50    const left = clamp(g.left ?? 0)
51    const [L, C, hue] = pal.ramp(left)
52    const tint = known ? C : 0
53    const low = known && left < LOW
54
55    const badge: Paint = pal.dark ? [0.33, tint * 0.4, hue] : [0.87, tint * 0.35, hue]
56    put(CAP_L, badge, undefined, low)
57    put(g.label.toUpperCase(), [pal.dark ? 0.9 : 0.3, (pal.dark ? 0.06 : 0.08) * Math.sign(tint), hue], badge, low)
58    put(CAP_R, badge, undefined, low)
59    put(' ', pal.text)
60
61    const track: Paint = pal.dark ? [0.26, tint * 0.25, hue] : [0.91, tint * 0.2, hue]
62    const exact = (left * w) / 100
63    let full = Math.floor(exact)
64    let eighth = Math.round((exact - full) * 8)
65    if (eighth === 8) (full += 1), (eighth = 0)
66    const fill = (i: number): Paint => [L - 0.07 * (1 - i / Math.max(1, w - 1)), C, hue] // darker base, bright head
67    put(CAP_L, known && full > 0 ? fill(0) : track)
68    for (let i = 0; i < w; i++) {
69      if (!known) put('╌', pal.faint, track)
70      else if (i < full) put('█', fill(i), track)
71      else if (i === full && eighth) put(' ▏▎▍▌▋▊▉'[eighth] ?? ' ', fill(i), track)
72      else put(' ', pal.text, track)
73    }
74    put(CAP_R, known && full >= w ? fill(w - 1) : track)
75
76    put((known ? `${Math.round(left)}%` : '--').padStart(5), known ? [L, C, hue] : pal.faint, undefined, low)
77    const t = tail(g)
78    if (t) put(t.slice(0, 2), pal.faint), put(t.slice(2), pal.text)
79  })
80  return out
81}
82
83// The row at time t (ms): the glint is a soft bump running left to right, then
84// resting for PAUSE; it lifts lightness and washes chroma, background too, so
85// it crosses the tracks as a streak.
86export function gaugeRow(gauges: Gauge[], now: number, t: number, columns = Infinity, pal: Palette = CLASSIC): Cell[] {
87  const cells = layout(gauges, now, columns, pal)
88  const period = ((cells.length + 6 * RADIUS) / SPEED) * 1000 + PAUSE
89  const pos = ((t % period) / 1000) * SPEED - 3 * RADIUS
90  const breath = 0.5 + 0.5 * Math.sin((2 * Math.PI * t) / BREATH_MS)
91  const lit = ([L, C, h]: Paint, k: number, b: number): Paint => [L + 0.16 * k + b, C * (1 - 0.5 * k), h]
92
93  return cells.map((c, x) => {
94    const d = x - pos
95    const k = Math.exp((-d * d) / (2 * RADIUS * RADIUS))
96    const b = c.breathe ? 0.09 * breath : 0
97    return { ch: c.ch, fg: lit(c.fg, k, b), bg: c.bg && lit(c.bg, k, b) }
98  })
99}
100
hooks/identity.ts 64 lines
1// The identity row, moved here from ~/.claude/statusline.sh: model, effort,
2// folder, branch, cost and the active modes, in the band's own look (a rounded
3// badge in the accent, effort pips on the palette's ramp).
4
5import { CLASSIC, type Palette } from './palettes'
6import { CAP_L, CAP_R, text, type Cell, type Paint } from './paint'
7
8export type Identity = { model?: string; effort?: string; folder?: string; branch?: string; usd?: number; plan?: string; modes: string[] }
9
10const EFFORTS = ['low', 'medium', 'high', 'xhigh', 'max']
11const GAP = '   '
12const PLAN: Paint = [0.42, 0.09, 85] // a gold badge
13const PLAN_LIGHT: Paint = [0.87, 0.07, 85]
14const icon = (code: number) => String.fromCharCode(code) // Nerd Font glyphs, as the old status line drew them
15export const BOLT = icon(0xf0e7)
16export const FOLDER = icon(0xf07b)
17const BRANCH = icon(0xe0a0)
18export const CAVEMAN = icon(0xf6d5)
19export const PONYTAIL = icon(0xf1b0)
20
21// The Pro or Max plan, from ~/.claude.json's oauthAccount (no secrets there):
22// on one, the session's cost is what the API would have charged, not a bill.
23export function planOf(config: { oauthAccount?: { organizationType?: string; organizationRateLimitTier?: string } }): string | undefined {
24  const type = config.oauthAccount?.organizationType
25  const tier = /_(\d+x)$/.exec(config.oauthAccount?.organizationRateLimitTier ?? '')?.[1]
26  if (type === 'claude_max') return tier ? `Max ${tier}` : 'Max'
27  if (type === 'claude_pro') return 'Pro'
28  return undefined
29}
30
31// "claude-opus-5-5" -> "Opus 5.5"; an alias ("opus") just capitalized
32export function prettyModel(id: string): string {
33  const m = /claude-([a-z]+)-(\d+)(?:-(\d+))?/.exec(id)
34  const name = m?.[1] ?? id
35  const title = name.charAt(0).toUpperCase() + name.slice(1)
36  return m ? `${title} ${m[2]}${m[3] ? `.${m[3]}` : ''}` : title
37}
38
39export function identityRow(id: Identity, accent: Paint, pal: Palette = CLASSIC): Cell[] {
40  const [, C, hue] = accent
41  const badge: Paint = pal.dark ? [0.33, C * 0.45, hue] : [0.88, C * 0.35, hue]
42  const ink: Paint = pal.dark ? [0.9, C * 0.5, hue] : [0.32, C * 0.7, hue]
43  const out: Cell[] = []
44  const gap = () => out.length && out.push(...text(GAP, pal.text))
45
46  if (id.model) out.push({ ch: CAP_L, fg: badge }, ...text(`${BOLT} ${id.model}`, ink, badge), { ch: CAP_R, fg: badge })
47  if (id.effort) {
48    gap()
49    const n = EFFORTS.indexOf(id.effort)
50    if (n >= 0) for (let i = 0; i < 5; i++) out.push({ ch: i <= n ? '▰' : '▱', fg: i <= n ? pal.ramp(100 - 25 * i) : pal.faint })
51    out.push(...text(n >= 0 ? ` ${id.effort}` : id.effort, n >= 0 ? pal.ramp(100 - 25 * n) : pal.faint))
52  }
53  if (id.folder) gap(), out.push(...text(`${FOLDER} `, pal.folder), ...text(id.folder, pal.text))
54  if (id.branch) gap(), out.push(...text(`${BRANCH} `, pal.branch), ...text(id.branch, pal.text))
55  if (id.usd !== undefined) gap(), out.push(...text(`$${id.usd.toFixed(2)}${id.plan ? ' via API' : ''}`, pal.faint))
56  if (id.plan) {
57    const plan = pal.dark ? PLAN : PLAN_LIGHT
58    const planInk: Paint = pal.dark ? [0.92, 0.08, 85] : [0.36, 0.09, 70]
59    out.push(...text(' ', pal.text), { ch: CAP_L, fg: plan }, ...text(id.plan, planInk, plan), { ch: CAP_R, fg: plan })
60  }
61  if (id.modes.length) out.push(...text(` ${id.modes.join(' ')}`, pal.faint))
62  return out
63}
64
hooks/look.ts 57 lines
1// What the person picked for the mini Claude and the band (/boneco), kept in
2// $.store under 'look'. Read field by field: the store may hold an older shape
3// or garbage, and a bad field falls back on its own default alone.
4
5export const PALETTE_KEYS = ['tema', 'classico', 'chamados', 'catppuccin', 'dracula', 'tokyo', 'nord', 'gruvbox', 'rose', 'synth', 'fosforo', 'ambar', 'acessivel', 'papel'] as const
6export const COLORS = ['paleta', 'fixa', 'arco', 'modelo', 'cena', 'contexto', 'effort'] as const
7export const EYE_MODES = ['vazados', 'grandes', 'led', 'oculos', 'visor'] as const
8export const SHAPES = ['classica', 'orelhas', 'redondo', 'fantasma'] as const
9export const HAT_KEYS = ['cartola', 'chef', 'coroa', 'bone', 'festa', 'aureola', 'antenas', 'chifres', 'gato', 'bruxo', 'obra', 'noel', 'palha', 'laco'] as const
10export const HATS = ['none', ...HAT_KEYS, 'cena', 'sazonal'] as const
11export const EXTRAS = ['susto', 'suor', 'aceno', 'ocio', 'pet'] as const
12
13export type PaletteKey = (typeof PALETTE_KEYS)[number]
14export type HatKey = (typeof HAT_KEYS)[number]
15export type Extra = (typeof EXTRAS)[number]
16export type Look = {
17  palette: PaletteKey
18  color: (typeof COLORS)[number]
19  fixed: string // '#rrggbb', with color 'fixa'
20  duo: boolean // dois tons
21  eyes: (typeof EYE_MODES)[number]
22  led: string // '#rrggbb', with eyes 'led'
23  cheeks: boolean
24  shape: (typeof SHAPES)[number]
25  hat: (typeof HATS)[number]
26  extras: Extra[]
27}
28
29export const DEFAULT_LOOK: Look = {
30  palette: 'tema', color: 'paleta', fixed: '#d77757', duo: false, eyes: 'vazados',
31  led: '#5ee6ff', cheeks: false, shape: 'classica', hat: 'none', extras: [],
32}
33
34const HEX = /^#[0-9a-f]{6}$/i
35export const isHex = (v: string) => HEX.test(v)
36const one = <T extends string>(list: readonly T[], v: unknown, d: T): T => ((list as readonly unknown[]).includes(v) ? (v as T) : d)
37const hex = (v: unknown, d: string) => (typeof v === 'string' && HEX.test(v) ? v.toLowerCase() : d)
38const bool = (v: unknown, d: boolean) => (typeof v === 'boolean' ? v : d)
39
40export function readLook(raw: unknown): Look {
41  const r = (raw && typeof raw === 'object' && !Array.isArray(raw) ? raw : {}) as Record<string, unknown>
42  const d = DEFAULT_LOOK
43  const extras = Array.isArray(r.extras) ? (r.extras as unknown[]) : []
44  return {
45    palette: one(PALETTE_KEYS, r.palette, d.palette),
46    color: one(COLORS, r.color, d.color),
47    fixed: hex(r.fixed, d.fixed),
48    duo: bool(r.duo, d.duo),
49    eyes: one(EYE_MODES, r.eyes, d.eyes),
50    led: hex(r.led, d.led),
51    cheeks: bool(r.cheeks, d.cheeks),
52    shape: one(SHAPES, r.shape, d.shape),
53    hat: one(HATS, r.hat, d.hat),
54    extras: EXTRAS.filter(x => extras.includes(x)), // known ones, once each, in a fixed order
55  }
56}
57
hooks/menu.ts 203 lines
1// /boneco: the menu that picks the look one part at a time (paleta, cor, olhos,
2// silhueta, chapéu, reações), the option under the focus ring previewed live.
3// This half is pure: the parts and their options, what a press does to the
4// look, the preview's rows. register.tsx draws the pane and owns $.
5
6import { composeBand, type BandState } from './band'
7import { STAGE_W, VERBS, stage, type Mood, type Scene } from './clawd'
8import { EXTRAS, isHex, type Extra, type Look } from './look'
9import { PALETTES, paletteOf } from './palettes'
10import { fit, text, type Cell } from './paint'
11
12export const MENU_ID = 'boneco'
13export const PREVIEW_KEY = 'boneco-preview'
14
15export type StepKey = 'palette' | 'color' | 'eyes' | 'shape' | 'hat' | 'extras'
16export const STEPS: readonly { key: StepKey; arg: string; title: string }[] = [
17  { key: 'palette', arg: 'paleta', title: 'Paleta' },
18  { key: 'color', arg: 'cor', title: 'Cor' },
19  { key: 'eyes', arg: 'olhos', title: 'Olhos' },
20  { key: 'shape', arg: 'silhueta', title: 'Silhueta' },
21  { key: 'hat', arg: 'chapeu', title: 'Chapéu' },
22  { key: 'extras', arg: 'reacoes', title: 'Reações' },
23]
24export const SUMMARY = STEPS.length // the step after the last part
25
26export type Option = { id: string; value: string; name: string; note: string; tag?: string }
27const LINE = '+1 linha na faixa'
28
29export const OPTIONS: Record<StepKey, Option[]> = {
30  palette: PALETTES.map((p, i) => ({ id: `P${i}`, value: p.key, name: p.name, note: p.note })),
31  color: [
32    { id: 'C1', value: 'paleta', name: 'Da paleta', note: 'O destaque da paleta, como o mod faz hoje com o /theme.' },
33    { id: 'C2', value: 'fixa', name: 'Cor fixa', note: 'Uma cor só dele, igual em qualquer paleta.' },
34    { id: 'C3', value: 'arco', name: 'Arco-íris', note: 'O matiz gira devagar, uma volta a cada 10 s.' },
35    { id: 'C4', value: 'modelo', name: 'Pelo modelo', note: 'Opus laranja, Sonnet azul, Haiku verde, Fable roxo.' },
36    { id: 'C5', value: 'cena', name: 'Pela cena', note: 'Cozinha laranja, leitura azul, mágica roxa, dança rosa…' },
37    { id: 'C6', value: 'contexto', name: 'Pelo contexto', note: 'Desbota abaixo de 50% de contexto e avermelha abaixo de 15%.' },
38    { id: 'C7', value: 'effort', name: 'Pelo effort', note: 'A mesma rampa dos pips: low frio, max quente.' },
39  ],
40  eyes: [
41    { id: 'O1', value: 'vazados', name: 'Vazados', note: 'Os furos de hoje, que mostram o fundo do terminal.' },
42    { id: 'O2', value: 'grandes', name: 'Grandes', note: 'Dois pixels de altura. Perdem o olhar para cima.' },
43    { id: 'O3', value: 'led', name: 'LED', note: 'Acesos numa cor; continuam piscando.' },
44    { id: 'O4', value: 'oculos', name: 'Óculos escuros', note: 'Lentes escuras com um reflexo a cada 3 s.' },
45    { id: 'O5', value: 'visor', name: 'Visor', note: 'Faixa escura com uma luz que varre de um lado a outro.' },
46  ],
47  shape: [
48    { id: 'S1', value: 'classica', name: 'Clássica', note: 'O desenho da tela de boas-vindas.' },
49    { id: 'S2', value: 'orelhas', name: 'Orelhinhas', note: 'Recorte no topo da cabeça. Some quando há chapéu.' },
50    { id: 'S3', value: 'redondo', name: 'Cantos redondos', note: 'Quatro cantos a menos, mais fofo.' },
51    { id: 'S4', value: 'fantasma', name: 'Fantasminha', note: 'Sem pernas: a barra de baixo ondula.' },
52  ],
53  hat: [
54    { id: 'H0', value: 'none', name: 'Sem chapéu', note: 'Faixa com 3 linhas, como hoje.' },
55    { id: 'H1', value: 'cartola', name: 'Cartola', note: 'Preta com fita vermelha.', tag: LINE },
56    { id: 'H2', value: 'chef', name: 'Chapéu de chef', note: 'Toque branco, ótimo com a cena de cozinha.', tag: LINE },
57    { id: 'H3', value: 'coroa', name: 'Coroa', note: 'Dourada, com uma pedra no meio.', tag: LINE },
58    { id: 'H4', value: 'bone', name: 'Boné', note: 'Aba virada para o lado.', tag: LINE },
59    { id: 'H5', value: 'festa', name: 'Chapéu de festa', note: 'Cone rosa com pompom.', tag: LINE },
60    { id: 'H6', value: 'aureola', name: 'Auréola', note: 'Flutua e brilha devagar.', tag: LINE },
61    { id: 'H7', value: 'antenas', name: 'Anteninhas', note: 'Da cor do corpo, de inseto.', tag: LINE },
62    { id: 'H8', value: 'chifres', name: 'Chifrinhos', note: 'Vermelhos, de diabinho.', tag: LINE },
63    { id: 'H9', value: 'gato', name: 'Orelhas de gato', note: 'Da cor do corpo.', tag: LINE },
64    { id: 'H10', value: 'bruxo', name: 'Chapéu de bruxo', note: 'Roxo, de aba larga.', tag: LINE },
65    { id: 'H11', value: 'obra', name: 'Capacete de obra', note: 'Amarelo, combina com a cena de construir.', tag: LINE },
66    { id: 'H12', value: 'noel', name: 'Gorro de Noel', note: 'Vermelho com pompom branco.', tag: LINE },
67    { id: 'H13', value: 'palha', name: 'Chapéu de palha', note: 'Aba bem larga, de festa junina.', tag: LINE },
68    { id: 'H14', value: 'laco', name: 'Laço', note: 'Rosa, preso de lado.', tag: LINE },
69    { id: 'H15', value: 'cena', name: 'Figurino por cena', note: 'Chef na cozinha, capacete na obra, bruxo na mágica, festa na dança…', tag: LINE },
70    { id: 'H16', value: 'sazonal', name: 'Do calendário', note: 'Bruxo em outubro, gorro em dezembro, palha em junho, festa em janeiro.', tag: LINE },
71  ],
72  extras: [
73    { id: 'X1', value: 'susto', name: 'Susto no erro', note: 'Uma ferramenta falhou: treme, olha para cima e mostra "!".' },
74    { id: 'X2', value: 'suor', name: 'Suando', note: 'Contexto abaixo de 15%: fica pálido e sua.' },
75    { id: 'X3', value: 'aceno', name: 'Aceno', note: 'Quando você responde a um pedido de permissão, ele acena por um instante.' },
76    { id: 'X4', value: 'ocio', name: 'Ócio variado', note: 'Parado, olha em volta, boceja, se espreguiça e bate o pé.' },
77    { id: 'X5', value: 'pet', name: 'Bichinho', note: 'Um companheiro de duas células que vai atrás dele.' },
78  ],
79}
80
81export const SWATCHES: Record<'fixa' | 'led', readonly (readonly [hex: string, name: string])[]> = {
82  fixa: [['#d77757', 'laranja Claude'], ['#f28fb3', 'rosa'], ['#6fa8ff', 'azul'], ['#7bd88f', 'verde'], ['#b18cff', 'roxo'], ['#f2c94c', 'amarelo'], ['#e8e8ee', 'branco'], ['#8b93a7', 'cinza robô']],
83  led: [['#5ee6ff', 'ciano'], ['#7dff9a', 'verde'], ['#ffc94d', 'âmbar'], ['#ff5d6c', 'vermelho'], ['#ffffff', 'branco']],
84}
85
86// option keys, 17 for the hats: 1-9 then letters, skipping c f r t v (the fixed buttons')
87const KEYS = '123456789abdeghij'
88export const hotkey = (i: number): string | undefined => KEYS[i]
89
90export type MenuState = { step: number; sub?: 'fixa' | 'led'; focused?: string; error?: string }
91export type Press = { look: Look; state: MenuState; close?: true }
92
93const plain = (s: string) => s.normalize('NFD').replace(/\p{M}/gu, '').trim().toLowerCase()
94export const openAt = (arg: string): MenuState => ({ step: Math.max(0, STEPS.findIndex(s => s.arg === plain(arg))) })
95
96const split = (key: string): [string, string] => {
97  const i = key.indexOf(':')
98  return i < 0 ? [key, ''] : [key.slice(0, i), key.slice(i + 1)]
99}
100const stepAt = (s: MenuState) => STEPS[s.step]?.key
101const known = (key: StepKey, value: string) => OPTIONS[key].some(o => o.value === value)
102
103export const isPicked = (look: Look, key: StepKey, value: string) =>
104  key === 'extras' ? look.extras.includes(value as Extra) : look[key] === value
105
106function apply(look: Look, key: StepKey, value: string): Look {
107  if (key !== 'extras') return { ...look, [key]: value } as Look
108  const on = look.extras.includes(value as Extra)
109  return { ...look, extras: EXTRAS.filter(x => (x === value ? !on : look.extras.includes(x))) }
110}
111const swatch = (look: Look, sub: 'fixa' | 'led', hex: string): Look => ({ ...look, [sub === 'fixa' ? 'fixed' : 'led']: hex.toLowerCase() }) as Look
112
113export function press(look: Look, s: MenuState, key: string): Press {
114  const step = stepAt(s)
115  const [kind, value] = split(key)
116  const stay = { look, state: s }
117  if (kind === 'opt') {
118    if (!step || !known(step, value)) return stay
119    const next = apply(look, step, value)
120    if (step === 'extras') return { look: next, state: { step: s.step } }
121    const sub = step === 'color' && value === 'fixa' ? 'fixa' : step === 'eyes' && value === 'led' ? 'led' : undefined
122    if (sub) return { look: next, state: { step: s.step, sub } }
123    return { look: next, state: { step: s.step + 1 } }
124  }
125  if (kind === 'sw') return s.sub && isHex(value) ? { look: swatch(look, s.sub, value), state: { step: s.step + 1 } } : stay
126  if (kind === 'tog') return value === 'duo' || value === 'cheeks' ? { look: { ...look, [value]: !look[value] } as Look, state: s } : stay
127  if (kind === 'nav') {
128    if (value === 'back') return { look, state: s.sub ? { step: s.step } : { step: Math.max(0, s.step - 1) } }
129    if (value === 'next') return { look, state: { step: Math.min(SUMMARY, s.step + 1) } }
130    if (value === 'restart') return { look, state: { step: 0 } }
131    if (value === 'close') return { look, state: s, close: true }
132  }
133  return stay
134}
135
136// the hex typed in the fixed color's field: '#a1b2c3', 'A1B2C3' and spaces around are fine
137export function typeHex(look: Look, s: MenuState, typed: string): Press {
138  if (s.sub !== 'fixa') return { look, state: s }
139  const hex = `#${typed.trim().replace(/^#/, '')}`.toLowerCase()
140  if (!isHex(hex)) return { look, state: { ...s, error: `"${typed.trim().slice(0, 16)}" não é uma cor: use #rrggbb` } }
141  return { look: swatch(look, 'fixa', hex), state: { step: s.step + 1 } }
142}
143
144// the look with the focused option on, unsaved; on Reações the focused one shown on
145export function preview(look: Look, s: MenuState): Look {
146  const step = stepAt(s)
147  const [kind, value] = split(s.focused ?? '')
148  if (kind === 'opt' && step && known(step, value)) return step === 'extras' && isPicked(look, step, value) ? look : apply(look, step, value)
149  if (kind === 'sw' && s.sub && isHex(value)) return swatch(look, s.sub, value)
150  return look
151}
152
153export function title(s: MenuState): string {
154  const st = STEPS[s.step]
155  return st ? `Mini Claude · ${s.step + 1}/${STEPS.length} ${st.title}` : 'Mini Claude · pronto'
156}
157
158export const progress = (s: MenuState): string =>
159  STEPS.map((st, i) => `${i < s.step ? '✓' : i === s.step ? '●' : '○'}${st.title}`).join(' ')
160
161export function summary(look: Look): string[] {
162  const named = (key: StepKey, value: string) => {
163    const o = OPTIONS[key].find(o => o.value === value)
164    return o ? `${o.id} ${o.name}` : value
165  }
166  return [
167    `Paleta: ${named('palette', look.palette)}`,
168    `Cor: ${named('color', look.color)}${look.color === 'fixa' ? ` ${look.fixed}` : ''}${look.duo ? ' + dois tons' : ''}`,
169    `Olhos: ${named('eyes', look.eyes)}${look.eyes === 'led' ? ` ${look.led}` : ''}${look.cheeks ? ' + bochechas' : ''}`,
170    `Silhueta: ${named('shape', look.shape)}`,
171    `Chapéu: ${named('hat', look.hat)}`,
172    `Reações: ${look.extras.length ? look.extras.map(x => named('extras', x)).join(', ') : 'nenhuma'}`,
173  ]
174}
175
176// the preview acts out every scene in turn, 2.4 s each, so a color or a hat is seen everywhere
177const DEMO: (Scene | 'idle')[] = ['idle', 'dance', 'cook', 'think', 'build', 'walk', 'magic', 'grow', 'wind']
178function demo(t: number): { mood: Mood; scene?: Scene } {
179  const s = DEMO[Math.floor(t / 2400) % DEMO.length] ?? 'idle'
180  if (s === 'idle') return { mood: { working: false, since: t - 1000 } }
181  return { mood: { working: true, since: t, word: VERBS[s].split(' ')[0], mode: 'thinking' }, scene: s }
182}
183
184// Paleta: the whole band; the other parts: the stage and, beside it, the option's name and note
185export function previewRows(b: BandState, s: MenuState, now: number, columns: number): Cell[][] {
186  const look = preview(b.look, s)
187  const step = stepAt(s)
188  if (step === 'palette') return composeBand({ ...b, look }, now, columns)
189  const pal = paletteOf(look.palette, b.themeAccent)
190  const { mood, scene } = demo(now)
191  const st = stage(mood, now, pal.accent, scene, {
192    look, palette: pal, model: b.ident.model, effortLevel: b.ident.effort,
193    ctxLeft: step === 'extras' ? 9 : step === 'color' ? 100 - ((now / 90) % 100) : 72,
194    reaction: step === 'extras' ? { sustoAt: now - (now % 2600), waveAt: now - ((now + 1300) % 2600) } : undefined, // a startle, then a wave, over and over
195  })
196  const [kind, value] = split(s.focused ?? '')
197  const o = step ? (OPTIONS[step].find(o => kind === 'opt' && o.value === value) ?? OPTIONS[step].find(o => isPicked(look, step, o.value))) : undefined
198  const lines = o ? [text(`${o.id} ${o.name}`, pal.text), text(o.note, pal.faint), text(o.tag ?? '', pal.faint)] : []
199  const right = Math.max(0, columns - STAGE_W - 2)
200  const off = st.length - 3
201  return st.map((row, i) => [...row, ...text('  ', pal.text), ...fit(lines[i - off] ?? [], right)])
202}
203
hooks/paint.ts 82 lines
1// Colors in OKLCH and the Raster cell grid they are painted into.
2
3export type Paint = readonly [L: number, C: number, hue: number]
4export type Cell = { ch: string; fg: Paint; bg?: Paint }
5
6export const TEXT: Paint = [0.7, 0.03, 275]
7export const FAINT: Paint = [0.47, 0.02, 275]
8export const CLAUDE = fromHex('#d77757') ?? [0.67, 0.13, 40]
9const DEFAULT = 0x01000000 // the terminal's own color
10
11const enc = (x: number) =>
12  x <= 0 ? 0 : x >= 1 ? 255 : Math.round(255 * (x <= 0.0031308 ? 12.92 * x : 1.055 * x ** (1 / 2.4) - 0.055))
13
14export function rgb([L, C, deg]: Paint): number {
15  const h = (deg * Math.PI) / 180
16  const a = C * Math.cos(h)
17  const b = C * Math.sin(h)
18  const l = (L + 0.3963377774 * a + 0.2158037573 * b) ** 3
19  const m = (L - 0.1055613458 * a - 0.0638541728 * b) ** 3
20  const s = (L - 0.0894841775 * a - 1.291485548 * b) ** 3
21  return (
22    (enc(4.0767416621 * l - 3.3077115913 * m + 0.2309699292 * s) << 16) |
23    (enc(-1.2684380046 * l + 2.6097574011 * m - 0.3413193965 * s) << 8) |
24    enc(-0.0041960863 * l - 0.7034186147 * m + 1.707614701 * s)
25  )
26}
27
28// '#rrggbb' / '#rgb' -> OKLCH; undefined for anything else (ansi names, rgb())
29export function fromHex(hex: string): Paint | undefined {
30  const m = /^#([0-9a-f]{6}|[0-9a-f]{3})$/i.exec(hex.trim())
31  if (!m?.[1]) return undefined
32  const s = m[1].length === 3 ? m[1].replace(/./g, c => c + c) : m[1]
33  const [r, g, b] = [0, 2, 4].map(i => {
34    const c = parseInt(s.slice(i, i + 2), 16) / 255
35    return c <= 0.04045 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4
36  }) as [number, number, number]
37  const l = Math.cbrt(0.4122214708 * r + 0.5363325363 * g + 0.0514459929 * b)
38  const mm = Math.cbrt(0.2119034982 * r + 0.6806995451 * g + 0.1073969566 * b)
39  const ss = Math.cbrt(0.0883024619 * r + 0.2817188376 * g + 0.6299787005 * b)
40  const A = 1.9779984951 * l - 2.428592205 * mm + 0.4505937099 * ss
41  const B = 0.0259040371 * l + 0.7827717662 * mm - 0.808675766 * ss
42  return [0.2104542553 * l + 0.793617785 * mm - 0.0040720468 * ss, Math.hypot(A, B), (Math.atan2(B, A) * 180) / Math.PI]
43}
44
45export const lift = ([L, C, h]: Paint, dL: number, cMul = 1): Paint => [L + dL, C * cMul, h]
46
47export const CAP_L = String.fromCharCode(0xe0b6) // Nerd Font half circles: rounded ends
48export const CAP_R = String.fromCharCode(0xe0b4)
49
50// Raster takes one printable width-1 BMP character a cell: keep ASCII, Latin
51// accents and the glyphs drawn here; anything else (emoji, CJK) becomes '·'.
52const DRAWN = /[\u2026\u203a\u2190-\u21ff\u22c6\u2500-\u25ff\u266a\u266b\u2713\u2722-\u273d\ue000-\uf8ff]/ // last range: Nerd Font icons
53export const safe = (s: string) =>
54  [...s].map(ch => (/[\x20-\x7e\u00a0-\u024f]/.test(ch) || DRAWN.test(ch) ? ch : '\u00b7')).join('')
55
56export const text = (s: string, fg: Paint, bg?: Paint): Cell[] => [...safe(s)].map(ch => ({ ch, fg, bg }))
57
58export function fit(cells: Cell[], width: number): Cell[] {
59  if (cells.length <= width) return cells
60  return [...cells.slice(0, Math.max(0, width - 1)), { ch: '…', fg: cells[width - 1]?.fg ?? FAINT }]
61}
62
63export function encode(rows: Cell[][], columns: number): string {
64  const words = new Uint32Array(rows.length * columns * 3)
65  rows.forEach((row, y) => {
66    for (let x = 0; x < columns; x++) {
67      const c = row[x]
68      const i = (y * columns + x) * 3
69      words[i] = c?.ch.codePointAt(0) ?? 0x20
70      words[i + 1] = c ? rgb(c.fg) : DEFAULT
71      words[i + 2] = c?.bg ? rgb(c.bg) : DEFAULT
72    }
73  })
74  return new Uint8Array(words.buffer).toBase64()
75}
76
77declare global {
78  interface Uint8Array {
79    toBase64(): string // ES2026: in the engine's runtime, not yet in lib es2023
80  }
81}
82
hooks/paths.ts 10 lines
1// Paths and the home folder on every system the engine runs on: Windows hands
2// paths with '\' (a folder may end in one, a share starts with two) and may
3// have no HOME, only USERPROFILE.
4
5export const homeOf = (home: string | undefined, profile: string | undefined): string => home || profile || ''
6
7const parts = (p: string) => p.split(/[\\/]/).filter(Boolean)
8export const baseName = (p: string): string | undefined => parts(p).at(-1)
9export const lastTwo = (p: string): string => parts(p).slice(-2).join('/')
10
hooks/palettes.ts 90 lines
1// The band's palettes (/boneco, part 1): the mascot's and the model badge's
2// accent, the ramp the gauges and effort pips run on (100 full -> 0 empty), and
3// the text, folder and branch colors. 'tema' is the band as it always was: the
4// theme's `claude` color on the classic palette.
5
6import type { PaletteKey } from './look'
7import { CLAUDE, FAINT, TEXT, fromHex, type Paint } from './paint'
8
9export type Palette = {
10  key: PaletteKey
11  name: string
12  note: string
13  accent: Paint
14  ramp: (left: number) => Paint
15  text: Paint
16  faint: Paint
17  folder: Paint
18  branch: Paint
19  dark: boolean // false: light badges and tracks, for a light terminal
20}
21
22const clamp = (v: number) => Math.min(100, Math.max(0, v))
23
24// green at 100% -> red at 0%, as ~/.claude/statusline.sh had it
25export function classicRamp(left: number): Paint {
26  const i = 4 * (1 - clamp(left) / 100)
27  return [0.82 - i * 0.035, 0.15 + i * 0.01, 150 - i * 32]
28}
29
30// OKLCH, the hue the short way round
31export function mix(a: Paint, b: Paint, k: number): Paint {
32  const d = ((((b[2] - a[2]) % 360) + 540) % 360) - 180
33  return [a[0] + (b[0] - a[0]) * k, a[1] + (b[1] - a[1]) * k, a[2] + d * k]
34}
35
36const hex = (h: string): Paint => fromHex(h) ?? CLAUDE
37function stopsRamp(stops: string[]): (left: number) => Paint {
38  const s = stops.map(hex)
39  return left => {
40    const x = (1 - clamp(left) / 100) * (s.length - 1)
41    const i = Math.min(s.length - 2, Math.floor(x))
42    return mix(s[i]!, s[i + 1]!, x - i)
43  }
44}
45
46type Spec = { key: PaletteKey; name: string; note: string; accent: string; stops: string[]; text: string; faint: string; folder: string; branch: string; dark?: false }
47const make = (p: Spec): Palette => ({
48  key: p.key, name: p.name, note: p.note, accent: hex(p.accent), ramp: stopsRamp(p.stops),
49  text: hex(p.text), faint: hex(p.faint), folder: hex(p.folder), branch: hex(p.branch), dark: p.dark ?? true,
50})
51
52export const CLASSIC: Palette = {
53  key: 'classico', name: 'Clássico', note: 'O laranja do Claude e a rampa verde → vermelho de hoje.',
54  accent: CLAUDE, ramp: classicRamp, text: TEXT, faint: FAINT, folder: [0.74, 0.11, 300], branch: [0.8, 0.11, 165], dark: true,
55}
56
57export const PALETTES: readonly Palette[] = [
58  { ...CLASSIC, key: 'tema', name: 'Do /theme', note: 'O destaque do seu tema do Claude Code sobre o clássico, como a faixa sempre foi.' },
59  CLASSIC,
60  make({ key: 'chamados', name: 'Chamados', note: 'O seu tema do PortalChamados: lima da marca, status do portal nos medidores.',
61    accent: '#50b838', stops: ['#4ade80', '#fbbf24', '#f47920', '#f87171'], text: '#a1a1aa', faint: '#5f5f69', folder: '#a78bfa', branch: '#60a5fa' }),
62  make({ key: 'catppuccin', name: 'Catppuccin Mocha', note: 'Pastel sobre azul-ardósia. Mauve no mascote.',
63    accent: '#cba6f7', stops: ['#a6e3a1', '#f9e2af', '#fab387', '#f38ba8'], text: '#bac2de', faint: '#6c7086', folder: '#b4befe', branch: '#94e2d5' }),
64  make({ key: 'dracula', name: 'Dracula', note: 'Roxo, rosa e ciano em alto contraste.',
65    accent: '#bd93f9', stops: ['#50fa7b', '#f1fa8c', '#ffb86c', '#ff5555'], text: '#e2e2dc', faint: '#6272a4', folder: '#ff79c6', branch: '#8be9fd' }),
66  make({ key: 'tokyo', name: 'Tokyo Night', note: 'Azul elétrico sobre noite fria.',
67    accent: '#7aa2f7', stops: ['#9ece6a', '#e0af68', '#ff9e64', '#f7768e'], text: '#a9b1d6', faint: '#565f89', folder: '#bb9af7', branch: '#73daca' }),
68  make({ key: 'nord', name: 'Nord', note: 'Gelo e aurora boreal, tudo mais calmo.',
69    accent: '#88c0d0', stops: ['#a3be8c', '#ebcb8b', '#d08770', '#bf616a'], text: '#d8dee9', faint: '#616e88', folder: '#b48ead', branch: '#8fbcbb' }),
70  make({ key: 'gruvbox', name: 'Gruvbox', note: 'Retrô quente, cara de terminal dos anos 80.',
71    accent: '#fe8019', stops: ['#b8bb26', '#fabd2f', '#fe8019', '#fb4934'], text: '#d5c4a1', faint: '#7c6f64', folder: '#d3869b', branch: '#8ec07c' }),
72  make({ key: 'rose', name: 'Rosé Pine', note: 'Rosa suave; a rampa vai de espuma a vinho.',
73    accent: '#ebbcba', stops: ['#9ccfd8', '#f6c177', '#ea9a97', '#eb6f92'], text: '#e0def4', faint: '#6e6a86', folder: '#c4a7e7', branch: '#9ccfd8' }),
74  make({ key: 'synth', name: 'Synthwave', note: 'Neon rosa e ciano, medidores de menta a vermelho.',
75    accent: '#ff7edb', stops: ['#72f1b8', '#36f9f6', '#fede5d', '#fe4450'], text: '#e0d7f5', faint: '#7a6a9a', folder: '#fede5d', branch: '#36f9f6' }),
76  make({ key: 'fosforo', name: 'Fósforo', note: 'Monitor CRT verde. Medidores só mudam de brilho.',
77    accent: '#5cff8a', stops: ['#8dffaa', '#46d872', '#2a9a4c', '#1d6a35'], text: '#5fd387', faint: '#2f6b45', folder: '#8dffaa', branch: '#8dffaa' }),
78  make({ key: 'ambar', name: 'Âmbar', note: 'Terminal âmbar monocromático.',
79    accent: '#ffb000', stops: ['#ffcd55', '#e09a00', '#a86f00', '#7a4f00'], text: '#e8a33a', faint: '#7a5a20', folder: '#ffcd55', branch: '#ffcd55' }),
80  make({ key: 'acessivel', name: 'Daltonismo', note: 'Rampa azul → laranja, que funciona para quem não distingue verde de vermelho.',
81    accent: '#d77757', stops: ['#4ea1ff', '#9fb4d9', '#f2c14e', '#f07b2a'], text: '#c9cbd6', faint: '#6b6f80', folder: '#b39cf0', branch: '#4ea1ff' }),
82  make({ key: 'papel', name: 'Papel', note: 'Para terminal de fundo claro: tinta escura, selos claros.', dark: false,
83    accent: '#c15f3c', stops: ['#1f9d55', '#a88a06', '#d9730d', '#d0312d'], text: '#3f4250', faint: '#8a8d9a', folder: '#7c4dcc', branch: '#0f8a6a' }),
84]
85
86export function paletteOf(key: PaletteKey, themeAccent: Paint): Palette {
87  const p = PALETTES.find(p => p.key === key) ?? PALETTES[0]!
88  return p.key === 'tema' ? { ...p, accent: themeAccent } : p
89}
90
hooks/wardrobe.ts 163 lines
1// What the mascot wears (/boneco, parts 2 to 5): body color, eyes, cheeks,
2// silhouette and hat, in the quadrant pixels of pixels.ts. Each piece keeps the
3// cells it touches to one color with holes, or two colors with none: a third
4// state cannot be drawn in one cell (toCells), and wardrobe.test.ts checks
5// that no outfit makes one.
6
7import type { HatKey, Look } from './look'
8import { mix, type Palette } from './palettes'
9import { fromHex, lift, type Paint } from './paint'
10import { dot, type Canvas } from './pixels'
11
12export type Scene = 'cook' | 'think' | 'build' | 'dance' | 'walk' | 'magic' | 'grow' | 'wind'
13export type Eyes = 'front' | 'up' | 'shut'
14
15// --- body color (part 2) ----------------------------------------------------------
16
17export const MODEL_COLORS: Record<string, Paint> = { Opus: [0.67, 0.13, 40], Sonnet: [0.7, 0.12, 250], Haiku: [0.8, 0.14, 150], Fable: [0.7, 0.15, 315] }
18export const SCENE_HUE: Record<Scene, number> = { cook: 45, think: 255, build: 90, walk: 170, magic: 305, dance: 350, grow: 140, wind: 215 }
19const EFFORTS = ['low', 'medium', 'high', 'xhigh', 'max']
20const ALARM: Paint = [0.64, 0.17, 25]
21
22export type BodyCtx = { ctxLeft?: number; model?: string; effortLevel?: string }
23
24// `accent`: the palette's (the theme's, on 'tema'); `model` as the band shows it ("Opus 5.5")
25export function bodyColor(look: Look, accent: Paint, pal: Palette, t: number, scene: Scene | undefined, o: BodyCtx = {}): Paint {
26  switch (look.color) {
27    case 'fixa':
28      return fromHex(look.fixed) ?? accent
29    case 'arco':
30      return [0.75, 0.15, (t / 28) % 360]
31    case 'modelo':
32      return MODEL_COLORS[(o.model ?? '').split(' ')[0] ?? ''] ?? accent
33    case 'cena':
34      return scene ? [0.73, 0.14, SCENE_HUE[scene]] : accent
35    case 'contexto': {
36      const left = o.ctxLeft ?? 100 // unknown: as if full
37      const pale = lift(accent, 0.08, 0.3)
38      if (left >= 50) return accent
39      if (left >= 15) return mix(accent, pale, (50 - left) / 35)
40      return mix(pale, ALARM, Math.min(1, (15 - left) / 10))
41    }
42    case 'effort': {
43      const n = EFFORTS.indexOf(o.effortLevel ?? '')
44      return n < 0 ? accent : pal.ramp(100 - 25 * n)
45    }
46    default:
47      return accent
48  }
49}
50
51// dois tons: the head lighter, the base darker; the change falls between cell rows
52export const tones = (look: Look, c: Paint): [Paint, Paint] => (look.duo ? [lift(c, 0.07, 0.85), lift(c, -0.05, 1.05)] : [c, c])
53
54// --- eyes and cheeks (part 3) -----------------------------------------------------
55
56export const BLUSH: Paint = [0.76, 0.13, 5]
57const SHADE: Paint = [0.2, 0.02, 270]
58const GLINT: Paint = [0.9, 0.02, 250]
59const VISOR: Paint = [0.24, 0.04, 250]
60const SCAN: Paint = [0.86, 0.15, 200]
61const EYE_PX: Record<Eyes, number[][]> = { front: [[5, 1], [12, 1]], up: [[5, 0], [12, 0]], shut: [] }
62
63export function face(cv: Canvas, x0: number, eyes: Eyes, look: Look, t: number) {
64  switch (look.eyes) {
65    case 'vazados':
66      for (const [x = 0, y = 0] of EYE_PX[eyes]) dot(cv, x0 + x, y, null)
67      return
68    case 'grandes': // two pixels tall: looking up changes nothing
69      if (eyes !== 'shut') for (const x of [5, 12]) dot(cv, x0 + x, 0, null), dot(cv, x0 + x, 1, null)
70      return
71    case 'led': {
72      const lc = fromHex(look.led) ?? SCAN
73      for (const [x = 0, y = 0] of EYE_PX[eyes]) dot(cv, x0 + x, y, lc)
74      return
75    }
76    case 'oculos': {
77      const g = t % 3400 // a glint crosses the left lens, then the right
78      const left = g < 150 ? GLINT : SHADE
79      const right = g >= 150 && g < 300 ? GLINT : SHADE
80      for (const x of [4, 5]) dot(cv, x0 + x, 1, left)
81      for (const x of [12, 13]) dot(cv, x0 + x, 1, right)
82      return
83    }
84    case 'visor': {
85      for (let x = 4; x <= 13; x++) dot(cv, x0 + x, 1, VISOR)
86      const k = Math.floor(t / 150) % 8 // the light sweeps cell by cell, there and back
87      const at = 4 + 2 * (k < 5 ? k : 8 - k)
88      dot(cv, x0 + at, 1, SCAN), dot(cv, x0 + at + 1, 1, SCAN)
89    }
90  }
91}
92
93// --- silhouette (part 4) ------------------------------------------------------------
94
95export function carved(shape: Look['shape'], x: number, y: number): boolean {
96  if (shape === 'orelhas') return y === 0 && x >= 6 && x <= 11
97  if (shape === 'redondo') return (y === 0 || y === 3) && (x === 3 || x === 14)
98  return false
99}
100
101// fantasminha: no legs, the bottom row ripples a pixel at a time
102export function ghostHem(cv: Canvas, x0: number, t: number, p: Paint) {
103  const ph = Math.floor(t / 240) % 2
104  for (let x = 3; x <= 14; x++) if ((x + ph) % 2 === 0) dot(cv, x0 + x, 4, p)
105}
106
107// --- hats (part 5): two pixel rows above the head, y -2 and -1 ---------------------
108
109const INK: Paint = [0.36, 0.03, 275]
110const BAND: Paint = [0.6, 0.19, 25]
111const CHEF: Paint = [0.96, 0.005, 250]
112const CHEF2: Paint = [0.86, 0.01, 250]
113const GOLD: Paint = [0.88, 0.15, 95]
114const RUBY: Paint = [0.6, 0.2, 15]
115const CAP: Paint = [0.62, 0.15, 255]
116const CAP2: Paint = [0.5, 0.13, 255]
117const PINK: Paint = [0.76, 0.15, 350]
118const DEVIL: Paint = [0.6, 0.2, 27]
119const WITCH: Paint = [0.5, 0.16, 305]
120const HARD: Paint = [0.84, 0.17, 85]
121const SANTA: Paint = [0.58, 0.2, 27]
122const STRAW: Paint = [0.83, 0.1, 88]
123const STRAW2: Paint = [0.7, 0.1, 78]
124const BOW: Paint = [0.74, 0.17, 355]
125
126// [x from, x to, y, color]; 'body' is the head's color, 'halo' a breathing gold
127type HatRun = readonly [from: number, to: number, y: -2 | -1, paint: Paint | 'body' | 'halo']
128export const HAT_PIXELS: Record<HatKey, readonly HatRun[]> = {
129  cartola: [[6, 11, -2, INK], [4, 5, -1, INK], [6, 11, -1, BAND], [12, 13, -1, INK]],
130  chef: [[5, 12, -2, CHEF], [6, 11, -1, CHEF2]],
131  coroa: [[5, 5, -2, GOLD], [8, 9, -2, RUBY], [12, 12, -2, GOLD], [5, 12, -1, GOLD]],
132  bone: [[5, 12, -2, CAP], [4, 13, -1, CAP], [14, 16, -1, CAP2]],
133  festa: [[8, 9, -2, GOLD], [7, 10, -1, PINK]],
134  aureola: [[6, 11, -2, 'halo']],
135  antenas: [[4, 4, -2, 'body'], [5, 5, -1, 'body'], [13, 13, -2, 'body'], [12, 12, -1, 'body']],
136  chifres: [[3, 3, -2, DEVIL], [4, 4, -1, DEVIL], [14, 14, -2, DEVIL], [13, 13, -1, DEVIL]],
137  gato: [[4, 4, -2, 'body'], [4, 5, -1, 'body'], [13, 13, -2, 'body'], [12, 13, -1, 'body']],
138  bruxo: [[9, 11, -2, WITCH], [3, 14, -1, WITCH]],
139  obra: [[5, 12, -2, HARD], [3, 14, -1, HARD]],
140  noel: [[6, 11, -2, SANTA], [12, 13, -2, CHEF], [4, 13, -1, CHEF]],
141  palha: [[6, 11, -2, STRAW], [2, 15, -1, STRAW2]],
142  laco: [[11, 11, -2, BOW], [14, 14, -2, BOW], [11, 14, -1, BOW]],
143}
144
145const SCENE_HAT: Record<Scene, HatKey> = { cook: 'chef', build: 'obra', magic: 'bruxo', dance: 'festa', walk: 'bone', grow: 'palha', wind: 'noel', think: 'cartola' }
146const SEASON_HAT: Partial<Record<number, HatKey>> = { 9: 'bruxo', 11: 'noel', 5: 'palha', 6: 'palha', 0: 'festa' } // by month, 0 = January
147
148export function hatFor(hat: Look['hat'], scene: Scene | undefined, month: number): HatKey | null {
149  if (hat === 'none') return null
150  if (hat === 'cena') return scene ? SCENE_HAT[scene] : null
151  if (hat === 'sazonal') return SEASON_HAT[month] ?? null
152  return hat
153}
154
155// a hat, even an automatic one between hats, keeps the band at 4 rows: it never jumps
156export const rowsFor = (look: Look): 3 | 4 => (look.hat === 'none' ? 3 : 4)
157
158export function wearHat(cv: Canvas, x0: number, hat: HatKey, body: Paint, t: number) {
159  const halo = lift(GOLD, 0.05 * Math.sin(t / 300))
160  for (const [from, to, y, k] of HAT_PIXELS[hat])
161    for (let x = from; x <= to; x++) dot(cv, x0 + x, y, k === 'body' ? body : k === 'halo' ? halo : k)
162}
163
hooks/pixels.ts 60 lines
1// The stage's pixel grid: quadrant pixels, 2x2 a cell, on 3 rows of cells; on
2// 4 when the mascot wears a hat, the scene then standing one whole cell lower
3// (y -2 and -1 are the hat's). A cell takes one glyph, a foreground color and
4// a background color.
5
6import type { HatKey, Look } from './look'
7import { TEXT, type Cell, type Paint } from './paint'
8
9export const STAGE_W = 22 // cells
10const PW = STAGE_W * 2 // pixels
11const QUAD = ' ▘▝▀▖▌▞▛▗▚▐▜▄▙▟█' // index = UL 1 | UR 2 | LL 4 | LR 8
12
13// what the mascot wears in this frame, read by clawd() wherever a scene draws it
14export type Dress = { look: Look; hat: HatKey | null; t: number }
15export type Canvas = { rows: 3 | 4; oy: 0 | 2; px: (Paint | null)[]; glyphs: Map<number, Cell>; dress: Dress; cell: number }
16
17export function blankCanvas(dress: Dress, rows: 3 | 4 = 3): Canvas {
18  return { rows, oy: rows === 4 ? 2 : 0, px: new Array<Paint | null>(PW * rows * 2).fill(null), glyphs: new Map(), dress, cell: 1 }
19}
20
21// x, y in scene pixels: y 0 is the head's top row
22export function dot(cv: Canvas, x: number, y: number, p: Paint | null) {
23  x = Math.round(x)
24  y = Math.round(y) + cv.oy
25  if (x >= 0 && x < PW && y >= 0 && y < cv.rows * 2) cv.px[y * PW + x] = p
26}
27export function glyph(cv: Canvas, cx: number, cy: number, ch: string, fg: Paint, bg?: Paint) {
28  cy += cv.oy / 2
29  if (cx >= 0 && cx < STAGE_W && cy >= 0 && cy < cv.rows) cv.glyphs.set(cy * STAGE_W + cx, { ch, fg, bg })
30}
31
32export function quad(cv: Canvas, cx: number, cy: number): (Paint | null)[] {
33  const i = 2 * cy * PW + 2 * cx
34  return [cv.px[i] ?? null, cv.px[i + 1] ?? null, cv.px[i + PW] ?? null, cv.px[i + PW + 1] ?? null]
35}
36const bits = (q: (Paint | null)[], hit: (p: Paint | null) => boolean) => q.reduce((n, p, i) => (hit(p) ? n | (1 << i) : n), 0)
37
38// One color a cell, the most-voted, as quadrants have always been drawn; and
39// two when all four are filled with exactly two: the fewer (on a tie, the first
40// in reading order) is the glyph, the other its background. Two colors and a
41// hole, or three colors, cannot be drawn in a cell: those fall back on the
42// vote, and no outfit makes one (wardrobe.test.ts).
43export function toCells(cv: Canvas): Cell[][] {
44  return Array.from({ length: cv.rows }, (_, cy) =>
45    Array.from({ length: STAGE_W }, (_, cx): Cell => {
46      const g = cv.glyphs.get(cy * STAGE_W + cx)
47      if (g) return g
48      const q = quad(cv, cx, cy)
49      const votes = new Map<Paint, number>()
50      for (const p of q) if (p) votes.set(p, (votes.get(p) ?? 0) + 1)
51      if (votes.size === 2 && q.every(Boolean)) {
52        const [[a], [b]] = [...votes].sort((x, y) => x[1] - y[1]) as [[Paint, number], [Paint, number]] // stable: a tie keeps reading order
53        return { ch: QUAD[bits(q, p => p === a)] ?? ' ', fg: a, bg: b }
54      }
55      const fg = [...votes].sort((x, y) => y[1] - x[1])[0]?.[0] ?? TEXT
56      return { ch: QUAD[bits(q, p => p !== null)] ?? ' ', fg }
57    }),
58  )
59}
60