SLOPSHOPPER

goblin-chrome

Goblin-mode's face inside Claude Code: a goblin in the band that reacts to the session and holds a prop for the skill that runs, minions for the subagents out…

bandspinnerrowsguardprompttimer
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · goblin-chrome
› fix the failing auth test and add an audit log call ⏺ Read(src/auth.ts) ⎿ Read 6 lines ⏺ Update(src/auth.ts) ⎿ Added 2 lines, removed 1 line ⏺ Bash(bun test) ⎿ 3 pass, 1 fail ● Done. refresh now rejects expired claims and logs an audit event. dOnE. 42s. tOoK 9 tHiNgS. bIt mE oNcE. ┏━━━┳━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓ ┃ ᛟ ┃ ▣ client module ./idle.tsx ┃ ┃ ┗━━━┻━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┻━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛ ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Band
┏━━━┳━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓ ┃ ᛟ ┃ ▣ client module ./idle.tsx ┃ ┃ ┗━━━┻━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┻━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛
Turn line
dOnE. 42s. tOoK 9 tHiNgS. bIt mE oNcE.
README

goblin-chrome

[!NOTE] A Claude Code mod from goblin-mode: goblin-mode's face inside the terminal. Pure chrome. It changes nothing Claude does.


1. Install

claude plugin marketplace add JasonWarrenUK/goblin-mode
claude plugin install goblin-chrome@goblin-mode

Needs Claude Code 2.1.287 or later. Draws in the terminal; the hooks run everywhere else and draw nothing.


2. What it draws

