Clawd, a pixel crab whose mood follows the session.

Small cards that sit under the Claude Code prompt, or docked beside the transcript in fullscreen. Each widget is its own mod, toggled with a slash command.
It started with a few useful ones (context, usage, file tree) and then got carried away: there are now 95 widgets, from git status and a turn timer to a pixel crab, a dungeon crawl and Tetris.
Try every widget in its own little terminal on the demo page: the real widget code runs in the browser against a simulated session, so you can type its slash commands, run a turn and play the games. It is a static page in docs/, published to GitHub Pages on every push to main that changes it; opening docs/index.html from a checkout works too.
Add the marketplace, then install the layout plugin and whichever widgets you want:
/plugin marketplace add oMaN-Rod/claude-code-widgets
/plugin install widgets@claude-code-widgets
/plugin install context-widget@claude-code-widgets
Every widget needs widgets, the layout plugin that places the cards.
Requires a Claude Code version with mod (function hook) support. The mod API is early access and may change between releases.
Required by every widget.
| Plugin | Command | What it shows | ||||||
|---|---|---|---|---|---|---|---|---|
widgets | `/widgets [side\ | above\ | below\ | close\ | <columns>\ | width <widget> <columns\ | reset>]` | Places the cards: below the prompt, above it, or docked beside the transcript in fullscreen |
What Claude is doing and what it is costing.
| Plugin | Command | What it shows | ||||||||
|---|---|---|---|---|---|---|---|---|---|---|
context-widget | `/context-widget [auto\ | detailed\ | grid\ | top\ | bar\ | line]` | The context window as a stacked bar, one colour per /context category | |||
usage-widget | /usage-widget | A bar per rate-limit window, time to reset, session cost | ||||||||
timer-widget | `/timer-widget [on\ | off\ | clear]` | The running turn's elapsed time, plus last, average and longest turn and a sparkline | ||||||
activity-widget | `/activity-widget [on\ | off\ | clear]` | The latest tool calls with their duration and whether they failed | ||||||
tasks-widget | `/tasks-widget [on\ | off\ | clear]` | The task list Claude is working through, with a progress bar | ||||||
checks-widget | `/checks-widget [on\ | off\ | clear]` | The latest test, lint and build runs: pass or fail, duration and how long ago | ||||||
timeline-widget | `/timeline-widget [on\ | off]` | The turn as a chart: one bar per tool call on a time axis, parallel calls stacked | |||||||
board-widget | `/board-widget [on\ | off\ | clear]` | A status board Claude writes itself through a pin tool: goal, findings and open questions | ||||||
forecast-widget | `/forecast-widget [on\ | off\ | clear]` | Context growth per turn as a chart, with the turns left before compaction; warns once when three or fewer are left | ||||||
guard-widget | `/guard-widget [on\ | off\ | clear]` | Permission checks this session: allowed, asked and denied, with what you keep being asked about | ||||||
stream-widget | `/stream-widget [on\ | off]` | A live tokens-per-second gauge and sparkline while Claude is writing (estimated from text length) | |||||||
sessions-widget | /relay <number> <message>, `/sessions-widget [on\ | off]` | Every Claude Code session open on this machine: folder, branch, working or waiting and for how long; /relay 1 <message> sends a line to one | |||||||
collision-widget | `/collision-widget [on\ | off\ | clear]` | Stops an edit to a file another Claude Code session on this machine changed since this one last read it, and has Claude read it again first | ||||||
sieve-widget | `/sieve-widget [on\ | off]` | A compaction that keeps every word you and Claude said and folds only the old tool traffic, with no summary and no tokens spent | |||||||
redact-widget | `/redact-widget [on\ | off\ | clear]` | Replaces API keys, tokens, private keys and passwords in command output and file reads before Claude sees them | ||||||
notebook-widget | `/notebook-widget [on\ | off\ | show\ | drop <number>\ | clear]` | Gives Claude a jot tool for writing down what its future self should know about this project, and reads the notes back next session | ||||
footnotes-widget | `/footnotes-widget [on\ | off\ | show\ | clear]` | Checks every file path, cited line and code symbol in Claude's last reply against the working tree, with no model call, and flags the ones that are not there | |||||
witness-widget | `/witness-widget [on\ | off\ | show\ | clear]` | Every line of hidden context the other widgets add to your prompts, word for word, with a running size | |||||
queue-widget | `/queue-widget [on\ | off\ | add <prompt>\ | until <command\ | off>\ | start\ | drop <number>\ | report\ | clear]` | A queue of prompts that run back to back while you are away, a gate command each must pass before the next starts, and a report of how each one ended |
done-widget | `/done-widget [on\ | off\ | add <criterion>\ | drop <number>\ | show\ | clear]` | A definition of done you write once: Claude ticks each item with evidence through its tick tool, and is pulled up when it says done with items open | |||
trial-widget | `/trial-widget [on\ | off\ | test <widget>\ | clear]` | A fair test of another widget: sessions alternate with it on and off, and the card compares how many turns end clean | |||||
aside-widget | `/aside-widget [on\ | off\ | ask <question>\ | clear]` | Ask a side question about the conversation, even mid-turn, and get the answer on a card without adding a turn to the transcript | |||||
tap-widget | `/tap-widget [on\ | off\ | list [word]\ | add <server> <tool> [json] [anyway]\ | run <n>\ | show <n>\ | drop <n>\ | clear]` | One line per tool of your connected MCP servers, called by the widget on a clock with no model: pull requests, errors, the next meeting | |
margin-widget | `/margin-widget [on\ | off\ | mark [remark]\ | drop <n>\ | send\ | clear]` | Mark passages of Claude's reply with the mouse, write a remark against each, and send them back as one quoted prompt | |||
loupe-widget | `/loupe-widget [on\ | off\ | look [text]\ | copy]` | Select a hash, path, name, timestamp or colour in the transcript with the mouse and the card says what it is, with no model call | |||||
strays-widget | `/strays-widget [on\ | off\ | stop <port>\ | forget <port>\ | clear]` | Servers this session started that still hold a port, with age and turn, one verb to stop one, and the survivors shown when the next session opens | ||||
premise-widget | `/premise-widget [on\ | off\ | show\ | fix <n>\ | clear]` | Quotes thinking-summary sentences that name a gap and a choice made anyway, unless the reply flags it, and starts your correction; no model call; needs "showThinkingSummaries": true in settings.json | ||||
earpiece-widget | `/earpiece-widget [on\ | off], /whisper <number> <note>` | Every running subagent with the tool it is on and its last sentence, and /whisper slips one of them a note without stopping the turn | |||||||
pen-widget | `/pen-widget [on\ | off\ | show\ | clear]` | The file, edit or command Claude is writing right now, drawn line by line as the tool call's arguments stream in, before the tool runs | |||||
outage-widget | `/outage-widget [on\ | off\ | check\ | clear]` | When a push or install fails on the network, checks the provider's status page and says whether GitHub, npm, PyPI or crates.io reports an incident | |||||
landmarks-widget | `/landmarks-widget [on\ | off\ | list\ | go <n>\ | clear]` | A numbered table of contents for the session, built as it happens from prompts, first edits, checks turning red or green, commits and questions; press a line to scroll the transcript to it | ||||
seen-widget | `/seen-widget [on\ | off\ | show\ | open [n]\ | clear]` | The pictures Claude looked at this session, image files it read and screenshots that came back from tools, drawn as Claude received them and opened full size with one command | ||||
amendments-widget | `/amendments-widget [on\ | off\ | show [n]\ | clear]` | What changed in the system prompt and the built-in tool descriptions Claude Code gives Claude since the version you last ran, with the before and after one command away | |||||
skimmed-widget | `/skimmed-widget [on\ | off\ | show\ | clear]` | The caveats in Claude's replies that left your screen while Claude was still writing and have not been back, quoted in full; it never claims that what was on screen was read | |||||
attic-widget | `/attic-widget [on\ | off\ | show\ | keep <tool>\ | stow <tool>\ | clear]` | Counts which tools Claude calls in this project, puts the unused ones behind ToolSearch, lists the daily ones up front, and reports how many schema tokens each request no longer carries | |||
rehearsal-widget | `/rehearsal-widget [on\ | off\ | show\ | forget <n>\ | clear]` | Which of the commands and edits Claude has made in this project would stop for permission or be refused right now, asked of the engine's own permission check without running anything | ||||
aim-widget | `/aim-widget [on\ | off\ | prod <word>\ | unprod <word>\ | show\ | clear]` | Where a command lands outside this folder: the kube context, cloud profile, Terraform workspace or database it is aimed at, named in the permission dialog | |||
earshot-widget | `/earshot-widget [on\ | off\ | last\ | clear]` | Whether Claude has got the message you typed while it was working: how late a request first carried it, and what Claude changed before it heard you |
The state of the working tree.
| Plugin | Command | What it shows | |||||
|---|---|---|---|---|---|---|---|
file-tree-widget | /file-tree-widget | The project directory; folders expand on click | |||||
git-widget | /git-widget | Branch, ahead/behind, staged, changed and untracked counts, and the last commit | |||||
changes-widget | `/changes-widget [on\ | off\ | clear]` | Files edited this session, most recent first, with an edit count each | |||
commits-widget | /commits-widget | The commits made since the session started | |||||
todos-widget | /todos-widget | TODO, FIXME, HACK and XXX comments in tracked files, counted and listed | |||||
diff-widget | `/diff-widget [on\ | off\ | clear]` | The last edit as a syntax-highlighted diff | |||
watch-widget | `/watch-widget [on\ | off\ | run\ | stop], /watch <command>` | /watch bun test reruns the command after every edit: a pass or fail light and the last failing lines | ||
map-widget | `/map-widget [on\ | off\ | clear]` | A pixel map of the tracked files, lit blue where Claude has read and green where it has edited | |||
stakes-widget | `/stakes-widget [on\ | off\ | clear]` | What a yes would lose, measured from git and written under the permission dialog for a destructive command | |||
ledger-widget | `/ledger-widget [on\ | off\ | scan\ | show\ | clear]` | What a project has cost across every session, from any folder or worktree in it: measured as each turn ends, and read back from the sessions Claude Code saved | |
squiggle-widget | `/squiggle-widget [on\ | off\ | check [text]]` | Underlines file names that do not exist, as you type them in the prompt box, and paints the ones that do green | |||
critic-widget | `/critic-widget [on\ | off\ | review\ | tell\ | clear]` | A second pair of eyes: a separate model reads the uncommitted diff and lists only real defects, which you can hand to Claude | |
customs-widget | `/customs-widget [on\ | off\ | show\ | trust <name>\ | clear]` | Looks up every package Claude installs on npm or PyPI before the command runs, and holds the install for a yes when the name is missing or under 30 days old. Scoped names and installs that name a registry, or sit beside a project .npmrc that does, are not looked up; user-level and environment registry settings, bunfig.toml, .yarnrc.yml and pip and uv config files are not seen | |
provenance-widget | `/provenance-widget [on\ | off\ | scan\ | look [<path>:<line>]\ | copy\ | clear]` | The conversation behind a line of code: for lines Claude is about to edit, or a path:line you ask about, the prompt you typed before they were written and the command that resumes that session |
green-widget | `/green-widget [on\ | off\ | tell\ | clear]` | What changed in the working tree since each test, lint or build command last passed, measured against a hidden git snapshot taken at that moment and handed to Claude on request |
Clocks, timers and reminders that do not depend on the session.
| Plugin | Command | What it shows | |||||
|---|---|---|---|---|---|---|---|
pomodoro-widget | `/pomodoro-widget [on\ | off\ | start\ | break\ | stop\ | <minutes>]` | A focus timer with a countdown, a progress bar and a count of finished sessions |
countdown-widget | `/countdown-widget [on\ | off\ | clear], /countdown <HH:MM\ | <n>m\ | <n>h> [label]` | Time left to a deadline you set, with a progress bar and a toast when it arrives | |
clocks-widget | `/clocks-widget [on\ | off\ | add <zone>\ | remove <zone>\ | clear]` | Your local time beside the time zones you add, such as Asia/Tokyo | |
notes-widget | `/notes-widget [on\ | off\ | clear], /note <text\ | done <n>>` | Pinned notes kept across sessions; /note <text> adds one, /note done <n> removes it | ||
coffee-widget | `/coffee-widget [on\ | off\ | refill\ | <minutes>]` | A cup that empties over 90 minutes and nudges you to take a break |
Pixel art that reacts to turns, tool calls, checks and context usage.
| Plugin | Command | What it shows | |||
|---|---|---|---|---|---|
pet-widget | `/pet-widget [on\ | off\ | <mood>]` | Clawd, a pixel crab: works during a turn, dizzy when a tool call fails, happy when tests pass. Earns XP and levels up across sessions, wears a hat once badges-widget has awarded a badge, and with two sessions open stays in the one you last prompted. Remembers each project and greets you with how long you were away and whether the checks were red | |
aquarium-widget | `/aquarium-widget [on\ | off\ | demo]` | A fish for every running tool call and agent | |
skyline-widget | `/skyline-widget [on\ | off\ | demo\ | clear]` | One building per turn, one floor per tool call |
train-widget | `/train-widget [on\ | off]` | A locomotive pulling one wagon per tool call this turn, coloured by tool | ||
garden-widget | `/garden-widget [on\ | off\ | reset]` | A plant: a leaf per tool call, a flower when checks pass, wilting when a call fails | |
campfire-widget | `/campfire-widget [on\ | off\ | stoke]` | A campfire that burns higher with tool calls and dies down to embers when idle | |
constellation-widget | `/constellation-widget [on\ | off\ | clear]` | A star per turn, joined into a constellation that gets a name after nine | |
fireworks-widget | `/fireworks-widget [on\ | off\ | demo]` | A night sky that sets off fireworks when checks pass, and a dud when they fail | |
invaders-widget | `/invaders-widget [on\ | off\ | demo\ | clear]` | An invader arrives for every failing check; passing checks shoot them down |
weather-widget | `/weather-widget [on\ | off\ | live\ | <percent>]` | Clear sky when context has room, a storm near compaction |
boss-widget | `/boss-widget [on\ | off]` | Context usage as a boss health bar; compaction defeats it and starts the next level | ||
sky-widget | `/sky-widget [on\ | off]` | The sky at your local time: sun by day, moon by night, more stars the longer the session runs | ||
world-widget | `/world-widget [on\ | off\ | clear]` | One scene for everything: sky by the clock, weather by context, a tower per turn, a train of tool calls and a wandering crab | |
quest-widget | `/quest-widget [on\ | off\ | reset]` | The session as a dungeon crawl: a room per turn, a monster per tool call, loot when checks pass; the hero is kept across sessions | |
race-widget | `/race-widget [on\ | off\ | clear]` | Parallel subagents as cars on a track, one stride per tool call, with a podium as they finish | |
moon-widget | `/moon-widget [on\ | off\ | north\ | south]` | The real moon right now, drawn for your hemisphere, with a countdown to the next full moon and what it means for your deploy |
Abstract pictures driven by tool activity.
| Plugin | Command | What it shows | |||
|---|---|---|---|---|---|
mosaic-widget | `/mosaic-widget [on\ | off\ | clear]` | One tile per tool call, coloured by tool; failures are red | |
sorting-widget | `/sorting-widget [on\ | off\ | step]` | A bar chart being sorted, one swap per tool call | |
equalizer-widget | `/equalizer-widget [on\ | off]` | Level meters that jump with each tool call and fall back to rest | ||
rain-widget | `/rain-widget [on\ | off]` | Falling code rain that speeds up the busier the turn gets | ||
orbit-widget | `/orbit-widget [on\ | off]` | A small solar system; the planets speed up while tool calls run | ||
life-widget | `/life-widget [on\ | off\ | reset]` | Conway's Game of Life; every tool call drops a glider | |
donut-widget | `/donut-widget [on\ | off]` | The spinning 3D donut; it spins faster while tool calls run | ||
pipes-widget | `/pipes-widget [on\ | off]` | The pipes screensaver; it grows while the session is idle and pauses while Claude works | ||
maze-widget | `/maze-widget [on\ | off\ | new]` | A first-person walk through a maze seeded by the project folder | |
marquee-widget | `/marquee-widget [on\ | off\ | clear\ | <text>]` | An LED ticker scrolling session events; any other text posts your own headline |
Snake, 2048 and Tetris play themselves until you click the board and take the keys.
| Plugin | Command | What it shows | ||
|---|---|---|---|---|
snake-widget | `/snake-widget [on\ | off]` | Snake; it plays itself until you take the keys | |
2048-widget | `/2048-widget [on\ | off]` | 2048; it plays itself until you take the keys | |
tetris-widget | `/tetris-widget [on\ | off]` | Tetris; it plays itself until you take the keys | |
minesweeper-widget | `/minesweeper-widget [on\ | off]` | Minesweeper: click to reveal, right-click or f to flag, r to restart | |
breakout-widget | `/breakout-widget [on\ | off\ | reset]` | A self-playing brick breaker; every tool call adds a row of bricks |
typer-widget | `/typer-widget [on\ | off]` | A typing game: words from your own file names fall, and you type them before they land |
| Plugin | Command | What it shows | |||
|---|---|---|---|---|---|
fortune-widget | `/fortune-widget [on\ | off\ | next]` | A one-line fortune that changes with every turn | |
8ball-widget | `/8ball-widget [on\ | off], /8ball <question>` | /8ball <question> gives an answer of doubtful reliability | ||
badges-widget | `/badges-widget [on\ | off\ | reset]` | Achievements earned across sessions, with a toast when one unlocks | |
sigil-widget | `/sigil-widget [on\ | off\ | clear]` | A pixel emblem generated from this session's activity, beside a gallery of the ones from earlier sessions | |
sound-widget | `/sound-widget [on\ | off\ | mute\ | test]` | A note per tool call, a chord when checks pass, a buzz on failure, with a piano roll (audio plays on macOS only) |
Placement, which widgets are on, and view modes are saved and restored in every session.
/widgets width pet 60 sets how wide one widget's card may grow (the default is 40 columns); /widgets width pet reset puts it back./widgets side docks the cards beside the transcript only in the fullscreen layout (/tui fullscreen). In the default layout it falls back to below the prompt.sound-widget plays audio on macOS only; elsewhere it stays silent and just draws the piano roll.board-widget registers a pin tool that Claude can call, so its description is part of the context while the board is on.watch-widget runs your command through sh -c, falling back to cmd /c.Each plugin under plugins/ is a mod: a manifest, a hooks module and its tests.
claude --plugin-dir plugins # load every plugin from this checkout
claude plugin validate plugins/<name> # check a manifest and hooks module
claude plugin test plugins/<name> # run its tests
Plugin storage ($.store) is read once per session, so a widget that has to see other live sessions keeps a file under its own folder instead ($.plugin.root).
Plugins cannot import from one another, so widgets shares card stacking and the pixel renderer as $.widgets (plugins/widgets/hooks/kit.tsx), which every widget calls.
docs/ is the demo page. bun run site/build.ts bundles every widget's hooks module into docs/mods.js and writes docs/catalog.js from the tables above, so a new widget appears on the page once it has a row here. docs/engine.js is a small stand-in for the mod engine (state, store, clock, commands, a made-up project and a scripted turn), and docs/view.js draws the card trees. bun run site/smoke.ts boots every widget in that engine and runs a turn; a widget that needs an engine call the stand-in lacks shows up there. docs/widgets.js holds recordings from the real interface, shown only if a widget fails to start.
New widgets are made by the Widget Factory in factory/: a crew of Claude Code agents that takes each widget through ideation, design, build, inspection and shipping, with a different agent inspecting than built it. Clone the repository and you can run your own:
https://github.com/user-attachments/assets/6833eb82-8b2e-4b4c-80ca-4194d48d10e7
bun run --cwd factory setup # checks what you need and prepares the floor
bun run --cwd factory floor # the factory floor in your browser
bun run --cwd factory line # opens a Claude Code session that runs the line
https://github.com/user-attachments/assets/d0953871-4935-4fa9-8ab3-f58b51739a17
factory/README.md explains the stations, the crew, the widget standard and how to contribute a widget.
MIT
hooks/register.tsx 432 lines1import { atom, read, update } from 'claude-code'
2import type { Elements, EngineInterface, Register, RenderElement, RenderSurface, Timer } from 'claude-code'
3
4import type { WidgetsPlace } from 'widgets'
5
6import type { PetMemory, PetMood, PetStatus } from '../types'
7
8type Tags = Pick<Elements[RenderSurface], 'Box' | 'Text'>
9
10const PANE = 'widgets'
11const CARD_COLUMNS = 40
12const TICK_MS = 600
13const FLASH_MS = 6000
14const SLEEPY_MS = 90_000
15const HOT_PERCENT = 80
16const MOODS: readonly string[] = ['sleep', 'idle', 'work', 'happy', 'dizzy', 'hot']
17const CHECKS = /\b(test|tests|pytest|jest|vitest|tsc|lint|build|check)\b/
18const RESTING: PetStatus = { isWorking: false, isHot: false, activeAt: 0, calls: 0, forced: null }
19const CLAWS = [
20 [
21 '..oooo................oooo..',
22 '.oo..oo..............oo..oo.',
23 ],
24 [
25 '..oooo................oooo..',
26 '.oooooo..............oooooo.',
27 ],
28] as const
29const BODY = [
30 '.oooooo...ee....ee...oooooo.',
31 '..dooo....ep....pe....oood..',
32 '...doo....oo....oo....ood...',
33 '....dooolllllllllllloood....',
34 '.....oooooooooooooooooo.....',
35 '.....oooooommmmmmoooooo.....',
36 '.....dooooooooooooooood.....',
37 '......dddddddddddddddd......',
38]
39const LEGS = [
40 [
41 '....oo..oo........oo..oo....',
42 '...oo..oo..........oo..oo...',
43 ],
44 [
45 '.....oo.oo........oo.oo.....',
46 '....oo..oo........oo..oo....',
47 ],
48] as const
49const SAYS: Record<PetMood, string> = {
50 sleep: 'zzz',
51 idle: 'waiting for you',
52 work: 'working…',
53 happy: 'checks passed!',
54 dizzy: 'ouch',
55 hot: 'context is filling up',
56}
57const POLL_TICKS = 5
58const SAY_MS = 12_000
59const HOUR_MS = 60 * 60_000
60const DAY_MS = 24 * HOUR_MS
61const LONG_TURN_MS = 10 * 60_000
62const BIG_TURN_CALLS = 25
63const HOME_FILE = '.home.json'
64const STAY_MS = 30 * 60_000
65const SHELLS = [0xd97757, 0xe8a23a, 0x9775fa]
66const HATS = [
67 { badges: 8, lines: ['c.cc.c', 'cccccc'], palette: { c: 0xffd43b } },
68 { badges: 4, lines: ['.tttt.', 'tbbbbt'], palette: { t: 0x1f2328, b: 0xe5484d } },
69 { badges: 1, lines: ['.kkkk.', 'kkkkkk'], palette: { k: 0x4dabf7 } },
70] as const
71const site = { plugin: 'widgets', key: 'site' } as const
72const widths = { plugin: 'widgets', key: 'widths' } as const
73const isOn = atom({ plugin: 'pet-widget', key: 'isOn' } as const, false)
74const tick = atom({ plugin: 'pet-widget', key: 'tick' } as const, 0)
75const status = atom({ plugin: 'pet-widget', key: 'status' } as const, RESTING)
76const growth = atom({ plugin: 'pet-widget', key: 'growth' } as const, { xp: 0 })
77const visit = atom({ plugin: 'pet-widget', key: 'visit' } as const, { id: '', isAway: false })
78
79let timer: Timer | undefined
80let home = ''
81let memory: PetMemory = { at: 0, isFailing: false, visits: 0 }
82
83const shade = (color: number, factor: number): number =>
84 (Math.round((color >> 16) * factor) << 16) |
85 (Math.round(((color >> 8) & 255) * factor) << 8) |
86 Math.round((color & 255) * factor)
87
88const isMood = (value: string): value is PetMood => MOODS.includes(value)
89
90const isHome = (value: unknown): value is { holder: string; at: number } =>
91 typeof value === 'object' &&
92 value !== null &&
93 typeof (value as { holder?: unknown }).holder === 'string' &&
94 typeof (value as { at?: unknown }).at === 'number'
95
96const claim = async ($: EngineInterface): Promise<void> => {
97 const me = await read($, visit)
98 if (me.id === '') return
99
100 const held = JSON.stringify({ holder: me.id, at: await $.clock.now() })
101 await $.fs.write(`${$.plugin.root}/${HOME_FILE}`, held).catch(() => undefined)
102 await update($, visit, held => ({ id: held?.id ?? me.id, isAway: false }))
103}
104
105const look = async ($: EngineInterface): Promise<void> => {
106 const me = await read($, visit)
107 const now = await $.clock.now()
108 if (me.id === '') return
109
110 let kept: unknown
111 try {
112 kept = JSON.parse(await $.fs.read(`${$.plugin.root}/${HOME_FILE}`))
113 } catch {
114 kept = undefined
115 }
116 if (!isHome(kept) || now - kept.at >= STAY_MS) {
117 await claim($)
118
119 return
120 }
121
122 const isAway = kept.holder !== me.id
123 if (isAway !== me.isAway) await update($, visit, held => ({ id: held?.id ?? me.id, isAway }))
124}
125
126const isMemory = (value: unknown): value is PetMemory =>
127 typeof value === 'object' &&
128 value !== null &&
129 typeof (value as PetMemory).at === 'number' &&
130 typeof (value as PetMemory).isFailing === 'boolean' &&
131 typeof (value as PetMemory).visits === 'number'
132
133const say = async ($: EngineInterface, text: string): Promise<void> => {
134 const until = (await $.clock.now()) + SAY_MS
135 await update($, status, held => ({ ...(held ?? RESTING), said: { text, until } }))
136}
137
138const greetingOf = (kept: PetMemory | undefined, now: number): string => {
139 if (kept === undefined) return 'a new project! I like it here'
140
141 const away = now - kept.at
142 if (away < HOUR_MS) return 'back already?'
143 if (away < DAY_MS) return kept.isFailing ? 'welcome back. the checks are still red' : 'welcome back'
144
145 const days = Math.floor(away / DAY_MS)
146
147 return `${days} ${days === 1 ? 'day' : 'days'} away. ${kept.isFailing ? 'the checks were red when you left' : 'all was green when you left'}`
148}
149
150const remember = async ($: EngineInterface): Promise<void> => {
151 if (home === '') return
152
153 memory = { ...memory, at: await $.clock.now() }
154 await $.store.set(`seen:${home}`, memory)
155}
156
157const pulse = async ($: EngineInterface): Promise<void> => {
158 const count = await update($, tick, held => ((held ?? 0) + 1) % 1_000_000)
159 if (count % POLL_TICKS === 0) await look($)
160}
161
162const enrol = async ($: EngineInterface): Promise<void> => {
163 const now = await $.clock.now()
164 await update($, visit, held =>
165 held === undefined || held.id === '' ? { id: `${now}-${Math.floor(Math.random() * 1_000_000)}`, isAway: false } : held,
166 )
167}
168
169const sync = async ($: EngineInterface): Promise<void> => {
170 const isWanted = await read($, isOn)
171 if (isWanted && timer === undefined) {
172 timer = $.clock.every(TICK_MS, () => {
173 void pulse($)
174 })
175 }
176 if (!isWanted && timer !== undefined) {
177 timer.cancel()
178 timer = undefined
179 }
180}
181
182const levelOf = (xp: number): number => 1 + Math.floor(Math.sqrt(xp / 20))
183
184const badgesOf = async ($: EngineInterface): Promise<number> => {
185 const earned = (await $.state.get({ plugin: 'badges-widget', key: 'earned' } as never)) as { value?: unknown }
186
187 return Array.isArray(earned.value) ? earned.value.length : 0
188}
189
190const moodAt = (held: PetStatus, now: number): PetMood => {
191 if (held.forced !== null && now < held.forced.until) return held.forced.mood
192 if (held.isWorking) return 'work'
193 if (held.isHot) return 'hot'
194
195 return now - held.activeAt > SLEEPY_MS ? 'sleep' : 'idle'
196}
197
198const wide = async ($: EngineInterface): Promise<number> =>
199 (await $.state.get(widths)).value?.['pet-widget'] ?? CARD_COLUMNS
200
201const show = async (
202 $: EngineInterface,
203 surface: RenderSurface,
204 { Box, Text }: Tags,
205 beneath: RenderElement,
206 place: WidgetsPlace,
207 columns: number,
208): Promise<RenderElement> => {
209 if (!(await read($, isOn))) return beneath
210 if ((await $.state.get(site)).value !== place) return beneath
211
212 const held = await read($, status)
213 const beat = await read($, tick)
214 const now = await $.clock.now()
215 const mood = moodAt(held, now)
216 const isStill = mood === 'sleep'
217 const step = mood === 'work' || mood === 'happy' ? beat % 2 : Math.floor(beat / 2) % 2
218 const isBlinking = mood === 'idle' && beat % 7 === 0
219 const { xp } = await read($, growth)
220 const level = levelOf(xp)
221 const form = SHELLS[Math.min(SHELLS.length - 1, Math.floor((level - 1) / 3))] ?? 0xd97757
222 const shell = mood === 'hot' ? 0xe5484d : isStill ? shade(form, 0.7) : form
223 const badges = await badgesOf($)
224 const hat = HATS.find(one => badges >= one.badges)
225
226 if ((await read($, visit)).isAway) {
227 return $.widgets.card({
228 beneath,
229 width: Math.min(await wide($), Math.max(20, columns)),
230 title: `Clawd Lv ${level}`,
231 note: 'away',
232 body: (
233 <Text dimColor wrap="wrap">
234 Clawd is visiting another session. It comes back when you send a prompt here.
235 </Text>
236 ),
237 })
238 }
239 const palette = {
240 o: shell,
241 d: shade(shell, 0.7),
242 l: mood === 'hot' ? 0xff8a80 : isStill ? shell : 0xf0a58c,
243 m: mood === 'happy' ? 0xffffff : 0x5a2e22,
244 e: mood === 'dizzy' && beat % 2 === 0 ? 0xd670d6 : 0xffffff,
245 p: mood === 'happy' ? 0x3fb950 : mood === 'dizzy' && beat % 2 === 1 ? 0xd670d6 : 0x1f2328,
246 }
247 const body =
248 isStill || isBlinking
249 ? BODY.map((line, row) => (row < 2 ? line.replaceAll('e', 'o').replaceAll('p', 'd') : line))
250 : BODY
251 const pose = isStill ? 0 : step
252 const picture = await $.widgets.picture({
253 surface,
254 key: 'pet',
255 columns: 32,
256 rows: 14,
257 marks: [
258 {
259 lines: [...(CLAWS[pose] ?? CLAWS[0]), ...body, ...(LEGS[pose] ?? LEGS[0])],
260 palette,
261 left: 2,
262 top: isStill ? 2 : 1 + step,
263 },
264 ...(hat === undefined
265 ? []
266 : [{ lines: hat.lines, palette: hat.palette, left: 13, top: isStill ? 2 : 1 + step }]),
267 ],
268 })
269
270 const said =
271 held.forced !== null && now < held.forced.until && held.forced.note !== '' ? held.forced.note
272 : held.said !== undefined && now < held.said.until ? held.said.text
273 : SAYS[mood]
274
275 return $.widgets.card({
276 beneath,
277 width: Math.min(await wide($), Math.max(20, columns)),
278 title: `Clawd Lv ${level}`,
279 note: mood,
280 body: (
281 <Box columnGap={2}>
282 {picture}
283 <Box flexDirection="column" justifyContent="center">
284 <Text wrap="wrap">{said}</Text>
285 {held.isWorking && <Text dimColor>{held.calls} tool calls this turn</Text>}
286 <Text dimColor>{xp} XP</Text>
287 </Box>
288 </Box>
289 ),
290 })
291}
292
293export const register: Register = on => {
294 on('session.start', async ($, e, next) => {
295 await $.command.register({
296 name: 'pet-widget',
297 description: 'Toggle Clawd, a pixel pet whose mood follows the session',
298 argumentHint: '[on|off|sleep|idle|work|happy|dizzy|hot]',
299 })
300 if ((await $.store.get('isOn')) === true) await update($, isOn, () => true)
301 const kept = await $.store.get('xp')
302 if (typeof kept === 'number') await update($, growth, () => ({ xp: kept }))
303 const now = await $.clock.now()
304 await update($, status, held => ({ ...(held ?? RESTING), isWorking: false, activeAt: now }))
305 await enrol($)
306 if (await read($, isOn)) await look($)
307 home = e.cwd
308 const seen = await $.store.get(`seen:${e.cwd}`)
309 await say($, greetingOf(isMemory(seen) ? seen : undefined, now))
310 memory = { at: now, isFailing: isMemory(seen) ? seen.isFailing : false, visits: (isMemory(seen) ? seen.visits : 0) + 1 }
311 if (await read($, isOn)) await $.store.set(`seen:${e.cwd}`, memory)
312 await sync($)
313
314 return next(e)
315 })
316
317 on('command.run', { command: 'pet-widget' }, async ($, e) => {
318 const arg = e.args.trim().toLowerCase()
319
320 if (isMood(arg)) {
321 const until = (await $.clock.now()) + FLASH_MS * 2
322 await update($, status, held => ({
323 ...(held ?? RESTING),
324 forced: { mood: arg, until, note: '' },
325 }))
326 await update($, isOn, () => true)
327 await $.store.set('isOn', true)
328 await sync($)
329
330 return { text: `Pet on, previewing ${arg}.` }
331 }
332 if (arg !== '' && arg !== 'on' && arg !== 'off') {
333 return { text: 'Usage: /pet-widget [on|off|sleep|idle|work|happy|dizzy|hot]' }
334 }
335
336 const isShown = await update($, isOn, shown => (arg === '' ? !(shown ?? false) : arg === 'on'))
337 await $.store.set('isOn', isShown)
338 const now = await $.clock.now()
339 await update($, status, held => ({ ...(held ?? RESTING), activeAt: now }))
340 await sync($)
341
342 return { text: isShown ? 'Pet on; /widgets places it.' : 'Pet off.' }
343 })
344
345 on('turn.start', async ($, e, next) => {
346 const now = await $.clock.now()
347 await enrol($)
348 if (await read($, isOn)) await claim($)
349 await update($, status, held => ({
350 ...(held ?? RESTING),
351 isWorking: true,
352 activeAt: now,
353 calls: 0,
354 startedAt: now,
355 }))
356
357 return next(e)
358 })
359
360 on('turn.complete', async ($, e, next) => {
361 if (e.agentId === undefined) {
362 const now = await $.clock.now()
363 const before = await read($, status)
364 await update($, status, held => ({ ...(held ?? RESTING), isWorking: false, activeAt: now }))
365 const hour = new Date(now).getHours()
366 if (before.isWorking && now - (before.startedAt ?? now) >= LONG_TURN_MS) await say($, 'phew, long one. stretch?')
367 else if (before.isWorking && hour < 5) await say($, "it's late. one more?")
368 await remember($)
369 }
370
371 return next(e)
372 })
373
374 on('tool.call', async ($, e, next) => {
375 const ran = await next(e)
376 if (!(await read($, isOn))) return ran
377
378 const now = await $.clock.now()
379 const command = String((e as { command?: unknown }).command ?? '')
380 const forced =
381 ran.isError === true ? { mood: 'dizzy' as const, until: now + FLASH_MS, note: `${e.tool} failed` }
382 : e.tool === 'Bash' && CHECKS.test(command) ? { mood: 'happy' as const, until: now + FLASH_MS, note: '' }
383 : undefined
384 if (ran.isError !== true) {
385 const grown = await update($, growth, held => ({ xp: (held?.xp ?? 0) + (forced?.mood === 'happy' ? 5 : 1) }))
386 await $.store.set('xp', grown.xp)
387 if (levelOf(grown.xp) > levelOf(grown.xp - (forced?.mood === 'happy' ? 5 : 1))) {
388 $.ui.toast(`Clawd reached level ${levelOf(grown.xp)}.`)
389 }
390 }
391 const isCheck = e.tool === 'Bash' && CHECKS.test(command)
392 const before = await read($, status)
393 const fails = ran.isError === true ? (before.fails ?? 0) + 1 : isCheck ? 0 : (before.fails ?? 0)
394 await update($, status, held => ({
395 ...(held ?? RESTING),
396 calls: (held ?? RESTING).calls + 1,
397 activeAt: now,
398 forced: forced ?? (held ?? RESTING).forced,
399 fails,
400 }))
401 if (isCheck) {
402 if (ran.isError !== true && memory.isFailing) await say($, 'green again!')
403 memory = { ...memory, isFailing: ran.isError === true }
404 }
405 if (ran.isError === true && fails === 3) await say($, 'third time... read the error?')
406 if (before.calls + 1 === BIG_TURN_CALLS) await say($, 'big one, this')
407
408 return ran
409 })
410
411 on('session.measure', async ($, e, next) => {
412 const isHot = (e.context.percent ?? 0) >= HOT_PERCENT
413 await update($, status, held => ({ ...(held ?? RESTING), isHot }))
414
415 return next(e)
416 })
417
418 on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e, next) =>
419 show($, e.surface, $.ui.resolve(e), await next(e), 'side', e.props.bodyColumns),
420 )
421
422 on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) =>
423 e.props.hasSurvey
424 ? next(e)
425 : show($, e.surface, $.ui.resolve(e), await next(e), 'above', e.props.bodyColumns),
426 )
427
428 on('ui.render', { component: 'PromptHint' }, async ($, e, next) =>
429 show($, e.surface, $.ui.resolve(e), await next(e), 'below', e.viewport?.columns ?? 80),
430 )
431}
432types/index.d.ts 34 lines1export type PetMood = 'sleep' | 'idle' | 'work' | 'happy' | 'dizzy' | 'hot'
2
3export type PetStatus = {
4 isWorking: boolean
5 isHot: boolean
6 activeAt: number
7 calls: number
8 forced: { mood: PetMood; until: number; note: string } | null
9 said?: { text: string; until: number }
10 fails?: number
11 startedAt?: number
12}
13
14export type PetGrowth = {
15 xp: number
16}
17
18export type PetMemory = {
19 at: number
20 isFailing: boolean
21 visits: number
22}
23
24export type PetVisit = {
25 id: string
26 isAway: boolean
27}
28
29declare module 'claude-code' {
30 interface PluginState {
31 'pet-widget': { isOn: boolean; tick: number; status: PetStatus; growth: PetGrowth; visit: PetVisit }
32 }
33}
34