Clawd, the Claude Code logo, runs around in the band above the prompt and reacts to the session.

A mod for Claude Code: Clawd, the small creature from the Claude Code banner, runs around in a strip above your prompt and reacts to the session.

There is also a version in which Clawd is the MatSci octopus: AutomatedAlchemy/clawd-matsci.
This is a fan project. Anthropic did not make it and does not endorse it.
claude plugin marketplace add Probst1nator/clawd
claude plugin install clawd@clawd
Start a new session. /clawd help explains the rest. /clawd off hides Clawd (it stays hidden in later sessions until /clawd on), and claude plugin disable clawd@clawd turns the mod off.
Tested with Claude Code 2.1.310. The mod uses plugin hooks that draw into the terminal, so older versions may not load it.
| Command | What it does |
|---|---|
/clawd | what Clawd is doing now |
/clawd help | every command; help uml draws how Clawd behaves |
/clawd jump 3 | play an act now, up to 5 times in a row |
/clawd a1 wave | a subagent's small Clawd plays an act |
/clawd act create, change, delete, preview | write, rewrite, remove or picture an act |
/clawd list acts | the acts; also made, emotes, skins, minis |
/clawd emote <emote> | for a while, Clawd turns into an emote's look or holds its thing |
/clawd emote create, change, delete, preview | make, redraw, remove or picture an emote |
/clawd skin <skin>, none, auto | the body Clawd wears all the time, for this session |
/clawd skin create, change, delete, preview | make, redraw, remove or picture a skin |
/clawd on, /clawd off | show or hide Clawd |
/clawd autopick | switch a model choosing what Clawd plays on or off (see below); now chooses once; haiku, sonnet or opus sets the model |
/clawd debug | switch showing each autopick's request and whole reply in the transcript on or off |
/clawd trace | switch writing each autopick to a file on or off |
While you type /clawd , a list above the prompt shows what fits, and a space writes out a word that fits one name.
By default the mod makes no model calls. Clawd picks random acts by itself.
/clawd autopick hands that choice to a model (Haiku). It reads what happens in the session and picks what Clawd and the small Clawds play: after each prompt and turn, and every 10 to 60 seconds. In a busy session that is about 100 calls an hour of about 1,500 tokens each, and it may have Opus write up to 5 new acts, emotes or skins a day. A skin it picks stays on for the rest of the session, unless you chose one with /clawd skin. All of it runs through your own Claude Code login and counts against your usage. /clawd autopick again stops it. /clawd autopick sonnet or opus has that model pick instead, at a higher cost per pick, and /clawd autopick haiku goes back. Both settings are remembered.
While Remote Control is on, Clawd wears an antenna and the autopicker pauses, so Clawd plays random acts. When Remote Control ends, the autopicker goes on as it was set.
/clawd emote create <name> [what it looks like] has Opus draw a new emote: a look Clawd turns into for a while, or a thing it holds or sets down beside it while it keeps its body. /clawd skin create <name> [what it looks like] draws a skin, a body Clawd wears all the time. /clawd act create <name> [what it does] has Opus write a new act. The name alone is enough: /clawd skin create claude_with_glasses draws what the name says. For a sentence such as /clawd skin create claude with glasses, Haiku picks the name. /clawd act change <act> <what to change>, /clawd emote change and /clawd skin change change one; with nothing after the name, they make it again from scratch. Each runs when you type it, or when Claude runs it through the clawd tool (below).
Opus makes each one as a background subagent of your session, the maker. It hands its drafts to a render tool of the mod, looks at the preview images and fixes them until it is satisfied, for up to 15 minutes; a small Clawd shows it working. The mod saves the last draft the maker looked at. The maker can read only the reference image and its own previews, and writes no file itself. In plan and auto mode the mod lets its own maker start. Where the maker cannot start, the mod falls back to up to three claude -p rounds for a look and one model call for an act.
The mod gives the session's Claude one tool, mcp__clawd__clawd, which takes any /clawd command as text and answers what /clawd would show. Claude Code loads it only when Claude asks for it, so until then it costs one line of context. Ask Claude to have Clawd wave, or to make a new act, and it can do it itself. A create or change Claude starts waits for the same limit of 5 a day as the autopicker's; one you type does not. A command from Claude that changes something (anything but playing, listing, help and previews) goes through your permission settings first, and where they ask, you decide.
New acts, emotes, skins, their preview images and the autopick traces (/clawd trace) go to ~/.claude/clawd/, or $CLAUDE_CONFIG_DIR/clawd/ when that is set. A plugin update leaves that folder alone. Writing preview images needs python3 on the PATH.
plugin/ is the mod: hooks/register.tsx holds the hooks, hooks/clawd-sim.ts the world, the animation and the drawing. Check it with claude plugin validate plugin and claude plugin test plugin.
This repository gets release snapshots from a private working copy. Issues are welcome.
MIT, see LICENSE.
hooks/register.tsx 2722 lines1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, Register, Timer } from 'claude-code'
3
4import {
5 ACTS,
6 ACT_PREVIEW_EVERY_S,
7 BAND_ROWS,
8 FLOOR_TEXT,
9 MAX_DELAY_S,
10 MAX_MINIS,
11 MAX_STEPS,
12 MINI_STALE_S,
13 PICKABLE,
14 PREVIEW_PER_LINE,
15 PREVIEW_POSES,
16 PREVIEW_PROP_POSES,
17 READ_HOLD_S,
18 SHEET_POSES,
19 SLEEP_AFTER_S,
20 TICK_MS,
21 actPreview,
22 bandRows,
23 bodyOf,
24 callActs,
25 callLabel,
26 clean,
27 createWorld,
28 emoteFrom,
29 emoteJson,
30 emotePreview,
31 emoteSheet,
32 endMini,
33 frameCells,
34 isAsleep,
35 isClawdCopy,
36 linkRoutine,
37 onPrompt,
38 onTool,
39 onTurnEnd,
40 perform,
41 resize,
42 routineFrom,
43 seeded,
44 setEdge,
45 setSkin,
46 skinAsEmote,
47 skinFrom,
48 skinJson,
49 skinPreview,
50 skinSheet,
51 spawnMini,
52 step,
53} from './clawd-sim'
54import type { ActKind, Call, Emote, Playable, Routine, Skin, Step, World } from './clawd-sim'
55import { contextParts, contextRows } from './clawd-context'
56import { ACT_COMMANDS, ALIASES, COMMANDS, EMOTE_COMMANDS, LIST_KINDS, MAX_REPEAT, SKIN_COMMANDS, isClawdDraft, marksFor, menuFor, menuLayout, namesFit, orderOf, writeOut } from './clawd-words'
57import type { ListKind, MadeKind, Menu, Names, Order } from './clawd-words'
58import { UML_LEGEND, UML_WIDTH, clawdUml, umlKinds } from './clawd-uml'
59import type { UmlKind } from './clawd-uml'
60
61// Clawd, the logo, runs in the band above the prompt: one full-width Raster
62// that a timer repaints with $.ui.blit. Session events steer it (the
63// behaviours are in clawd-sim.ts). Logo-style
64// quadrant blocks, Clawd standing on a floor line at the band's bottom, two
65// sub-pixels of headroom above him (BAND_ROWS), and a row more (TALL_ROWS)
66// during big jumps; two more (ANTENNA_ROWS) while he wears the Remote Control
67// antenna on a tall look. With only 3 rows to spare he bounces in place. The
68// band shows at any size the engine gives it, cut off where it is too small.
69const MENU_MIN_COLUMNS = 20
70const CLAWD_MAX_COLUMNS = 512 // the Raster limit
71// While /clawd is typed, a framed list hangs below Clawd's runway, whose floor
72// is the frame's top edge. At most this many names show.
73const MENU_ROWS = 7
74// The picker model picks what Clawd plays next (Haiku, Sonnet
75// from 2026-10-06, Haiku again from 2026-10-07; since 2026-10-08 Haiku unless
76// `/clawd autopick sonnet` or `opus` chose another): when a prompt is sent, when a turn ends, and
77// otherwise after a random 10 to 60 s. It reads the messages and tool calls
78// since its last pick, its rolling summary of the session, the situation
79// (time, idle time, what Clawd is doing) and the newest act a model made. It
80// may ask for a new act, emote or skin; Opus then writes the act's steps or draws the look, kept in data/ for
81// every session and host. A skin it calls or has drawn is Clawd's body for the
82// rest of the session, below the person's own /clawd skin choice. The top
83// right of the band shows the pick and, for a new act, its title.
84// Each running subagent gets a mini Clawd, which the
85// picker addresses on its own: one pick is a list of calls, like parallel tool
86// calls, each naming a body (or all of them), an act and a delay of 0 to 5 s.
87// The picker is off until `/clawd autopick on`; the choice is kept in $.store, as
88// is the picker model (`pickModel`).
89const PICK_MODELS = ['haiku', 'sonnet', 'opus'] as const
90type PickModel = (typeof PICK_MODELS)[number]
91const DEFAULT_PICK_MODEL: PickModel = 'haiku'
92const MAKE_MODEL = 'opus'
93const NAME_MODEL = 'haiku' // names what a sentence after create asks for
94const PICK_MIN_S = 10
95const PICK_MAX_S = 60
96const NEW_PER_DAY = 5 // new acts, emotes and skins the picker may ask for in any 24 hours, over all sessions and hosts
97const FEED_MAX = 40 // lines kept for the next pick
98const DAY_MS = 24 * 3600_000
99const TRACE_MAX = 50 // picks kept per session in picks/
100// The session's model runs /clawd commands through one tool. The engine lists
101// a registered tool behind ToolSearch, so until a model asks for it only the
102// name is in the context. It takes all of /clawd; a create or change it starts
103// counts against NEW_PER_DAY, which a person's typed one skips.
104const CLAWD_TOOL = 'mcp__clawd__clawd'
105const TOOL_DESCRIPTION = [
106 'Runs a /clawd command for Clawd, the Claude Code logo that runs in the band above the prompt, and its minis',
107 '(a1, a2, ...: a small Clawd for each running subagent). `command` is what the person would type after /clawd,',
108 'and the answer is the text /clawd shows them. Examples: "list acts", "list made", "list emotes", "list skins",',
109 '"list minis"; "act wave 2" plays an act 1 to 5 times; "a1 celebrate" has a mini play one; "emote huh" puts on a',
110 'look for a while; "skin matsci_octopus" wears a skin for the session, "skin auto" goes back; "" says what Clawd',
111 'is doing; "help"; "on" or "off" (remembered across sessions); "autopick on", "off", "now", "haiku", "sonnet" or',
112 '"opus"; "act create <name> [what it does]", "emote create <name> [image path] [what it looks like]", "skin create',
113 '..."; "act change <name> [what to change]"; "act delete <name>"; "act preview <name>" writes a PNG and answers',
114 'its path. emote and skin take the same create, change, delete and preview. Use full names: a short word plays',
115 `the one name it fits. Create and change start a ${MAKE_MODEL} run on the person's Claude usage, refused once`,
116 `${NEW_PER_DAY} acts, emotes and skins were made in the last 24 hours. Play acts and emotes when the person asks`,
117 'something of Clawd, or to mark a moment they would enjoy. Run create, change, delete, skin, on, off and',
118 'autopick only when the person asks for them.',
119].join(' ')
120// Emotes: looks Clawd takes for a while. emotes/ holds the
121// ones drawn by hand, data/emotes/ the ones a model drew. A model draws one in
122// a headless `claude -p` run, because $.model.complete takes no image: the run
123// may read the reference image and the preview of its draft and nothing else,
124// and the mod writes the files. A new emote starts as EMOTE_DRAFTS drafts in
125// one reply; the next round sees them side by side and picks one, and each later round sees the preview of its draft.
126const EMOTE_ROUNDS = 3
127const EMOTE_DRAFTS = 3
128const EMOTE_ROUND_MS = 300_000
129// Since 2026-10-26 one agent makes an act, an emote or a skin instead of the
130// rounds.
131// The mod registers it hidden, as clawd:maker. It hands each draft to the mod's
132// render tool, which checks it and draws the PNG with the mod's own previews,
133// Reads that PNG, and stops when it is satisfied; the mod keeps the last draft
134// that rendered. A tool.check hook lets it Read only the images it is given.
135// That hook only sees the maker when the spawn ran inside a hook of another
136// event (tested 2026-10-26): from a timer, or after the hook returned, every
137// hook of the mod is skipped for that agent. So a make is queued and started
138// from the band's ui.render hook (`spawnQueued`). When that does not happen
139// within MAKER_START_MS, or the spawn is refused, the rounds run as before.
140const RENDER_TOOL = 'mcp__clawd__render'
141const MAKER_TURNS = 40
142const MAKER_MS = 15 * 60_000 // after this the maker's calls are refused, as a subagent cannot be stopped
143const MAKER_GRACE_MS = 2 * 60_000 // then it has this long to answer before the make fails
144const MAKER_START_MS = 5_000
145const NO_ANSWER = 'no answer in time' // the end of a maker that never answered; its last draft is not saved
146// Parent modes the maker was tested under; in any other the spawn is refused and the rounds run.
147const MAKER_MODES = ['default', 'plan', 'auto', 'dontAsk']
148const MAKER_SYSTEM = [
149 'You make one thing for Clawd, the Claude Code logo drawn as a small creature in a terminal band above',
150 'the prompt: a look it takes, a skin it wears, or an act it plays. You work only with two tools:',
151 `${RENDER_TOOL} checks a draft and draws it as a PNG, and Read shows you that PNG.`,
152 `${RENDER_TOOL} is read-only: it only draws a preview image for you to look at, so it is allowed in plan mode too.`,
153 'Never call SubagentHandback: end with a plain text answer of one line, done or failed: <why>.',
154].join(' ')
155// How the maker works on an emote or a skin.
156const MAKER_LOOP = [
157 `How you work: load ${RENDER_TOOL} with ToolSearch (query "select:${RENDER_TOOL}"), then hand it a draft`,
158 'as {"draft": {...}}, or up to 3 drafts side by side as {"drafts": [...]}. It answers the path of a PNG, or',
159 'why a draft was refused. Read the PNG, look at it, fix the draft and render again, as often as it helps.',
160]
161const IMAGE = /\.(png|jpe?g|gif|webp)$/i
162// `/clawd` words no act, emote or skin may be named
163const RESERVED = [
164 ...Object.keys(COMMANDS),
165 ...Object.keys(ACT_COMMANDS),
166 ...Object.keys(EMOTE_COMMANDS),
167 ...Object.keys(SKIN_COMMANDS),
168 ...Object.keys(LIST_KINDS),
169 ...Object.keys(ALIASES),
170 'pick',
171]
172// What the built-in acts look like, for /clawd list and the menu while /clawd is typed.
173const ACT_WHAT: Partial<Record<ActKind, string>> = {
174 ...PICKABLE,
175 sleep: 'sits down and falls asleep',
176 wake: 'wakes up',
177 carry: 'fetches a brick for the pile',
178 kick: 'kicks the brick pile over',
179 read: 'holds up a scroll and looks down at it',
180}
181
182const isClawdOn = atom({ plugin: 'clawd', key: 'isClawdOn' } as const, true)
183const clawdRows = atom({ plugin: 'clawd', key: 'clawdRows' } as const, BAND_ROWS)
184const isTracing = atom({ plugin: 'clawd', key: 'isTracing' } as const, false)
185const isDebugging = atom({ plugin: 'clawd', key: 'isDebugging' } as const, false)
186const clawdMenu = atom({ plugin: 'clawd', key: 'clawdMenu' } as const, null)
187const clawdSkin = atom({ plugin: 'clawd', key: 'clawdSkin' } as const, null)
188const clawdPickedSkin = atom({ plugin: 'clawd', key: 'clawdPickedSkin' } as const, null)
189
190// Off in headless sessions and with CLAUDE_CLAWD_OFF=1. Tests set
191// CLAUDE_CLAWD_SEED so the band's random acts repeat.
192// `names` is what a `/clawd` word may name, read once per `/clawd` draft.
193// `dataDir` keeps what the mod makes (acts, emotes a model drew, previews,
194// traces): data/ beside the plugin where a checkout has one, as tools/clawd
195// does, else clawd/ in the Claude config folder, which a plugin update leaves
196// alone. `emoteDir` and `skinDir` hold the emotes and skins that ship with
197// the mod. `skin` is the skin Clawd wears now, as last read (`skinNow`):
198// `/clawd skin` chooses one for the session, else the autopicker picked one
199// for the session, else the plugin's clawd.json names one
200// (`fileSkin`), else
201// `ROOT_SKINS` gives one for the project root (`root`).
202const mod = {
203 isOff: false,
204 rand: Math.random,
205 dataDir: '',
206 emoteDir: '',
207 skinDir: '',
208 fileSkin: '',
209 root: '',
210 skin: null as MadeSkin | null,
211 project: '',
212 startedAt: 0,
213 names: undefined as Names | undefined,
214 isRemote: false, // Remote Control is on: Clawd wears an antenna and the autopicker pauses
215}
216
217/** An act a model made, as kept in data/acts/<name>.json. */
218type MadeAct = Routine & { made: string; project: string; why: string }
219
220/** What the file of a skin or an emote keeps besides the look: when, where and why it was made, its reference image, the file. */
221type Dated = { made: string; project: string; why: string; image: string; file: string }
222
223/** An emote from emotes/ (`made` empty) or data/emotes/. */
224type MadeEmote = Emote & Dated
225
226/** A skin from skins/ (`made` empty) or data/skins/. */
227type MadeSkin = Skin & Dated
228
229/** Emotes and skins are drawn, changed, kept and removed the same way, each in its own folders. */
230type LookKind = Exclude<MadeKind, 'act'>
231
232/** How a kind of look is read, written and drawn. */
233type Kit<T extends { name: string; title: string }> = {
234 kind: LookKind
235 parse: (raw: unknown) => T | string
236 json: (look: T) => Record<string, unknown>
237 preview: (look: T) => Uint8Array
238 sheet: (looks: T[]) => Uint8Array
239 check: (look: T) => string // why a newly drawn look is refused, or ''
240 what: (look: T) => string // one line on the look, for the overview a new drawing gets
241}
242// An emote is previewed on the skin Clawd wears now; with a clawd.json skin, on no other body.
243const EMOTE_KIT: Kit<Emote> = {
244 kind: 'emote',
245 parse: emoteFrom,
246 json: emoteJson,
247 preview: look => emotePreview(look, mod.skin, mod.fileSkin !== ''),
248 sheet: looks => emoteSheet(looks, mod.skin, mod.fileSkin !== ''),
249 check: look =>
250 isClawdCopy(look) ? "its shapes are Clawd's own body; leave out shapes and the other body fields, so the look keeps the body Clawd has" : '',
251 what: emoteWhat,
252}
253const SKIN_KIT: Kit<Skin> = {
254 kind: 'skin',
255 parse: skinFrom,
256 json: skinJson,
257 preview: skinPreview,
258 sheet: skinSheet,
259 check: () => '',
260 what: look => look.title,
261}
262
263/** One call as the picker made it, for the label and `/clawd`. */
264type Called = { who: string; name: string; delay: number }
265
266type Pick = { trigger: string; calls: Called[]; why: string; at: number; made?: MadeAct }
267
268/** One pick as it went: what the picker read, what it answered, what came of it. */
269type Trace = { at: string; trigger: string; system: string; prompt: string; reply: string; outcome: string }
270
271// The picker's working state; a hot reload starts it over.
272const brain = {
273 feed: [] as { n: number; text: string }[], // what happened since the last pick
274 seq: 0, // lines ever fed
275 seen: 0, // lines the last pick read
276 summary: '',
277 recent: [] as string[], // picks, newest first
278 last: null as Pick | null,
279 timer: null as Timer | null,
280 dueAt: 0, // when the timer fires; 0 while none is set
281 isPicking: false,
282 again: null as string | null, // a trigger that came in during a pick
283 making: '', // the act a model writes or the look it draws now, from a /clawd command or a picker's look
284 makeError: '', // why the last act, emote or skin a model made failed
285 shown: new Map<string, string>(), // each part of the picker's request as /clawd debug last showed it
286}
287
288// Clawd's working state; a hot reload starts Clawd over.
289const clawd = {
290 world: null as World | null,
291 requestId: null as string | null,
292 last: '',
293 rows: null as number | null, // the band's height as last written; null: not yet written this load
294}
295
296function clawdTick($: EngineInterface): void {
297 const w = clawd.world
298 const requestId = clawd.requestId
299 if (!w || !requestId) return // paused while the band is not mounted
300 step(w)
301 const rows = bandRows(w)
302 if (rows !== clawd.rows) {
303 clawd.rows = rows
304 void update($, clawdRows, () => rows) // the band redraws at its new height
305 }
306 const cells = frameCells(w)
307 if (cells === clawd.last) return
308 clawd.last = cells
309 void $.ui.blit({ requestId, key: 'clawd', cells }).then(r => {
310 if (r.deny === undefined || clawd.requestId !== requestId) return
311 // Unmounted, or a frame of the old height that reached the band after it
312 // grew or shrank (the band keeps one requestId). Nothing else redraws the
313 // band until its props change, so ask for the render that mounts it again;
314 // a band no longer shown draws no Raster, and the tick stays paused.
315 $.ui.log(`clawd: blit refused: ${r.deny}`, { to: 'debug' })
316 clawd.requestId = null
317 $.ui.invalidate('ui.render')
318 })
319}
320
321// While Remote Control is on, Clawd wears an antenna. No
322// hook event says when it goes on or off, but the engine keeps
323// CLAUDE_CODE_BRIDGE_SESSION_ID in its own environment while the session has a
324// Remote Control link (2.1.294), so the mod reads it every REMOTE_POLL_MS.
325// While it is on, the autopicker pauses and Clawd plays random acts; the stored
326// setting is left as it is and applies again when Remote Control ends.
327const REMOTE_POLL_MS = 1000
328
329async function pollRemote($: EngineInterface): Promise<void> {
330 const isRemote = Boolean(await $.env.get('CLAUDE_CODE_BRIDGE_SESSION_ID'))
331 if (isRemote === mod.isRemote) return
332 mod.isRemote = isRemote
333 if (clawd.world) clawd.world.antenna = isRemote
334 if (isRemote) {
335 brain.timer?.cancel()
336 brain.timer = null
337 brain.dueAt = 0
338 } else if (await isAutopicking($)) schedulePick($, await $.clock.now())
339 $.ui.log(`clawd: Remote Control ${isRemote ? 'on, antenna up, autopicker paused' : 'off, antenna down'}`, { to: 'debug' })
340}
341
342// --- the picker ----------------------------------------------------------------
343
344const PICK_SYSTEM =
345 'You direct Clawd, the Claude Code logo drawn as a small creature that runs around in a band ' +
346 'above the prompt of a Claude Code session, and a mini Clawd for each subagent the session runs. ' +
347 'The person sees Clawd while they work and sometimes talks to it or about it. When they give it a ' +
348 'name or compare it to something, they want to see it become that thing, which is what new acts, emotes and skins are for. ' +
349 'You pick what they play next so it fits what is going on, and you keep a short summary of the ' +
350 'session. Reply with one JSON object and nothing else.'
351
352const MAKE_SYSTEM =
353 'You write short choreographies for Clawd, the Claude Code logo drawn as a small creature, orange ' +
354 "in its own body, in a terminal band 4 rows high and as wide as the terminal. Reply with one JSON object and nothing else."
355
356function oneLine(s: string, n: number, end = false): string {
357 const t = s.replace(/\s+/g, ' ').trim()
358 if (t.length <= n) return t
359 return end ? `...${t.slice(-n)}` : `${t.slice(0, n)}...`
360}
361
362function feed(text: string): void {
363 brain.seq += 1
364 brain.feed.push({ n: brain.seq, text })
365 if (brain.feed.length > FEED_MAX) brain.feed.shift()
366}
367
368/** A subagent's mini id, or 'subagent' when it has none. */
369function miniName(agentId: string): string {
370 return clawd.world?.minis.find(m => m.agentId === agentId)?.id ?? 'subagent'
371}
372
373function toolLine(e: Record<string, unknown>, isError: boolean): string {
374 const keys = ['description', 'command', 'file_path', 'pattern', 'url', 'query', 'skill', 'prompt']
375 const what = keys.map(k => e[k]).find((v): v is string => typeof v === 'string' && v !== '')
376 const who = typeof e.agentId === 'string' ? ` (${miniName(e.agentId)})` : ''
377 return `tool ${String(e.tool)}${who} ${isError ? 'failed' : 'ok'}${what ? `: ${oneLine(what, 100)}` : ''}`
378}
379
380function callText(c: Called): string {
381 return `${c.who}: ${c.name}${c.delay > 0 ? ` +${c.delay} s` : ''}`
382}
383
384function parseJson(text: string): Record<string, unknown> | null {
385 const match = text.match(/\{[\s\S]*\}/)
386 if (!match) return null
387 try {
388 const value: unknown = JSON.parse(match[0])
389 return typeof value === 'object' && value !== null ? (value as Record<string, unknown>) : null
390 } catch {
391 return null
392 }
393}
394
395function ago(ms: number): string {
396 const s = Math.max(0, Math.round(ms / 1000))
397 return s < 120 ? `${s} s` : s < 7200 ? `${Math.round(s / 60)} min` : `${Math.round(s / 3600)} h`
398}
399
400/**
401 * The acts models made, newest first, from data/acts/, with their emote and
402 * play steps linked to `emotes` (read here when not given) and to each other.
403 * An emote step may also name a skin, which Clawd then wears for a while.
404 */
405async function loadMade($: EngineInterface, emotes?: Emote[]): Promise<MadeAct[]> {
406 const dir = `${mod.dataDir}/acts`
407 let entries: { name: string; kind: string }[] = []
408 try {
409 entries = await $.fs.list(dir)
410 } catch {
411 return [] // no act made yet
412 }
413 const made: MadeAct[] = []
414 for (const entry of entries) {
415 if (entry.kind !== 'file' || !entry.name.endsWith('.json')) continue
416 try {
417 const raw = JSON.parse(await $.fs.read(`${dir}/${entry.name}`)) as Record<string, unknown>
418 const routine = routineFrom(raw)
419 if (typeof routine === 'string') continue
420 const text = (v: unknown) => (typeof v === 'string' ? v : '')
421 made.push({ ...routine, made: text(raw.made), project: text(raw.project), why: text(raw.why) })
422 } catch {
423 // half-written or broken; skip it
424 }
425 }
426 const find = finder(made, emotes ?? (await loadEmotes($)), await loadSkins($))
427 return made.sort((a, b) => b.made.localeCompare(a.made)).map(r => linkRoutine(r, find))
428}
429
430/** What a name in an act's emote or play step stands for: a made act, an emote, or a skin worn for a while. */
431function finder(made: readonly Routine[], emotes: readonly Emote[], skins: readonly Skin[]): (name: string) => Playable | undefined {
432 return name => {
433 const skin = skins.find(x => x.name === name)
434 return made.find(r => r.name === name) ?? emotes.find(x => x.name === name) ?? (skin && skinAsEmote(skin))
435 }
436}
437
438/**
439 * The emotes or skins, read fresh on each use so a new file plays without a
440 * reload: the mod's own folder (emotes/, skins/) first, then the data folder's
441 * newest first. A model's never replaces a hand-drawn one of the same name.
442 */
443async function loadLooks<T extends { name: string; title: string }>($: EngineInterface, kit: Kit<T>): Promise<(T & Dated)[]> {
444 const found: (T & Dated)[] = []
445 for (const dir of [kit.kind === 'emote' ? mod.emoteDir : mod.skinDir, `${mod.dataDir}/${kit.kind}s`]) {
446 let entries: { name: string; kind: string }[] = []
447 try {
448 entries = await $.fs.list(dir)
449 } catch {
450 continue // none there yet
451 }
452 const here: typeof found = []
453 for (const entry of entries) {
454 if (entry.kind !== 'file' || !entry.name.endsWith('.json')) continue
455 try {
456 const raw = JSON.parse(await $.fs.read(`${dir}/${entry.name}`)) as Record<string, unknown>
457 const look = kit.parse(raw)
458 if (typeof look === 'string' || found.some(e => e.name === look.name)) continue
459 const text = (v: unknown) => (typeof v === 'string' ? v : '')
460 const file = `${dir}/${entry.name}`
461 here.push({ ...look, made: text(raw.made), project: text(raw.project), why: text(raw.why), image: text(raw.image), file })
462 } catch {
463 // half-written or broken; skip it
464 }
465 }
466 found.push(...here.sort((a, b) => b.made.localeCompare(a.made)))
467 }
468 return found
469}
470
471/** The emotes: emotes/, then data/emotes/. */
472async function loadEmotes($: EngineInterface): Promise<MadeEmote[]> {
473 return loadLooks($, EMOTE_KIT)
474}
475
476/** The skins: skins/, then data/skins/. */
477async function loadSkins($: EngineInterface): Promise<MadeSkin[]> {
478 return loadLooks($, SKIN_KIT)
479}
480
481/** data/ beside the plugin where a checkout has one, else clawd/ in the Claude config folder. */
482async function dataDirOf($: EngineInterface, root: string): Promise<string> {
483 const beside = `${root.replace(/\/[^/]*$/, '')}/data`
484 try {
485 if ((await $.fs.stat(beside)).kind === 'dir') return beside
486 } catch {
487 // no such folder
488 }
489 const config = (await $.env.get('CLAUDE_CONFIG_DIR')) || `${(await $.env.get('HOME')) ?? ''}/.claude`
490 return `${config}/clawd`
491}
492
493/** The skin the plugin's clawd.json names (`skin`, or `look` as until 2026-10-08), or ''. */
494async function fileSkinOf($: EngineInterface, root: string): Promise<string> {
495 try {
496 const raw = JSON.parse(await $.fs.read(`${root}/clawd.json`)) as { skin?: unknown; look?: unknown }
497 const name = raw.skin ?? raw.look
498 return typeof name === 'string' ? name : ''
499 } catch {
500 return '' // no clawd.json: Clawd is Clawd
501 }
502}
503
504// Without a clawd.json skin, a session whose project root has `part` in its
505// path, in any case, wears `skin`. The root moves with /cd and worktree moves but not with a
506// shell cd, so an agent passing through a MatSci folder does not switch it.
507const ROOT_SKINS = [{ part: 'matsci', skin: 'matsci_octopus' }]
508const ROOT_POLL_MS = 1000
509
510/**
511 * The skin for now and where it comes from: /clawd skin's choice, the
512 * autopicker's, clawd.json's, the project root's; '' for Clawd's own body.
513 */
514async function skinNow($: EngineInterface): Promise<{ name: string; from: string }> {
515 const chosen = await read($, clawdSkin)
516 if (chosen !== null) return { name: chosen, from: 'chosen with /clawd skin for this session' }
517 const picked = await read($, clawdPickedSkin)
518 if (picked !== null) return { name: picked, from: 'picked by the autopicker for this session; /clawd skin auto goes back' }
519 if (mod.fileSkin) return { name: mod.fileSkin, from: "named in the mod's clawd.json" }
520 const path = mod.root.toLowerCase()
521 const rule = ROOT_SKINS.find(r => path.includes(r.part))
522 return rule ? { name: rule.skin, from: `the project folder has "${rule.part}" in its path` } : { name: '', from: '' }
523}
524
525/** Reads the skin for now and gives it to Clawd: with a puff when it changes and `isChange`, else quietly. */
526async function applySkin($: EngineInterface, isChange: boolean): Promise<void> {
527 const { name } = await skinNow($)
528 mod.skin = name ? ((await loadSkins($)).find(x => x.name === name) ?? null) : null
529 if (clawd.world) setSkin(clawd.world, mod.skin, !isChange)
530}
531
532/** Reads the project root every ROOT_POLL_MS and changes the skin when the root asks for another. */
533async function pollRoot($: EngineInterface): Promise<void> {
534 let root: string
535 try {
536 root = await $.session.root()
537 } catch {
538 return
539 }
540 if (!root || root === mod.root) return
541 mod.root = root
542 const before = mod.skin?.name ?? ''
543 await applySkin($, true)
544 const after = mod.skin?.name ?? ''
545 if (after !== before) $.ui.log(`clawd: project root ${root}, skin ${after || 'none'}`, { to: 'debug' })
546}
547
548/** Whether the autopicker runs by itself (`/clawd autopick on`); off until then. */
549async function isAutopicking($: EngineInterface): Promise<boolean> {
550 return (await $.store.get('isAutopickOn')) === true
551}
552
553/** Whether the autopicker picks by itself now: switched on, and Remote Control off. */
554async function isPickingAlone($: EngineInterface): Promise<boolean> {
555 return !mod.isRemote && (await isAutopicking($))
556}
557
558/** The model the autopicker asks (`/clawd autopick haiku|sonnet|opus`); Haiku until another is chosen. */
559async function autopickModel($: EngineInterface): Promise<PickModel> {
560 const model = await $.store.get('pickModel')
561 return PICK_MODELS.find(m => m === model) ?? DEFAULT_PICK_MODEL
562}
563
564/** A local image's real path for an emote's reference, or '' when it is none. */
565async function imagePath($: EngineInterface, raw: string): Promise<string> {
566 const home = (await $.env.get('HOME')) ?? ''
567 const path = raw.startsWith('~/') ? `${home}/${raw.slice(2)}` : raw
568 if (!path.startsWith('/') || !IMAGE.test(path)) return ''
569 try {
570 const stat = await $.fs.stat(path, { resolve: true })
571 return stat.kind === 'file' && stat.realPath && IMAGE.test(stat.realPath) ? stat.realPath : ''
572 } catch {
573 return ''
574 }
575}
576
577/** Writes bytes to a file; $.fs.write takes text only. */
578async function writeBytes($: EngineInterface, path: string, bytes: Uint8Array): Promise<void> {
579 const code = 'import base64,os,sys;os.makedirs(os.path.dirname(sys.argv[1]),exist_ok=True);open(sys.argv[1],"wb").write(base64.b64decode(sys.stdin.read()))'
580 const base64 = (bytes as Uint8Array & { toBase64(): string }).toBase64()
581 const r = await $.process.run(['python3', '-c', code, path], { stdin: base64, timeoutMs: 20_000 })
582 if (r.exitCode !== 0) throw new Error(`python3 exited ${r.exitCode}: ${oneLine(r.stderr, 200)}`)
583}
584
585/** Draws an emote's or a skin's preview sheet to data/<kind>s/previews/<file>.png; the path. */
586async function previewLook<T extends { name: string; title: string }>($: EngineInterface, kit: Kit<T>, look: T, file = look.name): Promise<string> {
587 const path = `${mod.dataDir}/${kit.kind}s/previews/${file}.png`
588 await writeBytes($, path, kit.preview(look))
589 return path
590}
591
592// What an emote may have that a skin has not: a time, a prop and a tool.
593const EMOTE_EXTRAS = [
594 '- dur: seconds Clawd keeps the look, 3 to 20.',
595 "- accent (optional): the colour of '+' pixels, and of the prop and the tool where they give none.",
596 '- prop (optional): an object beside Clawd that is not part of its body: something that moves on its',
597 ' own, such as a rocket that lifts off, or something Clawd works on, such as a block it mines. Draw',
598 ' such a thing as a prop, not into the shapes, or it walks along with Clawd.',
599 ' {"rows": [...], "color": "#rrggbb", "x": -12, "path": [{"t": 0, "y": 0}, ...], "trail": false}.',
600 ' rows: # the prop colour, + the accent, . empty; at most 8 wide and 6 high (8 with',
601 ' "tall"); an even width keeps its pixels paired in cells. color: optional, the accent by default.',
602 " x: sub-pixels from Clawd's centre to the prop's centre as the look starts, negative behind Clawd;",
603 ' from then on the prop keeps to its path wherever Clawd goes. path: up to 8 keys in time order, t',
604 ' seconds since the look started (0 to dur), y the height of its bottom above the floor (0 to 24),',
605 ' x an optional sideways shift; straight lines between keys, then the last key holds. Past y 10 the',
606 ' prop has left the band. trail: true for sparks below it while it rises, like a flame.',
607 ' The path runs on its own clock and does not follow Clawd: after a wave and two hops Clawd goes on',
608 ' as always and may walk off, trip or sit down and sleep. Give a moving path only to a thing that',
609 ' moves by itself, such as a rocket or a ball rolling away. A thing Clawd works on stays on the',
610 ' floor: one key {"t": 0, "y": 0}. When the look ends, a prop on the floor breaks into its pixels.',
611 '- tool (optional): a thing Clawd holds in its front hand, such as a pointer or a pickaxe.',
612 ' {"rows": [...], "color": "#rrggbb"}. rows: # the tool colour, + the accent, . empty; at most 8 wide',
613 " and 4 high. color: optional, the accent by default. The first pixel of the bottom row sits one",
614 " pixel past the front arm's tip, and the tool moves with that tip from pose to pose without",
615 ' turning, so a wave between up and raised moves it too; a body without arms holds it against its',
616 " front edge. Give it a colour other than the body's (Clawd's own orange or its skin's), or it reads",
617 ' as part of the arm.',
618]
619
620/**
621 * What a new emote is asked to be: Clawd becomes the thing ('become'), or
622 * keeps its body and holds, uses or sets down the thing ('hold'); '' leaves
623 * it to the drawing model.
624 */
625type Form = 'become' | 'hold' | ''
626
627/**
628 * The prompt of one drawing round of an emote or a skin. With `change`, an
629 * existing look is changed: `isBefore` marks the first round, whose draft is
630 * the look as it is now. `others` lists the other looks of the kind, one line
631 * each, for the round that draws the drafts. With `isMaker`, it is the task
632 * of the maker agent, which renders and reads its own drafts (MAKER_LOOP).
633 */
634function emotePrompt(
635 kind: LookKind,
636 name: string,
637 title: string,
638 why: string,
639 image: string,
640 draft: string,
641 preview: string,
642 refused: string,
643 change = '',
644 isBefore = false,
645 drafts: string[] = [],
646 form: Form = '',
647 others: string[] = [],
648 isMaker = false,
649): string {
650 const poses = PREVIEW_POSES.map((p, i) => `${i + 1}. ${p}`).join('; ')
651 const propPoses = PREVIEW_PROP_POSES.map((p, i) => `${PREVIEW_POSES.length + i + 1}. ${p}`).join('; ')
652 const isEmote = kind === 'emote'
653 // A skin, and an emote that turns Clawd into the thing, has a body; an emote that holds the thing has none.
654 const hasBody = !isEmote || form !== 'hold'
655 const mayHold = isEmote && form !== 'become'
656 const propLines = isEmote ? [`A look with a prop gets one more line of ${PREVIEW_PROP_POSES.length} panels: ${propPoses}.`] : []
657 // A look that keeps the body is drawn on the skin and on Clawd's own body (emotePreview, emoteSheet), unless clawd.json names the skin.
658 const isTwice = isEmote && mayHold && mod.skin !== null && !mod.fileSkin
659 const twiceLines = isTwice
660 ? ["A look that keeps the body is shown on the skin and then, from a new line, in the same panels on Clawd's own body. It must work on both."]
661 : []
662 // A new look's first round draws several drafts; the next one picks from them.
663 const isDrafting = !change && !draft && drafts.length === 0
664 const skin = mod.skin ? `the skin ${mod.skin.name} ("${oneLine(mod.skin.title, 60)}", ${String(skinJson(mod.skin).color)})` : 'its own orange body'
665 const differ = !hasBody
666 ? 'the shape, size and colour of the tool and the prop, and where the prop stands'
667 : mayHold
668 ? 'which kind it is, silhouette, proportions, eyes, legs, arms, tool or prop'
669 : 'silhouette, proportions, eyes, legs or arms'
670 return [
671 `You ${change ? 'change a' : 'draw a new'} ${isEmote ? 'look' : 'skin'} for Clawd, the Claude Code logo, which runs around as a small creature in a`,
672 isEmote
673 ? 'terminal band above the prompt. For a while Clawd wears this look, and'
674 : 'terminal band above the prompt. As a skin, Clawd is drawn in this look instead of its own body all the time, and',
675 'moves as always: it walks, hops, looks around, blinks, trips, waves, and sits down to sleep.',
676 `The look: ${name}, "${title}".`,
677 `Why it was asked for: ${why || '(no reason given)'}`,
678 ...(change ? [`The change asked for now: "${change}". Make that change and keep what it does not touch.`] : []),
679 image
680 ? `The reference image is ${image}. Read it first and draw the look after it: its silhouette, colour and the features that make it recognisable at this tiny size.`
681 : 'There is no reference image; draw it from the title.',
682 ...(!isEmote
683 ? []
684 : !mayHold
685 ? ['This look turns Clawd into the thing: it has shapes and the body fields, and Clawd is drawn in them instead of its body.']
686 : !hasBody
687 ? ['This look keeps the body Clawd has and adds the thing: a tool in its hand, a prop beside it, or both.', 'It has no shapes and none of the body fields.']
688 : [
689 'A look is one of two kinds. One turns Clawd into the thing: it has shapes and the body fields, and',
690 'Clawd is drawn in them instead of its body. The other keeps the body Clawd has and adds the thing: a',
691 'tool in its hand, a prop beside it, or both; it has no shapes and none of the body fields. Take the',
692 'second when the thing is something Clawd holds, uses, makes or works on, and the first when Clawd',
693 'should become it: a creature, a character, a costume.',
694 ]),
695 ...(mayHold ? [`Clawd's body now is ${skin}. A look that keeps the body is drawn on it, and later on whatever body Clawd has then.`] : []),
696 '',
697 'How it is drawn: on a grid of sub-pixels, 2 x 2 per terminal cell, with quadrant block characters.',
698 'A terminal cell is about twice as high as wide, so a sub-pixel is too. A cell shows at most two',
699 'colours, so keep to one body colour: eyes are holes that show the dark terminal background. The',
700 'band is 4 rows (8 sub-pixels) high; with "tall": true it grows to 5 rows (10 sub-pixels) while Clawd',
701 "wears the look. Clawd's own body is 12 x 4 sub-pixels with four legs of 1 below it.",
702 '',
703 ...(isDrafting && others.length > 0
704 ? [`Clawd has these other ${isEmote ? 'emotes' : 'skins'}. Draw the new one so that it cannot be taken for any of them:`, ...others, '']
705 : []),
706 ...(isMaker
707 ? ['A draft is one JSON object:']
708 : isDrafting
709 ? [
710 `Draw ${EMOTE_DRAFTS} drafts that differ in how they show it: ${differ}. The`,
711 'next round sees them side by side and keeps the best. Reply with one JSON object and nothing else,',
712 `{"drafts": [${Array.from({ length: EMOTE_DRAFTS }, (_, i) => `draft ${i + 1}`).join(', ')}]}, each draft an object like this:`,
713 ]
714 : ['Reply with one JSON object and nothing else:']),
715 ...(hasBody
716 ? [
717 ...(mayHold ? ['for a look that turns Clawd into the thing,'] : []),
718 `{"name": "${name}", "title": "...", "color": "#rrggbb", "shapes": {...}, "legs": [...], "legLength": 2,`,
719 ` "wiggle": false, "armRow": 2, "arms": {...}, "tall": false,${isEmote ? ' "dur": 8,' : ''} "done": false}`,
720 ]
721 : []),
722 ...(mayHold
723 ? [
724 ...(hasBody ? ['and for one that keeps the body Clawd has,'] : []),
725 `{"name": "${name}", "title": "...", "accent": "#rrggbb", "tall": false, "dur": 8, "tool": {...}, "prop": {...}, "done": false}`,
726 'with a tool, a prop or both; leave out the one it does not use.',
727 ]
728 : []),
729 ...(hasBody
730 ? [
731 ...(mayHold ? ['The body fields, for a look that turns Clawd into the thing:'] : []),
732 '- color: the body colour; one that stands out on a dark background. "accent": "#rrggbb" is',
733 " optional, for '+' pixels; a '+' only shows where all 8 of its neighbours are body pixels.",
734 '- shapes: rows of characters, one string per row, at most 20 wide. # body, o an eye (a hole while',
735 ' open; it moves when Clawd looks around), + accent, . empty. normal: standing. squash: landing or',
736 ' crouching, wider and lower. stretch: rising in a jump, narrower and higher. flat: lying flat after',
737 ' a trip, 1 or 2 rows. Any shape left out is the normal one.',
738 '- legs: columns of the normal shape where legs hang below its last row, up to 8. legLength 0 to 3.',
739 " wiggle true: the leg tips sway like tentacles and crawl in a ripple; false: they step like Clawd's.",
740 "- armRow: the normal shape's row the arms grow from, or null for none. arms (optional): the arm",
741 " pixels as [dx, dy] from the body's edge on that row, dx outward and dy down, up to 4 per pose",
742 " and within 3. Clawd's are out [[1,0],[2,0]], up [[1,-1],[2,-2]], down [[1,1]], raised [[1,-1],[1,-2]].",
743 " Each pose is one line: the first pixel touches the body's edge, each next one the one before, no",
744 " branches; a pose that is not keeps Clawd's. Draw nothing held into the arms: at this size it reads",
745 ` as horns or a tail.${isEmote ? ' A held thing is the tool.' : ''}`,
746 '- Height limit: each shape, with legLength for normal and stretch, at most 6 sub-pixels, or 8 with',
747 ' "tall": true.',
748 ]
749 : []),
750 ...(isEmote ? [...(hasBody ? ['The fields of every look:'] : []), ...EMOTE_EXTRAS] : []),
751 ...(isMaker
752 ? [
753 '',
754 ...MAKER_LOOP,
755 `A single draft renders as a sheet of ${PREVIEW_POSES.length} panels, ${PREVIEW_PER_LINE} per line, each the band as the terminal shows`,
756 `it with Clawd in your look, in these poses: ${poses}.`,
757 ...propLines,
758 ...twiceLines,
759 `Several drafts render as one sheet: line k shows draft k, its number at the left, in ${SHEET_POSES.length} poses:`,
760 `${SHEET_POSES.join('; ')}.`,
761 ...(isTwice ? [`A draft that keeps the body shows them on the skin and then the same ${SHEET_POSES.length} on Clawd's own body.`] : []),
762 ...(draft
763 ? [
764 `The look as it is now: ${draft}`,
765 ...(preview ? [`Its preview is ${preview}. Read it first.`] : []),
766 'Make the change asked for, render it, and check first that the render carries the change.',
767 ]
768 : [`Start with ${EMOTE_DRAFTS} drafts side by side that differ in ${differ}, and keep the one that is easiest to recognise.`]),
769 'Compare each render with the reference image, or with the title when there is none, and fix what makes',
770 'it harder to recognise at this size: silhouette, eyes, legs, arms, proportions. Stop when no change',
771 'would make it clearly more recognisable. The look that is kept is the last draft you rendered alone,',
772 'so render your final draft alone.',
773 ]
774 : ['- done: true once you have seen the preview of this exact JSON and it looks right.']),
775 ...(refused ? ['', `Your last draft was refused: ${refused}. Fix that.`] : []),
776 ...(isMaker
777 ? []
778 : drafts.length > 0 && preview
779 ? [
780 '',
781 `Your ${drafts.length} drafts:`,
782 ...drafts.map((d, i) => `${i + 1}. ${d}`),
783 `Their sheet is ${preview}. Read it. Line k shows draft k, its number at the left, as the terminal`,
784 `shows the band, in ${SHEET_POSES.length} poses: ${SHEET_POSES.join('; ')}.`,
785 ...(isTwice
786 ? [`A draft that keeps the body shows them on the skin and then the same ${SHEET_POSES.length} on Clawd's own body. It must work on both.`]
787 : []),
788 'Compare them with the reference image, or with the title when there is none, and pick the one',
789 'that is easiest to recognise at this size. Fix what the sheet shows is off in it; a feature of',
790 'another draft may be taken over. Reply with the fixed JSON, "pick": its number, and "done": false.',
791 ]
792 : draft && isBefore
793 ? [
794 '',
795 `The look as it is now: ${draft}`,
796 ...(preview
797 ? [
798 `Its preview is ${preview}. Read it. It is a sheet of ${PREVIEW_POSES.length} panels, ${PREVIEW_PER_LINE} per line, each the`,
799 `band as the terminal shows it with Clawd in this look, in these poses: ${poses}.`,
800 ...propLines,
801 ...twiceLines,
802 ]
803 : []),
804 'Make the change asked for and reply with the changed JSON and "done": false.',
805 ]
806 : draft && preview
807 ? [
808 '',
809 `Your last draft: ${draft}`,
810 `Its preview is ${preview}. Read it. It is a sheet of ${PREVIEW_POSES.length} panels, ${PREVIEW_PER_LINE} per line, each the`,
811 `band as the terminal shows it with Clawd in your look, in these poses: ${poses}.`,
812 ...propLines,
813 ...twiceLines,
814 ...(change ? ['Check first that it carries the change asked for.'] : []),
815 'Compare it with the reference image, or with the title when there is none, and work out what',
816 'makes it harder to recognise at this size: silhouette, eyes, legs, arms, proportions. If any of',
817 'that can be fixed within the limits, reply with the corrected JSON and "done": false. Reply with',
818 'the same JSON and "done": true only when no change would make it clearly more recognisable.',
819 ]
820 : []),
821 ].join('\n')
822}
823
824/** A look a model drew, under the name asked for, with its own title or else the one asked for. */
825function lookFrom<T extends { name: string; title: string }>(kit: Kit<T>, raw: unknown, name: string, title: string): T | string {
826 const r = typeof raw === 'object' && raw !== null ? (raw as Record<string, unknown>) : {}
827 const look = kit.parse({ ...r, name, title: typeof r.title === 'string' && r.title.trim() ? r.title : title })
828 return typeof look === 'string' ? look : kit.check(look) || look
829}
830
831/** An emote or a skin to change, and the change asked for (/clawd emote change, /clawd skin change). */
832type Change<T> = { look: T & Dated; text: string }
833
834/**
835 * A model draws a new emote or skin: EMOTE_DRAFTS drafts, then a round in
836 * which it sees them side by side, picks one and fixes it, then a round in
837 * which it sees the pick's preview and corrects it. With `start`, the first
838 * draft is the look as it is now, and the model makes the change asked for.
839 * With `replace`, the look is drawn again from scratch and goes into that
840 * look's file. The look, or why there is none.
841 */
842async function makeEmote<T extends { name: string; title: string }>(
843 $: EngineInterface,
844 kit: Kit<T>,
845 name: string,
846 title: string,
847 why: string,
848 image: string,
849 start?: Change<T>,
850 form: Form = '',
851 replace?: T & Dated,
852): Promise<(T & Dated) | string> {
853 // The drafts are told the other looks of the kind; the one drawn again is left out.
854 const others = start ? [] : (await loadLooks($, kit)).filter(l => l.name !== name).map(l => `- ${l.name}: ${oneLine(kit.what(l), 100)}`)
855 let best: T | null = null
856 let draft = start ? JSON.stringify(kit.json(start.look)) : ''
857 let preview = start ? await previewLook($, kit, start.look, `${name}.before`) : ''
858 let drafts: string[] = [] // the drafts to pick from, as JSON
859 let refused = ''
860 for (let round = 1; round <= EMOTE_ROUNDS; round++) {
861 // The run may read the reference image and the newest preview, nothing else.
862 const reads = [image, preview].filter(Boolean).map(p => `Read(/${p})`)
863 const argv = [
864 'claude', '-p', '--model', MAKE_MODEL, '--effort', 'medium', '--safe-mode', '--setting-sources', '',
865 '--no-session-persistence', '--tools', 'Read', '--permission-mode', 'dontAsk',
866 ...(reads.length > 0 ? ['--allowedTools', ...reads] : []),
867 ]
868 const r = await $.process.run(argv, {
869 cwd: mod.dataDir,
870 stdin: emotePrompt(kit.kind, name, title, why, image, draft, preview, refused, start?.text, start !== undefined && round === 1, drafts, form, others),
871 timeoutMs: EMOTE_ROUND_MS,
872 })
873 if (r.exitCode !== 0) return `claude exited ${r.exitCode} in round ${round}: ${oneLine(r.stderr || r.stdout, 200)}`
874 const raw = parseJson(r.stdout)
875 if (!start && !draft && drafts.length === 0) {
876 // The drafts go on one sheet for the next round to pick from; a single one is a draft as usual.
877 const list = raw?.drafts
878 const looks = (Array.isArray(list) ? list : [raw]).slice(0, EMOTE_DRAFTS).map(d => lookFrom(kit, d, name, title))
879 const good = looks.filter((l): l is T => typeof l !== 'string')
880 refused = good.length > 0 ? '' : looks.join('; ') || 'no drafts'
881 best = good[0] ?? best
882 if (good.length > 1) {
883 drafts = good.map(l => JSON.stringify(kit.json(l)))
884 preview = `${mod.dataDir}/${kit.kind}s/previews/${name}.drafts.png`
885 await writeBytes($, preview, kit.sheet(good))
886 } else if (good[0]) {
887 draft = JSON.stringify(kit.json(good[0]))
888 preview = await previewLook($, kit, good[0], `${name}.draft${round}`)
889 }
890 continue
891 }
892 const look = lookFrom(kit, raw, name, title)
893 if (typeof look === 'string') {
894 refused = look
895 continue
896 }
897 refused = ''
898 // Done counts only for a draft whose preview the model has seen; for a
899 // change, not before the model has seen its own changed draft.
900 const json = JSON.stringify(kit.json(look))
901 best = look
902 if (raw?.done === true && json === draft && !(start && round === 1)) break
903 draft = json
904 drafts = []
905 preview = await previewLook($, kit, look, `${name}.draft${round}`)
906 }
907 if (!best) return `no usable draft in ${EMOTE_ROUNDS} rounds: ${refused}`
908 return saveLook($, kit, best, name, why, image, start, replace)
909}
910
911/** Writes a drawn emote or skin and its preview; a changed or redrawn one goes back into its file. */
912async function saveLook<T extends { name: string; title: string }>(
913 $: EngineInterface,
914 kit: Kit<T>,
915 best: T,
916 name: string,
917 why: string,
918 image: string,
919 start?: Change<T>,
920 replace?: T & Dated,
921): Promise<T & Dated> {
922 const made = new Date(await $.clock.now()).toISOString()
923 // A changed or redrawn look goes back where it was; the old one is kept in data/<kind>s/old/.
924 const was = start?.look ?? replace
925 const file = was?.file ?? `${mod.dataDir}/${kit.kind}s/${name}.json`
926 if (was) await $.fs.write(await oldPath($, kit.kind, name), await $.fs.read(file))
927 const changed = start ? { change: start.text } : {}
928 await $.fs.write(file, `${JSON.stringify({ ...kit.json(best), made, project: mod.project, why, image, ...changed }, null, 2)}\n`)
929 await previewLook($, kit, best)
930 return { ...best, made, project: mod.project, why, image, file }
931}
932
933/** Where an act's, an emote's or a skin's old file goes when it is changed or deleted: data/<kind>s/old/<name>.<time>.json. */
934async function oldPath($: EngineInterface, kind: MadeKind, name: string): Promise<string> {
935 const stamp = new Date(await $.clock.now()).toISOString().replace(/[:.]/g, '-')
936 return `${mod.dataDir}/${kind}s/old/${name}.${stamp}.json`
937}
938
939/**
940 * Starts drawing an emote in the background; it plays on `who` when done. It
941 * runs from a timer, so it outlives the hook that asked for it. With
942 * `replace`, that emote is drawn again from scratch.
943 */
944function startEmote(
945 $: EngineInterface,
946 name: string,
947 title: string,
948 why: string,
949 image: string,
950 who: string,
951 start?: Change<Emote>,
952 form: Form = '',
953 replace?: MadeEmote,
954): void {
955 brain.making = name
956 const w = clawd.world
957 const label = start ? ` · changing ${name}: "${start.text}"` : replace ? ` · drawing ${name} again` : ` · new emote coming: "${title}"`
958 if (w) callLabel(w, [], label)
959 $.clock.after(1, () => void drawEmote($, name, title, why, image, who, start, form, replace))
960}
961
962async function drawEmote(
963 $: EngineInterface,
964 name: string,
965 title: string,
966 why: string,
967 image: string,
968 who: string,
969 start?: Change<Emote>,
970 form: Form = '',
971 replace?: MadeEmote,
972): Promise<void> {
973 const result = await drawn($, EMOTE_KIT, name, title, why, image, start, form, replace)
974 if (typeof result === 'string') return
975 const w = clawd.world
976 if (w) {
977 callActs(w, [{ who, what: result, delay: 0 }])
978 callLabel(w, [{ who, name: `${name} (${start ? 'changed' : replace ? 'drawn again' : 'new emote'}) "${result.title}"` }])
979 }
980 brain.recent = [`${who}: ${name}`, ...brain.recent].slice(0, 8)
981 $.ui.toast(start ? `Clawd's emote ${name} is changed` : replace ? `Clawd's emote ${name} is drawn again` : `Clawd has a new emote: ${name}`)
982}
983
984/**
985 * Who wears a new skin for the rest of the session: the person, as with
986 * /clawd skin <skin>, or the autopicker, whose skin a /clawd skin choice outranks.
987 */
988type SkinSlot = 'chosen' | 'picked'
989
990/**
991 * Starts drawing a skin in the background, as startEmote does an emote. A
992 * new skin is worn for the rest of the session, in `slot`; a changed or
993 * redrawn one comes on when it is the skin worn now.
994 */
995function startSkin(
996 $: EngineInterface,
997 name: string,
998 title: string,
999 why: string,
1000 image: string,
1001 start?: Change<Skin>,
1002 replace?: MadeSkin,
1003 slot: SkinSlot = 'chosen',
1004): void {
1005 brain.making = name
1006 const w = clawd.world
1007 const label = start ? ` · changing the skin ${name}: "${start.text}"` : replace ? ` · drawing the skin ${name} again` : ` · new skin coming: "${title}"`
1008 if (w) callLabel(w, [], label)
1009 $.clock.after(1, () => void drawSkin($, name, title, why, image, start, replace, slot))
1010}
1011
1012async function drawSkin(
1013 $: EngineInterface,
1014 name: string,
1015 title: string,
1016 why: string,
1017 image: string,
1018 start: Change<Skin> | undefined,
1019 replace: MadeSkin | undefined,
1020 slot: SkinSlot,
1021): Promise<void> {
1022 const result = await drawn($, SKIN_KIT, name, title, why, image, start, '', replace)
1023 if (typeof result === 'string') return
1024 if (!start && !replace && slot === 'chosen') await update($, clawdSkin, () => name)
1025 if (!start && !replace && slot === 'picked') await update($, clawdPickedSkin, () => name)
1026 await applySkin($, true)
1027 const w = clawd.world
1028 if (w) callLabel(w, [], ` · skin ${name} (${start ? 'changed' : replace ? 'drawn again' : 'new'}) "${result.title}"`)
1029 $.ui.toast(
1030 start ? `Clawd's skin ${name} is changed` : replace ? `Clawd's skin ${name} is drawn again` : `Clawd wears its new skin ${name} for this session`,
1031 )
1032}
1033
1034/** Draws the look; on failure, says so in the band, a toast and /clawd, and answers why. */
1035async function drawn<T extends { name: string; title: string }>(
1036 $: EngineInterface,
1037 kit: Kit<T>,
1038 name: string,
1039 title: string,
1040 why: string,
1041 image: string,
1042 start?: Change<T>,
1043 form: Form = '',
1044 replace?: T & Dated,
1045): Promise<(T & Dated) | string> {
1046 let result: (T & Dated) | string
1047 try {
1048 result = (await makeLookByMaker($, kit, name, title, why, image, start, form, replace)) ?? (await makeEmote($, kit, name, title, why, image, start, form, replace))
1049 } catch (err) {
1050 result = String(err)
1051 } finally {
1052 brain.making = ''
1053 }
1054 if (typeof result !== 'string') return result
1055 failed($, start ? `${kit.kind} change` : replace ? `${kit.kind} redraw` : `new ${kit.kind}`, name, result)
1056 return result
1057}
1058
1059/** Says in the band, a toast and /clawd that making an act, an emote or a skin failed, and why. */
1060function failed($: EngineInterface, what: string, name: string, why: string): void {
1061 const w = clawd.world
1062 if (w) callLabel(w, [], ` · ${what} failed`)
1063 $.ui.log(`clawd: ${what} ${name} failed: ${why}`, { to: 'debug' })
1064 $.ui.toast(`Clawd's ${what} ${name} failed; /clawd says why`)
1065 brain.makeError = `${name}: ${why}`
1066}
1067
1068/** One make the maker agent works on: what its Read may open, how a draft is rendered, and how it ends. */
1069type MakerJob = {
1070 kind: MadeKind
1071 name: string
1072 prompt: string
1073 reads: Set<string> // exact paths: the reference image and the PNGs it was given
1074 render: (draft: unknown, drafts: unknown) => Promise<string>
1075 state: 'queued' | 'spawning' | 'running' | 'ended'
1076 deadline: number
1077 started: (agentId: string | undefined, why: string) => void
1078 ended: (answer: string, reason: string) => void
1079}
1080
1081// The maker's working state; a hot reload starts it over, and a maker of the old load is refused everything.
1082const maker = {
1083 type: '', // `<plugin>:maker` once registered; '' leaves every make to the rounds
1084 queue: [] as MakerJob[],
1085 jobs: new Map<string, MakerJob>(), // by agentId, while it runs
1086 others: new Map<string, boolean>(), // other subagents: whether each is a maker this load did not start
1087}
1088
1089/** How a maker run went: its answer, or why it did not start, in which case the rounds run. */
1090type MakerEnd = { isStarted: false; why: string } | { isStarted: true; answer: string; reason: string }
1091
1092/** Queues a make for `spawnQueued` and asks for a band render; resolves once the maker answered, or did not start. */
1093function runMaker($: EngineInterface, kind: MadeKind, name: string, prompt: string, reads: Set<string>, render: MakerJob['render']): Promise<MakerEnd> {
1094 if (!maker.type) return Promise.resolve({ isStarted: false, why: 'no maker agent is registered' })
1095 return new Promise<MakerEnd>(resolve => {
1096 const job: MakerJob = {
1097 kind,
1098 name,
1099 prompt,
1100 reads,
1101 render,
1102 state: 'queued',
1103 deadline: 0,
1104 started: (agentId, why) => {
1105 if (agentId !== undefined || job.state === 'ended') return
1106 job.state = 'ended'
1107 resolve({ isStarted: false, why })
1108 },
1109 ended: (answer, reason) => {
1110 if (job.state === 'ended') return
1111 job.state = 'ended'
1112 for (const [id, j] of maker.jobs) if (j === job) maker.jobs.delete(id)
1113 resolve({ isStarted: true, answer, reason })
1114 },
1115 }
1116 maker.queue.push(job)
1117 $.ui.invalidate('ui.render')
1118 $.clock.after(MAKER_START_MS, () => {
1119 if (job.state !== 'queued') return
1120 maker.queue = maker.queue.filter(j => j !== job)
1121 job.started(undefined, `not started within ${MAKER_START_MS / 1000} s, so no band was drawn`)
1122 })
1123 // A maker that never answers (a stall, a reload) fails the make; the rounds do not run then.
1124 $.clock.after(MAKER_START_MS + MAKER_MS + MAKER_GRACE_MS, () => job.ended('', NO_ANSWER))
1125 })
1126}
1127
1128/**
1129 * Starts the queued makes, from the band's ui.render hook: only a spawn made
1130 * inside a hook leaves the maker's tool calls to this mod's tool.check and
1131 * tool.call hooks. Never call it from a timer or after a hook returned.
1132 */
1133async function spawnQueued($: EngineInterface): Promise<void> {
1134 for (let job = maker.queue.shift(); job; job = maker.queue.shift()) {
1135 job.state = 'spawning'
1136 let why = ''
1137 try {
1138 const now = await $.clock.now()
1139 const r = await $.agent.spawn({ subagentType: maker.type, prompt: job.prompt, description: `clawd: ${job.kind} ${job.name}` })
1140 if ('agentId' in r && r.agentId) {
1141 // Ended while the spawn ran (its time ran out): it stays out of the jobs, so the stray check refuses its calls.
1142 if ((job.state as MakerJob['state']) === 'ended') continue
1143 job.deadline = now + MAKER_MS
1144 maker.jobs.set(r.agentId, job)
1145 job.state = 'running'
1146 job.started(r.agentId, '')
1147 continue
1148 }
1149 why = 'deny' in r ? String(r.deny) : 'no agent id'
1150 } catch (err) {
1151 why = err instanceof Error ? err.message : String(err)
1152 }
1153 job.started(undefined, why)
1154 }
1155}
1156
1157/** The verdict on a call in a maker's loop: render, ToolSearch, and Read of the exact files it was given; nothing after its time. */
1158function makerVerdict(job: MakerJob, tool: string, input: Record<string, unknown>, now: number): { decision: 'allow' } | { decision: 'deny'; reason: string } {
1159 if (now > job.deadline) return { decision: 'deny', reason: 'clawd: the time for this make is up; answer now with one line.' }
1160 if (tool === RENDER_TOOL || tool === 'ToolSearch') return { decision: 'allow' }
1161 if (tool === 'Read' && typeof input.file_path === 'string' && job.reads.has(input.file_path)) return { decision: 'allow' }
1162 return { decision: 'deny', reason: `clawd: the maker may only call ${RENDER_TOOL} and Read the files it was given.` }
1163}
1164
1165/** Whether a subagent this load did not start is a maker, of an earlier load; asked once per agent. */
1166async function isStrayMaker($: EngineInterface, agentId: string): Promise<boolean> {
1167 const known = maker.others.get(agentId)
1168 if (known !== undefined) return known
1169 const isMaker = (await $.agent.list()).find(a => a.id === agentId)?.type === maker.type
1170 maker.others.set(agentId, isMaker)
1171 return isMaker
1172}
1173
1174/** What a maker run came to: the made thing's draft, why it failed, or undefined when it did not start. */
1175function makerOutcome(end: MakerEnd, name: string, hasDraft: boolean): string | undefined {
1176 if (!end.isStarted) return undefined
1177 // A draft is kept only through the render tool, which answers only in a confined maker's loop.
1178 if (!hasDraft) return `the maker rendered no usable draft (${end.reason}): ${oneLine(end.answer, 200) || 'no answer'}`
1179 if (end.reason === NO_ANSWER) return `the maker did not answer in time for ${name}`
1180 if (/^failed\b/i.test(end.answer.trim())) return `the maker gave up on ${name}: ${oneLine(end.answer, 200)}`
1181 return ''
1182}
1183
1184/**
1185 * The maker draws an emote or a skin, rendering to previews/<name>.r<N>.png;
1186 * with `start` it changes that look, with `replace` it draws it again. The
1187 * look, why it failed, or undefined when the maker did not start.
1188 */
1189async function makeLookByMaker<T extends { name: string; title: string }>(
1190 $: EngineInterface,
1191 kit: Kit<T>,
1192 name: string,
1193 title: string,
1194 why: string,
1195 image: string,
1196 start?: Change<T>,
1197 form: Form = '',
1198 replace?: T & Dated,
1199): Promise<(T & Dated) | string | undefined> {
1200 if (!maker.type) return undefinedhooks/clawd-sim.ts 2599 lines1// Clawd, the Claude Code logo, as a small creature living in the band above
2// the prompt, and a mini Clawd for each running subagent. This file is the
3// pure part: the world, the behaviours, and the drawing into Raster cells. It
4// never touches `$`; register.tsx drives it.
5//
6// Units: the band is a grid of sub-pixels, 2 x 2 per terminal cell, drawn
7// with the quadrant blocks the logo itself uses (▐▛███▜▌). x grows to the
8// right and `row` downwards. A body's height above the ground, `y`, grows
9// upwards. Nothing is a stored frame: every pose comes from the current
10// motion (speed, distance walked, vertical speed, time since landing).
11
12export const TICK_MS = 50
13const DT = TICK_MS / 1000
14const GRAVITY = 120 // sub-pixels per second squared
15export const WALK = 12 // sub-pixels per second
16const RUN = 36
17// A wiggly look's ripple: one stride per this many sub-pixels walked, twice as
18// many running, so a sprint's wave stays slower than the frames.
19const STRIDE = 8
20const EASE_S = 0.4 // an eased move takes this long to reach full speed, and to stop from it
21export const SLEEP_AFTER_S = 180 // idle seconds without any session event
22export const MINI_STALE_S = 900 // a mini whose subagent was silent this long leaves
23export const MAX_MINIS = 6 // minis on screen at once; more subagents get none
24export const MINI_GAP = 6 // sub-pixels a mini's stop keeps clear of Clawd's edge (besideClawd)
25export const MAX_DELAY_S = 5 // how far ahead a model's call may start
26const LAYERS = [4, 3, 2, 1] // bricks per pile layer, bottom up, as far as the band is tall
27/** The band's height in rows, and its height while a body does a big jump. */
28export const BAND_ROWS = 4
29export const TALL_ROWS = 5
30/** The band's height while Clawd wears a tall look and the Remote Control antenna. */
31export const ANTENNA_ROWS = 6
32const TALL_HOLD_S = 0.6 // the band stays tall this long after a big jump, so a second one does not resize it
33export const READ_HOLD_S = 1.2 // the scroll stays up this long after the last reading call
34
35const ORANGE = 0xd77757 // the logo's colour
36// One colour per mini, in turn, so the label can say which mini is which.
37const MINI_COLORS = [0x6fb3d2, 0x8fc96f, 0xc89be0, 0xe0c060, 0x5fc7b0, 0xe08fa8]
38const BODY_COLORS = new Set([ORANGE, ...MINI_COLORS])
39const BRICK = 0x8696a8
40const BRICK_DARK = 0x67788d
41const DUST = 0x8a8a9a
42const GOLD = 0xffc857
43const SNOOZE = 0xa8b4ff
44const WHITE = 0xf0f0f0
45const PAPER = 0xe8dcb8 // the scroll a reading body holds
46const ROLL = 0x8b5e34 // its rolled ends
47const SWEAT = 0x7fd4ff
48const ANTENNA = 0xa8a8a8 // the antenna Clawd wears while Remote Control is on
49const SIGNAL = 0x5fd47a // its tip
50const SIGNAL_DIM = 0x2f6b3d // its tip as it blinks
51const FLOOR = 0x7a7a7a // the floor line, grey like the prompt border
52export const FLOOR_TEXT = '#7a7a7a' // FLOOR as a Text color, for the menu's frame below the band
53const LABEL = 0x9a9aa8 // the line at the top right: what was picked
54const LABEL_SPARE = 4 // cells right of the label: the engine's `[-]` and a gap
55const DEFAULT = 0x01000000 // Raster: the terminal's own colour
56const EMPTY = -1
57
58// Quadrant glyph by mask: upper-left 1, upper-right 2, lower-left 4, lower-right 8.
59const QUAD = [
60 0x20, 0x2598, 0x259d, 0x2580, 0x2596, 0x258c, 0x259e, 0x259b, 0x2597, 0x259a, 0x2590, 0x259c,
61 0x2584, 0x2599, 0x259f, 0x2588,
62]
63
64type Shape = 'normal' | 'squash' | 'stretch' | 'flat'
65type Arms = 'out' | 'up' | 'down' | 'wave' | 'flail' | 'none'
66type Eyes = 'open' | 'closed' | 'wide' | 'down' // down: reading, at the scroll; no routine or emote sets it
67type Leg = 'down' | 'up' | 'out' // the front leg: up drawn away, out kicked forward along the floor; only the kick sets it
68type Size = { w: number; h: number; eyes: [number, number]; eyeRow: number; armRow: number }
69
70// Body sizes in sub-pixels. `normal` is the logo: 12 x 4 with eye holes at
71// x 2 and 9 on row 1, arms on row 2 and four one-pixel legs below.
72const SHAPES: Record<Shape, Size> = {
73 normal: { w: 12, h: 4, eyes: [2, 9], eyeRow: 1, armRow: 2 },
74 squash: { w: 14, h: 3, eyes: [3, 10], eyeRow: 1, armRow: 1 },
75 stretch: { w: 10, h: 5, eyes: [2, 7], eyeRow: 1, armRow: 2 },
76 flat: { w: 16, h: 2, eyes: [3, 12], eyeRow: 0, armRow: 1 },
77}
78// A mini is half the logo: 6 x 3 with eye holes at x 1 and 4 on row 1, one
79// pixel of arm a side and two legs.
80const MINI_SHAPES: Record<Shape, Size> = {
81 normal: { w: 6, h: 3, eyes: [1, 4], eyeRow: 1, armRow: 2 },
82 squash: { w: 8, h: 2, eyes: [2, 5], eyeRow: 0, armRow: 1 },
83 stretch: { w: 6, h: 4, eyes: [1, 4], eyeRow: 1, armRow: 2 },
84 flat: { w: 9, h: 1, eyes: [2, 6], eyeRow: 0, armRow: 0 },
85}
86
87export const ACTS = [
88 'idle', 'wander', 'run', 'hop', 'jump', 'celebrate', 'trip', 'sleep', 'wake', 'wave', 'look',
89 'think', 'chase', 'peek', 'carry', 'alert', 'kick', 'read',
90] as const
91// Acts only a routine plays: hold a pose, put a glyph over the head, throw
92// sparks, move at a chosen speed, play another made act.
93const STEP_ONLY = ['pose', 'mark', 'sparks', 'move', 'play'] as const
94// `leave`: a mini whose subagent finished runs off the band. `emote`: Clawd
95// takes an emote's look.
96export type ActKind = (typeof ACTS)[number] | (typeof STEP_ONLY)[number] | 'routine' | 'leave' | 'emote'
97
98/** The acts a model may pick, with what each looks like. */
99export const PICKABLE: Partial<Record<ActKind, string>> = {
100 idle: 'stands and looks around',
101 wander: 'walks somewhere nearby',
102 run: 'runs across the band',
103 hop: 'a small hop',
104 jump: 'a big jump sideways',
105 celebrate: 'two hops with sparks, then a wave',
106 trip: 'trips, lies flat with dizzy stars, gets up',
107 wave: 'waves',
108 look: 'looks left and right',
109 think: 'looks up with a question mark',
110 chase: 'chases a sparkle and jumps to catch it',
111 peek: 'runs off one edge and comes back from the other',
112 alert: 'an exclamation mark, eyes wide',
113}
114
115// What a routine step may be: the pickable acts, the step-only ones, and an emote by name.
116const STEP_KINDS = [...Object.keys(PICKABLE), ...STEP_ONLY, 'emote'] as ActKind[]
117const ARMS: Arms[] = ['out', 'up', 'down', 'wave', 'flail', 'none']
118const EYES: Eyes[] = ['open', 'closed', 'wide']
119const SHAPE_NAMES = ['normal', 'squash', 'stretch', 'flat'] as const
120// ASCII only: a glyph a terminal draws two cells wide would shift the row.
121const MARKS: Record<string, number> = { '!': 0xf0f0f0, '?': 0xf0f0f0, '*': 0xffc857, '+': 0xffc857, '~': 0x7fd4ff, z: 0xa8b4ff, o: 0x7fd4ff, '^': 0xf0f0f0, '#': 0xd77757 }
122export const MAX_STEPS = 12
123
124/** One step of a routine; `routineFrom` checks it and fills in nothing. */
125export type Step = {
126 do: ActKind
127 to?: number // wander, run, move: where to, 0 left edge to 1 right edge
128 dir?: number // jump, a run or move with wrap: -1 left, 1 right
129 n?: number // hop: how many; sparks: how many
130 height?: number // hop, jump: sub-pixels
131 dur?: number // idle, wave, look, think, pose: seconds; emote: how long the look stays
132 // arms, eyes, look and up apply on top of any step, so a run can wave
133 arms?: Arms
134 eyes?: Eyes
135 shape?: Shape // pose
136 look?: number // -1 back, 0 centre, 1 forward
137 up?: boolean // looks up
138 sit?: boolean // pose
139 glyph?: string // mark
140 sparks?: boolean // hop
141 wrap?: boolean // run, move: off the edge in `dir`, straight back in from the other one, on to `to`
142 speed?: 'walk' | 'run' | number // wander, run, move: a number counts walking speeds, run is 3
143 ease?: boolean // wander, run, move: speeds up from a stand and slows to a stop
144 name?: string // emote: the look to put on; play: the made act to play
145 worn?: Emote // emote: the look `name` found, filled in by `linkRoutine`
146 inner?: Step[] // play: the steps of the act `name` found, filled in by `linkRoutine`
147}
148
149/** A named act made of steps, written by a model and kept in data/acts/. */
150export type Routine = { name: string; title: string; steps: Step[] }
151
152/**
153 * A body drawn and animated the way Clawd is, from a JSON file. A shape is
154 * rows of characters: `#` body, `o` an eye (a hole while open), `+` the
155 * accent colour, anything else empty. As a skin, Clawd wears it all the time instead of its own body:
156 * from skins/ (drawn by hand) or data/skins/ (drawn by a model), chosen by
157 * clawd.json, the project folder or `/clawd skin`. Emotes and acts play on it.
158 */
159export type Skin = {
160 name: string
161 title: string
162 color: number
163 accent: number
164 shapes: Record<Shape, string[]> // a shape the file leaves out is the normal one
165 legs: number[] // leg columns, counted in the normal shape
166 legLength: number
167 isWiggly: boolean // the legs sway like tentacles and crawl in a ripple instead of stepping
168 armRow: number | null // the normal shape's row the arms grow from; null: no arms
169 armPoses: Record<ArmPose, [number, number][]> // [dx, dy] from the body's edge, as Clawd's
170 isTall: boolean // the band grows a row while Clawd wears it, as for a big jump
171}
172
173/**
174 * A look Clawd takes for a while, from a JSON file in
175 * emotes/ (drawn by hand) or data/emotes/ (drawn by a model). It turns Clawd
176 * into another body, or keeps the body Clawd has, its skin or its own, and
177 * adds a prop or a tool; it may do both.
178 */
179export type Emote = {
180 name: string
181 title: string
182 accent: number // the colour of `+` pixels in the body, the prop and the tool
183 isTall: boolean // the band grows a row while Clawd wears it, as for a big jump
184 body: Skin | null // the body it gives Clawd for its time; null: Clawd keeps the one it has
185 dur: number // seconds it stays on when played
186 prop: Prop | null
187 tool: Tool | null
188}
189
190/**
191 * A thing Clawd holds in its front hand while it wears the look. It has its own colours, so it
192 * does not read as a horn or a tail the way a tool drawn into the arms does.
193 * The first pixel of its bottom row sits one pixel past the front arm's tip,
194 * so it follows the arm's pose without turning.
195 */
196export type Tool = {
197 rows: string[] // `#` the tool's colour, `+` the emote's accent, anything else empty
198 color: number
199}
200
201/**
202 * An object beside Clawd that is not part of its body: it
203 * starts `x` sub-pixels from Clawd's centre, forward as Clawd faces when the
204 * look starts, and from then on keeps to its path, wherever Clawd goes.
205 */
206export type Prop = {
207 rows: string[] // `#` the prop's colour, `+` the emote's accent, anything else empty
208 color: number
209 x: number
210 path: PropKey[] // in time order; straight lines between keys, then the last key holds
211 hasTrail: boolean // sparks below it while it rises, a rocket's flame
212}
213
214/** `t` seconds after the look starts the prop is `x` forward and its bottom `y` above the floor. */
215type PropKey = { t: number; x: number; y: number }
216
217/** The arm positions an emote may draw its own way; the other arm acts are made of them. */
218type ArmPose = 'out' | 'up' | 'down' | 'raised'
219
220export type Act = {
221 kind: ActKind
222 t0: number // world time the current stage started
223 stage: number
224 dur?: number
225 to?: number
226 speed?: number
227 dir?: number // a run or move with wrap: -1 left, 1 right
228 wrap?: boolean // run, move: a lap through the edges
229 ease?: boolean // wander, run, move: an arrive, EASE_S each way
230 n?: number
231 height?: number
232 look?: number
233 next?: number
234 gaze?: number // a routine step's look, on top of what the act sets; idle uses `look` for its glances
235 arms?: Arms
236 sparks?: boolean
237 eyes?: Eyes
238 shape?: Shape
239 lookUp?: boolean
240 sit?: boolean
241 glyph?: string
242 steps?: Step[] // routine
243 routine?: string // the routine this act is, or is a step of
244 step?: number // the routine's step this act comes from, counted from 1
245 via?: string // the made act a play step plays, for its acts
246 emote?: Emote // emote
247 isPick?: boolean // a model's call
248 isReflex?: boolean // a reaction to a session event; a model's call waits for it
249 isRandom?: boolean // rolled from the idle tables; a read cuts it short
250}
251
252export type Particle = {
253 x: number
254 row: number
255 vx: number
256 vrow: number
257 fall: number // added to vrow per second
258 age: number
259 life: number
260 glyph: string
261 color: number
262}
263
264/** One creature: Clawd itself, or a mini Clawd for a subagent. */
265export type Body = {
266 id: string // 'clawd', or a mini's: a1, a2, ...
267 color: number
268 isMini: boolean
269 x: number // centre, sub-pixels
270 y: number // feet above the ground
271 vx: number
272 vy: number
273 facing: 1 | -1
274 walked: number // distance travelled; drives the gait
275 strides: number // a wiggly look's strides taken; drives its ripple
276 dustAt: number
277 landedAt: number
278 blinkAt: number
279 act: Act | null
280 queue: Act[]
281 // this tick's intent, set by the act
282 arms: Arms
283 eyes: Eyes
284 look: number // -1 back, 0 centre, 1 forward
285 lookUp: boolean
286 shape: Shape | null
287 sitting: boolean
288 frontLeg: Leg
289 reading: boolean // holds a scroll
290 carrying: boolean
291 wearing: Emote | null // the emote whose look it has
292 wornAt: number
293 wornUntil: number
294 propStart: { left: number; dir: 1 | -1 } | null // the prop's left column and the way the body faced, as the look started
295}
296
297/** A mini Clawd: it comes when its subagent starts and leaves when it ends. */
298export type Mini = Body & {
299 agentId: string
300 title: string // the Agent tool's description
301 kind: string // the subagent type
302 since: number // world time it came
303 tools: number // its subagent's tool calls
304 lastEventAt: number
305 isLeaving: boolean
306 isGone: boolean
307}
308
309/** What a body can be told to play: a built-in act, a routine, or an emote. */
310export type Playable = ActKind | Routine | Emote
311
312/** A model's call: `who` (a body's id, or 'all') plays `what` after `delay` seconds. */
313export type Call = { who: string; what: Playable; delay: number }
314
315/** A part of the label, in its own colour. */
316export type LabelPart = { text: string; color: number }
317
318/** The world is Clawd itself plus everything around it. */
319export type World = Body & {
320 cols: number
321 rows: number
322 t: number
323 rand: () => number
324 mode: 'idle' | 'work'
325 lastEventAt: number
326 tallUntil: number // the band stays tall until this time
327 pile: number
328 pileAt: number // left edge of the pile, an even sub-pixel x
329 spark: { x: number; row: number; vx: number; age: number; isFleeing: boolean } | null
330 particles: Particle[]
331 label: LabelPart[] // drawn at the top right of the band
332 edge: LabelPart[] | null // while /clawd is typed: the floor is the menu's top edge, with this title
333 minis: Mini[]
334 minisMade: number // for the minis' ids and colours
335 due: { at: number; who: string; acts: Act[] }[] // model calls waiting for their time
336 skin: Skin | null // the body Clawd has whenever no emote gives it another; null: its own
337 antenna: boolean // Remote Control is on: Clawd wears an antenna on whatever look it has
338}
339
340// --- setup -------------------------------------------------------------------
341
342function newBody(id: string, color: number, isMini: boolean, x: number): Body {
343 return {
344 id,
345 color,
346 isMini,
347 x,
348 y: 0,
349 vx: 0,
350 vy: 0,
351 facing: 1,
352 walked: 0,
353 strides: 0,
354 dustAt: 0,
355 landedAt: -1,
356 blinkAt: 2,
357 act: null,
358 queue: [],
359 arms: 'out',
360 eyes: 'open',
361 look: 0,
362 lookUp: false,
363 shape: null,
364 sitting: false,
365 frontLeg: 'down',
366 reading: false,
367 carrying: false,
368 wearing: null,
369 wornAt: 0,
370 wornUntil: 0,
371 propStart: null,
372 }
373}
374
375export function createWorld(cols: number, rows: number, rand: () => number = Math.random): World {
376 const w: World = {
377 ...newBody('clawd', ORANGE, false, -12),
378 cols,
379 rows,
380 t: 0,
381 rand,
382 mode: 'idle',
383 lastEventAt: 0,
384 tallUntil: 0,
385 pile: 0,
386 pileAt: 0,
387 spark: null,
388 particles: [],
389 label: [],
390 edge: null,
391 minis: [],
392 minisMade: 0,
393 due: [],
394 skin: null,
395 antenna: false,
396 }
397 resize(w, cols, rows)
398 // Clawd walks in from the left and says hello.
399 w.queue.push(make(w, 'wander', { to: Math.round(cols * 0.5) }), make(w, 'wave', { dur: 1.2 }))
400 return w
401}
402
403export function resize(w: World, cols: number, rows: number): void {
404 // Rows count from the top, so when the band grows upwards the particles
405 // move down with the floor.
406 const shift = 2 * (rows - w.rows)
407 for (const p of w.particles) p.row += shift
408 if (w.spark) w.spark.row += shift
409 w.cols = cols
410 w.rows = rows
411 const W = cols * 2
412 // Even, about 80% across, with room on its right for Clawd to drop bricks.
413 w.pileAt = Math.max(0, 2 * Math.round(Math.min(W * 0.8, W - 34) / 2))
414 for (const c of bodies(w)) if (c.x > W + 16) c.x = W + 16
415}
416
417/** A deterministic random source for tests. */
418export function seeded(seed: number): () => number {
419 let s = seed >>> 0
420 return () => {
421 s = (s + 0x6d2b79f5) >>> 0
422 let r = Math.imul(s ^ (s >>> 15), 1 | s)
423 r = (r + Math.imul(r ^ (r >>> 7), 61 | r)) ^ r
424 return ((r ^ (r >>> 14)) >>> 0) / 4294967296
425 }
426}
427
428/** Clawd first, then the minis. */
429export function bodies(w: World): Body[] {
430 return [w, ...w.minis]
431}
432
433/** The body a model's call names: 'clawd' or a mini's id; none for a mini on its way out. */
434export function bodyOf(w: World, who: string): Body | undefined {
435 if (who === 'clawd') return w
436 return w.minis.find(m => m.id === who && !m.isLeaving)
437}
438
439function make(w: World, kind: ActKind, extra: Partial<Act> = {}): Act {
440 return { kind, t0: w.t, stage: 0, ...extra }
441}
442
443function reflex(w: World, kind: ActKind, extra: Partial<Act> = {}): Act {
444 return make(w, kind, { ...extra, isReflex: true })
445}
446
447function between(w: World, lo: number, hi: number): number {
448 return lo + w.rand() * (hi - lo)
449}
450
451function width(w: World): number {
452 return w.cols * 2
453}
454
455// The feet stand on the upper half of the band's last row, as in the logo
456// (`▘▘ ▝▝`), and the rest of that row is a floor line (`─`) for them to stand
457// on. Claude Code keeps a blank row above the prompt box that no mod reaches,
458// so the floor is as close to the prompt as Clawd gets.
459function ground(w: World): number {
460 return w.rows * 2 - 2
461}
462
463/** Sub-pixel rows above standing Clawd's head; jumps stay within them. */
464function headroom(w: World): number {
465 return Math.max(0, w.rows * 2 - 6)
466}
467
468/** How far a standing body's top is above its feet, in sub-pixels. */
469function bodyHeight(w: World, c: Body): number {
470 const look = shownLook(w, c)
471 if (look) return look.shapes.normal.length + look.legLength - 1
472 return c.isMini ? 3 : 4
473}
474
475/** Sub-pixel rows above a standing body's head; its jumps stay within them. */
476function roomAbove(w: World, c: Body): number {
477 return shownLook(w, c) ? Math.max(0, ground(w) - bodyHeight(w, c)) : headroom(w)
478}
479
480/**
481 * The body a body has now: its emote's, else Clawd's skin; null: its own. A
482 * tall skin shows in any band; in a terminal too short for the tall band its
483 * head is cut off at the top.
484 */
485function shownLook(w: World, c: Body): Skin | null {
486 return c.wearing?.body ?? (c === w ? w.skin : null)
487}
488
489function pileCapacity(w: World): number {
490 let n = 0
491 while (brickSpot(w, n)) n += 1
492 return n
493}
494
495function isAirborne(c: Body): boolean {
496 return c.y > 0 || c.vy > 0
497}
498
499// --- session events (called by register.tsx) ---------------------------------------
500
501/** Replaces what `c` is doing with `acts`; a carried brick falls off. */
502export function interrupt(w: World, c: Body, acts: Act[]): void {
503 if (c.carrying && acts[0]?.kind !== 'trip') dropBrick(w, c)
504 c.act = null
505 c.queue = [...acts, ...c.queue.filter(a => a.kind === 'carry')]
506}
507
508export function onPrompt(w: World): void {
509 const wasAsleep = w.act?.kind === 'sleep'
510 w.lastEventAt = w.t
511 w.mode = 'work'
512 const plan = wasAsleep ? [reflex(w, 'wake')] : [reflex(w, 'alert'), reflex(w, 'hop', { n: 1, height: 2 })]
513 if (w.pile > 0) plan.push(reflex(w, 'kick'))
514 interrupt(w, w, plan)
515}
516
517/**
518 * A tool call: a brick for the pile, a read when the call only read
519 * (`isReading`), or a trip when it failed. A subagent's call goes to its mini;
520 * without one, to Clawd.
521 */
522export function onTool(w: World, isError: boolean, agentId?: string, isReading = false): void {
523 const mini = agentId === undefined ? undefined : w.minis.find(m => m.agentId === agentId && !m.isLeaving)
524 const c: Body = mini ?? w
525 if (mini) {
526 mini.lastEventAt = w.t
527 mini.tools += 1
528 } else {
529 w.lastEventAt = w.t
530 }
531 if (isError) {
532 interrupt(w, c, [reflex(w, 'trip')])
533 return
534 }
535 if (!mini && w.mode !== 'work') return
536 if (isReading) {
537 read(w, c)
538 return
539 }
540 const pending = (b: Body) => b.queue.filter(a => a.kind === 'carry').length + (b.act?.kind === 'carry' ? 1 : 0)
541 const all = bodies(w).reduce((sum, b) => sum + pending(b), 0)
542 if (pending(c) < 2 && w.pile + all < pileCapacity(w)) c.queue.push(reflex(w, 'carry'))
543}
544
545// Reads in a row make one read that ends READ_HOLD_S after the last. A read
546// cuts an act from the idle tables short (not a peek, which may be off the
547// band) and waits behind everything else.
548function read(w: World, c: Body): void {
549 if (c.act?.kind === 'read') {
550 c.act.dur = Math.max(c.act.dur ?? 0, w.t - c.act.t0 + READ_HOLD_S)
551 return
552 }
553 if (c.queue.some(a => a.kind === 'read')) return
554 const act = reflex(w, 'read', { dur: READ_HOLD_S })
555 if (c.act?.isRandom && c.act.kind !== 'peek') {
556 c.act = null
557 c.queue.unshift(act)
558 } else {
559 c.queue.push(act)
560 }
561}
562
563export function onTurnEnd(w: World, reason: string): void {
564 w.lastEventAt = w.t
565 w.mode = 'idle'
566 w.queue = w.queue.filter(a => a.kind !== 'carry')
567 if (reason === 'error') interrupt(w, w, [reflex(w, 'trip')])
568 else if (reason === 'aborted') interrupt(w, w, [reflex(w, 'look', { dur: 1.5 }), reflex(w, 'think', { dur: 1.5 })])
569 else interrupt(w, w, [reflex(w, 'celebrate')])
570}
571
572/** A subagent started: its mini runs in from an edge. None past MAX_MINIS. */
573export function spawnMini(w: World, agentId: string, title: string, kind: string): Mini | null {
574 if (w.minis.filter(m => !m.isLeaving).length >= MAX_MINIS) return null
575 const n = w.minisMade
576 w.minisMade += 1
577 const W = width(w)
578 const fromLeft = w.rand() < 0.5
579 const mini: Mini = {
580 ...newBody(`a${n + 1}`, MINI_COLORS[n % MINI_COLORS.length] ?? ORANGE, true, fromLeft ? -8 : W + 8),
581 agentId,
582 title,
583 kind,
584 since: w.t,
585 tools: 0,
586 lastEventAt: w.t,
587 isLeaving: false,
588 isGone: false,
589 }
590 mini.queue.push(reflex(w, 'run', { to: besideClawd(w, between(w, 0.1, 0.7) * W) }), reflex(w, 'alert'))
591 w.minis.push(mini)
592 return mini
593}
594
595/**
596 * Where a mini headed for x stops instead, so it stands beside Clawd rather
597 * than behind it: x moved out of Clawd's width plus MINI_GAP, to the nearer
598 * side, or to the other one when the nearer side is off the band.
599 */
600export function besideClawd(w: World, x: number): number {
601 const W = width(w)
602 const reach = clawdWidth(w) / 2 + MINI_GAP
603 if (Math.abs(x - w.x) >= reach) return x
604 const left = w.x - reach
605 const right = w.x + reach
606 const sides = x < w.x ? [left, right] : [right, left]
607 return sides.find(to => to >= 8 && to <= W - 8) ?? x
608}
609
610/** Clawd's width in sub-pixels, of its look when it wears one. */
611function clawdWidth(w: World): number {
612 const rows = shownLook(w, w)?.shapes.normal
613 return rows ? Math.max(...rows.map(r => r.length)) : SHAPES.normal.w
614}
615
616/** A subagent ended: its mini celebrates (or trips) and runs off the band. */
617export function endMini(w: World, agentId: string, reason: string): Mini | undefined {
618 const mini = w.minis.find(m => m.agentId === agentId && !m.isLeaving)
619 if (mini) leave(w, mini, reason)
620 return mini
621}
622
623function leave(w: World, mini: Mini, reason: string): void {
624 mini.isLeaving = true
625 mini.queue = []
626 w.due = w.due.filter(d => d.who !== mini.id)
627 interrupt(w, mini, [reflex(w, reason === 'answer' ? 'celebrate' : 'trip'), reflex(w, 'leave')])
628}
629
630/** True while a body wants the tall band: during a big jump and shortly after. */
631export function wantsTall(w: World): boolean {
632 return w.t < w.tallUntil
633}
634
635/** The band's height in rows that the world wants now: a row more while tall, two with the antenna on a tall look. */
636export function bandRows(w: World): number {
637 if (!wantsTall(w)) return BAND_ROWS
638 return w.antenna && shownLook(w, w)?.isTall ? ANTENNA_ROWS : TALL_ROWS
639}
640
641/** `/clawd [who] <act> [n]`: do it now, `n` times in a row; false when `who` is not there. */
642export function perform(w: World, what: Playable, n = 1, who = 'clawd'): boolean {
643 const c = bodyOf(w, who)
644 if (!c) return false
645 if (c === w) w.lastEventAt = w.t
646 interrupt(w, c, Array.from({ length: n }, () => actFor(w, what)))
647 return true
648}
649
650/**
651 * A model's calls, like parallel tool calls: each named body (or 'all') plays
652 * its calls in the order given, starting at the smallest `delay` (0 to 5 s)
653 * among them. At its time a call cuts in on what the body does, except a
654 * reaction to a session event, which it waits for. Calls replace a body's
655 * earlier calls still waiting. Answers the ids that got calls.
656 */
657export function callActs(w: World, calls: Call[]): string[] {
658 const slots = new Map<string, { at: number; acts: Act[] }>()
659 for (const call of calls) {
660 const targets = call.who === 'all' ? bodies(w).filter(b => bodyOf(w, b.id)) : [bodyOf(w, call.who)]
661 const at = w.t + Math.min(MAX_DELAY_S, Math.max(0, Number.isFinite(call.delay) ? call.delay : 0))
662 for (const b of targets) {
663 if (!b) continue
664 const slot = slots.get(b.id) ?? { at, acts: [] }
665 slot.at = Math.min(slot.at, at)
666 slot.acts.push(actFor(w, call.what, { isPick: true }))
667 slots.set(b.id, slot)
668 }
669 }
670 w.due = w.due.filter(d => !slots.has(d.who))
671 for (const [who, slot] of slots) {
672 const b = bodyOf(w, who)
673 if (b) b.queue = b.queue.filter(a => !a.isPick)
674 w.due.push({ at: slot.at, who, acts: slot.acts })
675 }
676 startDue(w)
677 return [...slots.keys()]
678}
679
680// Starts the calls whose time has come.
681function startDue(w: World): void {
682 if (!w.due.some(d => d.at <= w.t + 1e-9)) return
683 const now = w.due.filter(d => d.at <= w.t + 1e-9)
684 w.due = w.due.filter(d => d.at > w.t + 1e-9)
685 for (const d of now) {
686 const b = bodyOf(w, d.who)
687 if (!b) continue
688 // Reactions to session events go first, bricks to fetch after the call.
689 const ahead = b.queue.filter(a => a.isReflex && a.kind !== 'carry')
690 const after = b.queue.filter(a => !a.isPick && !(a.isReflex && a.kind !== 'carry'))
691 b.queue = [...ahead, ...d.acts, ...after]
692 if (!b.act?.isReflex && ahead.length === 0) b.act = null
693 }
694}
695
696export function isAsleep(w: World): boolean {
697 return w.act?.kind === 'sleep'
698}
699
700/** The text with only characters one cell wide (Latin-1 and Latin Extended). */
701export function clean(text: string): string {
702 return text.replace(/[^\x20-\x7e -ɏ]/g, '')
703}
704
705/** The line at the top right of the band; only characters one cell wide. */
706export function setLabel(w: World, label: string | LabelPart[]): void {
707 const parts = typeof label === 'string' ? [{ text: label, color: LABEL }] : label
708 w.label = parts.map(p => ({ text: clean(p.text), color: p.color })).filter(p => p.text)
709 const first = w.label[0]
710 if (first) first.text = first.text.trimStart()
711 const last = w.label[w.label.length - 1]
712 if (last) last.text = last.text.trimEnd()
713}
714
715/** The floor as the top edge of the `/clawd` menu: the title in the terminal's colour, the note dim; null for the plain floor. */
716export function setEdge(w: World, title: string | null, note = ''): void {
717 if (title === null) w.edge = null
718 else w.edge = [{ text: clean(title), color: DEFAULT }, { text: note ? clean(` · ${note}`) : '', color: LABEL }].filter(p => p.text)
719}
720
721/**
722 * The label for a model's calls: `clawd: wave · a1: hop+peek`, each part in
723 * its body's colour, then `note` in grey.
724 */
725export function callLabel(w: World, calls: { who: string; name: string }[], note = ''): void {
726 const byWho = new Map<string, string[]>()
727 for (const c of calls) byWho.set(c.who, [...(byWho.get(c.who) ?? []), c.name])
728 const parts: LabelPart[] = []
729 for (const [who, names] of byWho) {
730 if (parts.length > 0) parts.push({ text: ' · ', color: LABEL })
731 const b = who === 'all' ? undefined : w.minis.find(m => m.id === who) ?? (who === 'clawd' ? w : undefined)
732 parts.push({ text: `${who}: ${names.join('+')}`, color: b?.color ?? LABEL })
733 }
734 // Without calls, a note starts the label, so it loses its leading ` · `.
735 if (note) parts.push({ text: parts.length > 0 ? note : note.replace(/^ · /, ''), color: LABEL })
736 setLabel(w, parts)
737}
738
739function actFor(w: World, what: Playable, extra: Partial<Act> = {}): Act {
740 if (typeof what === 'string') return make(w, what, extra)
741 if ('steps' in what) return make(w, 'routine', { routine: what.name, steps: what.steps, ...extra })
742 return make(w, 'emote', { emote: what, ...extra })
743}
744
745/**
746 * Checks a routine a model wrote: a snake_case name, a title, and 1 to 12
747 * steps of known acts. Numbers are clamped and unknown fields dropped; the
748 * answer is the routine, or what is wrong with it.
749 */
750export function routineFrom(raw: unknown): Routine | string {
751 if (typeof raw !== 'object' || raw === null) return 'not an object'
752 const r = raw as Record<string, unknown>
753 const name = typeof r.name === 'string' ? r.name : ''
754 if (!/^[a-z][a-z0-9_]{1,30}$/.test(name)) return `bad name ${JSON.stringify(r.name)}`
755 if ((ACTS as readonly string[]).includes(name) || STEP_KINDS.includes(name as ActKind)) return `${name} is a built-in act`
756 const title = typeof r.title === 'string' ? r.title.trim().slice(0, 80) : ''
757 if (!title) return 'no title'
758 if (!Array.isArray(r.steps) || r.steps.length === 0) return 'no steps'
759 const steps: Step[] = []
760 for (const raw of r.steps.slice(0, MAX_STEPS)) {
761 const s = (typeof raw === 'object' && raw !== null ? raw : {}) as Record<string, unknown>
762 const kind = s.do as ActKind
763 if (!STEP_KINDS.includes(kind)) return `unknown step ${JSON.stringify(s.do)}`
764 const num = (v: unknown, lo: number, hi: number) =>
765 typeof v === 'number' && Number.isFinite(v) ? Math.min(hi, Math.max(lo, v)) : undefined
766 const one = <T>(v: unknown, from: readonly T[]) => (from.includes(v as T) ? (v as T) : undefined)
767 const step: Step = { do: kind }
768 const set = <K extends keyof Step>(key: K, value: Step[K] | undefined) => {
769 if (value !== undefined) step[key] = value
770 }
771 set('to', num(s.to, 0, 1))
772 set('dir', s.dir === -1 || s.dir === 1 ? s.dir : undefined)
773 set('n', num(s.n, 1, kind === 'sparks' ? 8 : 3))
774 set('height', num(s.height, 1, 6))
775 set('dur', kind === 'emote' ? num(s.dur, 1, 20) : num(s.dur, 0.2, 4))
776 set('arms', one(s.arms, ARMS))
777 set('eyes', one(s.eyes, EYES))
778 set('shape', one(s.shape, SHAPE_NAMES))
779 set('look', s.look === -1 || s.look === 0 || s.look === 1 ? s.look : undefined)
780 set('up', typeof s.up === 'boolean' ? s.up : undefined)
781 set('sit', typeof s.sit === 'boolean' ? s.sit : undefined)
782 set('sparks', typeof s.sparks === 'boolean' ? s.sparks : undefined)
783 set('wrap', typeof s.wrap === 'boolean' ? s.wrap : undefined)
784 set('speed', s.speed === 'walk' || s.speed === 'run' ? s.speed : num(s.speed, 0.25, 4))
785 set('ease', typeof s.ease === 'boolean' ? s.ease : undefined)
786 if (kind === 'mark') {
787 if (typeof s.glyph !== 'string' || !(s.glyph in MARKS)) return `bad glyph ${JSON.stringify(s.glyph)}`
788 step.glyph = s.glyph
789 }
790 if (kind === 'emote' || kind === 'play') {
791 if (typeof s.name !== 'string' || !/^[a-z][a-z0-9_]{1,30}$/.test(s.name)) return `bad ${kind} name ${JSON.stringify(s.name)}`
792 if (kind === 'play' && s.name === name) return `${name} plays itself`
793 step.name = s.name
794 }
795 steps.push(step)
796 }
797 return { name, title, steps }
798}
799
800const EMOTE_MAX_W = 20 // sub-pixels, the arms come on top
801// Clawd's arms: [dx, dy] from the body's edge on the arm row.
802const CLAWD_ARMS: Record<ArmPose, [number, number][]> = {
803 out: [[1, 0], [2, 0]],
804 up: [[1, -1], [2, -2]],
805 down: [[1, 1]],
806 raised: [[1, -1], [1, -2]],
807}
808// High with the legs, so a sub-pixel stays free above the head: in the 4-row
809// band, and in the 5-row band for a tall emote.
810const EMOTE_MAX_H = 6
811const TALL_EMOTE_MAX_H = 8
812const PROP_MAX_W = 8
813const PROP_MAX_KEYS = 8
814const PROP_MAX_Y = 24 // sub-pixels; past about 10 the prop has left the band
815const TOOL_MAX_W = 8
816const TOOL_MAX_H = 4
817
818const colorOf = (v: unknown) => (typeof v === 'string' && /^#[0-9a-fA-F]{6}$/.test(v) ? Number.parseInt(v.slice(1), 16) : undefined)
819
820// Rows of pixel characters: only the `marks` count, the rest become `.`, and
821// empty rows above and below go.
822function pixelRows(v: unknown, marks: string): string[] | undefined {
823 if (!Array.isArray(v) || !v.every(line => typeof line === 'string')) return undefined
824 const other = new RegExp(`[^${marks}]`, 'g')
825 const lines = (v as string[]).map(line => line.replace(other, '.'))
826 const isEmpty = (line: string | undefined) => line !== undefined && !/[^.]/.test(line)
827 while (isEmpty(lines[0])) lines.shift()
828 while (isEmpty(lines[lines.length - 1])) lines.pop()
829 return lines.length > 0 ? lines : undefined
830}
831
832/** Checks an emote's prop; the prop, or what is wrong with it. */
833function propOf(raw: unknown, isTall: boolean, dur: number, accent: number): Prop | string {
834 if (typeof raw !== 'object' || raw === null) return 'not an object'
835 const r = raw as Record<string, unknown>
836 const rows = pixelRows(r.rows, '#+')
837 if (!rows) return 'no rows'
838 const wide = Math.max(...rows.map(line => line.length))
839 if (wide > PROP_MAX_W) return `rows are ${wide} wide, at most ${PROP_MAX_W}`
840 const maxH = isTall ? TALL_EMOTE_MAX_H : EMOTE_MAX_H
841 if (rows.length > maxH) return `rows are ${rows.length} high, at most ${maxH}`
842 const color = r.color === undefined ? accent : colorOf(r.color)
843 if (color === undefined) return `bad color ${JSON.stringify(r.color)}, want #rrggbb`
844 const num = (v: unknown) => (typeof v === 'number' && Number.isFinite(v) ? v : undefined)
845 const keys = Array.isArray(r.path) ? r.path : []
846 if (keys.length === 0) return 'no path'
847 if (keys.length > PROP_MAX_KEYS) return `path has ${keys.length} keys, at most ${PROP_MAX_KEYS}`
848 const path: PropKey[] = []
849 for (const key of keys) {
850 const k = (typeof key === 'object' && key !== null ? key : {}) as Record<string, unknown>
851 const t = num(k.t)
852 const y = num(k.y)
853 if (t === undefined || y === undefined) return 'a path key needs t and y'
854 if (t < 0 || t > dur) return `path t ${t} is outside 0 to dur (${dur})`
855 if (t < (path[path.length - 1]?.t ?? 0)) return 'path keys are not in time order'
856 path.push({ t, x: Math.min(40, Math.max(-40, num(k.x) ?? 0)), y: Math.min(PROP_MAX_Y, Math.max(0, y)) })
857 }
858 const x = Math.min(30, Math.max(-30, Math.round(num(r.x) ?? -12)))
859 return { rows, color, x, path, hasTrail: r.trail === true }
860}
861
862/** Checks an emote's tool; the tool, or what is wrong with it. */
863function toolOf(raw: unknown, accent: number): Tool | string {
864 if (typeof raw !== 'object' || raw === null) return 'not an object'
865 const r = raw as Record<string, unknown>
866 const rows = pixelRows(r.rows, '#+')
867 if (!rows) return 'no rows'
868 const wide = Math.max(...rows.map(line => line.length))
869 if (wide > TOOL_MAX_W) return `rows are ${wide} wide, at most ${TOOL_MAX_W}`
870 if (rows.length > TOOL_MAX_H) return `rows are ${rows.length} high, at most ${TOOL_MAX_H}`
871 const color = r.color === undefined ? accent : colorOf(r.color)
872 if (color === undefined) return `bad color ${JSON.stringify(r.color)}, want #rrggbb`
873 return { rows, color }
874}
875
876/** A look's snake_case name that is no built-in act, and its title; or what is wrong with them. */
877function nameOf(r: Record<string, unknown>): { name: string; title: string } | string {
878 const name = typeof r.name === 'string' ? r.name : ''
879 if (!/^[a-z][a-z0-9_]{1,30}$/.test(name)) return `bad name ${JSON.stringify(r.name)}`
880 if ((ACTS as readonly string[]).includes(name) || STEP_KINDS.includes(name as ActKind)) return `${name} is a built-in act`
881 const title = typeof r.title === 'string' ? r.title.trim().slice(0, 80) : ''
882 if (!title) return 'no title'
883 return { name, title }
884}
885
886/**
887 * Checks a skin from a file or a model: a snake_case name that is no
888 * built-in act, a title, a colour, and a normal shape that fits the band.
889 * Shapes it leaves out are the normal one; numbers are clamped. The answer is
890 * the skin, or what is wrong with it.
891 */
892export function skinFrom(raw: unknown): Skin | string {
893 if (typeof raw !== 'object' || raw === null) return 'not an object'
894 const r = raw as Record<string, unknown>
895 const named = nameOf(r)
896 if (typeof named === 'string') return named
897 const { name, title } = named
898 const color = colorOf(r.color)
899 if (color === undefined) return `bad color ${JSON.stringify(r.color)}, want #rrggbb`
900 const raws = (typeof r.shapes === 'object' && r.shapes !== null ? r.shapes : {}) as Record<string, unknown>
901 // Only body, eye and accent pixels count.
902 const rowsOf = (v: unknown) => pixelRows(v, '#o+')
903 const normal = rowsOf(raws.normal)
904 if (!normal) return 'no normal shape'
905 const legLength = typeof r.legLength === 'number' && Number.isFinite(r.legLength) ? Math.min(3, Math.max(0, Math.round(r.legLength))) : 1
906 const isTall = r.tall === true
907 const maxH = isTall ? TALL_EMOTE_MAX_H : EMOTE_MAX_H
908 const shapes = { normal } as Record<Shape, string[]>
909 for (const shape of SHAPE_NAMES) {
910 const lines = shape === 'normal' ? normal : (rowsOf(raws[shape]) ?? normal)
911 const wide = Math.max(...lines.map(line => line.length))
912 if (wide > EMOTE_MAX_W) return `${shape} is ${wide} wide, at most ${EMOTE_MAX_W}`
913 const high = lines.length + (shape === 'normal' || shape === 'stretch' ? legLength : 0)
914 if (high > maxH) return `${shape} is ${high} high with its legs, at most ${maxH}${isTall ? '' : ' (8 with "tall": true)'}`
915 shapes[shape] = lines
916 }
917 const nw = Math.max(...normal.map(line => line.length))
918 const legs = (Array.isArray(r.legs) ? r.legs : [])
919 .filter((x): x is number => typeof x === 'number' && Number.isInteger(x) && x >= 0 && x < nw)
920 .slice(0, 8)
921 const armRow = typeof r.armRow === 'number' && Number.isInteger(r.armRow) && r.armRow >= 0 && r.armRow < normal.length ? r.armRow : null
922 // Arm poses the file gives replace Clawd's: up to 4 pixels each, within 3 of the edge, in one
923 // line: the first touches the edge, each next one the one before. Any other pose keeps Clawd's,
924 // since a fork drawn as a tool reads as horns or a tail.
925 const arms = (typeof r.arms === 'object' && r.arms !== null ? r.arms : {}) as Record<string, unknown>
926 const armPoses = { ...CLAWD_ARMS }
927 for (const pose of Object.keys(CLAWD_ARMS) as ArmPose[]) {
928 const v = arms[pose]
929 if (!Array.isArray(v)) continue
930 const pixels = v
931 .filter(
932 (p): p is [number, number] =>
933 Array.isArray(p) && p.length === 2 && p.every(n => Number.isInteger(n) && Math.abs(n) <= 3),
934 )
935 .slice(0, 4)
936 const isLine = pixels.every(([dx, dy], i) => {
937 const [px, py] = pixels[i - 1] ?? [0, 0]
938 return Math.abs(dx - px) <= 1 && Math.abs(dy - py) <= 1
939 })
940 if (pixels.length > 0 && isLine) armPoses[pose] = pixels
941 }
942 const accent = colorOf(r.accent) ?? WHITE
943 return { name, title, color, accent, shapes, legs, legLength, isWiggly: r.wiggle === true, armRow, armPoses, isTall }
944}
945
946/**
947 * Checks an emote from a file or a model: a time, and a body as a skin has
948 * (with `shapes`), a prop, a tool, or several of them. Without shapes Clawd
949 * keeps the body it has. The answer is the emote, or what is wrong with it.
950 */
951export function emoteFrom(raw: unknown): Emote | string {
952 if (typeof raw !== 'object' || raw === null) return 'not an object'
953 const r = raw as Record<string, unknown>
954 const named = nameOf(r)
955 if (typeof named === 'string') return named
956 const body = r.shapes === undefined || r.shapes === null ? null : skinFrom(r)
957 if (typeof body === 'string') return body
958 const accent = body?.accent ?? colorOf(r.accent) ?? WHITE
959 const isTall = r.tall === true
960 const dur = typeof r.dur === 'number' && Number.isFinite(r.dur) ? Math.min(20, Math.max(3, r.dur)) : 8
961 const prop = r.prop === undefined || r.prop === null ? null : propOf(r.prop, isTall, dur, accent)
962 if (typeof prop === 'string') return `prop: ${prop}`
963 const tool = r.tool === undefined || r.tool === null ? null : toolOf(r.tool, accent)
964 if (typeof tool === 'string') return `tool: ${tool}`
965 if (!body && !prop && !tool) return 'no shapes, prop or tool: an emote changes the body, adds a thing, or both'
966 return { ...named, accent, isTall, body, dur, prop, tool }
967}
968
969/** A skin worn for a while, as an act's emote step may ask: an emote with the skin's body and nothing else. */
970export function skinAsEmote(skin: Skin): Emote {
971 return { name: skin.name, title: skin.title, accent: skin.accent, isTall: skin.isTall, body: skin, dur: 8, prop: null, tool: null }
972}
973
974/**
975 * Whether an emote's body is a copy of Clawd's own: the logo's normal shape
976 * in about its orange. A model that draws a thing to hold tends to copy the
977 * body along with it, and the copy then hides any skin (three emotes had one
978 * until 2026-10-08). A recoloured Clawd is not a copy.
979 */
980export function isClawdCopy(look: Emote): boolean {
981 if (!look.body) return false
982 const { w, h, eyes, eyeRow } = SHAPES.normal
983 const own = Array.from({ length: h }, (_, r) => Array.from({ length: w }, (_, x) => (r === eyeRow && eyes.includes(x) ? 'o' : '#')).join(''))
984 const near = (a: number, b: number) => [16, 8, 0].every(k => Math.abs(((a >> k) & 255) - ((b >> k) & 255)) <= 24)
985 return JSON.stringify(look.body.shapes.normal) === JSON.stringify(own) && near(look.body.color, ORANGE)
986}
987
988/** The colour of an emote's puff: its body's, else its tool's or prop's. */
989function emoteColor(look: Emote): number {
990 return look.body?.color ?? look.tool?.color ?? look.prop?.color ?? look.accent
991}
992
993const hex = (n: number) => `#${n.toString(16).padStart(6, '0')}`
994
995/** A skin as JSON, the way skinFrom reads it. */
996export function skinJson(look: Skin): Record<string, unknown> {
997 return {
998 name: look.name,
999 title: look.title,
1000 color: hex(look.color),
1001 accent: hex(look.accent),
1002 shapes: look.shapes,
1003 legs: look.legs,
1004 legLength: look.legLength,
1005 wiggle: look.isWiggly,
1006 armRow: look.armRow,
1007 arms: look.armPoses,
1008 tall: look.isTall,
1009 }
1010}
1011
1012/** An emote as JSON, the way emoteFrom reads it. */
1013export function emoteJson(look: Emote): Record<string, unknown> {
1014 const head = look.body ? skinJson(look.body) : { name: look.name, title: look.title, accent: hex(look.accent), tall: look.isTall }
1015 return {
1016 ...head,
1017 dur: look.dur,
1018 ...(look.prop
1019 ? { prop: { rows: look.prop.rows, color: hex(look.prop.color), x: look.prop.x, path: look.prop.path, trail: look.prop.hasTrail } }
1020 : {}),
1021 ...(look.tool ? { tool: { rows: look.tool.rows, color: hex(look.tool.color) } } : {}),
1022 }
1023}
1024
1025/**
1026 * Fills in what a routine's emote and play steps name; `find` answers a made
1027 * act or an emote by name. The played act's own play steps are dropped, so
1028 * acts play each other one level deep. A step whose name finds nothing, or
1029 * the wrong kind, stays empty and plays nothing.
1030 */
1031export function linkRoutine<R extends Routine>(r: R, find: (name: string) => Playable | undefined, isInner = false): R {
1032 const steps = r.steps.map(s => {
1033 if (s.do !== 'emote' && s.do !== 'play') return s
1034 const step: Step = { ...s }
1035 delete step.worn
1036 delete step.inner
1037 const found = s.name ? find(s.name) : undefined
1038 if (typeof found !== 'object') return step
1039 if (s.do === 'emote' && !('steps' in found)) step.worn = found
1040 if (s.do === 'play' && !isInner && 'steps' in found) step.inner = linkRoutine(found, find, true).steps
1041 return step
1042 })
1043 return { ...r, steps }
1044}
1045
1046/** A routine's steps as acts, in the units the acts use; a play step becomes the acts of the steps it plays. */
1047function stepActs(w: World, a: Act, steps = a.steps ?? [], outer?: { step: number; via: string }): Act[] {
1048 return steps.flatMap((s, i) => {
1049 if (s.do === 'play') return outer || !s.inner ? [] : stepActs(w, a, s.inner, { step: i + 1, via: s.name ?? '' })
1050 if (s.do === 'emote' && !s.worn) return []
1051 const act = make(w, s.do, { routine: a.routine, step: outer?.step ?? i + 1, isPick: a.isPick, isReflex: a.isReflex })
1052 if (outer) act.via = outer.via
1053 if (s.worn) act.emote = s.worn
1054 const isMove = s.do === 'wander' || s.do === 'run' || s.do === 'move'
1055 if (s.to !== undefined && isMove) act.to = s.to * width(w)
1056 if (s.dir !== undefined && s.do === 'jump') act.to = s.dir
1057 if (s.wrap && (s.do === 'run' || s.do === 'move')) {
1058 act.wrap = true
1059 if (s.dir !== undefined) act.dir = s.dir
1060 }
1061 if (s.speed !== undefined && isMove) act.speed = s.speed === 'walk' ? WALK : s.speed === 'run' ? RUN : s.speed * WALK
1062 if (s.ease && isMove) act.ease = true
1063 if (s.n !== undefined) act.n = Math.round(s.n)
1064 if (s.height !== undefined) act.height = s.height
1065 if (s.dur !== undefined) act.dur = s.dur
1066 if (s.arms) act.arms = s.arms
1067 if (s.eyes) act.eyes = s.eyes
1068 if (s.shape) act.shape = s.shape
1069 if (s.look !== undefined) act.gaze = s.look
1070 if (s.up) act.lookUp = true
1071 if (s.sit) act.sit = true
1072 if (s.sparks) act.sparks = true
1073 if (s.glyph) act.glyph = s.glyph
1074 return [act]
1075 })
1076}
1077
1078// --- the tick --------------------------------------------------------------------
1079
1080export function step(w: World): void {
1081 w.t += DT
1082 startDue(w)
1083 for (const c of bodies(w)) {
1084 c.arms = 'out'
1085 c.eyes = 'open'
1086 c.look = 0
1087 c.lookUp = false
1088 c.shape = null
1089 c.sitting = false
1090 c.frontLeg = 'down'
1091 c.reading = false
1092 if (!isAirborne(c)) c.vx = 0
1093 const isNew = c.act === null
1094 let act = (c.act ??= nextAct(w, c))
1095 // An act that ends in the tick it starts (a mark, sparks, a routine or
1096 // another macro) hands the tick on to the next queued act, so no frame
1097 // shows the neutral pose between two steps. A random act waits for the
1098 // next tick, so a finished routine still leaves the body free for a tick.
1099 for (let n = 0; ; n++) {
1100 if (isBigJump(act)) w.tallUntil = w.t + TALL_HOLD_S
1101 const isDone = runAct(w, c, act)
1102 if (isDone) c.act = null
1103 if (!isDone || !isNew || c.queue.length === 0 || n >= 4 * MAX_STEPS) break
1104 act = c.act = nextAct(w, c)
1105 }
1106 overlay(c, act)
1107 physics(w, c)
1108 if (c.wearing?.prop) moveProp(w, c, c.wearing.prop)
1109 if (c.wearing && w.t >= c.wornUntil && !isAirborne(c)) {
1110 puff(w, c, emoteColor(c.wearing))
1111 const prop = c.wearing.prop
1112 if (prop) {
1113 // A prop left on the floor breaks apart like a mined block; one still in the air goes in a puff.
1114 const box = propBox(w, c, prop)
1115 if (box.bottom >= ground(w)) breakProp(w, c, c.wearing, prop)
1116 else if (box.bottom >= 0) puffAt(w, box.left + box.width / 2, box.bottom - box.height + 1, box.height, box.width / 2 + 2, prop.color)
1117 }
1118 c.wearing = null
1119 }
1120 // A tall look keeps the band tall; a tall skin all the time, so the prompt does not move between looks.
1121 if (c.wearing?.isTall || shownLook(w, c)?.isTall) w.tallUntil = w.t + TALL_HOLD_S
1122 }
1123 if (w.antenna) w.tallUntil = w.t + TALL_HOLD_S // the antenna's tip needs the second row of headroom
1124 moveParticles(w)
1125 moveSpark(w)
1126 for (const c of bodies(w)) {
1127 if (w.t > c.blinkAt + 0.12) c.blinkAt = w.t + between(w, 2, 6)
1128 }
1129 for (const m of w.minis) {
1130 if (!m.isLeaving && w.t - m.lastEventAt > MINI_STALE_S) leave(w, m, 'stale')
1131 }
1132 w.minis = w.minis.filter(m => !m.isGone)
1133}
1134
1135const WORK_TABLE: [ActKind, number][] = [['wander', 22], ['run', 18], ['think', 18], ['look', 10], ['idle', 10], ['hop', 6], ['jump', 6], ['chase', 4], ['peek', 3], ['wave', 3]]
1136const IDLE_TABLE: [ActKind, number][] = [['wander', 28], ['idle', 26], ['look', 10], ['wave', 5], ['hop', 6], ['jump', 5], ['run', 7], ['chase', 6], ['peek', 4], ['think', 3]]
1137const MINI_TABLE: [ActKind, number][] = [['wander', 28], ['think', 18], ['idle', 16], ['look', 12], ['run', 10], ['hop', 8], ['jump', 4], ['wave', 4]]
1138
1139function nextAct(w: World, c: Body): Act {
1140 const queued = c.queue.shift()
1141 if (queued) return { ...queued, t0: w.t, stage: 0 }
1142 if (!c.isMini && w.mode === 'idle' && w.t - w.lastEventAt > SLEEP_AFTER_S) return make(w, 'sleep')
1143 const table = c.isMini ? MINI_TABLE : w.mode === 'work' ? WORK_TABLE : IDLE_TABLE
1144 let roll = w.rand() * table.reduce((sum, [, weight]) => sum + weight, 0)
1145 for (const [kind, weight] of table) {
1146 roll -= weight
1147 if (roll <= 0) return make(w, kind, { isRandom: true })
1148 }
1149 return make(w, 'idle', { isRandom: true })
1150}
1151
1152// The jump act, the sparkle chase and the turn-end hops get the tall band.
1153function isBigJump(a: Act): boolean {
1154 return a.kind === 'jump' || a.kind === 'chase' || (a.kind === 'hop' && a.sparks === true)
1155}
1156
1157/**
1158 * A routine step's arms, eyes, look and up win over what its act set: the
1159 * upper-body layer of a layered animation (ANIMATION.md, S1).
1160 */
1161function overlay(c: Body, a: Act): void {
1162 if (a.arms) c.arms = a.arms
1163 if (a.eyes) c.eyes = a.eyes
1164 if (a.gaze !== undefined) c.look = a.gaze
1165 if (a.lookUp) c.lookUp = true
1166}
1167
1168/**
1169 * Reynolds' arrive: from a stand the speed grows to full in EASE_S, and near
1170 * the target it falls so that a constant braking stops it there in EASE_S.
1171 * `e` is the time since the move started.
1172 */
1173function eased(speed: number, e: number, gap: number, isStart: boolean, isEnd: boolean): number {
1174 const rate = speed / EASE_S
1175 let v = speed
1176 if (isStart) v = Math.min(v, rate * (e + DT))
1177 if (isEnd) v = Math.min(v, Math.sqrt(2 * rate * Math.abs(gap)))
1178 return v
1179}
1180
1181/** Moves towards `to`; true once there. */
1182function moveTo(c: Body, to: number, speed: number): boolean {
1183 const gap = to - c.x
1184 c.look = 1 // on the arriving tick too, so the eyes do not snap to the middle for a frame
1185 if (Math.abs(gap) <= speed * DT) {
1186 c.x = to
1187 return true
1188 }
1189 c.vx = Math.sign(gap) * speed
1190 return false
1191}
1192
1193function jumpUp(w: World, c: Body, height: number): void {
1194 const room = roomAbove(w, c)
1195 // The half step makes up for what the stepwise integration loses, so the
1196 // apex reaches `height` instead of half a sub-pixel below it.
1197 if (room > 0) c.vy = Math.sqrt(2 * GRAVITY * Math.max(0.5, Math.min(height, room))) + (GRAVITY * DT) / 2
1198}
1199
1200function nextStage(w: World, a: Act): void {hooks/clawd-context.ts 77 lines1/**
2 * What `/clawd debug` shows of an autopick's request. Pure, no `$`.
3 *
4 * A `$.ui.log` row takes no colour, so a label leads each line instead. A part
5 * of the request is shown in full the first time and whenever it changed; after
6 * that it is left out and named. This diff is against what was shown, not the
7 * API's prompt cache: the prompt starts with the session summary, which changes
8 * at every pick, so that cache can serve the system prompt at most. The header
9 * row gives the real cache counts.
10 */
11
12/** One part of a picker request: the system prompt, a `<tag>` block of the prompt, or the text around them. */
13export type Part = { name: string; text: string }
14
15/**
16 * Splits a request into `system`, each `<tag>...</tag>` block of the prompt
17 * (named by its tag), and `instructions` for each run of lines outside a block.
18 * A name that comes twice gets a number, so every part has its own.
19 */
20export function contextParts(system: string, prompt: string): Part[] {
21 const parts: Part[] = [{ name: 'system', text: system }]
22 const lines = prompt.split('\n')
23 let rest: string[] = []
24 const add = (name: string, text: string) => {
25 const n = parts.filter(p => p.name === name || p.name.startsWith(`${name} `)).length
26 parts.push({ name: n ? `${name} ${n + 1}` : name, text })
27 }
28 for (let i = 0; i < lines.length; i++) {
29 const tag = /^<([a-z_]+)>/.exec(lines[i] ?? '')?.[1]
30 const end = tag ? lines.findIndex((l, j) => j >= i && l.includes(`</${tag}>`)) : -1
31 if (!tag || end < 0) {
32 rest.push(lines[i] ?? '')
33 continue
34 }
35 if (rest.length) add('instructions', rest.join('\n'))
36 rest = []
37 add(tag, lines.slice(i, end + 1).join('\n'))
38 i = end
39 }
40 if (rest.length) add('instructions', rest.join('\n'))
41 return parts
42}
43
44function chars(n: number): string {
45 return n < 1000 ? `${n} chars` : `${(n / 1000).toFixed(1)}k chars`
46}
47
48/**
49 * The rows for one pick. First a line naming the parts shown and the parts left
50 * out because they are as last shown, with their size. Then every line of each
51 * part shown, led by `new` or, for a line the part already had when it was last
52 * shown, `same`. `shown` holds the text last shown per part and is updated.
53 */
54export function contextRows(parts: Part[], shown: Map<string, string>): string[] {
55 const fresh = parts.filter(p => shown.get(p.name) !== p.text)
56 const kept = parts.filter(p => shown.get(p.name) === p.text)
57 const head = ['context']
58 if (fresh.length === parts.length) head.push(`all ${parts.length} parts`)
59 else head.push(fresh.length ? `shown: ${fresh.map(p => p.name).join(', ')}` : 'nothing new')
60 if (kept.length) {
61 const size = kept.reduce((n, p) => n + p.text.length, 0)
62 head.push(`left out, as shown before: ${kept.map(p => p.name).join(', ')} (${chars(size)})`)
63 }
64 if (fresh.some(p => p.name === 'system')) head.push("the CLI's identity block sent before the system prompt is not visible to a mod")
65 const rows = [head.join(' · ')]
66 for (const p of fresh) {
67 const before = new Set(shown.get(p.name)?.split('\n') ?? [])
68 const lines = p.text.split('\n')
69 lines.forEach((line, i) => {
70 const text = p.name === 'system' && i === 0 ? `system: ${line}` : line
71 rows.push(`${before.has(line) ? 'same' : 'new '} │ ${text}`)
72 })
73 shown.set(p.name, p.text)
74 }
75 return rows
76}
77hooks/clawd-words.ts 460 lines1// `/clawd` as typed. A word may be cut short while it fits one name
2// (`/clawd cel` plays celebrate). While the person types, a framed list
3// above the prompt shows the names the word at the cursor fits (`menuFor`),
4// the words are painted green (fits one name) or red (fits none), and a space
5// after a word that fits one name writes it out. Tab never reaches a plugin, so
6// the space does its job. Pure, no `$`: register.tsx passes the names in and
7// draws what comes back.
8
9export const MAX_REPEAT = 5 // `/clawd jump 3`: at most this many in a row
10
11/** The words `/clawd` takes besides acts, emotes and minis, with what each does. */
12export const COMMANDS: Readonly<Record<string, string>> = {
13 help: 'what Clawd plays and every command; help uml draws it',
14 act: 'Clawd plays an act: a move such as jump or wave; act create, change, delete, preview',
15 emote: "Clawd takes an emote's look for a while; emote create, change, delete, preview",
16 skin: "Clawd's body for this session: a skin, auto or none; skin create, change, delete, preview",
17 list: 'the names of one kind: acts, made, emotes, skins or minis',
18 on: 'show Clawd (remembered)',
19 off: 'hide Clawd (remembered)',
20 autopick: 'switch the model picker on or off; now picks once; haiku (default), sonnet or opus sets its model',
21 trace: 'switch writing each autopick to a file on or off',
22 debug: "switch showing each autopick's request and whole reply here on or off",
23}
24/**
25 * Acts, emotes and skins take the same four commands, create, change, delete
26 * and preview; a skin has auto and none besides. No act, emote or
27 * skin may take one of these names.
28 */
29export type MadeKind = 'act' | 'emote' | 'skin'
30/** What `/clawd act` takes besides an act's name. change and delete take a made act only: a built-in act is code. */
31export const ACT_COMMANDS: Readonly<Record<string, string>> = {
32 create: 'a model writes a new act (uses your Claude usage)',
33 change: "a model changes a made act's steps, or with no words writes it again from scratch (uses your Claude usage); edit and modify work too",
34 delete: 'remove a made act; the file goes to acts/old/',
35 preview: 'a PNG of an act, the band every half second while it plays',
36}
37/**
38 * What `/clawd emote` takes besides an emote's name.
39 */
40export const EMOTE_COMMANDS: Readonly<Record<string, string>> = {
41 create: 'a model draws a new emote (uses your Claude usage)',
42 change: "a model changes an emote's look, or with no words draws it again from scratch (uses your Claude usage); edit and modify work too",
43 delete: 'remove an emote; the file goes to emotes/old/',
44 preview: 'a PNG of an emote in every pose',
45}
46/** What `/clawd skin` takes besides a skin's name. */
47export const SKIN_COMMANDS: Readonly<Record<string, string>> = {
48 auto: 'the skin clawd.json or the project folder gives; the default',
49 none: "Clawd's own body for this session",
50 create: 'a model draws a new skin (uses your Claude usage)',
51 change: "a model changes a skin's look, or with no words draws it again from scratch (uses your Claude usage); edit and modify work too",
52 delete: 'remove a skin; the file goes to skins/old/',
53 preview: 'a PNG of a skin in every pose',
54}
55/** What `/clawd list` takes. */
56export const LIST_KINDS = {
57 acts: 'the built-in acts',
58 made: 'acts a model wrote',
59 emotes: 'looks Clawd takes for a while',
60 skins: 'bodies Clawd wears all the time instead of its own',
61 minis: 'small Clawds, one per running subagent',
62} as const
63export type ListKind = keyof typeof LIST_KINDS
64/** Other words for commands, taken only in full and never offered. */
65export const ALIASES: Readonly<Record<string, string>> = { '?': 'help', ls: 'list', edit: 'change', modify: 'change' }
66const A: Record<MadeKind, string> = { act: 'an act', emote: 'an emote', skin: 'a skin' }
67/** Commands that start a model run or remove something run only when typed in full, with why. */
68function inFull(verb: string, kind: MadeKind): string {
69 return verb === 'create' || verb === 'change' ? 'it starts a model run' : verb === 'delete' ? `it removes ${A[kind]}` : ''
70}
71
72export type Kind = 'command' | 'mini' | 'emote' | 'skin' | 'made' | 'act'
73/** The names a word may take now, each with a short description, in the order offered. */
74export type Names = {
75 minis: Readonly<Record<string, string>>
76 emotes: Readonly<Record<string, string>>
77 skins: Readonly<Record<string, string>>
78 made: Readonly<Record<string, string>>
79 acts: Readonly<Record<string, string>>
80 isSkinOnly?: boolean // clawd.json names a skin, so Clawd has no body of its own: /clawd skin has no none
81}
82export type Fit = { kind: Kind; name: string; what: string }
83
84const TABLES = { mini: 'minis', emote: 'emotes', skin: 'skins', made: 'made', act: 'acts' } as const
85/** What a menu row says before the description when names of several kinds are listed. */
86const KIND_WORD: Record<Kind, string> = { command: '', mini: '', emote: 'emote', skin: 'skin', made: 'made act', act: 'act' }
87const FIRST: Kind[] = ['command', 'mini', 'emote', 'made', 'act']
88const PLAYS: Kind[] = ['act', 'made']
89const rowsOf = (rows: Readonly<Record<string, string>>): Fit[] => Object.entries(rows).map(([name, what]) => ({ kind: 'command', name, what }))
90const LIST_ROWS: Fit[] = rowsOf(LIST_KINDS)
91const TRACE_ROWS: Fit[] = [
92 { kind: 'command', name: 'on', what: 'write each autopick to a file' },
93 { kind: 'command', name: 'off', what: 'stop writing the autopicks' },
94]
95const DEBUG_ROWS: Fit[] = [
96 { kind: 'command', name: 'on', what: "each autopick's request, reply, tokens and outcome in the transcript, not sent to the model" },
97 { kind: 'command', name: 'off', what: 'stop showing them' },
98]
99const AUTOPICK_ROWS: Fit[] = [
100 { kind: 'command', name: 'now', what: 'a model chooses what plays next, once (uses your Claude usage)' },
101 { kind: 'command', name: 'on', what: 'a model chooses every 10 to 60 s (remembered; uses your Claude usage)' },
102 { kind: 'command', name: 'off', what: 'random acts only, no model calls (remembered)' },
103 { kind: 'command', name: 'haiku', what: 'Haiku picks: the default and the cheapest (remembered)' },
104 { kind: 'command', name: 'sonnet', what: 'Sonnet picks: more of your Claude usage per pick (remembered)' },
105 { kind: 'command', name: 'opus', what: 'Opus picks: the most of your Claude usage per pick (remembered)' },
106]
107const HELP_ROWS: Fit[] = [{ kind: 'command', name: 'uml', what: 'how Clawd behaves and how new acts are made, as UML' }]
108
109function table(kinds: readonly Kind[], names: Names): Fit[] {
110 const out: Fit[] = []
111 for (const kind of kinds) {
112 const rows = kind === 'command' ? COMMANDS : names[TABLES[kind]]
113 for (const [name, what] of Object.entries(rows)) if (!out.some(f => f.name === name)) out.push({ kind, name, what })
114 }
115 return out
116}
117
118/** The names a typed word fits: the name itself, else the names it starts, else those it is part of. */
119export function fitsOf(word: string, rows: readonly Fit[]): Fit[] {
120 const w = word.toLowerCase()
121 const alias = rows.find(f => f.kind === 'command' && f.name === ALIASES[w])
122 if (alias) return [{ kind: 'command', name: w, what: alias.what }]
123 const exact = rows.filter(f => f.name === w)
124 if (exact.length > 0) return exact
125 const starts = rows.filter(f => f.name.startsWith(w))
126 return starts.length > 0 ? starts : rows.filter(f => f.name.includes(w))
127}
128
129/** The names of these kinds a typed word fits. */
130export function namesFit(word: string, kinds: readonly Kind[], names: Names): Fit[] {
131 return fitsOf(word, table(kinds, names))
132}
133
134/** How `/clawd act`, `/clawd emote` and `/clawd skin` read the words after them. */
135type KindWords = {
136 verbs: Fit[] // the commands, offered before the names
137 names: readonly Kind[] // what `/clawd <kind> <name>` and preview take
138 owned: Kind // what change and delete take: the ones a file holds
139 ownedOf: string // those, as the menu names them
140 ownedList: ListKind // the `/clawd list` kind that names them
141 create: string // what follows create's new name
142 change: string // what follows change's name
143}
144const KIND_WORDS: Record<MadeKind, KindWords> = {
145 act: {
146 verbs: rowsOf(ACT_COMMANDS),
147 names: PLAYS,
148 owned: 'made',
149 ownedOf: 'made acts',
150 ownedList: 'made',
151 create: '[what it does; else the name says it]',
152 change: '[what to change; nothing writes it again]',
153 },
154 emote: {
155 verbs: rowsOf(EMOTE_COMMANDS),
156 names: ['emote'],
157 owned: 'emote',
158 ownedOf: 'emotes',
159 ownedList: 'emotes',
160 create: '[image path] [what it looks like; else the name says it]',
161 change: '[image path] [what to change; nothing draws it again]',
162 },
163 skin: {
164 verbs: rowsOf(SKIN_COMMANDS),
165 names: ['skin'],
166 owned: 'skin',
167 ownedOf: 'skins',
168 ownedList: 'skins',
169 create: '[image path] [what it looks like; else the name says it]',
170 change: '[image path] [what to change; nothing draws it again]',
171 },
172}
173const LISTED: Record<MadeKind, ListKind> = { act: 'acts', emote: 'emotes', skin: 'skins' }
174
175/** After `/clawd act`, `emote` or `skin`: its commands (a skin's none only without isSkinOnly), then the names. */
176function kindRows(kind: MadeKind, names: Names): Fit[] {
177 const words = KIND_WORDS[kind]
178 return [...words.verbs.filter(row => !(row.name === 'none' && names.isSkinOnly)), ...table(words.names, names)]
179}
180
181function onlyFit(word: string, rows: readonly Fit[]): Fit | undefined {
182 const fits = fitsOf(word, rows)
183 return fits.length === 1 ? fits[0] : undefined
184}
185
186/** What the next word may be, after the words before it; `of` names the rows' kind. */
187type Place = { rows: Fit[]; of: string } | { free: string } | { count: true } | { end: true }
188const END: Place = { end: true }
189const COUNT: Place = { count: true }
190
191function placeAfter(before: readonly string[], names: Names): Place {
192 const [first, ...rest] = before
193 if (first === undefined) return { rows: table(FIRST, names), of: 'names' }
194 const fit = onlyFit(first, table(FIRST, names))
195 if (!fit) return END
196 const name = ALIASES[fit.name] ?? fit.name
197 // After a mini: an act, then how many times. A mini takes no commands.
198 if (fit.kind === 'mini') {
199 const [act] = rest
200 if (act === undefined) return { rows: table(PLAYS, names), of: 'acts' }
201 return rest.length === 1 && onlyFit(act, table(PLAYS, names)) ? COUNT : END
202 }
203 if (fit.kind === 'act' || fit.kind === 'made') return rest.length === 0 ? COUNT : END
204 if (fit.kind !== 'command') return END
205 if (name === 'act' || name === 'emote' || name === 'skin') return kindPlace(name, rest, names)
206 if (rest.length > 0) return END
207 if (name === 'list') return { rows: LIST_ROWS, of: 'kinds' }
208 if (name === 'trace') return { rows: TRACE_ROWS, of: 'words' }
209 if (name === 'debug') return { rows: DEBUG_ROWS, of: 'words' }
210 if (name === 'autopick') return { rows: AUTOPICK_ROWS, of: 'words' }
211 if (name === 'help') return { rows: HELP_ROWS, of: 'words' }
212 return END
213}
214
215/**
216 * What comes after `/clawd act`, `emote` or `skin` and these words: a command
217 * or a name; after a command its words, after an act's name how many times.
218 */
219function kindPlace(kind: MadeKind, rest: readonly string[], names: Names): Place {
220 const words = KIND_WORDS[kind]
221 const [first, ...more] = rest
222 if (first === undefined) return { rows: kindRows(kind, names), of: 'names' }
223 const fit = onlyFit(first, kindRows(kind, names))
224 if (!fit) return END
225 if (fit.kind !== 'command') return kind === 'act' && more.length === 0 ? COUNT : END
226 const verb = ALIASES[fit.name] ?? fit.name
227 if (verb === 'auto' || verb === 'none') return END
228 if (verb === 'create') return more.length === 0 ? { free: '<new_name> in snake_case' } : { free: words.create }
229 if (more.length === 0) {
230 return verb === 'preview' ? { rows: table(words.names, names), of: LISTED[kind] } : { rows: table([words.owned], names), of: words.ownedOf }
231 }
232 return verb === 'change' ? { free: words.change } : END
233}
234
235type Word = { text: string; start: number; end: number }
236
237/** The words after `/clawd `, with their offsets; undefined for any other draft. */
238function wordsOf(draft: string): Word[] | undefined {
239 const head = /^\s*\/clawd(?=\s)/.exec(draft)
240 if (!head) return undefined
241 const out: Word[] = []
242 const re = /\S+/g
243 re.lastIndex = head[0].length
244 for (let m = re.exec(draft); m; m = re.exec(draft)) out.push({ text: m[0], start: m.index, end: m.index + m[0].length })
245 return out
246}
247
248/** True for a draft that is a `/clawd` command with arguments to come. */
249export function isClawdDraft(draft: string): boolean {
250 return wordsOf(draft) !== undefined
251}
252
253/** A row of the `/clawd` menu: a name, what it is, and the part of the name the typed word matches (from = to: none). */
254export type MenuRow = { name: string; what: string; from: number; to: number }
255
256/** The framed list above the prompt while `/clawd` is typed. */
257export type Menu = {
258 title: string // `/clawd` and the words before the one at the cursor: `/clawd act`
259 note: string // after the title: how to use the list, or what goes here
260 rows: MenuRow[] // every name the word at the cursor fits, in the order offered
261 isOne: boolean // the typed word fits one name; its row is marked
262 count: string // `2 of 22 fit` while the typed word fits several names
263 next: string // what follows the fitting names: `then [1-5] times in a row`
264}
265
266// Skins are not in FIRST: they sort after the commands, as emotes and acts do.
267const rank = (f: Fit): number => (FIRST.includes(f.kind) ? FIRST.indexOf(f.kind) : FIRST.length)
268
269/** What comes after these words, when it is short to say: a count or a free text. */
270function nextAfter(before: readonly string[], names: Names): string {
271 const place = placeAfter(before, names)
272 if ('count' in place) return `then [1-${MAX_REPEAT}] times in a row`
273 if ('free' in place) return `then ${place.free}`
274 return ''
275}
276
277/** The menu for the word at the cursor; undefined for any other draft, or when nothing goes there. */
278export function menuFor(draft: string, cursor: number, names: Names): Menu | undefined {
279 const before = draft.slice(0, cursor)
280 const words = wordsOf(before)
281 if (!words) return undefined
282 const typing = /\s$/.test(before) ? '' : (words.pop()?.text ?? '')
283 const done = words.map(w => w.text)
284 const place = placeAfter(done, names)
285 if ('end' in place) return undefined
286 // At most two words: an emote's name and create's or change's description stay out.
287 const menu: Menu = { title: ['/clawd', ...done.slice(0, 2)].join(' '), note: '', rows: [], isOne: false, count: '', next: '' }
288 if ('free' in place) return { ...menu, note: place.free }
289 if ('count' in place) return { ...menu, note: `[1-${MAX_REPEAT}] times in a row` }
290 const isTop = done.length === 0
291 if (!typing) {
292 // At the top, the commands and minis; acts and emotes come by typing, or after act and emote.
293 const all = isTop ? place.rows.filter(f => f.kind === 'command' || f.kind === 'mini') : place.rows
294 const rows = [...all].sort((a, b) => rank(a) - rank(b)).map(f => ({ name: f.name, what: f.what, from: 0, to: 0 }))
295 return { ...menu, note: isTop ? 'type to narrow, space writes a single fit out' : `${rows.length} ${place.of}`, rows }
296 }
297 const fits = [...fitsOf(typing, place.rows)].sort((a, b) => rank(a) - rank(b))
298 const [only] = fits
299 if (!only) return { ...menu, note: `nothing is called "${typing}"`, next: '/clawd help shows what there is' }
300 const typed = typing.toLowerCase()
301 const rows = fits.map(f => {
302 const at = f.name.indexOf(typed)
303 const kind = isTop ? KIND_WORD[f.kind] : ''
304 return { name: f.name, what: kind ? `${kind}: ${f.what}` : f.what, from: Math.max(0, at), to: at < 0 ? 0 : at + typed.length }
305 })
306 const nexts = [...new Set(fits.map(f => nextAfter([...done, f.name], names)))]
307 const next = nexts.length === 1 ? (nexts[0] ?? '') : ''
308 if (fits.length === 1) return { ...menu, note: typing === only.name ? '' : 'space writes it out', rows, isOne: true, next }
309 return { ...menu, note: `${place.of} that fit "${typing}"`, rows, count: `${fits.length} of ${place.rows.length} fit`, next }
310}
311
312/** The rows that fit in `room` rows, and the bottom edge's text: the count, what comes next, the names left out. */
313export function menuLayout(menu: Menu, room: number): { rows: MenuRow[]; foot: string } {
314 const rows = menu.rows.slice(0, Math.max(0, room))
315 const left = menu.rows.slice(rows.length).map(r => r.name)
316 const more = left.length > 0 ? `+${left.length} more: ${left.join(' ')}` : ''
317 return { rows, foot: [menu.count, menu.next, more].filter(Boolean).join(' · ') }
318}
319
320/** Each word that can be checked, and whether it fits one name (true) or none (false). */
321export function marksFor(draft: string, names: Names): { start: number; end: number; isFit: boolean }[] {
322 const words = wordsOf(draft) ?? []
323 const marks: { start: number; end: number; isFit: boolean }[] = []
324 for (const [i, word] of words.entries()) {
325 const place = placeAfter(
326 words.slice(0, i).map(w => w.text),
327 names,
328 )
329 if (!('rows' in place)) break
330 const n = fitsOf(word.text, place.rows).length
331 if (n === 1) marks.push({ start: word.start, end: word.end, isFit: true })
332 else if (n === 0) marks.push({ start: word.start, end: word.end, isFit: false })
333 }
334 return marks
335}
336
337/**
338 * After a space typed at `cursor`: the draft with the word before that space
339 * written out in full, when it fits exactly one name and is short of it.
340 */
341export function writeOut(draft: string, cursor: number, names: Names): { text: string; cursor: number } | undefined {
342 const before = draft.slice(0, cursor - 1)
343 const words = wordsOf(before)
344 const last = words?.pop()
345 if (!words || !last || last.end !== before.length) return undefined
346 const place = placeAfter(
347 words.map(w => w.text),
348 names,
349 )
350 if (!('rows' in place)) return undefined
351 const fits = fitsOf(last.text, place.rows)
352 const [fit] = fits
353 if (fits.length !== 1 || !fit || fit.name === last.text || ALIASES[last.text]) return undefined
354 return { text: draft.slice(0, last.start) + fit.name + draft.slice(last.end), cursor: cursor + fit.name.length - last.text.length }
355}
356
357/** What `/clawd <args>` asks for. */
358export type Order =
359 | { kind: 'status' }
360 | { kind: 'command'; name: string; rest: string[] }
361 | { kind: 'list'; of: ListKind }
362 | { kind: 'play'; who: string; fit: Fit; count: number }
363 | { kind: 'unclear'; text: string }
364
365/** The one name a word fits, or why there is none; `where` names the command that lists them. */
366function oneFit(word: string, rows: readonly Fit[], where: string): Fit | string {
367 const fits = fitsOf(word, rows)
368 const [fit] = fits
369 if (fits.length === 1 && fit) return fit
370 if (!fit) return `Clawd: nothing is called "${word}". ${where} shows what there is.`
371 const shown = fits.slice(0, 8).map(f => f.name)
372 return `Clawd: "${word}" fits ${fits.length} names: ${shown.join(', ')}${fits.length > shown.length ? ', ...' : ''}. Type more of it.`
373}
374
375function countOf(word: string | undefined): number {
376 return Math.min(MAX_REPEAT, Math.max(1, Number.parseInt(word ?? '1', 10) || 1))
377}
378
379function unclear(text: string): Order {
380 return { kind: 'unclear', text }
381}
382
383/** A mini plays the act named by rest[0], rest[1] times. */
384function miniOrder(who: string, rest: readonly string[], names: Names): Order {
385 const [act, n] = rest
386 if (act === undefined) return unclear(`Clawd: which act? E.g. /clawd ${who} wave. /clawd list acts shows them.`)
387 const what = oneFit(act, table(PLAYS, names), '/clawd list acts')
388 if (typeof what !== 'string') return { kind: 'play', who, fit: what, count: countOf(n) }
389 return unclear(onlyFit(act, table(['emote'], names)) ? `Clawd: emotes are for Clawd only, not for ${who}.` : what)
390}
391
392/**
393 * `/clawd act <act> [n]` plays an act, `/clawd emote <emote>` an emote, and
394 * `/clawd skin <skin>|auto|none` chooses Clawd's body for the session.
395 * `/clawd <kind> <command> ...` creates, changes, deletes or previews one of
396 * them; the order is the kind with the command's full name first. change and
397 * delete take the full name of one a file holds, so an act's must be a made one.
398 */
399function kindOrder(kind: MadeKind, rest: readonly string[], names: Names): Order {
400 const words = KIND_WORDS[kind]
401 const [first, ...more] = rest
402 if (first === undefined) {
403 if (kind === 'skin') return { kind: 'command', name: 'skin', rest: [] }
404 return unclear(`Clawd: which ${kind}? /clawd ${kind} <${kind}> plays one; ${kind} create, change, delete and preview work on them. /clawd list ${LISTED[kind]} shows them.`)
405 }
406 const fit = oneFit(first, kindRows(kind, names), `/clawd list ${LISTED[kind]}`)
407 if (typeof fit === 'string') {
408 const look = kind === 'act' ? onlyFit(first, table(['emote'], names)) : undefined
409 return unclear(look ? `Clawd: ${look.name} is an emote; /clawd emote ${look.name} plays it.` : fit)
410 }
411 if (fit.kind === 'skin') return { kind: 'command', name: 'skin', rest: [fit.name] }
412 if (fit.kind !== 'command') return { kind: 'play', who: 'clawd', fit, count: kind === 'act' ? countOf(more[0]) : 1 }
413 const verb = ALIASES[fit.name] ?? fit.name
414 const reason = inFull(verb, kind)
415 if (reason && first !== fit.name) return unclear(`Clawd: type ${verb} in full; ${reason}.`)
416 if (verb === 'change' || verb === 'delete') {
417 const [name] = more
418 if (name === undefined) return unclear(`Clawd: which ${kind}? /clawd ${kind} ${verb} <${kind}>${verb === 'change' ? ' [what to change]' : ''}.`)
419 const owned = table([words.owned], names)
420 if (!owned.some(f => f.name === name)) {
421 if (kind === 'act' && Object.hasOwn(names.acts, name)) {
422 return unclear(`Clawd: ${name} is built in; only made acts can be ${verb === 'change' ? 'changed' : 'deleted'}. /clawd list made shows them.`)
423 }
424 const one = onlyFit(name, owned)
425 return unclear(
426 one ? `Clawd: type the ${kind}'s full name: /clawd ${kind} ${verb} ${one.name}.` : `Clawd: there is no ${kind} ${name}. /clawd list ${words.ownedList} shows them.`,
427 )
428 }
429 }
430 return { kind: 'command', name: kind, rest: [verb, ...more] }
431}
432
433/** The words after `/clawd`, read as one order. `clawd` as the first word names Clawd, as a mini id names that mini. */
434export function orderOf(args: readonly string[], names: Names): Order {
435 const words = args[0] === 'clawd' && args.length > 1 ? args.slice(1) : [...args]
436 const [first, ...rest] = words
437 if (first === undefined) return { kind: 'status' }
438 const fit = oneFit(first, table(FIRST, names), '/clawd help')
439 if (typeof fit === 'string') {
440 // These were top-level emote commands until 2026-10-07; acts, emotes and skins take them now.
441 const verb = ALIASES[first] ?? first
442 if (Object.hasOwn(ACT_COMMANDS, verb)) return unclear(`Clawd: ${verb} what? /clawd act ${verb}, /clawd emote ${verb} or /clawd skin ${verb}.`)
443 // A skin is no act: it is worn all session, so it takes the skin command.
444 const skin = fitsOf(first, table(FIRST, names)).length === 0 ? onlyFit(first, table(['skin'], names)) : undefined
445 return unclear(skin ? `Clawd: ${skin.name} is a skin; /clawd skin ${skin.name} puts it on for this session.` : fit)
446 }
447 if (fit.kind === 'act' || fit.kind === 'made') return { kind: 'play', who: 'clawd', fit, count: countOf(rest[0]) }
448 if (fit.kind === 'emote') return { kind: 'play', who: 'clawd', fit, count: 1 }
449 if (fit.kind === 'mini') return miniOrder(fit.name, rest, names)
450 const name = ALIASES[fit.name] ?? fit.name
451 if (name === 'act' || name === 'emote' || name === 'skin') return kindOrder(name, rest, names)
452 if (name === 'list') {
453 const [of] = rest
454 if (of === undefined) return unclear('Clawd: list what? /clawd list acts | made | emotes | skins | minis.')
455 const what = oneFit(of, LIST_ROWS, '/clawd help')
456 return typeof what === 'string' ? unclear(what) : { kind: 'list', of: what.name as ListKind }
457 }
458 return { kind: 'command', name, rest }
459}
460hooks/clawd-uml.ts 273 lines1// `/clawd help uml`. A command's answer is transcript text, so the
2// diagrams are box-drawing characters, at most UML_WIDTH columns wide. A
3// CommandOutput render hook in register.tsx colours them by umlKinds; the stored row stays
4// plain text. Pure, no `$`: register.tsx passes the numbers in, so a changed
5// constant shows here too.
6
7/** The numbers and model names the diagrams name. */
8export type UmlFacts = {
9 sleepAfterS: number // idle seconds before Clawd falls asleep
10 readHoldS: number // the scroll stays up this long after the last reading call
11 miniStaleS: number // a mini whose subagent was silent this long leaves
12 maxMinis: number
13 pickMinS: number
14 pickMaxS: number
15 maxDelayS: number // a pick's calls start up to this far apart
16 newPerDay: number // new acts, emotes and skins the autopicker may ask for in 24 h
17 maxSteps: number // steps in a made act
18 emoteDrafts: number
19 emoteRounds: number
20 pickModel: string
21 makeModel: string
22}
23
24export const UML_WIDTH = 78
25
26const cells = (s: string) => [...s].length
27const pad = (s: string, n: number) => s + ' '.repeat(Math.max(0, n - cells(s)))
28
29/** A UML state or action: a rounded box `inner` cells wide; a state's name gets a compartment of its own. */
30function node(inner: number, lines: readonly string[], name?: string): string[] {
31 const rule = '─'.repeat(inner + 2)
32 return [
33 `╭${rule}╮`,
34 ...(name === undefined ? [] : [`│ ${pad(name, inner)} │`, `├${rule}┤`]),
35 ...lines.map(l => `│ ${pad(l, inner)} │`),
36 `╰${rule}╯`,
37 ]
38}
39
40/** A UML note: a square box `inner` cells wide. */
41function note(inner: number, lines: readonly string[]): string[] {
42 const rule = '─'.repeat(inner + 2)
43 return [`┌${rule}┐`, ...lines.map(l => `│ ${pad(l, inner)} │`), `└${rule}┘`]
44}
45
46/** Blocks side by side, row by row, each padded to its width. */
47function beside(...blocks: [width: number, rows: readonly string[]][]): string[] {
48 const height = Math.max(...blocks.map(([, rows]) => rows.length))
49 return Array.from({ length: height }, (_, i) => blocks.map(([w, rows]) => pad(rows[i] ?? '', w)).join('').trimEnd())
50}
51
52/** One row, each text starting at its column. */
53function at(...parts: [col: number, text: string][]): string {
54 let row = ''
55 for (const [col, text] of parts) row = pad(row, col) + text
56 return row
57}
58
59/** Clawd itself: idle, work and asleep, and what moves it between them. */
60function clawdStates(f: UmlFacts): string[] {
61 const up = 59 // the column of the line from Asleep up to Work
62 return [
63 '1. Clawd (UML state machine)',
64 '',
65 ' ● session start / Clawd walks in and waves',
66 ' │',
67 ' ▼',
68 ...beside(
69 [26, node(22, ['do / random acts from', ' the idle table', '', '', ''], 'Idle')],
70 [22, ['', ' prompt sent', ' / alert, hop,', ' kick [1]', `${'─'.repeat(21)}▶`, '', `◀${'─'.repeat(21)}`, ' turn ends / [4]']],
71 [28, node(24, ['do / random acts from', ' the work table', 'read call / scroll [2]', 'other call / carry [3]', ''], 'Work')],
72 ),
73 at([3, '│'], [17, '▲'], [up, '▲']),
74 at([3, '│'], [5, `after ${f.sleepAfterS} s`], [17, '│'], [19, 'failed call / trip,'], [up, '│'], [up + 2, 'prompt sent']),
75 at([3, '│'], [5, 'without an'], [17, '│'], [19, '/clawd <act>'], [up, '│'], [up + 2, '/ wake, kick [1]']),
76 at([3, '│'], [5, 'event'], [17, '│'], [up, '│']),
77 at([3, '▼'], [17, '│'], [up, '│']),
78 ...beside([26, node(22, ['do / sleep'], 'Asleep')], [up - 26 + 1, ['', '', '', `${'─'.repeat(up - 26)}┘`, '']]).map((row, i) =>
79 i < 3 ? at([0, row], [up, '│']) : row,
80 ),
81 '',
82 ...note(72, [
83 'In every state',
84 'failed tool call / trip',
85 '/clawd <act> / the act plays at once and cuts in on anything',
86 `autopick / ${f.pickModel} calls acts for Clawd and the minis, up to ${f.maxDelayS} s apart.`,
87 ` After /clawd autopick on, it picks every ${f.pickMinS} to ${f.pickMaxS} s and right after a`,
88 ' prompt, a turn end and a subagent starting or ending. A call cuts in',
89 ' on a random act and waits while Clawd reacts to a session event.',
90 ' Asleep with no mini, the timer picks nothing; a pick that does play',
91 ' ends in sleep again.',
92 ]),
93 '[1] kick: only while bricks lie on the pile; Clawd kicks it over.',
94 `[2] scroll: held up until ${f.readHoldS} s after the last call that only reads (Read, or`,
95 ' a Bash call the engine judges read-only). It cuts a random act short.',
96 '[3] carry: Clawd fetches a brick for the pile, until the pile is full.',
97 ' The turn end drops the bricks still waiting.',
98 '[4] celebrate; trip after an error; look and think when you stopped it.',
99 ]
100}
101
102/** A mini Clawd, from its subagent's start until it has run off. */
103function miniStates(f: UmlFacts): string[] {
104 const back = 60 // the column of the line from Mini round to Leaving
105 const leaving = node(13, ['do / run off', ' the band'], 'Leaving')
106 return [
107 `2. A mini Clawd (UML state machine): one per running subagent, at most ${f.maxMinis}.`,
108 '',
109 ' ● subagent starts / a mini runs in from an edge, alert',
110 ' │',
111 ' ▼',
112 ...beside(
113 [28, node(24, ['do / random acts from', ' the mini table', 'its read call / scroll', 'its other call / carry', 'its failed call / trip'], 'Mini (a1, a2, ...)')],
114 [24, ['', ' subagent ends', ' / celebrate, or trip', ' without an answer', `${'─'.repeat(23)}▶`]],
115 [26, [...leaving.map((row, i) => (i === 4 ? `${row} ──▶ ◉` : row)), at([back - 52, '▲']), at([back - 52, '│']), at([back - 52, '│'])]],
116 ),
117 at([3, '│'], [5, `${Math.round(f.miniStaleS / 60)} min without an event / trip`], [back, '│']),
118 at([3, `└${'─'.repeat(back - 4)}┘`]),
119 ]
120}
121
122/** Two blocks of the activity diagram side by side, the shorter one's flow line drawn on to the same height. */
123function pair(left: readonly string[], right: readonly string[]): string[] {
124 const height = Math.max(left.length, right.length)
125 const fill = (rows: readonly string[]) => [...rows, ...Array<string>(height - rows.length).fill(' │')]
126 return beside([40, fill(left)], [37, fill(right)])
127}
128
129/** How a new act, emote or skin comes about, and how Clawd finds it afterwards. */
130function making(f: UmlFacts): string[] {
131 const right = 43 // the column of the look flow
132 const ask = '◇──[new.look: become, hold or skin]'
133 return [
134 '3. A new act, emote or skin (UML activity diagram)',
135 '',
136 at([3, '● autopick'], [right, '● /clawd emote or skin']),
137 at([3, '▼'], [right, '│ create or change']),
138 ...beside(
139 [right, node(36, [`${f.pickModel} reads what happened and every`, 'name; it answers with calls, why and', 'new: an act, emote or skin it wants'])],
140 [1, ['│', '│', '│', '│', '│']],
141 ),
142 at([3, '│ plays the calls'], [right, '│']),
143 at([3, `◇──[no new, or ${f.newPerDay} made in 24 h]──▶ ◉`], [right, '│']),
144 at([3, '◇──[it exists]──▶ play or wear it ──▶ ◉'], [right, '│']),
145 at([3, `${ask}${'─'.repeat(right - 3 - cells(ask))}┤`]),
146 at([3, '│ [a move]'], [right, '│ [nothing being made]']),
147 at([3, '│◀──● /clawd act create or change'], [right, '▼']),
148 at([3, '▼']),
149 ...pair(
150 node(34, [
151 `${f.makeModel} writes 1 to ${f.maxSteps} steps from the`,
152 'pickable acts and pose, mark and',
153 'sparks. A change starts from the',
154 'steps as they are; one with no',
155 'words writes it again. (makeAct)',
156 ]),
157 node(33, [
158 `${f.makeModel} draws it in up to ${f.emoteRounds} rounds:`,
159 `${f.emoteDrafts} drafts on one sheet, told the`,
160 'others of its kind; it picks one,',
161 'fixes it and checks its preview.',
162 'A change starts from the look as',
163 'it is; one with no words draws it',
164 'again from scratch.',
165 '(makeEmote; claude -p per round)',
166 ]),
167 ),
168 at([3, '◇──[routineFrom refuses]──▶ ◉'], [right, '◇──[no usable draft]──▶ ◉']),
169 at([3, '▼'], [right, '▼']),
170 ...pair(
171 node(34, ['write acts/<name>.json in the', 'data folder; a change or rewrite', 'moves the old file to acts/old/']),
172 node(33, ['write <kind>s/<name>.json and a', 'preview PNG in the data folder; a', 'change or redraw moves the old', 'file to <kind>s/old/ there']),
173 ),
174 at([3, '▼'], [right, '▼']),
175 ...pair(node(34, ['play it on new.for, or on Clawd']), node(33, ['Clawd plays an emote, or wears a', 'skin for the session'])),
176 at([3, '▼'], [right, '▼']),
177 at([3, '◉'], [right, '◉']),
178 '',
179 ...note(72, [
180 'Registered: there is no list to add a name to. Each autopick, each',
181 '/clawd and the menu while you type read acts/, emotes/ and skins/ in',
182 "the data folder and the plugin's emotes/ and skins/ afresh. The next",
183 `pick offers the new name to ${f.pickModel}, and /clawd <name> and /clawd list`,
184 'take it at once, without a reload. A file that fails the check is',
185 "skipped. A hand-drawn look in the plugin wins over a model's of the",
186 'same name. /clawd act, emote or skin delete moves the file to old/.',
187 'The data folder is clawd/ in the Claude config folder (~/.claude), or',
188 'data/ beside the plugin in a checkout. A skin the autopicker makes or',
189 'calls stays on for the session. A skin chosen with /clawd skin wins,',
190 'and the autopicker then gets no skins.',
191 ]),
192 'A built-in act is code: its name in ACTS and a case in runAct (clawd-sim.ts),',
193 'a line in PICKABLE so models and made acts may use it, a weight in a random',
194 'table if it should play by itself, then /reload-plugins.',
195 ]
196}
197
198/** The first line of the diagrams; the render hook finds the answer by it. */
199export const UML_LEGEND = 'Read as UML: ╭╮ a state or an action, ● start, ◉ end, ◇ a decision, [a guard],'
200
201/** The three diagrams, one line per row. */
202export function clawdUml(f: UmlFacts): string[] {
203 return [
204 UML_LEGEND,
205 'event / what Clawd does.',
206 '',
207 ...clawdStates(f),
208 '',
209 ...miniStates(f),
210 '',
211 ...making(f),
212 ]
213}
214
215/** What a run of cells in the diagrams is; register.tsx gives each kind its colour. */
216export type UmlKind = 'text' | 'heading' | 'state' | 'name' | 'note' | 'flow' | 'end' | 'guard' | 'footnote'
217
218const BOXES = [
219 { kind: 'state', corners: '╭╮╰╯' },
220 { kind: 'note', corners: '┌┐└┘' },
221] as const
222const FLOW = new Set([...'─│┤├┘└┐┌▶◀▲▼'])
223
224/**
225 * Each line cut into runs of one kind. A box's frame is found by walking its
226 * edges from the top left corner, and the row above a `├` divider is the
227 * state's name. The rest goes by character, brackets and the heading's number.
228 */
229export function umlKinds(lines: readonly string[]): { text: string; kind: UmlKind }[][] {
230 const grid = lines.map(l => [...l])
231 const ch = (r: number, c: number) => grid[r]?.[c] ?? ''
232 const kinds = grid.map(row => row.map((): UmlKind | undefined => undefined))
233 const mark = (r: number, c: number, kind: UmlKind) => {
234 const row = kinds[r]
235 if (row && c < row.length) row[c] = kind
236 }
237 grid.forEach((row, r) =>
238 row.forEach((corner, c) => {
239 for (const { kind, corners } of BOXES) {
240 if (corner !== corners[0]) continue
241 let right = c + 1
242 while (ch(r, right) === '─') right++
243 let bottom = r + 1
244 while (ch(bottom, c) === '│' || ch(bottom, c) === '├') bottom++
245 if (right === c + 1 || ch(r, right) !== corners[1] || ch(bottom, c) !== corners[2] || ch(bottom, right) !== corners[3]) continue
246 for (let y = r; y <= bottom; y++) {
247 const isRule = y === r || y === bottom || ch(y, c) === '├'
248 for (let x = c; x <= right; x++) if (isRule || x === c || x === right) mark(y, x, kind)
249 if (ch(y, c) === '├') for (let x = c + 1; x < right; x++) mark(y - 1, x, 'name')
250 }
251 }
252 }),
253 )
254 return grid.map((row, r) => {
255 const line = lines[r] ?? ''
256 const marks = kinds[r] ?? []
257 for (const m of line.matchAll(/\[[^\]]+\]/g)) {
258 const from = cells(line.slice(0, m.index))
259 for (let x = from; x < from + cells(m[0]); x++) marks[x] ??= /^\[\d\]$/.test(m[0]) ? 'footnote' : 'guard'
260 }
261 const runs: { text: string; kind: UmlKind }[] = []
262 row.forEach((cell, c) => {
263 const kind =
264 marks[c] ??
265 ('●◉'.includes(cell) ? 'end' : cell === '◇' ? 'guard' : '╭╮╰╯'.includes(cell) ? 'state' : FLOW.has(cell) ? 'flow' : /^\d\. /.test(line) ? 'heading' : 'text')
266 const last = runs[runs.length - 1]
267 if (last?.kind === kind) last.text += cell
268 else runs.push({ text: cell, kind })
269 })
270 return runs
271 })
272}
273types/index.d.ts 46 lines1/** Clawd's band state, as kept in $.state. */
2export type ClawdState = {
3 isClawdOn: boolean
4 clawdRows: number
5 isTracing: boolean
6 isDebugging: boolean
7 clawdSkin: string | null
8 clawdPickedSkin: string | null
9 clawdMenu: {
10 title: string
11 note: string
12 rows: { name: string; what: string; from: number; to: number }[]
13 isOne: boolean
14 count: string
15 next: string
16 } | null
17}
18
19declare module 'claude-code' {
20 interface PluginState {
21 'clawd': {
22 /** Clawd, the logo, running in the band above the prompt (/clawd on|off). */
23 isClawdOn: boolean
24 /** The band's height in rows: 4, 5 during a big jump or a tall look or skin, 6 with the Remote Control antenna on a tall look or skin. */
25 clawdRows: number
26 /** Each pick goes to picks/<session id>.jsonl in the data folder (/clawd trace [on|off]). */
27 isTracing: boolean
28 /** Each pick's whole reply, tokens and outcome go to the transcript (/clawd debug [on|off]). */
29 isDebugging: boolean
30 /** The skin /clawd skin chose for this session: a skin's name, '' for Clawd's own body; null: none chosen, clawd.json or the project folder decides. */
31 clawdSkin: string | null
32 /** The skin the autopicker called or had drawn for this session: a skin's name; null: none. A /clawd skin choice wins over it; /clawd skin auto clears both. */
33 clawdPickedSkin: string | null
34 /** The framed list above the prompt while a /clawd command is typed (clawd-words.ts `Menu`); null otherwise. */
35 clawdMenu: {
36 title: string
37 note: string
38 rows: { name: string; what: string; from: number; to: number }[]
39 isOne: boolean
40 count: string
41 next: string
42 } | null
43 }
44 }
45}
46