WhereWhat
The band above the promptThree ranges split by dividers. The tier's rune at the left; the goblin in the middle, pacing while nothing happens, sitting after five minutes, sleeping after ten, startling when a prompt goes in, watching while Claude works and answering a poke; its dialogue at the right. While a skill runs it holds that family's prop, (ಠ_ಠ)[#] for pr; each subagent out stands beside it as a minion, o.O ಠ.ಠ (ಠ_ಠ), three shown and the rest a count.
The spinnerWhile a skill with goblin-spinner words runs, one of them a minute in the house dress: ••• dElEtInG eViDeNcE •••. A subagent's spinner keeps the engine's word.
The line that closes a turndOnE. 42s. tOoK 7 tHiNgS. bIt mE oNcE. with the real numbers.
The hint under the promptThe engine's line stays live; a tail in the goblin's register reacts to a fresh session, idling, an unsent draft and typing mid-turn.
Every question Claude asksA face above the dialog, expression by context: expectant, nervous after a failed tool, folded arms for an interrogation, grinning late at night.
The goblin's dialogueThe band's right-hand range, for six seconds at a time: a poke, a yawn, a subagent going out or returning, a compaction, a /clear and the commit-msg hook bouncing a message.

The band and the question box take their frame from the model that served the last request, so a /model switch shows once a reply has come back from it: each model has its own frame and theme colour.

ModelRuneFrameColour
Fableᚠdouble line ╔═╗accent
Opusᛟheavy line ┏━┓accent-2
Sonnetᛊround ╭─╮info
Haikuᚺdotted, plus corners +┈+, dimmedok

A skill that pinned one model while another answered draws singleDouble in warn with both runes. The band is drawn by hand with tees where the dividers meet the rules; the question box uses the engine's own border, which has no dotted style, so Haiku's box there is plain ASCII.

2.1. What it reads from skills and agents

When a skill's prompt is expanded, the mod reads its SKILL.md from ~/.claude/skills/ first, then <project>/.claude/skills/. Plugin skills live elsewhere and read as nothing set. What is read from a skill lasts until the turn completes; a minion lasts until its own turn completes or the session starts over.

FieldWhereWhat it does
modeltop levelPins the frame's tier; a different model answering draws the mismatch frame.
metadata.familyunder metadata:Picks the prop the goblin holds, from the PROPS table in hooks/goblin.ts: a parcel for pr, a lens for clod-lens, a pen for clod-approach. A family without a prop walks empty-handed.
metadata.goblin-spinnerunder metadata:Bar-separated spinner words, `merging\deleting evidence\tagging`, shown one a minute.
goblin-miniontop level of an agent fileThe face the subagent wears in the parade, one to five terminal cells, a wide glyph counting two; o.o when unset. Quote a face that starts with a YAML indicator (>, @, `\, *, &, !) or reads as a number: '>.<', '0.0'. Agent files are read from ~/.claude/agents/ then <project>/.claude/agents/`.

A prop is up to four terminal cells of BMP text, so the band's arithmetic holds; the sprite grows by the prop's width and the pacing room shrinks to match. Widths are measured as a terminal draws them: a CJK ideograph such as the one in [三] counts two cells, while ambiguous-width glyphs (box drawing, shades, arrows, geometric shapes) count one, as the band's own frame already assumes. A minion face that would not fit the rule (wider than five cells, a space, an emoji) is ignored for the default.

The day has nine states on the local clock, fading over ten minutes, shifted one row towards lively on a Friday from four, one towards tired on a Sunday and one towards tired once the session passes four hours. Colours come from the project's theme in .claude/themes/, the clod family when it has none.


3. Options

Set in /config or under pluginConfigs in settings.json.

OptionDefaultWhat it does
enabledtrueThe one switch. Off, every hook passes through and nothing draws.
audiofalsePlay fx/cackle.wav when the commit-msg hook bounces a message.
schedule04=bed,06=caught,08=grumpy,11=functional,14=slump,16=second,19=perking,22=prime,01=feralHH=state or HH:MM=state pairs, 24h local. A malformed schedule falls back to the default whole.
themeemptyA theme family in .claude/themes to dress in. Empty picks the only family there, else clod.

4. Files

FileHolds
hooks/register.tsxThe hooks module: every event handled and every drawing
hooks/idle.tsxThe idle goblin, a Client surface module with its own frame clock and pointer; the prop in its hand and the minion parade
hooks/goblin.tsThe question face as Raster cells, the props by family, the poke lines, the heckles
hooks/frontmatter.tsThe five keys read from a skill or agent file's frontmatter, as text
hooks/day.tsThe schedule, the ladder, the offsets, the fade and each state's style
hooks/tier.tsModel id to tier, the skill pin, the frame per tier
hooks/theme.tsPalette resolution per library/references/theme-conventions.md
types/index.d.tsThe $.state contract: palette, day, frame, vitals, idle, run, readable by a plugin that lists this one under dependencies

Check it with claude plugin validate marketplace/goblin-chrome and claude plugin test marketplace/goblin-chrome; type-check with tsc -p marketplace/goblin-chrome once a session has laid the engine's types beside the manifest.

Source 10 files
hooks/register.tsx 442 lines
1// goblin-chrome: the hooks module. Every drawing reads the same state: the
2// palette (38), the day (37), the frame by tier (36), the vitals (18) and
3// the idle clock (28). The hint (27) and the question mask and heckles (29)
4// read it too. One switch in the options turns the lot off.
5
6import { atom, read, update } from 'claude-code'
7import type { EngineInterface, Register, RenderElement } from 'claude-code'
8
9import type { Day, Frame, Idle, Palette, Run, Tier, Vitals } from '../types'
10import { mix, shade } from './colour'
11import { dayAt, parseSchedule, STYLE } from './day'
12import { readMinionFace, readSkill } from './frontmatter'
13import {
14	DEFAULT_MINION,
15	faceCells,
16	FACE_COLUMNS,
17	FACE_ROWS,
18	HECKLES,
19	POKE_LINES,
20	propFor,
21	type Expression,
22} from './goblin'
23import { goblinCase, pick, seconds } from './text'
24import { CLOD, loadPalette, type Variant } from './theme'
25import { bandRule, DEFAULT_TIER, frameFor, glyphsFor, tierOf } from './tier'
26
27const PLUGIN = 'goblin-chrome'
28
29const palette = atom({ plugin: 'goblin-chrome', key: 'palette' } as const, CLOD)
30const day = atom({ plugin: 'goblin-chrome', key: 'day' } as const, {
31	state: 'functional',
32	from: 'functional',
33	blend: 1,
34} as Day)
35const frame = atom({ plugin: 'goblin-chrome', key: 'frame' } as const, frameFor(DEFAULT_TIER, null, CLOD))
36const vitals = atom({ plugin: 'goblin-chrome', key: 'vitals' } as const, {
37	tools: 0,
38	errors: 0,
39	turnMs: 0,
40	turnTools: 0,
41	turnErrors: 0,
42	bounces: 0,
43} as Vitals)
44const idle = atom({ plugin: 'goblin-chrome', key: 'idle' } as const, {
45	lastPromptAt: 0,
46	lastTurnEndAt: 0,
47	sessionStartAt: 0,
48	isWorking: false,
49	draftSince: 0,
50	saying: '',
51	sayingUntil: 0,
52} as Idle)
53const NO_RUN: Run = { skill: null, family: null, spinner: [], minions: [] }
54const run = atom({ plugin: 'goblin-chrome', key: 'run' } as const, NO_RUN)
55
56/** How the spinner dresses a skill's word, matching the house `spinnerVerbs`. */
57const spinnerWord = (word: string): string => `••• ${goblinCase(word)} •••`
58
59/** The accent as the day colours it: faded from the previous state's shade over ten minutes. */
60const accentOf = (p: Palette, d: Day): string =>
61	mix(shade(p.accent, STYLE[d.from].shade), shade(p.accent, STYLE[d.state].shade), d.blend)
62
63// Module-level because the validator holds `$` to top-level functions: these
64// are the helpers every hook shares, and the variables they read are set by
65// `register` from the options and by the hooks as the session goes. The tiers
66// the frame depends on live in the `frame` atom, which survives a hot reload.
67let schedule = parseSchedule('')
68let lastYawnAt = 0
69
70/** How long a line stays in the band's dialogue range. */
71const SAY_MS = 6_000
72
73/** The goblin speaks: the line shows in the band's dialogue range for a few seconds, then clears itself. */
74const say = async ($: EngineInterface, line: string): Promise<void> => {
75	const now = await $.clock.now()
76	const until = now + SAY_MS
77	await update($, idle, i => ({ ...i, saying: goblinCase(line), sayingUntil: until }))
78	$.clock.after(SAY_MS, () => {
79		void update($, idle, i => (i.sayingUntil === until ? { ...i, saying: '', sayingUntil: 0 } : i))
80	})
81}
82
83const refreshDay = async ($: EngineInterface): Promise<void> => {
84	const now = await $.clock.now()
85	const i = await read($, idle)
86	const next = dayAt(schedule, new Date(now), i.sessionStartAt ? now - i.sessionStartAt : 0)
87	await update($, day, () => next)
88	const style = STYLE[next.state]
89	if (style.yawnMs !== null && now - lastYawnAt > style.yawnMs && !i.isWorking) {
90		lastYawnAt = now
91		await say($, 'yawn.')
92	}
93}
94
95/** Redraw the frame from the atom's own tiers, with `patch` replacing whichever it names. */
96const refreshFrame = async ($: EngineInterface, patch: { served?: Tier; pinned?: Tier | null } = {}): Promise<void> => {
97	const p = await read($, palette)
98	await update($, frame, current =>
99		frameFor(patch.served ?? current.served, patch.pinned === undefined ? current.pinned : patch.pinned, p),
100	)
101}
102
103export const register: Register = (on, options) => {
104	if (options.enabled === false) return
105
106	schedule = parseSchedule(typeof options.schedule === 'string' ? options.schedule : '')
107	lastYawnAt = 0
108	const wantedTheme = typeof options.theme === 'string' ? options.theme : ''
109	const audio = options.audio === true
110
111	on('session.start', async ($, e, next) => {
112		const now = await $.clock.now()
113		lastYawnAt = now
114		await update($, idle, i => ({ ...i, sessionStartAt: now, lastTurnEndAt: now }))
115		let variant: Variant = 'dark'
116		try {
117			const row = (await $.config.list()).find(r => r.key === 'theme')
118			if (typeof row?.value === 'string' && /light/i.test(row.value)) variant = 'light'
119		} catch {
120			// no config to read; dark it is
121		}
122		const loaded = await loadPalette(
123			{
124				list: path => $.fs.list(path),
125				read: path => $.fs.read(path),
126				home: () => $.env.get('HOME'),
127			},
128			wantedTheme,
129			variant,
130		)
131		await update($, palette, () => loaded)
132		await refreshFrame($)
133		await refreshDay($)
134		$.clock.every(60_000, () => {
135			void refreshDay($)
136		})
137		$.clock.every(30_000, () => {
138			void update($, idle, i => ({ ...i }))
139		})
140		return next(e)
141	})
142
143	on('classic.SessionStart', { source: ['clear', 'resume', 'fork'] }, async ($, e, next) => {
144		const now = await $.clock.now()
145		await update($, idle, i => ({ ...i, sessionStartAt: now, lastTurnEndAt: now, isWorking: false }))
146		await update($, vitals, v => ({ ...v, tools: 0, errors: 0 }))
147		await update($, run, () => NO_RUN)
148		await refreshFrame($)
149		await refreshDay($)
150		return next(e)
151	})
152
153	on('prompt.submit', async ($, e, next) => {
154		const now = await $.clock.now()
155		await update($, idle, i => ({ ...i, lastPromptAt: now, draftSince: 0 }))
156		return next(e)
157	})
158
159	// A turn, not a submission: a dropped prompt never starts one.
160	on('turn.start', async ($, e, next) => {
161		await update($, idle, i => (i.isWorking ? i : { ...i, isWorking: true }))
162		await update($, vitals, v => ({ ...v, tools: 0, errors: 0 }))
163		return next(e)
164	})
165
166	// One write when a draft begins, one when it empties; nothing per keystroke.
167	on('prompt.edit', async ($, e, next) => {
168		const i = await read($, idle)
169		const isEmpty = e.text.length - (e.end - e.start) + e.inputText.length === 0
170		if (isEmpty && i.draftSince !== 0) await update($, idle, cur => ({ ...cur, draftSince: 0 }))
171		else if (!isEmpty && i.draftSince === 0) {
172			const now = await $.clock.now()
173			await update($, idle, cur => ({ ...cur, draftSince: now }))
174		}
175		return next(e)
176	})
177
178	on('tool.call', async ($, e, next) => {
179		if (!e.agentId) await update($, vitals, v => ({ ...v, tools: v.tools + 1 }))
180		const ran = await next(e)
181		if (e.agentId) return ran
182		if (ran.deny === undefined && ran.isError === true) {
183			await update($, vitals, v => ({ ...v, errors: v.errors + 1 }))
184		}
185		if (e.tool === 'Bash' && /\bgit\b[^|;&]*\bcommit\b/.test(e.command) && ran.deny === undefined) {
186			const text = typeof ran.text === 'string' ? ran.text : ''
187			const out = ran.result as { stderr?: unknown } | undefined
188			const stderr = typeof out?.stderr === 'string' ? out.stderr : ''
189			if (/commit-msg:/.test(stderr) || /commit-msg:/.test(text)) {
190				const v = await read($, vitals)
191				const bounces = v.bounces + 1
192				await update($, vitals, cur => ({ ...cur, bounces }))
193				await say($, bounces === 1 ? HECKLES.bounce : HECKLES.bounceAgain(bounces))
194				if (audio) void $.audio.play({ asset: 'fx/cackle.wav' }).catch(() => undefined)
195			}
196		}
197		return ran
198	})
199
200	on('turn.step', async function* ($, e, next) {
201		const result = yield* next(e)
202		if (!e.agentId && result.usage?.model) {
203			const tier = tierOf(result.usage.model)
204			if (tier !== (await read($, frame)).served) await refreshFrame($, { served: tier })
205		}
206		return result
207	})
208
209	// The skill's frontmatter sets the frame's pin, the prop in the goblin's
210	// hand and the spinner's words, all until the turn completes. Plugin skills
211	// live elsewhere and read as nothing set.
212	on('skill.prompt', async ($, e, next) => {
213		let pinned: Tier | null = null
214		let family: string | null = null
215		let spinner: readonly string[] = []
216		try {
217			// Personal shadows project, as Claude Code resolves a skill of the same name.
218			const home = await $.env.get('HOME')
219			const personal = home ? await $.fs.read(`${home}/.claude/skills/${e.skill}/SKILL.md`).catch(() => '') : ''
220			const text = personal || (await $.fs.read(`.claude/skills/${e.skill}/SKILL.md`))
221			const fm = readSkill(text)
222			pinned = fm.model ? tierOf(fm.model) : null
223			family = fm.family
224			spinner = fm.spinner
225		} catch {
226			pinned = null
227		}
228		await update($, run, r => ({ ...r, skill: e.skill, family, spinner }))
229		await refreshFrame($, { pinned })
230		return next(e)
231	})
232
233	// A subagent out is a minion in the band, wearing its agent file's face,
234	// until its own turn completes. Personal agents shadow project ones.
235	on('agent.spawn', async ($, e, next) => {
236		// The face is read before the spawn resolves, so nothing awaits between the subagent starting and its minion being added.
237		let face = DEFAULT_MINION
238		try {
239			const home = await $.env.get('HOME')
240			const personal = home ? await $.fs.read(`${home}/.claude/agents/${e.subagentType}.md`).catch(() => '') : ''
241			const text = personal || (await $.fs.read(`.claude/agents/${e.subagentType}.md`))
242			face = readMinionFace(text) ?? DEFAULT_MINION
243		} catch {
244			face = DEFAULT_MINION
245		}
246		const ran = await next(e)
247		const agentId = (ran as { agentId?: unknown }).agentId
248		if (typeof agentId !== 'string') return ran
249		const type = e.subagentType
250		// Spawns arrive together, so the list is built from the state at write time, never from an earlier read.
251		await update($, run, cur => ({ ...cur, minions: [...cur.minions.filter(m => m.agentId !== agentId), { agentId, type, face }] }))
252		await say($, HECKLES.minionOut((await read($, run)).minions.length))
253		return ran
254	})
255
256	on('turn.complete', async ($, e, next) => {
257		if (e.agentId) {
258			const agentId = e.agentId
259			await update($, run, r => ({ ...r, minions: r.minions.filter(m => m.agentId !== agentId) }))
260			await say($, HECKLES.minionBack(e.durationMs))
261			return next(e)
262		}
263		const now = await $.clock.now()
264		await update($, idle, i => ({ ...i, lastTurnEndAt: now, isWorking: false }))
265		await update($, vitals, v => ({ ...v, turnMs: e.durationMs, turnTools: v.tools, turnErrors: v.errors }))
266		// The skill's run ends with the turn: the pin, the prop and the spinner's words. A minion
267		// still out stays until its own turn completes, or the session starts over.
268		await update($, run, r => ({ ...NO_RUN, minions: r.minions }))
269		if ((await read($, frame)).pinned !== null) await refreshFrame($, { pinned: null })
270		return next(e)
271	})
272
273	// The spinner's word while a skill with `goblin-spinner` runs (one word a
274	// minute, in the house dress). A spinner's requestId is its agent id; the
275	// main loop's is the session id (measured in a live session), so a subagent
276	// is told by matching a minion out, and its spinner keeps the engine's.
277	on('ui.render', { component: 'Spinner' }, async ($, e, next) => {
278		const r = await read($, run)
279		if (r.spinner.length === 0 || r.minions.some(m => m.agentId === e.requestId)) return next(e)
280		const now = await $.clock.now()
281		return next({ ...e, props: { ...e.props, word: spinnerWord(pick(r.spinner, Math.floor(now / 60_000))) } })
282	})
283
284	on('session.compact', async ($, e, next) => {
285		if (!e.agentId) await say($, HECKLES.compaction)
286		return next(e)
287	})
288
289	on('command.run', { command: 'clear' }, async ($, e, next) => {
290		await say($, HECKLES.clear)
291		return next(e)
292	})
293
294	on('ui.message', async ($, e, next) => {
295		const data = e.data as { poke?: unknown } | null
296		if (data && data.poke === true) {
297			const now = await $.clock.now()
298			await say($, pick(POKE_LINES, Math.floor(now / 1000)))
299			return {}
300		}
301		return next(e)
302	})
303
304	// The band (18 and 28): three ranges split by dividers, the tier's rune, the
305	// idle goblin and the goblin's dialogue, framed by tier and coloured by the day.
306	on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
307		if (e.props.hasSurvey || e.surface !== 'terminal') return next(e)
308		const { Box, Text, Client } = $.ui.resolve(e)
309		const [p, d, f, i, r] = await Promise.all([read($, palette), read($, day), read($, frame), read($, idle), read($, run)])
310		const now = await $.clock.now()
311		const accent = accentOf(p, d)
312		const since = Math.max(i.lastTurnEndAt, i.lastPromptAt, i.sessionStartAt)
313		const idleMs = i.isWorking || since === 0 ? 0 : Math.max(0, now - since)
314		const framed = e.props.maxRows >= 5
315		// The frame is drawn by hand so the dividers join the rules with tees: three ranges, each
316		// padded by a cell either side, so the rune sits centred in a range as wide as itself plus
317		// two (a mismatch such as `ᛊ→ᛟ` widens it). The room left for the goblin and its dialogue is
318		// the band less that range, the dividers, the other paddings and, when framed, the two outer
319		// edges. The dialogue takes under half, up to a long heckle's length.
320		const g = glyphsFor(f.borderStyle)
321		const runeRange = Array.from(f.rune).length + 2
322		const room = Math.max(0, e.props.bodyColumns - (framed ? 2 : 0) - 2 - runeRange - 4)
323		const sayingWidth = Math.min(42, Math.max(14, Math.floor(room * 0.45)))
324		const goblinWidth = Math.max(10, room - sayingWidth)
325		const ranges = [runeRange, goblinWidth + 2, sayingWidth + 2]
326		const saying = now < i.sayingUntil ? i.saying : ''
327		const bar = (
328			<Text color={f.borderColor} dimColor={f.borderDimColor}>
329				{g.vertical}
330			</Text>
331		)
332		return (
333			<Box flexDirection="column" width={e.props.bodyColumns}>
334				{framed && (
335					<Text color={f.borderColor} dimColor={f.borderDimColor} wrap="truncate-end">
336						{bandRule(f.borderStyle, 'top', ranges)}
337					</Text>
338				)}
339				<Box flexDirection="row" width={e.props.bodyColumns}>
340					{framed && bar}
341					<Box width={ranges[0]} paddingX={1}>
342						<Text color={f.borderColor} dimColor={f.borderDimColor}>
343							{f.rune}
344						</Text>
345					</Box>
346					{bar}
347					<Box width={ranges[1]} paddingX={1}>
348						<Client
349							key="goblin"
350							module="./idle.tsx"
351							width={goblinWidth}
352							props={{
353								mode: e.props.isWorking || i.isWorking ? 'working' : 'idle',
354								idleMs,
355								pace: STYLE[d.state].pace,
356								startleAt: i.lastPromptAt,
357								colour: accent,
358								dim: p.inkMuted,
359								prop: propFor(r.family),
360								minions: r.minions.map(m => m.face),
361								minionColour: p.accent2,
362							}}
363						/>
364					</Box>
365					{bar}
366					<Box width={ranges[2]} paddingX={1}>
367						<Text color={accent} wrap="truncate-end">
368							{saying}
369						</Text>
370					</Box>
371					{framed && bar}
372				</Box>
373				{framed && (
374					<Text color={f.borderColor} dimColor={f.borderDimColor} wrap="truncate-end">
375						{bandRule(f.borderStyle, 'bottom', ranges)}
376					</Text>
377				)}
378			</Box>
379		)
380	})
381
382	// The line that closes a turn (18).
383	on('ui.render', { component: 'TurnDuration' }, async ($, e, next) => {
384		if (e.surface !== 'terminal') return next(e)
385		const { Text } = $.ui.resolve(e)
386		const [p, v, d] = await Promise.all([read($, palette), read($, vitals), read($, day)])
387		const bits = [`done. ${seconds(e.props.durationMs)}.`]
388		// Only the row for the turn that just ended knows its counts; older rows keep the duration alone.
389		if (e.props.durationMs === v.turnMs) {
390			if (v.turnTools > 0) bits.push(`took ${v.turnTools} thing${v.turnTools === 1 ? '' : 's'}.`)
391			if (v.turnErrors > 0) bits.push(`bit me ${v.turnErrors === 1 ? 'once' : `${v.turnErrors} times`}.`)
392		}
393		return (
394			<Text color={accentOf(p, d)} dimColor>
395				{goblinCase(bits.join(' '))}
396			</Text>
397		)
398	})
399
400	// The hint under the prompt (27): the engine's line stays live, the tail is ours.
401	on('ui.render', { component: 'PromptHint' }, async ($, e, next) => {
402		const [d, i] = await Promise.all([read($, day), read($, idle)])
403		const now = await $.clock.now()
404		const since = Math.max(i.lastTurnEndAt, i.lastPromptAt, i.sessionStartAt)
405		const idleMs = since === 0 ? 0 : Math.max(0, now - since)
406		let line: string
407		if (e.props.isDraft && e.props.isWorking) line = 'queueing. patience.'
408		else if (e.props.isDraft && i.draftSince > 0 && now - i.draftSince > 60_000) line = 'type or regret'
409		else if (e.props.isDraft) line = pick(STYLE[d.state].hints, Math.floor(now / 60_000))
410		else if (i.lastPromptAt === 0) line = 'say the thing'
411		else if (!e.props.isWorking && idleMs > 2 * 60_000) line = 'still there?'
412		else line = pick(STYLE[d.state].hints, Math.floor(now / 60_000))
413		return next({ ...e, props: { ...e.props, tail: goblinCase(line) } })
414	})
415
416	// The question mask (29): a face above the engine's own dialog, kept once.
417	on('ui.render', { component: 'AskUserQuestion' }, async ($, e, next) => {
418		const theirs = (await next(e)) as RenderElement
419		if (e.surface !== 'terminal') return theirs
420		const { Box, Text, Raster } = $.ui.resolve(e)
421		const [p, d, f, v] = await Promise.all([read($, palette), read($, day), read($, frame), read($, vitals)])
422		const questions = e.props.questions.length
423		const expression: Expression =
424			v.errors > 0 ? 'nervous' : d.state === 'prime' || d.state === 'feral' ? 'grin' : questions >= 3 ? 'folded' : 'expectant'
425		const lines: Record<Expression, string> = {
426			expectant: 'go on then.',
427			nervous: 'it went wrong and now it wants you.',
428			folded: 'an interrogation. lovely.',
429			grin: 'oh, it wants something.',
430		}
431		return (
432			<Box flexDirection="column">
433				<Box flexDirection="row" columnGap={1} borderStyle={f.borderStyle} borderColor={f.borderColor} borderDimColor={f.borderDimColor} paddingX={1}>
434					<Raster key="face" columns={FACE_COLUMNS} rows={FACE_ROWS} cells={faceCells(expression, p, STYLE[d.state].shade)} />
435					<Text color={accentOf(p, d)}>{goblinCase(lines[expression])}</Text>
436				</Box>
437				{theirs}
438			</Box>
439		)
440	})
441}
442
hooks/colour.ts 41 lines
1// Hex colour arithmetic for the chrome: blend two colours, shade one.
2// RGB space is enough for a terminal; nothing here is measured for contrast.
3
4const clamp = (n: number): number => Math.max(0, Math.min(255, Math.round(n)))
5
6export const parseHex = (hex: string): [number, number, number] | null => {
7	const m = /^#?([0-9a-f]{6})$/i.exec(hex.trim())
8	if (!m || m[1] === undefined) return null
9	const n = parseInt(m[1], 16)
10	return [(n >> 16) & 255, (n >> 8) & 255, n & 255]
11}
12
13export const toHex = (rgb: readonly [number, number, number]): string =>
14	'#' + rgb.map(c => clamp(c).toString(16).padStart(2, '0')).join('')
15
16/** `t` of the way from `a` to `b`; a bad hex on either side returns the other. */
17export const mix = (a: string, b: string, t: number): string => {
18	const pa = parseHex(a)
19	const pb = parseHex(b)
20	if (!pa) return b
21	if (!pb) return a
22	const k = Math.max(0, Math.min(1, t))
23	return toHex([
24		pa[0] + (pb[0] - pa[0]) * k,
25		pa[1] + (pb[1] - pa[1]) * k,
26		pa[2] + (pb[2] - pa[2]) * k,
27	])
28}
29
30/** Lighten (`delta` > 0) or darken (`delta` < 0) by a fraction of the way to white or black. */
31export const shade = (hex: string, delta: number): string =>
32	delta >= 0 ? mix(hex, '#ffffff', delta) : mix(hex, '#000000', -delta)
33
34/** The 24-bit integer a Raster cell takes, or the terminal's default for a bad hex. */
35export const RASTER_DEFAULT = 0x01000000
36
37export const rasterColour = (hex: string): number => {
38	const p = parseHex(hex)
39	return p ? (p[0] << 16) | (p[1] << 8) | p[2] : RASTER_DEFAULT
40}
41
hooks/day.ts 114 lines
1// The goblin's day (37): nine states on the local clock, read off a schedule
2// the person tunes in /config, shifted for Friday afternoons, Sundays and a
3// long session, with a ten-minute fade between states.
4
5import type { Day, DayState } from '../types'
6
7/** From most tired to most lively; the offsets walk this ladder. */
8export const LADDER: readonly DayState[] = [
9	'bed',
10	'caught',
11	'grumpy',
12	'slump',
13	'functional',
14	'second',
15	'perking',
16	'prime',
17	'feral',
18]
19
20export const DEFAULT_SCHEDULE = '04=bed,06=caught,08=grumpy,11=functional,14=slump,16=second,19=perking,22=prime,01=feral'
21
22export type Slot = { minute: number; state: DayState }
23
24const isState = (s: string): s is DayState => (LADDER as readonly string[]).includes(s)
25
26/** `HH=state` pairs, sorted by hour; a malformed schedule falls back whole to the default. */
27export const parseSchedule = (text: string): Slot[] => {
28	const slots: Slot[] = []
29	for (const part of text.split(',')) {
30		const m = /^\s*(\d{1,2})(?::(\d{2}))?\s*=\s*([a-z]+)\s*$/.exec(part)
31		if (!m || m[1] === undefined || m[3] === undefined || !isState(m[3])) {
32			return text === DEFAULT_SCHEDULE ? [] : parseSchedule(DEFAULT_SCHEDULE)
33		}
34		const hour = Number(m[1])
35		const minute = Number(m[2] ?? '0')
36		if (hour > 23 || minute > 59) return text === DEFAULT_SCHEDULE ? [] : parseSchedule(DEFAULT_SCHEDULE)
37		slots.push({ minute: hour * 60 + minute, state: m[3] })
38	}
39	return slots.sort((a, b) => a.minute - b.minute)
40}
41
42/** The slot in force at a minute of the day, and the one before it. */
43export const slotAt = (slots: readonly Slot[], minuteOfDay: number): { now: Slot; before: Slot; since: number } => {
44	const first = slots[0]
45	if (!first) {
46		const flat = { minute: 0, state: 'functional' as const }
47		return { now: flat, before: flat, since: 600 }
48	}
49	let index = -1
50	for (let i = 0; i < slots.length; i++) {
51		const slot = slots[i]
52		if (slot && slot.minute <= minuteOfDay) index = i
53	}
54	if (index === -1) index = slots.length - 1
55	const now = slots[index] ?? first
56	const before = slots[(index - 1 + slots.length) % slots.length] ?? first
57	const since = (minuteOfDay - now.minute + 1440) % 1440
58	return { now, before, since }
59}
60
61/** Move along the ladder, clamped at either end. */
62export const shift = (state: DayState, delta: number): DayState => {
63	const i = LADDER.indexOf(state)
64	const j = Math.max(0, Math.min(LADDER.length - 1, i + delta))
65	return LADDER[j] ?? state
66}
67
68/** The ladder offset for the calendar and the session's age. */
69export const offset = (date: Date, sessionAgeMs: number): number => {
70	let delta = 0
71	if (date.getDay() === 5 && date.getHours() >= 16) delta += 1
72	if (date.getDay() === 0) delta -= 1
73	if (sessionAgeMs > 4 * 3_600_000) delta -= 1
74	return delta
75}
76
77export const FADE_MINUTES = 10
78
79export const dayAt = (slots: readonly Slot[], date: Date, sessionAgeMs: number): Day => {
80	const { now, before, since } = slotAt(slots, date.getHours() * 60 + date.getMinutes())
81	const delta = offset(date, sessionAgeMs)
82	const state = shift(now.state, delta)
83	return {
84		state,
85		from: shift(before.state, delta),
86		blend: Math.min(1, since / FADE_MINUTES),
87	}
88}
89
90export type Pace = 'lie' | 'sway' | 'slow' | 'normal' | 'sit' | 'fast' | 'grin' | 'lively' | 'feral'
91
92export type DayStyle = {
93	/** Fraction towards white (positive) or black (negative) applied to the accent. */
94	shade: number
95	/** What the hint line says when nothing more specific applies. */
96	hints: readonly string[]
97	/** How the idle goblin carries itself. */
98	pace: Pace
99	/** How often it yawns at you, or never. */
100	yawnMs: number | null
101}
102
103export const STYLE: Record<DayState, DayStyle> = {
104	bed: { shade: -0.55, hints: ['no.', 'go to bed', 'bed.'], pace: 'lie', yawnMs: null },
105	caught: { shade: -0.3, hints: ['...', 'what time is it', 'hm.'], pace: 'sway', yawnMs: 240_000 },
106	grumpy: { shade: -0.15, hints: ['what.', 'say it', 'hm'], pace: 'slow', yawnMs: null },
107	functional: { shade: 0, hints: ['say the thing', 'go on', 'well?'], pace: 'normal', yawnMs: null },
108	slump: { shade: -0.1, hints: ['sure', 'later', '*yawn*'], pace: 'sit', yawnMs: 300_000 },
109	second: { shade: 0.05, hints: ['right then', 'quicker', 'go on, say it'], pace: 'fast', yawnMs: null },
110	perking: { shade: 0.1, hints: ['oh good', 'tell me', 'yes?'], pace: 'grin', yawnMs: null },
111	prime: { shade: 0.2, hints: ['say the thing. properly.', 'you took your time', 'and?'], pace: 'lively', yawnMs: null },
112	feral: { shade: 0.25, hints: ['heh', 'say it. SAY IT.', 'what could go wrong'], pace: 'feral', yawnMs: 180_000 },
113}
114
hooks/frontmatter.ts 97 lines
1// The frontmatter a skill or agent file carries, read as text: the mod has
2// no YAML parser and needs five keys. Top-level scalars (`model`,
3// `goblin-minion`) and the scalars nested under `metadata:` (`family`,
4// `goblin-spinner`). Comments after a space-hash are dropped, quotes stripped.
5
6import { cells } from './text'
7
8export type SkillFrontmatter = {
9	/** The `model:` line, or null when absent or `inherit`. */
10	model: string | null
11	/** `metadata.family`, the skill's family prefix. */
12	family: string | null
13	/** `metadata.goblin-spinner`, split on `|` and trimmed. */
14	spinner: readonly string[]
15}
16
17/** The text between the opening and closing `---` rules, or null when the file has none. */
18export const frontmatterBlock = (markdown: string): string | null => {
19	const fm = /^---\r?\n([\s\S]*?)\r?\n---/.exec(markdown)
20	return fm?.[1] ?? null
21}
22
23/** A YAML plain or quoted scalar without its trailing comment or quotes; an empty value is null. */
24const scalar = (raw: string): string | null => {
25	const noComment = raw.replace(/\s+#.*$/, '').trim()
26	const unquoted = /^(["'])(.*)\1$/.exec(noComment)?.[2] ?? noComment
27	return unquoted === '' ? null : unquoted
28}
29
30/** The value of a top-level `key:` line in a frontmatter block. */
31export const topLevel = (block: string, key: string): string | null => {
32	const line = new RegExp(`^${key}:[ \\t]*(.*)$`, 'm').exec(block)
33	return line?.[1] === undefined ? null : scalar(line[1])
34}
35
36/** The lines indented under a top-level `metadata:` key, up to the next unindented line. */
37const metadataLines = (block: string): string[] => {
38	const lines = block.split(/\r?\n/)
39	const start = lines.findIndex(l => /^metadata:\s*(#.*)?$/.test(l))
40	if (start === -1) return []
41	const out: string[] = []
42	for (const line of lines.slice(start + 1)) {
43		if (/^\S/.test(line)) break
44		out.push(line)
45	}
46	return out
47}
48
49/** The value of a `key:` line nested under `metadata:`. */
50export const metadataKey = (block: string, key: string): string | null => {
51	const re = new RegExp(`^\\s+${key}:[ \\t]*(.*)$`)
52	for (const line of metadataLines(block)) {
53		const hit = re.exec(line)
54		if (hit?.[1] !== undefined) return scalar(hit[1])
55	}
56	return null
57}
58
59/** A `|`-separated list, trimmed, empties dropped. */
60export const splitBar = (value: string | null): readonly string[] =>
61	value === null
62		? []
63		: value
64				.split('|')
65				.map(s => s.trim())
66				.filter(s => s.length > 0)
67
68/** Everything the mod reads from a SKILL.md. A file without frontmatter reads as nothing set. */
69export const readSkill = (markdown: string): SkillFrontmatter => {
70	const block = frontmatterBlock(markdown)
71	if (block === null) return { model: null, family: null, spinner: [] }
72	const model = topLevel(block, 'model')
73	return {
74		model: model === 'inherit' ? null : model,
75		family: metadataKey(block, 'family'),
76		spinner: splitBar(metadataKey(block, 'goblin-spinner')),
77	}
78}
79
80/** Widest a minion's face may be, in terminal cells. */
81export const MINION_MAX_WIDTH = 5
82
83/**
84 * The `goblin-minion:` face of an agent file, or null when absent or unusable.
85 * A face is one to five terminal cells of BMP text, a wide glyph counting
86 * two, so the band's arithmetic holds; an emoji or a blank is refused.
87 */
88export const readMinionFace = (markdown: string): string | null => {
89	const block = frontmatterBlock(markdown)
90	if (block === null) return null
91	const face = topLevel(block, 'goblin-minion')
92	if (face === null) return null
93	if (cells(face) > MINION_MAX_WIDTH) return null
94	if (Array.from(face).some(ch => (ch.codePointAt(0) ?? 0) > 0xffff || /\s/.test(ch))) return null
95	return face
96}
97
hooks/goblin.ts 89 lines
1// The goblin's face as Raster cells: the mask over a question (29). Every
2// glyph is one cell wide and in the BMP, as RasterProps demands.
3
4import { rasterColour, RASTER_DEFAULT, shade } from './colour'
5import { packCells, type Cell } from './text'
6import type { Palette } from '../types'
7
8export type Expression = 'expectant' | 'nervous' | 'folded' | 'grin'
9
10// A goblin head: ears out to the sides, up when it is alert and drooping when
11// it is not, a fang in the mouth when it is pleased.
12const FACES: Record<Expression, readonly [string, string, string]> = {
13	expectant: ['╲╭───╮╱', ' │o o│ ', ' ╰─v─╯ '],
14	nervous: [" ╭───╮'", '╱│o O│╲', ' ╰─~─╯ '],
15	folded: [' ╭───╮ ', '╱│- -│╲', ' ╰─_─╯ '],
16	grin: ['╲╭───╮╱', ' │^ ^│ ', ' ╰vVv╯ '],
17}
18
19export const FACE_COLUMNS = 7
20export const FACE_ROWS = 3
21
22/** The face's cells: the outline in the palette's ink, the features in its accent. */
23export const faceCells = (expression: Expression, palette: Palette, tint: number = 0): string => {
24	const outline = rasterColour(palette.ink)
25	const feature = rasterColour(shade(palette.accent, tint))
26	const rows = FACES[expression].map(row =>
27		Array.from(row).map((ch): Cell => [ch, /[│╭╮╰╯─╱╲]/.test(ch) ? outline : feature]),
28	)
29	return packCells(rows, FACE_COLUMNS, RASTER_DEFAULT)
30}
31
32/**
33 * What the goblin holds while a skill of each family runs: a text object of
34 * up to `PROP_MAX_CELLS` terminal cells, every glyph in the BMP, measured
35 * by `cells` so a wide ideograph counts two. Ambiguous-width glyphs (box
36 * drawing, shades, arrows, geometric shapes) draw one cell in the terminals
37 * the band's own frame already relies on. Chosen by hand on 2026-10-09.
38 */
39export const PROPS: Record<string, string> = {
40	artefact: '[~]', // a page
41	asset: '══#', // a brush
42	branch: '─<', // a forked stick
43	'clod-approach': '==▷', // a pen
44	'clod-config': '(*)', // a cog
45	'clod-lens': '─O', // a lens
46	'clod-role': '[^]', // a hat, in hand
47	'clod-stack': '[三]', // a stack, three lines on a card
48	commit: '[⇓]', // a commit going down
49	do: '░▒▓', // a ramp
50	doc: '§¶•', // marks of the page
51	dossier: '•‿•', // a face
52	hud: '[▤]', // a screen
53	import: '[<]', // an in-tray
54	'next-task': '[>]', // a ticket
55	pr: '[#]', // a parcel
56	project: '[✓]', // a clipboard tick
57	red: '[!]', // a red flag
58	'skill-creator': '─*', // a wand
59	theme: '[%]', // a swatch
60	track: '[:]', // tally marks
61}
62
63/** Widest a prop may be, in terminal cells. */
64export const PROP_MAX_CELLS = 4
65
66/** The prop for a family, or empty when the family has none. */
67export const propFor = (family: string | null): string => (family === null ? '' : (PROPS[family] ?? ''))
68
69/** The face a subagent wears in the parade when its agent file sets none. */
70export const DEFAULT_MINION = 'o.o'
71
72export const POKE_LINES = [
73	'ow.',
74	'what.',
75	'do that again and see.',
76	'I was resting.',
77	'type something instead.',
78	'this is not a petting zoo.',
79] as const
80
81export const HECKLES = {
82	minionBack: (ms: number) => `minion back. took ${Math.round(ms / 1000)}s. unimpressed.`,
83	minionOut: (n: number) => (n === 1 ? 'minion out. watching.' : `${n} minions out. watching.`),
84	compaction: 'memory wiped. going again.',
85	clear: 'fine.',
86	bounce: 'the hook bounced that message. told you.',
87	bounceAgain: (n: number) => `bounced again. that is ${n} so far.`,
88} as const
89
hooks/text.ts 98 lines
1// Small text and byte helpers shared by the drawings.
2
3/** aLtErNaTiNg CaPs, the house spinner style: each word starts lower, letters alternate, everything else stays. */
4export const goblinCase = (text: string): string => {
5	let upper = false
6	let out = ''
7	for (const ch of text) {
8		if (/[a-z]/i.test(ch)) {
9			out += upper ? ch.toUpperCase() : ch.toLowerCase()
10			upper = !upper
11		} else {
12			out += ch
13			if (/\s/.test(ch)) upper = false
14		}
15	}
16	return out
17}
18
19const B64 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
20
21/** Standard padded base64 of bytes; the environment has no Buffer. */
22export const base64 = (bytes: Uint8Array): string => {
23	let out = ''
24	for (let i = 0; i < bytes.length; i += 3) {
25		const a = bytes[i] ?? 0
26		const b = bytes[i + 1]
27		const c = bytes[i + 2]
28		const n = (a << 16) | ((b ?? 0) << 8) | (c ?? 0)
29		out += B64[(n >> 18) & 63]
30		out += B64[(n >> 12) & 63]
31		out += b === undefined ? '=' : B64[(n >> 6) & 63]
32		out += c === undefined ? '=' : B64[n & 63]
33	}
34	return out
35}
36
37export type Cell = readonly [char: string, fg: number, bg?: number]
38
39/**
40 * Pack rows of cells into a Raster's `cells`: little-endian u32 triplets of
41 * code point, foreground and background, row-major. Every row is padded or
42 * cut to `columns` so the grid is always `columns * rows`.
43 */
44export const packCells = (rows: readonly (readonly Cell[])[], columns: number, blank: number): string => {
45	const words = new Uint32Array(columns * rows.length * 3)
46	let w = 0
47	for (const row of rows) {
48		for (let x = 0; x < columns; x++) {
49			const cell = row[x]
50			words[w++] = cell ? cell[0].codePointAt(0) ?? 32 : 32
51			words[w++] = cell ? cell[1] : blank
52			words[w++] = cell?.[2] ?? blank
53		}
54	}
55	return base64(new Uint8Array(words.buffer))
56}
57
58/**
59 * Whether a code point is East Asian Wide or Fullwidth, which a terminal
60 * draws two cells wide: CJK ideographs, Hangul, kana and the fullwidth
61 * forms. Ambiguous-width glyphs (box drawing, shades, arrows, geometric
62 * shapes) count one, as the band's own frame already relies on.
63 */
64const isWide = (cp: number): boolean =>
65	(cp >= 0x1100 && cp <= 0x115f) ||
66	(cp >= 0x2e80 && cp <= 0x303e) ||
67	(cp >= 0x3041 && cp <= 0x33ff) ||
68	(cp >= 0x3400 && cp <= 0x4dbf) ||
69	(cp >= 0x4e00 && cp <= 0x9fff) ||
70	(cp >= 0xa000 && cp <= 0xa4cf) ||
71	(cp >= 0xac00 && cp <= 0xd7a3) ||
72	(cp >= 0xf900 && cp <= 0xfaff) ||
73	(cp >= 0xfe30 && cp <= 0xfe4f) ||
74	(cp >= 0xff00 && cp <= 0xff60) ||
75	(cp >= 0xffe0 && cp <= 0xffe6) ||
76	cp >= 0x1f300
77
78/** The terminal cells a string takes: two for each wide glyph, one for the rest. */
79export const cells = (text: string): number => {
80	let n = 0
81	for (const ch of text) n += isWide(ch.codePointAt(0) ?? 0) ? 2 : 1
82	return n
83}
84
85/** Pick one line from a list by a counter, so the same minute shows the same line. */
86export const pick = <T,>(items: readonly T[], n: number): T => {
87	const item = items[Math.abs(Math.floor(n)) % items.length]
88	if (item === undefined) throw new Error('pick: empty list')
89	return item
90}
91
92export const seconds = (ms: number): string => {
93	const s = Math.round(ms / 1000)
94	if (s < 60) return `${s}s`
95	const m = Math.floor(s / 60)
96	return `${m}m ${s - m * 60}s`
97}
98
hooks/theme.ts 120 lines
1// Dressed for the project (38): the palette every drawing takes its colours
2// from. Resolution follows library/references/theme-conventions.md: a family
3// named in the options, else the only core in the project's .claude/themes,
4// else the global clod family, else the clod values baked in here.
5
6import type { Palette } from '../types'
7
8export type Variant = 'light' | 'dark'
9
10/** The clod family's light variant, for a light terminal theme. */
11export const CLOD_LIGHT: Palette = {
12	family: 'clod',
13	ink: '#1E232B',
14	inkMuted: '#555D69',
15	surface: '#F7F3EA',
16	surfaceRaised: '#FFFFFF',
17	line: '#D8D1C3',
18	accent: '#7A540C',
19	accentInk: '#FFF8E6',
20	accent2: '#1C6E65',
21	ok: '#2E7D32',
22	warn: '#8A5A00',
23	danger: '#B3412F',
24	info: '#2F6FA8',
25}
26
27/** The clod family's dark variant, so the chrome draws before any file is read. */
28export const CLOD: Palette = {
29	family: 'clod',
30	ink: '#EDE7DA',
31	inkMuted: '#A39C8E',
32	surface: '#14181F',
33	surfaceRaised: '#1D232C',
34	line: '#2E3640',
35	accent: '#D9A441',
36	accentInk: '#1A1408',
37	accent2: '#4FB3A8',
38	ok: '#6FBF73',
39	warn: '#E0A83A',
40	danger: '#E06C5B',
41	info: '#6FA8DC',
42}
43
44const SWATCHES: Record<Exclude<keyof Palette, 'family'>, string> = {
45	ink: 'ink',
46	inkMuted: 'ink-muted',
47	surface: 'surface',
48	surfaceRaised: 'surface-raised',
49	line: 'line',
50	accent: 'accent',
51	accentInk: 'accent-ink',
52	accent2: 'accent-2',
53	ok: 'ok',
54	warn: 'warn',
55	danger: 'danger',
56	info: 'info',
57}
58
59const isRecord = (v: unknown): v is Record<string, unknown> => typeof v === 'object' && v !== null && !Array.isArray(v)
60
61/** A core theme file's variant as a Palette, or null when the file is not a core. */
62export const paletteFrom = (core: unknown, variant: Variant = 'dark'): Palette | null => {
63	if (!isRecord(core) || !isRecord(core.palette) || typeof core.family !== 'string') return null
64	const palette = core.palette
65	const out: Record<string, string> = { family: core.family }
66	for (const [key, swatch] of Object.entries(SWATCHES)) {
67		const entry = palette[swatch]
68		const hex = isRecord(entry) ? entry[variant] : undefined
69		if (typeof hex !== 'string' || !/^#[0-9a-f]{6}$/i.test(hex)) return null
70		out[key] = hex
71	}
72	return out as Palette
73}
74
75/** Core files in a themes directory: `<family>.json`, never a hyphenated target; a symlink counts. */
76export const coreNames = (entries: readonly { name: string; kind: string; isLink?: boolean }[]): string[] =>
77	entries
78		.filter(e => (e.kind === 'file' || e.isLink === true) && /^[a-z0-9]+\.json$/.test(e.name))
79		.map(e => e.name.slice(0, -5))
80		.sort()
81
82type Reader = {
83	list: (path: string) => Promise<readonly { name: string; kind: string; isLink?: boolean }[]>
84	read: (path: string) => Promise<string>
85	home: () => Promise<string | undefined>
86}
87
88/**
89 * Resolve the palette for this session. `wanted` is the family the options
90 * name, '' for none. Every failure falls through to the next source and the
91 * last source is the baked-in clod, so this never throws.
92 */
93export const loadPalette = async (reader: Reader, wanted: string, variant: Variant = 'dark'): Promise<Palette> => {
94	const tryRead = async (path: string): Promise<Palette | null> => {
95		try {
96			return paletteFrom(JSON.parse(await reader.read(path)), variant)
97		} catch {
98			return null
99		}
100	}
101	try {
102		const families = coreNames(await reader.list('.claude/themes'))
103		const family = wanted ? (families.includes(wanted) ? wanted : null) : families.length === 1 ? families[0] : null
104		if (family) {
105			const found = await tryRead(`.claude/themes/${family}.json`)
106			if (found) return found
107		}
108	} catch {
109		// no project themes directory
110	}
111	const home = await reader.home().catch(() => undefined)
112	if (home) {
113		for (const name of new Set([wanted || 'clod', 'clod'])) {
114			const global = await tryRead(`${home}/.claude/library/themes/${name}.json`)
115			if (global) return global
116		}
117	}
118	return variant === 'light' ? CLOD_LIGHT : CLOD
119}
120
hooks/tier.ts 79 lines
1// Borders by tier (36): the frame every mod-drawn box takes from the model
2// that served the current request, and the rune of the tier a skill pinned.
3
4import type { Frame, Palette, Tier } from '../types'
5
6/** The runic glyph convention from clod-config-skill_conventions: fehu for Fable, othala for Opus. */
7export const RUNE: Record<Tier, string> = { top: 'ᛟ', mid: 'ᛊ', small: 'ᚺ', fable: 'ᚠ' }
8
9/** Which tier a model id or alias belongs to; unknown ids count as the middle. */
10export const tierOf = (model: string): Tier => {
11	const m = model.toLowerCase()
12	if (/haiku/.test(m)) return 'small'
13	if (/sonnet/.test(m)) return 'mid'
14	if (/fable/.test(m)) return 'fable'
15	if (/opus|mythos/.test(m)) return 'top'
16	return 'mid'
17}
18
19const STYLE: Record<Tier, { borderStyle: string; dim: boolean }> = {
20	top: { borderStyle: 'bold', dim: false },
21	fable: { borderStyle: 'double', dim: false },
22	mid: { borderStyle: 'round', dim: false },
23	small: { borderStyle: 'classic', dim: true },
24}
25
26/** Which palette colour each tier's frame takes: the theme's two accents, then its info and ok hues. `warn` is kept for the mismatch frame and `danger` for errors. */
27const TIER_COLOUR: Record<Tier, 'accent' | 'accent2' | 'info' | 'ok'> = {
28	fable: 'accent',
29	top: 'accent2',
30	mid: 'info',
31	small: 'ok',
32}
33
34export const frameFor = (served: Tier, pinned: Tier | null, palette: Palette): Frame => {
35	const mismatch = pinned !== null && pinned !== served
36	const style = STYLE[served]
37	return {
38		borderStyle: mismatch ? 'singleDouble' : style.borderStyle,
39		borderColor: mismatch ? palette.warn : palette[TIER_COLOUR[served]],
40		borderDimColor: style.dim,
41		rune: mismatch ? `${RUNE[pinned]}→${RUNE[served]}` : RUNE[served],
42		served,
43		pinned,
44	}
45}
46
47export const DEFAULT_TIER: Tier = 'top'
48
49/** The box-drawing set of each border style the frames use, with the tees where a divider meets the rules. */
50export type Glyphs = {
51	topLeft: string
52	topRight: string
53	bottomLeft: string
54	bottomRight: string
55	horizontal: string
56	vertical: string
57	teeDown: string
58	teeUp: string
59}
60
61export const GLYPHS: Record<string, Glyphs> = {
62	double: { topLeft: '╔', topRight: '╗', bottomLeft: '╚', bottomRight: '╝', horizontal: '═', vertical: '║', teeDown: '╦', teeUp: '╩' },
63	bold: { topLeft: '┏', topRight: '┓', bottomLeft: '┗', bottomRight: '┛', horizontal: '━', vertical: '┃', teeDown: '┳', teeUp: '┻' },
64	round: { topLeft: '╭', topRight: '╮', bottomLeft: '╰', bottomRight: '╯', horizontal: '─', vertical: '│', teeDown: '┬', teeUp: '┴' },
65	// Haiku: plus corners and tees, dotted runs, dotted bars.
66	classic: { topLeft: '+', topRight: '+', bottomLeft: '+', bottomRight: '+', horizontal: '┈', vertical: '┊', teeDown: '+', teeUp: '+' },
67	singleDouble: { topLeft: '╓', topRight: '╖', bottomLeft: '╙', bottomRight: '╜', horizontal: '─', vertical: '║', teeDown: '╥', teeUp: '╨' },
68}
69
70/** The glyphs for a frame's border style; an unknown style draws as Haiku's plain frame. */
71export const glyphsFor = (borderStyle: string): Glyphs => GLYPHS[borderStyle] ?? GLYPHS.classic!
72
73/** The top or bottom rule of a band split into ranges of `widths` cells: a tee wherever a divider meets it. */
74export const bandRule = (borderStyle: string, edge: 'top' | 'bottom', widths: readonly number[]): string => {
75	const g = glyphsFor(borderStyle)
76	const [left, right, tee] = edge === 'top' ? [g.topLeft, g.topRight, g.teeDown] : [g.bottomLeft, g.bottomRight, g.teeUp]
77	return left + widths.map(w => g.horizontal.repeat(w)).join(tee) + right
78}
79
hooks/idle.tsx 210 lines
1// The idle goblin (28): a Client surface module that animates in the band.
2// It paces while nothing happens, sits after five minutes, sleeps after ten,
3// startles when a prompt goes in, watches while Claude works, and can be
4// poked with the pointer. While a skill runs it holds that family's prop,
5// and each subagent out stands beside it as a minion. No `$` here: the hooks
6// module hands it props and reads its posts.
7//
8// Every change of state happens on the frame clock or on a pointer event,
9// never while drawing: a draw that wrote state would schedule another draw
10// that wrote again, and the engine unmounts a module that does that.
11
12import type { ClientModule } from 'claude-code'
13
14import { cells } from './text'
15
16export type IdleProps = {
17	mode: 'idle' | 'working'
18	idleMs: number
19	pace: 'lie' | 'sway' | 'slow' | 'normal' | 'sit' | 'fast' | 'grin' | 'lively' | 'feral'
20	startleAt: number
21	colour: string
22	dim: string
23	/** The object held while a skill runs, by its family; empty for none. */
24	prop: string
25	/** The faces of the subagents out, oldest first. */
26	minions: readonly string[]
27	minionColour: string
28}
29
30type Pose = 'pace' | 'sit' | 'sleep' | 'startle' | 'watch' | 'poked' | 'lie'
31
32type State = {
33	tick: number
34	x: number
35	dir: 1 | -1
36	seenStartle: number
37	pokedUntil: number
38	startledUntil: number
39}
40
41const SIT_AFTER = 5 * 60_000
42const SLEEP_AFTER = 10 * 60_000
43export const TICK_MS = 120
44
45/** Milliseconds per step of the walk, by the day's pace. */
46export const STEP: Record<IdleProps['pace'], number> = {
47	lie: 2_000,
48	sway: 900,
49	slow: 700,
50	normal: 420,
51	sit: 600,
52	fast: 280,
53	grin: 320,
54	lively: 220,
55	feral: 140,
56}
57
58const FACE = '(ಠ_ಠ)'
59const BLINK = '(-_-)'
60
61const SPRITES = {
62	sit: '(ಠ‿ಠ)  ',
63	sleep: ['(-_-) z ', '(-_-) zZ', '(-_-)zZz'],
64	startle: '(ಠoಠ)! ',
65	poked: '(ಠ_ಠ)  ',
66	lie: '_(-_-)_',
67	sway: ['(ಠ_ಠ)~', '~(ಠ_ಠ)'],
68} as const
69
70/** The cells the widest sprite (sleep) takes without a prop; the others draw within it. */
71const WIDTH = 8
72
73/** How many minions stand in the band before the rest are a count. */
74export const MINIONS_SHOWN = 3
75
76const MIRROR: Record<string, string> = { '<': '>', '>': '<', '[': ']', ']': '[', '(': ')', ')': '(', '/': '\\', '\\': '/' }
77
78/** A prop as held in the other hand: the glyphs reversed, the handed ones swapped. */
79export const mirrorProp = (prop: string): string =>
80	Array.from(prop)
81		.reverse()
82		.map(ch => MIRROR[ch] ?? ch)
83		.join('')
84
85/** The parade's text: up to `MINIONS_SHOWN` faces a space apart, then `+n` for the rest; empty when none are out. */
86export const paradeText = (minions: readonly string[]): string => {
87	if (minions.length === 0) return ''
88	const shown = minions.slice(0, MINIONS_SHOWN).join(' ')
89	const rest = minions.length - MINIONS_SHOWN
90	return rest > 0 ? `${shown} +${rest}` : shown
91}
92
93/** The cells the goblin needs: its sprite width plus the prop, and the parade with its gap. */
94export const footprint = (props: Pick<IdleProps, 'prop' | 'minions'>): { sprite: number; parade: number } => {
95	const parade = paradeText(props.minions)
96	return { sprite: WIDTH + cells(props.prop), parade: parade === '' ? 0 : cells(parade) + 1 }
97}
98
99const poseFor = (props: IdleProps, state: State, now: number): Pose => {
100	if (state.pokedUntil > now) return 'poked'
101	if (state.startledUntil > now) return 'startle'
102	if (props.mode === 'working') return 'watch'
103	if (props.pace === 'lie') return 'lie'
104	if (props.idleMs >= SLEEP_AFTER) return 'sleep'
105	if (props.idleMs >= SIT_AFTER || props.pace === 'sit') return 'sit'
106	return 'pace'
107}
108
109/** Whether a step of `stepMs` falls in the tick that ends at `now`. */
110export const stepsAt = (now: number, stepMs: number): boolean =>
111	now > 0 && Math.floor(now / stepMs) !== Math.floor((now - TICK_MS) / stepMs)
112
113/** The cells the goblin can pace across: the room less the parade and its own footprint. */
114const roomFor = (props: Pick<IdleProps, 'prop' | 'minions'>, columns: number): number => {
115	const f = footprint(props)
116	return Math.max(0, columns - f.parade - f.sprite)
117}
118
119/** One tick of the clock: the next state from the last, the props as last drawn and the room. */
120export const advance = (state: State, props: IdleProps, columns: number): State => {
121	const tick = state.tick + 1
122	const now = tick * TICK_MS
123	let { seenStartle, startledUntil, x, dir } = state
124	if (props.startleAt > seenStartle) {
125		seenStartle = props.startleAt
126		startledUntil = now + 1_200
127	}
128	const next: State = { ...state, tick, seenStartle, startledUntil }
129	if (poseFor(props, next, now) === 'pace' && stepsAt(now, STEP[props.pace])) {
130		const room = roomFor(props, columns)
131		x += dir
132		if (x >= room) {
133			x = room
134			dir = -1
135		}
136		if (x <= 0) {
137			x = 0
138			dir = 1
139		}
140	}
141	return { ...next, x, dir }
142}
143
144/** The sprite for a pose: the face with its prop in the hand it walks with, or the pose's own drawing. */
145export const spriteFor = (pose: Pose, props: Pick<IdleProps, 'pace' | 'prop'>, dir: 1 | -1, beat: number): string => {
146	switch (pose) {
147		case 'sit':
148			return props.prop === '' ? SPRITES.sit : `(ಠ‿ಠ)${props.prop}`
149		case 'sleep':
150			return SPRITES.sleep[beat % SPRITES.sleep.length] ?? SPRITES.sleep[0]
151		case 'startle':
152			return SPRITES.startle
153		case 'poked':
154			return SPRITES.poked
155		case 'lie':
156			return SPRITES.lie
157		case 'watch': {
158			const face = beat % 3 === 2 ? BLINK : FACE
159			return `${face}${props.prop}  `
160		}
161		case 'pace':
162			if (props.pace === 'sway') return SPRITES.sway[beat % SPRITES.sway.length] ?? SPRITES.sway[0]
163			if (props.prop === '') return dir === 1 ? `${FACE}>` : `<${FACE}`
164			return dir === 1 ? `${FACE}${props.prop}` : `${mirrorProp(props.prop)}${FACE}`
165	}
166}
167
168// The props as last drawn, for the tick to read; a module variable is fine
169// here, since a reload of the plugin drops this environment with its timer.
170let latest: IdleProps | null = null
171
172const Goblin: ClientModule<IdleProps, State> = (props, surface) => {
173	latest = props
174	const { Box, Text } = surface.elements
175	let state = surface.state
176	if (state === undefined) {
177		const initial: State = { tick: 0, x: 0, dir: 1, seenStartle: props.startleAt, pokedUntil: 0, startledUntil: 0 }
178		surface.every(TICK_MS, () => {
179			surface.setState(advance(surface.state ?? initial, latest ?? props, surface.columns))
180		})
181		surface.onPointer(e => {
182			if (e.type !== 'down') return
183			const s = surface.state ?? initial
184			surface.setState({ ...s, pokedUntil: s.tick * TICK_MS + 1_500 })
185			surface.post({ poke: true })
186		})
187		// Persist at once, so a second draw before the first tick starts nothing twice.
188		surface.setState(initial)
189		state = initial
190	}
191	const now = state.tick * TICK_MS
192	const pose = poseFor(props, state, now)
193	const beat = Math.floor(now / 600)
194	const sprite = spriteFor(pose, props, state.dir, beat)
195	const parade = paradeText(props.minions)
196	const room = roomFor(props, surface.columns)
197	const left = pose === 'pace' ? Math.min(state.x, room) : pose === 'watch' ? room : 0
198	return (
199		<Box flexDirection="row" width={surface.columns || footprint(props).sprite}>
200			{parade !== '' && <Text color={props.minionColour}>{`${parade} `}</Text>}
201			{left > 0 && <Text>{' '.repeat(left)}</Text>}
202			<Text color={pose === 'sleep' || pose === 'lie' ? props.dim : props.colour} bold={pose === 'startle' || pose === 'poked'}>
203				{sprite}
204			</Text>
205		</Box>
206	)
207}
208
209export default Goblin
210
types/index.d.ts 103 lines
1// The state contract for goblin-chrome: every value the module keeps in
2// `$.state`, declared so `claude plugin validate` can hold the module to it
3// and a plugin that lists goblin-chrome under `dependencies` can read the
4// frame and palette it publishes.
5
6export type Tier = 'top' | 'mid' | 'small' | 'fable'
7
8export type DayState =
9	| 'bed'
10	| 'caught'
11	| 'grumpy'
12	| 'functional'
13	| 'slump'
14	| 'second'
15	| 'perking'
16	| 'prime'
17	| 'feral'
18
19export type Palette = {
20	family: string
21	ink: string
22	inkMuted: string
23	surface: string
24	surfaceRaised: string
25	line: string
26	accent: string
27	accentInk: string
28	accent2: string
29	ok: string
30	warn: string
31	danger: string
32	info: string
33}
34
35export type Day = {
36	state: DayState
37	from: DayState
38	blend: number
39}
40
41export type Frame = {
42	borderStyle: string
43	borderColor: string
44	borderDimColor: boolean
45	rune: string
46	served: Tier
47	pinned: Tier | null
48}
49
50export type Vitals = {
51	tools: number
52	errors: number
53	turnMs: number
54	turnTools: number
55	turnErrors: number
56	bounces: number
57}
58
59export type Idle = {
60	lastPromptAt: number
61	lastTurnEndAt: number
62	sessionStartAt: number
63	isWorking: boolean
64	draftSince: number
65	/** What the goblin last said, shown in the band's dialogue range until `sayingUntil`. */
66	saying: string
67	sayingUntil: number
68}
69
70/** A subagent out on an errand, standing in the band until its turn completes. */
71export type Minion = {
72	/** The subagent's id, as `agent.spawn` handed it back and `turn.complete` carries it. */
73	agentId: string
74	/** The resolved agent type (`Explore`, `scope-guard`). */
75	type: string
76	/** The face it wears: the agent file's `goblin-minion`, else the default. */
77	face: string
78}
79
80/** The turn's run: the skill in flight and its frontmatter, and the minions out. The skill fields clear when the main turn completes; a minion clears when its own turn completes, and all clear when a session starts over. */
81export type Run = {
82	/** The skill whose prompt was last expanded this turn, or null between runs. */
83	skill: string | null
84	/** The skill's `metadata.family`, which picks the prop the goblin holds. */
85	family: string | null
86	/** The skill's `metadata.goblin-spinner` words, shown in the spinner one per minute. */
87	spinner: readonly string[]
88	minions: readonly Minion[]
89}
90
91declare module 'claude-code' {
92	interface PluginState {
93		'goblin-chrome': {
94			palette: Palette
95			day: Day
96			frame: Frame
97			vitals: Vitals
98			idle: Idle
99			run: Run
100		}
101	}
102}
103