Clawd, the Claude pet, sits right above your prompt, on the right, with its laptop: it types while Claude works, brings a smaller helper in its color per…

Marketplace de plugins para Claude Code.
# 1. Agregar el marketplace
/plugin marketplace add Menendez2004/menendez-market
# 2. Instalar los plugins que quieras
/plugin install dev-orchestrator@menendez-market
/plugin install qa@menendez-market
/plugin install unit-test-generator@menendez-market
/plugin install api-handoff@menendez-market
/plugin install endpoint-security-audit@menendez-market
/plugin install clawd-pet@menendez-market
(Desde la terminal también funciona: claude plugin marketplace add Menendez2004/menendez-market.)
| Plugin | Descripción |
|---|---|
dev-orchestrator | Human-in-the-loop development orchestrator with a 2-level hierarchy. Claude lo reconoce solo, sin invocarlo: un hook UserPromptSubmit le da prioridad cuando pides un plan ("crea un plan", "planifica", "plan this") o una tarea de varios pasos, y en cualquier prompt en modo plan. Adopts the Lead's plan, or, if none is given, deploys a read-only Planner Agent on Opus (orch-planner) to draft one, then launches one Task Agent per step in its own terminal (or inline for small steps) and its own git worktree, applying each finished step to the Lead's working tree as a checked, uncommitted patch, starting each step as soon as its dependencies finish, cerrando sola la sesión (y su pestaña) de cada Task Agent en cuanto su paso queda Complete o Failed (un paso Blocked sigue abierto para que respondas ahí), and each agent can use read-only research sub-agents (Sonnet 5) that prioritize graphify. Si la skill ponytail está disponible, todo agente que escribe código la usa para no escribir código innecesario (sin recortar nada del paso ni de validaciones/seguridad). Execution runs on the latest Opus (Task Agents and the orchestrator session). Never runs tests; runs checks once at the end. No crea unit tests a menos que se pidan. Al terminar y pasar los checks, el orquestador hace commit y push como el usuario logeado en git, nunca con co-autores, con mensajes Conventional Commits 1.0.0 (force-push, merge, rebase y PRs siguen siendo del Lead). Escalates to the Lead on ambiguity or destructive actions. |
qa | Suite de QA (se instala completa). Incluye las skills: qa-orchestrator (orquesta sesiones de QA: lanza agentes de prueba en paralelo, recolecta resultados, hace triage de bugs y genera reportes), qa-happy-path (prueba los flujos principales de la UI con Playwright), qa-api-adversary (intenta romper la API: auth, validación, duplicados, condiciones de carrera, requests malformados), qa-debugger (aplica correcciones mínimas a los bugs reportados) y qa-personality-builder (crea personalidades de QA propias del proyecto en .qa/config.yml). |
clawd-pet | Mod (no es una skill): Clawd, la mascota de Claude, vive justo encima del prompt del CLI, a la derecha, con su laptop. Saluda cuando estás presente, teclea en su laptop mientras Claude trabaja, se pone casco en modo plan, trae un ayudante más pequeño y de su mismo color por cada subagente que esté corriendo (con lentes si investiga, con casco azul si planea, con su laptop verde azulada si programa), queda noqueado cuando falla un comando y se duerme con un "Zzz" flotando cuando dejas de escribir (60 s por defecto; cámbialo con idleSeconds en /config). Escribe cualquier cosa para despertarlo; /pet lo oculta o lo muestra, y /pet color <nombre o #hex> (o /config) le cambia el color: orange, blue, green, purple, pink, red, yellow, gray o cualquier hexadecimal. |
unit-test-generator | Genera unit tests estrictos y aislados con el runner, la librería de mocks y las factories que ya usa el repo. Los datos salen de Faker o de factories (nunca objetos escritos a mano), con semilla fija, patrón AAA y casos de éxito, ramas, entradas inválidas, límites, errores y efectos secundarios. Exige al menos 90% de coverage (líneas, sentencias, ramas y funciones) en la unidad probada. Nunca modifica código de producción: reporta los bugs que encuentra. |
api-handoff | Escribe e implementa documentos de handoff (Markdown) entre frontend y backend. Para frontend: el endpoint que debe consumir; para backend: el endpoint que debe construir. Cada endpoint lleva su finalidad, método y ruta completa, auth, parámetros, headers, el body exacto (tabla de campos + ejemplo JSON que deben coincidir), todas las respuestas de éxito y error, efectos secundarios y criterios de aceptación verificables, todo extraído del código real (lo que no está decidido queda como TBD + pregunta abierta). Usa una plantilla fija con front matter YAML e incluye un script validador, para que cualquier otra sesión de Claude pueda implementarlo tal cual y reportar diferencias con el contrato. |
endpoint-security-audit | Auditoría de seguridad de caja blanca de los endpoints de una API y de las funciones que usan sus rutas. Arma el mapa de rutas (método, ruta completa, handler, cadena de middleware y auth) con un script incluido, y sigue cada dato del request por el handler y por cada servicio, repositorio y helper que llama. Revisa autenticación, autorización por objeto y por función (BOLA/IDOR, BFLA), inyección (SQL, NoSQL, comandos), path traversal y subida de archivos, SSRF, mass assignment, exposición de datos y rutas del servidor, rate limits y lógica de dinero (montos negativos, condiciones de carrera, idempotencia). Cada hallazgo lleva archivo:línea, el request que lo dispara, severidad, OWASP API Top 10 + CWE y la corrección; lo que no se puede confirmar va aparte. Solo lee código: nunca ataca un sistema en ejecución. |
.claude-plugin/
marketplace.json # catálogo: cada plugin apunta a sus skills
plugins/
skills/
dev-orchestrator/ # SKILL.md + references/, rules/, agents/, hooks/route_prompt.py + close_session.py
qa/ # todas las skills de QA
qa-orchestrator/ # SKILL.md + references/, rules/, assets/
qa-happy-path/ # SKILL.md + rules/
qa-api-adversary/ # SKILL.md + rules/
qa-debugger/ # SKILL.md + rules/
qa-personality-builder/ # SKILL.md + references/, rules/
unit-test-generator/ # SKILL.md + references/, rules/
api-handoff/ # SKILL.md + references/ (plantilla, ejemplos), rules/, scripts/validate_handoff.py
endpoint-security-audit/ # SKILL.md + references/ (descubrimiento de rutas, sinks, OWASP, plantilla), rules/, scripts/list_routes.py
mods/
clawd-pet/ # .claude-plugin/plugin.json + hooks/register.tsx, types/, tests/
Cada entrada de marketplace.json usa "strict": false y declara sus skills con "skills": [...]. dev-orchestrator carga solo su skill (sus agentes orch-planner y orch-researcher, y su hook de ruteo), unit-test-generator, api-handoff y endpoint-security-audit cargan solo la suya, y el plugin qa carga las cinco skills de plugins/skills/qa/ juntas, porque qa-orchestrator lanza a las demás.
Para agregar una skill nueva: crea plugins/skills/<nombre>/SKILL.md y agrega una entrada en .claude-plugin/marketplace.json. Una skill de QA nueva va en plugins/skills/qa/<nombre>/ y se agrega a la lista skills del plugin qa. Valida con:
claude plugin validate .
Los mods (plugins de function hooks, como clawd-pet) viven en plugins/mods/<nombre>/ con su propio .claude-plugin/plugin.json, y su entrada en marketplace.json usa "source": "./plugins/mods/<nombre>". Cada cambio a un mod debe subir su version (en su plugin.json y en su entrada de marketplace.json): Claude Code guarda la copia instalada por versión, y si la versión no cambia /plugin update no la reemplaza. Para probarlos:
claude plugin validate plugins/mods/clawd-pet
claude plugin test plugins/mods/clawd-pet
claude --plugin-dir plugins/mods/clawd-pet # sesión de prueba con el mod cargadohooks/register.tsx 815 lines1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, Register } from 'claude-code'
3
4import type { Helper, HelperKind, PetMood } from '../types'
5
6const mood = atom({ plugin: 'clawd-pet', key: 'mood' } as const, 'awake')
7const frame = atom({ plugin: 'clawd-pet', key: 'frame' } as const, 0)
8const isHidden = atom({ plugin: 'clawd-pet', key: 'isHidden' } as const, false)
9const laptopStep = atom({ plugin: 'clawd-pet', key: 'laptopStep' } as const, 0)
10const isPlanMode = atom({ plugin: 'clawd-pet', key: 'isPlanMode' } as const, false)
11const helpers = atom({ plugin: 'clawd-pet', key: 'helpers' } as const, [] as Helper[])
12
13// How long Clawd stays knocked out after a command fails.
14const ERROR_MS = 3000
15
16// A quarter second a frame, so the typing looks quick; the laptop moves on
17// every other frame, so it still takes about two seconds to come out.
18const TICK_MS = 250
19
20// Where the laptop is, one step every other tick toward OPEN while Claude
21// works and back toward STOWED once it stops.
22const STOWED = 0 // Clawd faces you, the laptop behind its back, one corner peeking out
23const TURNED = 1 // Clawd turns sideways, facing left, and grabs the laptop
24const LIFTED = 2 // pulled out, held up closed in front of it
25const SET_DOWN = 3 // set down closed on the ground in front of it
26const OPEN = 4 // opened sideways, the screen tilted back; Clawd types
27
28// Fixed colors, so Clawd stays vivid whatever the terminal theme.
29const DEFAULT_COLOR = 'orange'
30const EYE_BLACK = '#000000'
31const LAPTOP_GREY = '#A8A8A8'
32const LAPTOP_DIM = '#5C5C5C'
33const SPARK_YELLOW = '#FFD166'
34const Z_FADED = '#7A5A4A'
35const SCREEN_GLOW = '#CFE3F7'
36const SCREEN_DIM = '#8FB4DA'
37const HAT_YELLOW = '#E8B04B'
38const HAT_BADGE = '#B07A1E'
39const GLASSES = '#3B7DDD'
40const LENS = '#EAF4FF'
41const THINK_BLUE = '#7FB8F0'
42// The helpers wear Clawd's color too; only their gear differs: a blue hard
43// hat and a teal laptop.
44const HELPER_HAT = '#3D8BFD'
45const HELPER_HAT_BADGE = '#1F5FBF'
46const HELPER_LAPTOP = '#2BB3A3'
47
48// At most this many helpers stand next to Clawd; the rest show as "+N".
49const MAX_HELPERS = 3
50
51// The colors Clawd can be, by the name the person picks in /config or types
52// after `/pet color`; any #RRGGBB (or #RGB) works too.
53const PALETTE: Record<string, string> = {
54 orange: '#E8713A',
55 blue: '#4A90E2',
56 green: '#4CAF50',
57 purple: '#9B59B6',
58 pink: '#E86A9B',
59 red: '#E74C3C',
60 yellow: '#F1C40F',
61 gray: '#95A5A6',
62}
63
64// The hex a color name or hex code stands for, as #RRGGBB, or undefined when
65// it is neither a palette name nor a well-formed hex code.
66function toHex(color: string): string | undefined {
67 const value = color.trim().toLowerCase()
68 const named = PALETTE[value]
69 if (named !== undefined) {
70 return named
71 }
72 const short = /^#?([0-9a-f])([0-9a-f])([0-9a-f])$/.exec(value)
73 if (short) {
74 return `#${short[1]}${short[1]}${short[2]}${short[2]}${short[3]}${short[3]}`
75 }
76 const long = /^#?([0-9a-f]{6})$/.exec(value)
77 return long ? `#${long[1]}` : undefined
78}
79
80// The same color at 60% brightness: shut eyes are drawn in it, so they read
81// as a darker line on any body color.
82function darken(hex: string): string {
83 const n = Number.parseInt(hex.slice(1), 16)
84 const channel = (shift: number) => Math.round(((n >> shift) & 0xff) * 0.6)
85 return `#${[16, 8, 0].map(shift => channel(shift).toString(16).padStart(2, '0')).join('')}`
86}
87
88// Clawd's body color and its darker shade, set from the person's choice when
89// the module loads (and again when they change it with /pet color).
90let BODY = PALETTE[DEFAULT_COLOR] ?? '#E8713A'
91let BODY_DARK = darken(BODY)
92
93function paint(hex: string) {
94 BODY = hex
95 BODY_DARK = darken(hex)
96}
97
98// One run of characters in a single style.
99type Seg = { text: string; color?: string; backgroundColor?: string; bold?: boolean }
100
101// Clawd as a 9×5 pixel sprite, two pixel rows per terminal row (half
102// blocks), so it is two and a half rows tall, close to the sticker's shape;
103// the head starts halfway down the top row:
104//
105// . # # # # # # # . row 0 head
106// # # E # # # E # # row 1 arms and eyes
107// # # # # # # # # # row 2 arms
108// . # # # # # # # . row 3 body
109// . # . # . # . # . row 4 legs
110//
111// An eye is one pixel: black when open (`▀`, black over orange), a dark
112// orange line when it blinks or while asleep. Facing you, Clawd only idles
113// and sleeps; asleep it lies still and only the Zs above it move. To work it
114// turns sideways (below).
115type Eyes = 'open' | 'blink' | 'asleep'
116
117function petRows(eyes: Eyes): Seg[][] {
118 const body = (text: string): Seg => ({ text, color: BODY, bold: true })
119 const eye: Seg =
120 eyes === 'open'
121 ? { text: '▀', color: EYE_BLACK, backgroundColor: BODY }
122 : { text: '▀', color: BODY_DARK, backgroundColor: BODY }
123
124 return [
125 [body(' ▄▄▄▄▄▄▄ ')],
126 [body('██'), eye, body('███'), eye, body('██')],
127 [body(' █▀█▀█▀█ ')],
128 ]
129}
130
131// Clawd in profile, facing left, as it works: the same 9×5 body with both
132// eyes toward the front (left) and one arm, the front one, reaching out to
133// the keyboard; the back arm is hidden behind its body.
134//
135// . # # # # # # # . row 0 head
136// . # E # # E # # . row 1 eyes
137// A # # # # # # # . row 2 front arm (at rest)
138// a # # # # # # # . row 3 front arm (on the keys)
139// . # . # . # . # . row 4 legs
140//
141// Typing, the front arm drops one pixel onto the keys and back up.
142function sidePetRows(isArmDown: boolean): Seg[][] {
143 const body = (text: string): Seg => ({ text, color: BODY, bold: true })
144 const eye: Seg = { text: '▀', color: EYE_BLACK, backgroundColor: BODY }
145
146 return [
147 [body(' ▄▄▄▄▄▄▄ ')],
148 [body(`${isArmDown ? ' ' : '▄'}█`), eye, body('██'), eye, body('██ ')],
149 [body(`${isArmDown ? '▀' : ' '}█▀█▀█▀█ `)],
150 ]
151}
152
153// The corner of the laptop peeking out from behind Clawd's back, one column
154// right of its head: dim while stowed, bright while Clawd turns and grabs it,
155// gone once out.
156function behindRows(step: number): Seg[][] {
157 const none: Seg[] = [{ text: ' ' }]
158 if (step === STOWED) {
159 return [[{ text: '▐', color: LAPTOP_DIM }], none, none]
160 }
161 if (step === TURNED) {
162 return [[{ text: '█', color: LAPTOP_GREY }], none, none]
163 }
164 return [none, none, none]
165}
166
167// The laptop, seen from the side like Clawd, five columns wide at every step
168// so Clawd never shifts: held up closed at arm height, set down closed, then
169// opened with the screen tilted back toward the left and the keyboard
170// running up to Clawd's front arm. While Clawd types the screen flickers.
171function laptopRows(step: number, isWorking: boolean, tick: number): Seg[][] {
172 const empty: Seg[] = [{ text: ' ' }]
173 const grey = (text: string): Seg => ({ text, color: LAPTOP_GREY, bold: true })
174
175 if (step === LIFTED) {
176 return [empty, [{ text: ' ' }, grey('▄▄▄')], empty]
177 }
178 if (step === SET_DOWN) {
179 return [empty, empty, [{ text: ' ' }, grey('▀▀▀')]]
180 }
181 if (step === OPEN) {
182 const screen: Seg = {
183 text: '╲',
184 color: isWorking && tick % 2 === 1 ? SCREEN_DIM : SCREEN_GLOW,
185 bold: true,
186 }
187 return [
188 [screen, { text: ' ' }],
189 [{ text: ' ' }, screen, { text: ' ' }],
190 [{ text: ' ' }, grey('▀▀▀')],
191 ]
192 }
193 return [empty, empty, empty]
194}
195
196// The hard hat Clawd wears while Claude is in plan mode: a yellow dome with
197// a darker badge in the row above its head, and the brim painted over the
198// empty top half of its head row, so it sits right on top of the head.
199function hatRow(): Seg[] {
200 const hat = (text: string, color = HAT_YELLOW): Seg => ({ text, color, bold: true })
201 return [{ text: ' ' }, hat('▄▄'), hat('▄', HAT_BADGE), hat('▄▄'), { text: ' ' }]
202}
203
204function brimRow(): Seg[] {
205 return [
206 { text: '▀', color: HAT_YELLOW, bold: true },
207 { text: '▀▀▀▀▀▀▀', color: HAT_YELLOW, backgroundColor: BODY, bold: true },
208 { text: '▀', color: HAT_YELLOW, bold: true },
209 ]
210}
211
212// Planning, Clawd faces you under its hard hat and marches in place: its
213// legs step between two stances every half second.
214function marchingLegs(tick: number): Seg[] {
215 const legs = Math.floor(tick / 2) % 2 === 0 ? ' █▀█▀█▀█ ' : ' ▀█▀█▀█▀ '
216 return [{ text: legs, color: BODY, bold: true }]
217}
218
219// Knocked out after a command fails: Clawd lies flat on its back, its legs
220// in the air, its eyes crossed out (×), with stars spinning over it and the
221// laptop tumbling off behind it.
222//
223// . . . . . . . . . legs up
224// . # . # . # . # .
225// # # X # # # X # # flat body
226// # # # # # # # # #
227function knockedOutRows(): Seg[][] {
228 const body = (text: string): Seg => ({ text, color: BODY, bold: true })
229 const eye: Seg = { text: '×', color: EYE_BLACK, backgroundColor: BODY, bold: true }
230 return [
231 [body(' ▄ ▄ ▄ ▄ ')],
232 [body('██'), eye, body('███'), eye, body('██')],
233 ]
234}
235
236const STARS = [' ✦ ✧ ', ' ✧ ✦ ', ' ✧ ✦ ', ' ✦ ✧ ']
237
238function starRow(tick: number): Seg[] {
239 const stars = STARS[Math.floor(tick / 2) % STARS.length] ?? ''
240 return [...stars].map(ch => (ch === ' ' ? { text: ch } : { text: ch, color: SPARK_YELLOW, bold: true }))
241}
242
243// The sparks that pop out of the laptop while Clawd types, one frame per
244// tick, in the row above the laptop and as wide as it.
245const SPARKS = [' ✻ ', ' · ✻ ', '✻ · ', ' ✻ ·']
246
247function sparkRow(tick: number): Seg[] {
248 const sparks = SPARKS[tick % SPARKS.length] ?? ''
249 return [...sparks].map(ch =>
250 ch === '✻' ? { text: ch, color: BODY, bold: true } : ch === '·' ? { text: ch, color: SPARK_YELLOW, bold: true } : { text: ch },
251 )
252}
253
254// The Zs that float up out of Clawd's head while it sleeps, in the row above
255// it: each is born small over the top of its head and drifts right one column
256// every half second, growing from `·` to `z` to `Z` and fading on its last
257// step. Two are in the air at once, three steps apart.
258const Z_SHAPES = ['·', 'z', 'z', 'Z', 'Z']
259const Z_CYCLE = 6
260
261function sleepRow(tick: number): Seg[] {
262 const cells: Seg[] = Array.from({ length: 9 }, () => ({ text: ' ' }))
263 const beat = Math.floor(tick / 2)
264 for (const offset of [0, 3]) {
265 const age = (beat + offset) % Z_CYCLE
266 const shape = Z_SHAPES[age]
267 if (shape !== undefined) {
268 cells[4 + age] = { text: shape, color: age === Z_SHAPES.length - 1 ? Z_FADED : BODY, bold: age >= 3 }
269 }
270 }
271 return cells
272}
273
274// What kind of helper a subagent type brings: researchers (Explore, a
275// research or search agent, the docs guide) wear glasses, planners (Plan, a
276// planner) the hard hat, and everyone else codes on a laptop.
277function helperKind(subagentType: string): HelperKind {
278 const type = subagentType.toLowerCase()
279 if (/explore|research|search|guide/.test(type)) {
280 return 'research'
281 }
282 if (/plan/.test(type)) {
283 return 'plan'
284 }
285 return 'code'
286}
287
288// A helper is a smaller Clawd, 7×4 pixels (two rows) instead of 9×5:
289//
290// . # # # # # . row 0 head
291// # # E # E # # row 1 arms and eyes
292// . # # # # # . row 2 body
293// . # . # . # . row 3 legs
294//
295// An eye is the lower half of a head-row cell, black under the body color.
296const helperBody = (text: string): Seg => ({ text, color: BODY, bold: true })
297const helperEye = (): Seg => ({ text: '▄', color: EYE_BLACK, backgroundColor: BODY })
298
299function smallLegs(isStepping = false): Seg[] {
300 return [helperBody(isStepping ? ' ▀█▀█▀ ' : ' █▀█▀█ ')]
301}
302
303// A researcher is the same size as the other helpers, 7×4 pixels, in round
304// glasses: blue rims over its eyes joined at the bridge, the temples out
305// over its arms, white glass with a pupil in each lens.
306//
307// . G G # G G . row 0 head, the tops of the rims
308// G P W G P W G row 1 lenses, bridge and temples
309// . # # # # # . row 2 body
310// . # . # . # . row 3 legs
311//
312// The pupils (P) glance left and right as it reads.
313const RESEARCHER_WIDTH = 7
314
315function researcherRows(tick: number): Seg[][] {
316 const lens = Math.floor(tick / 6) % 2 === 0 ? 'PW' : 'WP'
317 const art = ['.GG#GG.', `G${lens}G${lens}G`, '.#####.', '.#.#.#.']
318 const color = (pixel: string | undefined): string | undefined =>
319 pixel === '#' ? BODY : pixel === 'G' ? GLASSES : pixel === 'W' ? LENS : pixel === 'P' ? EYE_BLACK : undefined
320 return [0, 2].map(row => halfBlocks(art[row] ?? '', art[row + 1] ?? '', color))
321}
322
323// Two pixel rows as one terminal row of half blocks: the upper pixel in the
324// top half of each cell, the lower one in the bottom half.
325function halfBlocks(upper: string, lower: string, color: (pixel: string | undefined) => string | undefined): Seg[] {
326 return [...upper].map((pixel, i) => {
327 const top = color(pixel)
328 const bottom = color(lower[i])
329 if (top === undefined && bottom === undefined) {
330 return { text: ' ' }
331 }
332 if (top === undefined) {
333 return { text: '▄', color: bottom, bold: true }
334 }
335 if (bottom === undefined || bottom === top) {
336 return { text: bottom === top ? '█' : '▀', color: top, bold: true }
337 }
338 return { text: '▀', color: top, backgroundColor: bottom, bold: true }
339 })
340}
341
342// A question mark floating over a researcher's head, moving one column every
343// half second.
344function thinkRow(tick: number): Seg[] {
345 const cells: Seg[] = Array.from({ length: RESEARCHER_WIDTH }, () => ({ text: ' ' }))
346 cells[2 + (Math.floor(tick / 2) % 4)] = { text: '?', color: THINK_BLUE, bold: true }
347 return cells
348}
349
350// A planner's blue hard hat: the dome in the row above, the brim over the top
351// of its head, the eyes and arms showing under it.
352function smallHatRow(): Seg[] {
353 const hat = (text: string, color = HELPER_HAT): Seg => ({ text, color, bold: true })
354 return [{ text: ' ' }, hat('▄▄'), hat('▄', HELPER_HAT_BADGE), hat('▄▄'), { text: ' ' }]
355}
356
357function smallBrimRow(): Seg[] {
358 const brim = (backgroundColor: string): Seg => ({ text: '▀', color: HELPER_HAT, backgroundColor, bold: true })
359 return [brim(BODY), brim(BODY), brim(EYE_BLACK), brim(BODY), brim(EYE_BLACK), brim(BODY), brim(BODY)]
360}
361
362// A coder in profile, facing left at its teal laptop, the front arm tapping
363// the keys: the screen tilted back, the keyboard at its feet, sparks above.
364//
365// . # # # # # . head
366// A E # E # # . eyes toward the front, front arm (at rest)
367// a # # # # # . front arm (on the keys, level with them)
368// . # . # . # . legs
369//
370// Typing, the front arm drops one pixel onto the keys and back up, like
371// Clawd's own; it never reaches down to the legs, so it taps the keyboard,
372// not the floor.
373function smallCoderRows(tick: number): Seg[][] {
374 const isArmDown = tick % 2 === 1
375 const screen: Seg = { text: '╲', color: tick % 2 === 1 ? SCREEN_DIM : SCREEN_GLOW, bold: true }
376 const keys: Seg = { text: '▀▀', color: HELPER_LAPTOP, bold: true }
377 const spark = (['✻ ', ' · ', ' ✻', ' ✻ '][tick % 4] ?? ' ').split('')
378 return [
379 [
380 ...spark.map(ch => (ch === '✻' ? { text: ch, color: BODY, bold: true } : ch === '·' ? { text: ch, color: SPARK_YELLOW, bold: true } : { text: ch })),
381 { text: ' ' },
382 ],
383 [screen, { text: ' ' }, helperBody(isArmDown ? ' ' : '▄'), helperEye(), helperBody('█'), helperEye(), helperBody('██ ')],
384 [{ text: ' ' }, keys, helperBody(`${isArmDown ? '▀' : ' '}█▀█▀█ `)],
385 ]
386}
387
388// One helper standing next to Clawd, three rows tall, each row the same width
389// at every tick: a coder at its laptop, a planner under its hard hat
390// marching in place, a researcher in its round glasses.
391function helperRows(kind: HelperKind, tick: number): Seg[][] {
392 if (kind === 'code') {
393 return smallCoderRows(tick)
394 }
395 if (kind === 'plan') {
396 return [smallHatRow(), smallBrimRow(), smallLegs(Math.floor(tick / 2) % 2 === 1)]
397 }
398 return [thinkRow(tick), ...researcherRows(tick)]
399}
400
401// Writes the mood only when it changed, so an idle tick redraws nothing new.
402async function setMood($: EngineInterface, next: PetMood) {
403 if ((await read($, mood)) !== next) {
404 await update($, mood, () => next)
405 }
406}
407
408// Sends a finished subagent's helper away.
409async function dismissHelper($: EngineInterface, id: string) {
410 const list = (await read($, helpers)) ?? []
411 if (list.some(h => h.id === id)) {
412 await update($, helpers, l => (l ?? []).filter(h => h.id !== id))
413 }
414}
415
416// What moodNow needs to know beyond the plugin's state.
417type Clock = {
418 lastActivityAt: number
419 isTurnRunning: boolean
420 errorUntil: number
421 idleMs: number
422 // How many Plan subagents are running: Claude planning without plan mode.
423 planAgents: number
424 // What the footer under the prompt last said about plan mode, and what of
425 // it the plugin has already recorded (see the PromptHint hook).
426 footerSaysPlan: boolean
427 footerEverSaidPlan: boolean
428 footerApplied: boolean | undefined
429}
430
431// Clawd's mood right now: knocked out for a few seconds after a failed
432// command, planning or working while a turn runs, asleep once the person has
433// been idle long enough, awake otherwise.
434async function moodNow($: EngineInterface, c: Clock): Promise<PetMood> {
435 const now = await $.clock.now()
436 if (now < c.errorUntil) {
437 return 'error'
438 }
439 if (c.isTurnRunning) {
440 return c.planAgents > 0 || (await read($, isPlanMode)) ? 'planning' : 'working'
441 }
442 return now - c.lastActivityAt >= c.idleMs ? 'sleeping' : 'awake'
443}
444
445// Records whether plan mode is on. The engine's plan-mode notes switch it
446// both ways; the settings-hook events' `permission_mode` only ever switches it
447// on, so a field they leave stale cannot take the hat off mid-plan.
448async function notePermissionMode($: EngineInterface, permissionMode: string | undefined) {
449 if (permissionMode !== undefined && (await read($, isPlanMode)) !== (permissionMode === 'plan')) {
450 await update($, isPlanMode, () => permissionMode === 'plan')
451 }
452}
453
454export const register: Register = (on, options) => {
455 const idleMs = Math.max(5, Number(options.idleSeconds ?? 60)) * 1000
456 // A custom hex in /config wins over the palette pick; a malformed one is
457 // ignored and the pick is used.
458 paint(toHex(String(options.customColor ?? '')) ?? toHex(String(options.color ?? DEFAULT_COLOR)) ?? BODY)
459 const c: Clock = {
460 lastActivityAt: 0,
461 isTurnRunning: false,
462 errorUntil: 0,
463 idleMs,
464 planAgents: 0,
465 footerSaysPlan: false,
466 footerEverSaidPlan: false,
467 footerApplied: undefined,
468 }
469
470 on('session.start', async ($, e, next) => {
471 c.lastActivityAt = await $.clock.now()
472 await update($, mood, () => 'awake')
473 await update($, helpers, () => [])
474
475 $.clock.every(TICK_MS, async () => {
476 // Shift+Tab: the footer is the first to show the mode changed. Its word
477 // is recorded once each time it changes; it only switches plan mode off
478 // once it has been seen saying it is on, so a footer that never shows
479 // the mode leaves the other signals in charge.
480 if (c.footerApplied !== c.footerSaysPlan && (c.footerSaysPlan || c.footerEverSaidPlan)) {
481 await notePermissionMode($, c.footerSaysPlan ? 'plan' : 'default')
482 c.footerApplied = c.footerSaysPlan
483 }
484 const current = await moodNow($, c)
485 await setMood($, current)
486 if ((await read($, frame)) % 2 === 0) {
487 // Working, the laptop comes out; knocked out, it stays where it was;
488 // otherwise (planning included) it goes back behind Clawd's back.
489 await update($, laptopStep, step =>
490 current === 'working'
491 ? Math.min(OPEN, (step ?? STOWED) + 1)
492 : current === 'error'
493 ? (step ?? STOWED)
494 : Math.max(STOWED, (step ?? STOWED) - 1),
495 )
496 }
497 await update($, frame, n => ((n ?? 0) + 1) % 1000)
498 })
499
500 // The pet keeps living even if the command cannot be registered.
501 try {
502 await $.command.register({
503 name: 'pet',
504 description: 'Show or hide Clawd, the Claude pet above the prompt; /pet color changes its color.',
505 argumentHint: '[color <name|#hex>]',
506 })
507 } catch {}
508
509 return next(e)
510 })
511
512 // `/pet` shows or hides Clawd; `/pet color` lists the colors; `/pet color
513 // <name|#hex>` repaints it now and saves the choice in the plugin's /config
514 // options (a name in "color", a hex in "customColor"), so it lasts.
515 on('command.run', { command: 'pet' }, async ($, e) => {
516 const [sub, ...rest] = e.args.trim().split(/\s+/)
517 if (sub !== 'color') {
518 const hidden = await update($, isHidden, h => !h)
519 return { text: hidden ? 'Clawd went home. Run /pet to bring it back.' : 'Clawd is back!' }
520 }
521
522 const names = Object.keys(PALETTE).join(', ')
523 const wanted = rest.join(' ')
524 if (wanted === '') {
525 return { text: `Clawd's colors: ${names}, or any hex like #00BCD4. Now: ${BODY}.` }
526 }
527
528 const hex = toHex(wanted)
529 if (hex === undefined) {
530 return { text: `"${wanted}" is not a color I know. Use one of: ${names}, or a hex like #00BCD4.` }
531 }
532
533 paint(hex)
534 const name = wanted.trim().toLowerCase()
535 const saves =
536 PALETTE[name] !== undefined
537 ? [
538 { key: 'clawd-pet.color', value: name },
539 { key: 'clawd-pet.customColor', value: '' },
540 ]
541 : [{ key: 'clawd-pet.customColor', value: hex }]
542 for (const save of saves) {
543 const { deny } = await $.config.set(save)
544 if (deny !== undefined) {
545 return { text: `Clawd is ${hex} for now, but the color could not be saved: ${deny}` }
546 }
547 }
548 return { text: `Clawd is now ${PALETTE[name] !== undefined ? name : hex}.` }
549 })
550
551 // Anything the person does in the prompt box wakes Clawd up.
552 on('prompt.edit', async ($, e, next) => {
553 c.lastActivityAt = await $.clock.now()
554 await setMood($, await moodNow($, c))
555 return next(e)
556 })
557
558 on('prompt.submit', async ($, e, next) => {
559 c.isTurnRunning = true
560 c.lastActivityAt = await $.clock.now()
561 await setMood($, await moodNow($, c))
562 return next(e)
563 })
564
565 on('turn.start', async ($, e, next) => {
566 c.isTurnRunning = true
567 c.lastActivityAt = await $.clock.now()
568 await setMood($, await moodNow($, c))
569 return next(e)
570 })
571
572 on('turn.complete', async ($, e, next) => {
573 // A subagent's turn ending is that subagent done: its helper leaves, and
574 // Clawd's own turn goes on.
575 if (e.agentId !== undefined) {
576 await dismissHelper($, e.agentId)
577 return next(e)
578 }
579 c.isTurnRunning = false
580 c.lastActivityAt = await $.clock.now()
581 await setMood($, await moodNow($, c))
582 return next(e)
583 })
584
585 on('classic.UserPromptSubmit', async ($, e, next) => {
586 if (e.permission_mode === 'plan') {
587 await notePermissionMode($, 'plan')
588 }
589 return next(e)
590 })
591
592 on('classic.PostToolUse', async ($, e, next) => {
593 if (e.permission_mode === 'plan') {
594 await notePermissionMode($, 'plan')
595 }
596 return next(e)
597 })
598
599 // The engine's own record of plan mode: while it is on, every request of
600 // the main conversation carries a `plan_mode` reminder (and a
601 // `plan_mode_reentry` note when Claude goes back into it); when it ends, a
602 // `plan_mode_exit` note is made once. A subagent's rows are left out: only
603 // the main conversation's mode puts the hat on.
604 on('prompt.attachment', { type: 'plan_mode' }, async ($, e, next) => {
605 if (e.agentId === undefined) {
606 await notePermissionMode($, 'plan')
607 }
608 return next(e)
609 })
610
611 on('prompt.attachment', { type: 'plan_mode_reentry' }, async ($, e, next) => {
612 if (e.agentId === undefined) {
613 await notePermissionMode($, 'plan')
614 }
615 return next(e)
616 })
617
618 on('prompt.attachment', { type: 'plan_mode_exit' }, async ($, e, next) => {
619 if (e.agentId === undefined) {
620 await notePermissionMode($, 'default')
621 }
622 return next(e)
623 })
624
625 // Entering plan mode puts the hat on; a plan accepted takes it off.
626 on('tool.call', { tool: 'EnterPlanMode' }, async ($, e, next) => {
627 const result = await next(e)
628 if (!result.deny && !result.isError) {
629 await update($, isPlanMode, () => true)
630 }
631 return result
632 })
633
634 on('tool.call', { tool: 'ExitPlanMode' }, async ($, e, next) => {
635 const result = await next(e)
636 if (!result.deny && !result.isError) {
637 await update($, isPlanMode, () => false)
638 }
639 return result
640 })
641
642 // Each subagent Claude starts (in the foreground or the background) brings
643 // a helper of its kind next to Clawd, until it finishes.
644 on('agent.spawn', async ($, e, next) => {
645 const result = await next(e)
646 const id = result.agentId
647 if (id !== undefined && !('deny' in result && result.deny)) {
648 const kind = helperKind(e.subagentType)
649 await update($, helpers, list => [...(list ?? []).filter(h => h.id !== id), { id, kind }])
650 }
651 return result
652 })
653
654 on('classic.SubagentStop', async ($, e, next) => {
655 await dismissHelper($, e.agent_id)
656 return next(e)
657 })
658
659 // Asked to plan, Claude may hand the work to its Plan subagent without
660 // entering plan mode: Clawd plans (hard hat on) while that agent runs.
661 on('tool.call', { tool: 'Agent' }, async ($, e, next) => {
662 if (e.subagent_type !== 'Plan') {
663 return next(e)
664 }
665 c.planAgents += 1
666 try {
667 return await next(e)
668 } finally {
669 c.planAgents -= 1
670 }
671 })
672
673 // The footer under the prompt says "plan mode on" while plan mode is on, the
674 // moment Shift+Tab switches it. A drawing never writes state, so this only
675 // notes what the line says; the timer records it.
676 on('ui.render', { component: 'PromptHint' }, ($, e, next) => {
677 c.footerSaysPlan = /plan mode on/i.test(e.props.hint)
678 c.footerEverSaidPlan = c.footerEverSaidPlan || c.footerSaysPlan
679 return next(e)
680 })
681
682 // A failing command (a build, a test run, a script) knocks Clawd out for a
683 // few seconds; an interrupt does not count.
684 on('classic.PostToolUseFailure', async ($, e, next) => {
685 if (e.permission_mode === 'plan') {
686 await notePermissionMode($, 'plan')
687 }
688 if (e.tool_name === 'Bash' && !e.is_interrupt) {
689 c.errorUntil = (await $.clock.now()) + ERROR_MS
690 await setMood($, 'error')
691 }
692 return next(e)
693 })
694
695 // Clawd sits in the band right above the prompt, against its right edge,
696 // on rows of its own so nothing squeezes it: four where the band has them
697 // (the top one for the sparks and the floating Zs), three otherwise. The
698 // row count never changes with the mood, so the prompt never jumps.
699 on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
700 if (e.props.hasSurvey || e.props.maxRows < 3 || (await read($, isHidden))) {
701 return next(e)
702 }
703
704 const current = await read($, mood)
705 const tick = await read($, frame)
706 const step = await read($, laptopStep)
707 const { Box, Text } = $.ui.resolve(e)
708
709 const isWorking = current === 'working'
710 const isTyping = isWorking && step === OPEN
711 const isAsleep = current === 'sleeping'
712 const isPlanning = current === 'planning'
713 const isKnockedOut = current === 'error'
714 const wearsHat = !isAsleep && !isKnockedOut && (isPlanning || (await read($, isPlanMode)))
715 const eyes: Eyes = isAsleep ? 'asleep' : current === 'awake' && tick % 28 === 27 ? 'blink' : 'open'
716 // From the moment it turns to grab the laptop until it has put it back,
717 // Clawd is in profile; otherwise it faces you.
718 const isSideways = step > STOWED && !isKnockedOut
719 const bubble =
720 isKnockedOut
721 ? ['', '', '', 'oops!']
722 : isPlanning
723 ? ['', '', '', `planning${'.'.repeat((Math.floor(tick / 2) % 3) + 1)}`]
724 : isAsleep
725 ? ['', '', '', 'Zzz…']
726 : isTyping
727 ? ['', '', '', '']
728 : isWorking
729 ? ['', '', '', step <= TURNED ? 'hmm…' : 'got it!']
730 : step > STOWED
731 ? ['', '', '', 'done!']
732 : ['', '', '', 'hi!']
733 const blank: Seg[] = [{ text: ' ' }]
734 const laptop = [isTyping ? sparkRow(tick) : [{ text: ' ' }], ...laptopRows(step, isWorking, tick)]
735 const front = petRows(eyes)
736 const body: Seg[][] = isKnockedOut
737 ? [[{ text: ' ' }], ...knockedOutRows()]
738 : isSideways
739 ? sidePetRows(isTyping && tick % 2 === 1)
740 : isPlanning
741 ? [front[0] ?? blank, front[1] ?? blank, marchingLegs(tick)]
742 : front
743 const head = body[0] ?? blank
744 const pet = [
745 isKnockedOut ? starRow(tick) : isAsleep ? sleepRow(tick) : wearsHat ? hatRow() : blank,
746 wearsHat ? brimRow() : head,
747 ...body.slice(1),
748 ]
749 const tumblingLaptop: Seg[][] = [
750 [{ text: ' ' }],
751 [{ text: '▞', color: LAPTOP_GREY, bold: true }],
752 [{ text: '▀', color: LAPTOP_DIM }],
753 ]
754 const behind = [blank, ...(isKnockedOut ? tumblingLaptop : behindRows(step))]
755 const rows = e.props.maxRows >= 4 ? 4 : 3
756
757 // The helpers stand to Clawd's left, as many as the band has room for
758 // (Clawd itself takes about 30 columns; a researcher 7 plus its margin,
759 // any other helper 10 plus its margin).
760 const team = (await read($, helpers)) ?? []
761 const shown: typeof team = []
762 let room = e.props.bodyColumns - 30
763 for (const helper of team) {
764 const width = (helper.kind === 'research' ? RESEARCHER_WIDTH : 10) + 1
765 if (shown.length >= MAX_HELPERS || width > room) {
766 break
767 }
768 shown.push(helper)
769 room -= width
770 }
771 const extra = team.length - shown.length
772 const fit = <T,>(column: T[]): T[] => column.slice(Math.max(0, column.length - rows))
773
774 const drawRow = (segs: Seg[], key: string) => (
775 <Text key={key}>
776 {segs.map((seg, i) => (
777 <Text key={`${key}-${i}`} color={seg.color} backgroundColor={seg.backgroundColor} bold={seg.bold}>
778 {seg.text}
779 </Text>
780 ))}
781 </Text>
782 )
783
784 // As wide as the band, everything pushed to its right end.
785 return (
786 <Box flexDirection="row" alignItems="flex-end" justifyContent="flex-end" width={e.props.bodyColumns}>
787 {extra > 0 ? (
788 <Box flexDirection="column" marginRight={1}>
789 <Text color={BODY} bold>
790 +{extra}
791 </Text>
792 </Box>
793 ) : null}
794 {shown.map(helper => (
795 <Box key={`helper-${helper.id}`} flexDirection="column" marginRight={1}>
796 {fit(helperRows(helper.kind, tick)).map((r, i) => drawRow(r, `helper-${helper.id}-${i}`))}
797 </Box>
798 ))}
799 <Box flexDirection="column" alignItems="flex-end">
800 {fit(bubble).map((row, i) => (
801 <Text key={`bubble-${i}`} color={isAsleep ? Z_FADED : BODY} bold={!isAsleep}>
802 {row || ' '}
803 </Text>
804 ))}
805 </Box>
806 <Box flexDirection="column" marginLeft={1}>
807 {fit(laptop).map((r, i) => drawRow(r, `laptop-${i}`))}
808 </Box>
809 <Box flexDirection="column">{fit(pet).map((r, i) => drawRow(r, `pet-${i}`))}</Box>
810 <Box flexDirection="column">{fit(behind).map((r, i) => drawRow(r, `behind-${i}`))}</Box>
811 </Box>
812 )
813 })
814}
815types/index.d.ts 21 lines1export type PetMood = 'awake' | 'working' | 'planning' | 'error' | 'sleeping'
2
3// What a subagent's helper does: reads in glasses, plans under the hard hat,
4// or codes on its laptop.
5export type HelperKind = 'research' | 'plan' | 'code'
6
7export type Helper = { id: string; kind: HelperKind }
8
9declare module 'claude-code' {
10 interface PluginState {
11 'clawd-pet': {
12 mood: PetMood
13 frame: number
14 isHidden: boolean
15 laptopStep: number
16 isPlanMode: boolean
17 helpers: Helper[]
18 }
19 }
20}
21