A little comic above the prompt: Claude acts out what the agent is doing in animated pixel scenes, from a home hub with keepsakes

A Claude Code plugin marketplace with my mods and plugins.
/plugin marketplace add CatraMyBeloved/catras-claude-code-collection
/plugin install agent-comic@catras-claude-code-collection
/plugin install cache-keepalive@catras-claude-code-collection
/plugin install claudle@catras-claude-code-collection
The repo is private, so git must be authenticated (e.g. gh auth login). If the SSH attempt fails, set CLAUDE_CODE_PLUGIN_PREFER_HTTPS=1.
A pixel comic in the band above the prompt: a little Claude acts out what the agent is doing.
hub_add, deferred, so it costs no context until used); the hub keeps six. /comic-hub lists them./comic-pet: he lights up, and a headpat is sent as your message ("Here, have a headpat. You are doing amazing!"), which Claude answers.hybrid (default) has the model set up the session's world and stage each turn's opening and wrap-up in it, and plays canned scenes in between; full stages everything with the model; off uses no tokens at all. Set it with /config, along with the model, pace and whether the comic stays up between turns.$.comic (a garden, a pond, a minigame). Between turns, wooden signs in the hub's top corners lead to them (a/d once the band has focus); while Claude works the comic takes the band back. With no place installed nothing changes. How to build one: EXTENDING.md; a complete example is pond-place./comic svg image (default) draws it as a picture, /comic svg frame in a sandboxed frame, in case a surface does not animate the picture.Commands: /comic (on/off, or /comic svg image|frame), /comic-pet, /comic-hub, /comic-stats, /comic-feel <mood>, /comic-demo.
Keeps Claude Code's prompt cache warm while you think, so the next prompt reads the conversation from the cache instead of paying to write it again.
cache ▰▰▰▰▰▰▱▱ 41:12 (1h), in calm tones: sage green, sand yellow for the last 10 minutes, dusty rose for the last 3 (a 5-minute cache keeps the same proportions). The timer restarts with every request of the main conversation.auto follows Claude Code's own rules: FORCE_PROMPT_CACHING_5M, then CLAUDE_CODE_PROMPT_CACHE_TTL, the promptCacheTtl setting and ENABLE_PROMPT_CACHING_1H; otherwise 1 hour on a subscription within plan limits and 5 minutes on an API key, a cloud provider or usage credits. The mod cannot always tell when a subscription draws on credits; set the lifetime to 5m in /config then./keepalive opens a pane with the bar, the expiry time, the cached prefix size, a timeline of hits, misses and keep-alives, and buttons to ping now (p) or pause (k).Commands: /keepalive (gauge), /keepalive status, /keepalive on|off, /keepalive now. Set the mode (prompt or off), lifetime, lead and idle cutoff with /config.
Why a message and not an invisible side request: a side request ($.model.fork) re-sends the conversation, but Claude Code caches it as a separate entry, so it never kept the main conversation's cache warm in testing.
Programming mini-games in a side pane, to play while the agent works. Claude writes every round, pitches it at your level and grades free-text answers.
In the terminal, click a card in fullscreen mode, or press ctrl+x tab and use the keys the pane lists; in the desktop app and VS Code, click, or press the key marked on a button once the pane has focus. Commands: /claudle, /claudle play <game>, /claudle answer <text>, /claudle topics a, b, c, /claudle stats, /claudle reset. Set the quizmaster model (sonnet, opus or haiku) with /config.
claude plugin validate .
claude plugin test plugins/cache-keepalive
claude plugin test plugins/claudle
claude plugin test examples/pond-place
examples/ holds example plugins that are not in the marketplace; copy one as a starting point.
CACHE_KEEPALIVE_HEADLESS=1 lets cache-keepalive run under claude -p --plugin-dir plugins/cache-keepalive, for checking its cache behaviour without an interactive session.
GPL-3.0. Copyright (c) 2026 Ole Stein.
hooks/register.tsx 422 lines1// agent-comic: a pixel comic in the band above the prompt, where a little Claude acts out what the agent
2// is doing. This module wires it into Claude Code: the hooks, the commands and the band.
3//
4// stage.ts plays and draws the comic, with the hub (home.ts) and the subagents' helpers (helpers.ts);
5// director.ts stages it from what the agent does (activity.ts) with the model or canned scenes;
6// state.ts and places.ts keep the ring of places other plugins add through $.comic (EXTENDING.md).
7
8import type { EngineInterface, On, Register } from 'claude-code'
9
10import type { Comic } from '../types'
11import { CUES, clearFinishedTasks, observe } from './activity'
12import { RASTER_KEY, desktopChunk, getSvgMode, hideBand, setSvgMode, startBand, terminalCells } from './band'
13import { DEMO_MS, demoScene, feelBeat } from './demo'
14import {
15 act, addToTurn, beginTurn, endTurn, forgetWorld, heard, isTurnRunning, leaveWorld, note, pauseFor, startDirector, stats, tick, toolEnded, toolStarted,
16} from './director'
17import { HUB_STORE_KEY, HUB_TOOL, HUB_TOOL_SPEC, MAX_HUB_ITEMS, addHubItem, asHubItems, hubItemFrom } from './hub'
18import type { HubItem } from './hub'
19import { givePat, pats } from './pets'
20import { COMIC_VERSION, HUB, asPlace, kit, routeOf } from './places'
21import { describeCall } from './prompt'
22import { applySettings, settings, stage } from './runtime'
23import { MOODS } from './scene'
24import type { Mood } from './scene'
25import {
26 addPlace, checkPlace, goTo, isEnabled, isLingering, placeAlive, removePlace, routeNow, setEnabled, setLingering, stepTo, stops, syncState, whereNow,
27} from './state'
28
29const LINGER_MS = 25_000 // the band stays this long after a turn ends
30const FEEL_MS = 9000 // the band stays up this long for a /comic-feel
31const MAX_ROWS = 10
32const MIN_ROWS = 6
33const PET_KEY = 'pet'
34const SIGN_LEFT = 'sign-left'
35const SIGN_RIGHT = 'sign-right'
36const HUB_TOOL_NAME = new RegExp(`^mcp__agent-comic__${HUB_TOOL}$`)
37const MAX_HUB_ADDS = 2 // keepsakes per session: a milestone, not a habit
38/** Tools that put a question to the person, who must answer before the turn goes on. */
39const ASKS_PERSON = new Set(['AskUserQuestion', 'ExitPlanMode'])
40const FEELINGS = MOODS.filter((m): m is Exclude<Mood, 'neutral'> => m !== 'neutral')
41
42/** The keepsakes in the hub (kept across sessions), and how many Claude added this session. */
43const hub = { items: [] as HubItem[], added: 0 }
44let linger: { cancel: () => void } | null = null
45
46/** A turn runs, or Claude answers a pat. */
47const isWorking = () => isTurnRunning() || pats.isAnswering
48const sync = ($: EngineInterface) => syncState($, isWorking)
49
50export const register: Register = (on, options) => {
51 applySettings(options)
52 startDirector()
53 registerPlaces(on)
54 registerSession(on)
55 registerCommands(on)
56 registerHub(on)
57 registerTurns(on)
58 registerBand(on)
59}
60
61/** Keeps the band up for `ms` with no turn running, then lets it go. */
62async function lingerFor($: EngineInterface, ms: number) {
63 await setLingering($, true)
64 await sync($)
65 linger?.cancel()
66 linger = $.clock.after(ms, () => {
67 void setLingering($, false).then(() => sync($)).catch(() => undefined)
68 })
69}
70
71/** Plays something of the person's own (the demo, a /comic-feel): the band stays up for it, and the director waits. */
72async function showFor($: EngineInterface, ms: number) {
73 pauseFor(ms)
74 await lingerFor($, ms)
75}
76
77/** $.comic: other plugins add places to the comic's world (EXTENDING.md), and the hub's signs lead there. */
78function registerPlaces(on: On) {
79 // its plain answers; the hooks below do the work, since only a hook has $
80 on('engine.create', async ($, e, next) => {
81 const built = await next(e)
82 const comic: Comic = {
83 version: async () => COMIC_VERSION,
84 addPlace: async () => undefined,
85 removePlace: async () => undefined,
86 places: async () => [HUB],
87 route: async () => ({ left: null, right: null }),
88 go: async () => undefined,
89 step: async () => undefined,
90 alive: async () => undefined,
91 kit: async () => kit(),
92 }
93 return { ...built, comic }
94 })
95
96 on('comic.addPlace', async ($, e, next) => {
97 const place = asPlace(e)
98 if (place) await addPlace($, place)
99 return next(e)
100 })
101
102 on('comic.removePlace', async ($, e, next) => {
103 if (typeof e.id === 'string') await removePlace($, e.id)
104 return next(e)
105 })
106
107 on('comic.places', async $ => ({ value: await stops($) }))
108
109 on('comic.route', async $ => ({ value: await routeNow($) }))
110
111 on('comic.go', async ($, e, next) => {
112 if (e.id === null || typeof e.id === 'string') await goTo($, e.id, null)
113 return next(e)
114 })
115
116 on('comic.step', async ($, e, next) => {
117 if (e.dir === -1 || e.dir === 1) await stepTo($, e.dir)
118 return next(e)
119 })
120
121 on('comic.alive', async ($, e, next) => {
122 const place = asPlace(e)
123 if (place) await placeAlive($, place)
124 return next(e)
125 })
126
127 // a sign at the hub's edge: Claude goes to the place beside it
128 on('ui.press', { element: SIGN_LEFT }, async $ => {
129 await stepTo($, -1)
130 return { element: SIGN_LEFT }
131 })
132
133 on('ui.press', { element: SIGN_RIGHT }, async $ => {
134 await stepTo($, 1)
135 return { element: SIGN_RIGHT }
136 })
137}
138
139/** The session opens at home among the keepsakes of earlier sessions, and the clocks start. */
140function registerSession(on: On) {
141 on('session.start', async ($, e, next) => {
142 const stored = await $.store.get('enabled')
143 if (typeof stored === 'boolean') await setEnabled($, stored)
144 await sync($)
145
146 await $.command.register({ name: 'comic', description: 'Turn the agent comic above the prompt on or off' })
147 await $.command.register({ name: 'comic-demo', description: 'Play the comic tour: every mood, then every action, captioned' })
148 await $.command.register({ name: 'comic-stats', description: 'Show the tokens the comic director has spent: this session and today' })
149 await $.command.register({ name: 'comic-feel', description: `Make Claude act out a mood: ${FEELINGS.join(', ')}` })
150 await $.command.register({ name: 'comic-pet', description: 'Give the little Claude above the prompt a pat' })
151 await $.command.register({ name: 'comic-hub', description: 'List the keepsakes in the comic hub, or remove one: /comic-hub remove <n>' })
152
153 hub.items = asHubItems(await $.store.get(HUB_STORE_KEY))
154 stage.home.setItems(hub.items)
155 stage.startHome()
156 await $.tool.register(HUB_TOOL_SPEC)
157
158 await startBand($)
159 $.clock.every(1000, () => tick($).catch(() => undefined))
160 $.clock.every(1000, () => checkPlace($).catch(() => undefined))
161 return next(e)
162 })
163
164 // a /clear is a new conversation: its first turn sets up a new world
165 on('session.end', async ($, e, next) => {
166 if (e.reason === 'clear') forgetWorld()
167 return next(e)
168 })
169}
170
171function registerCommands(on: On) {
172 on('command.run', { command: 'comic' }, async ($, e) => {
173 const [verb, mode] = e.args.trim().split(/\s+/)
174 if (verb === 'svg') {
175 if (mode !== 'image' && mode !== 'frame') return { text: `Desktop drawing: ${getSvgMode()}. Use /comic svg image or /comic svg frame.` }
176 await setSvgMode($, mode)
177 $.ui.invalidate('ui.render')
178 return { text: `Desktop drawing set to ${mode}.` }
179 }
180 const isOn = !(await isEnabled($))
181 await setEnabled($, isOn)
182 await $.store.set('enabled', isOn)
183 await sync($)
184 return { text: isOn ? 'Comic on: it plays above the prompt while Claude works.' : 'Comic off.' }
185 })
186
187 on('command.run', { command: 'comic-demo' }, async $ => {
188 stage.queue(demoScene(), true)
189 leaveWorld() // the tour plays in a world of its own; the next turn goes back to the session's
190 await showFor($, DEMO_MS)
191 return { text: `Comic tour playing above the prompt (about ${Math.round(DEMO_MS / 1000)}s): ${FEELINGS.length} moods, then the actions.` }
192 })
193
194 on('command.run', { command: 'comic-stats' }, async $ => ({ text: await stats($) }))
195
196 on('command.run', { command: 'comic-hub' }, async ($, e) => {
197 const remove = /^remove\s+(\d+)$/.exec(e.args.trim())
198 if (remove) {
199 const n = Number(remove[1])
200 if (n < 1 || n > hub.items.length) return { text: `No keepsake ${n}: the hub has ${hub.items.length}.` }
201 const gone = hub.items[n - 1]!
202 hub.items = hub.items.filter((_, i) => i !== n - 1)
203 await $.store.set(HUB_STORE_KEY, hub.items)
204 stage.home.setItems(hub.items)
205 return { text: `Removed the ${gone.kind} "${gone.label}".` }
206 }
207 if (!hub.items.length) return { text: 'The hub has no keepsakes yet. Claude adds one after a real milestone.' }
208 const lines = hub.items.map((h, i) => `${i + 1}. ${h.kind}: ${h.label} (${new Date(h.at).toISOString().slice(0, 10)})`)
209 return { text: `Keepsakes in the hub, oldest first:\n${lines.join('\n')}\n\nRemove one with /comic-hub remove <n>.` }
210 })
211
212 // a pat: the ♥ at the band's edge, or /comic-pet
213 on('ui.press', { element: PET_KEY }, async $ => {
214 givePat($)
215 return { element: PET_KEY }
216 })
217
218 on('command.run', { command: 'comic-pet' }, async $ => {
219 givePat($)
220 return { text: 'A headpat, on its way.' }
221 })
222
223 on('command.run', { command: 'comic-feel' }, async ($, e) => {
224 const mood = FEELINGS.find(m => m === e.args.trim().toLowerCase())
225 if (!mood) return { text: `Usage: /comic-feel <mood>, one of: ${FEELINGS.join(', ')}` }
226 stage.interject([feelBeat(mood)])
227 await showFor($, FEEL_MS)
228 return { text: `Claude is ${mood}.` }
229 })
230}
231
232/** The comic's own tool: Claude keeps a milestone in the hub. */
233function registerHub(on: On) {
234 on('tool.call', { tool: HUB_TOOL_NAME }, async ($, e) => {
235 if (hub.added >= MAX_HUB_ADDS) return { result: 'Not added: the hub already got its keepsake this session. Keep the next one for another milestone.' }
236 const item = hubItemFrom(e, Date.now())
237 if ('error' in item) return { result: `Not added: ${item.error}.` }
238 hub.added++
239 const { items, retired } = addHubItem(hub.items, item)
240 hub.items = items
241 await $.store.set(HUB_STORE_KEY, hub.items)
242 stage.home.setItems(hub.items.slice(0, -1))
243 stage.home.addItem(item)
244 const room = retired ? ` The hub holds ${MAX_HUB_ITEMS}, so the oldest, the ${retired.kind} "${retired.label}", was retired.` : ''
245 return { result: `Added a ${item.kind} "${item.label}" to the hub; it is there whenever Claude Code starts.${room}` }
246 })
247}
248
249/** A turn, from the person's prompt to its end: what the agent does goes to the director and the stage. */
250function registerTurns(on: On) {
251 on('prompt.submit', async ($, e, next) => {
252 // our own headpat (should a hook of ours see it): its turn is told apart as it starts, below
253 const origin = e.origin as { kind?: string; name?: string } | undefined
254 if (origin?.kind === 'plugin' && origin.name === 'agent-comic') return next(e)
255 linger?.cancel()
256 // typed over the running turn, or delivered into it: the same story goes on
257 if (e.turnId !== undefined) {
258 addToTurn(e.text)
259 return next(e)
260 }
261 clearFinishedTasks()
262 beginTurn($, e.text)
263 await sync($)
264 return next(e)
265 })
266
267 on('tool.call', async ($, e, next) => {
268 const input = e as unknown as Record<string, unknown>
269 // a subagent's own tool calls: its small Claude acts them out
270 if (e.agentId) stage.helpers.activity(e.agentId, e.tool)
271 // a subagent started from the main thread: a small Claude walks in, and reports back when it is done
272 const isHelper = e.tool === 'Agent' && !e.agentId
273 if (isHelper) {
274 const label = typeof input.description === 'string' ? input.description : 'helper'
275 stage.helpers.start(e.tool_use_id, label, input.run_in_background === true)
276 }
277 // the main thread's own calls: a mark over Claude's head at once, while the director catches up
278 const isMain = !e.agentId && !isHelper
279 if (isMain) {
280 const cue = CUES[e.tool]
281 if (cue) stage.cue(cue)
282 toolStarted(e.tool_use_id, describeCall(input, {}))
283 // a question for the person: he turns to them until it is answered
284 if (ASKS_PERSON.has(e.tool)) stage.attention = 'question'
285 }
286 const startedAt = Date.now()
287 let ran: Awaited<ReturnType<typeof next>>
288 try {
289 ran = await next(e)
290 } finally {
291 toolEnded(e.tool_use_id)
292 // answered (a question, or a permission prompt on the way): back to the story
293 if (isMain) stage.attention = null
294 }
295 if (isMain) {
296 if (ran.isError || ran.deny) stage.cue('fail')
297 observe(input, ran, act)
298 }
299 if (isHelper) {
300 // back within a few seconds: it was only launched and works on in the background
301 if (input.run_in_background === true || Date.now() - startedAt < 5000) stage.helpers.background(e.tool_use_id)
302 else stage.helpers.done(e.tool_use_id)
303 }
304 note(describeCall(input, ran))
305 return ran
306 })
307
308 // a permission dialog about to be put to the person (no hook answered it, and in auto mode
309 // the classifier did not settle it): he turns to them while it is up
310 on('classic.PermissionRequest', async ($, e, next) => {
311 const answer = await next(e)
312 const isAnswered = (answer as { decision?: unknown } | undefined)?.decision !== undefined
313 if (!isAnswered && !(e as { agent_id?: string }).agent_id) stage.attention = 'permission'
314 return answer
315 })
316
317 // the tool is running (its progress row is up): the dialog was answered
318 on('ui.render', { component: 'ToolProgress' }, async ($, e, next) => {
319 if (stage.attention === 'permission') stage.attention = null
320 return next(e)
321 })
322
323 // a subagent finished, foreground or background: its small Claude walks over and reports
324 on('classic.SubagentStop', async ($, e, next) => {
325 stage.helpers.doneByAgent(e.agent_id)
326 return next(e)
327 })
328
329 on('session.append', async ($, e, next) => {
330 const stored = await next(e)
331 if (e.door === 'response' && !e.agentId && !pats.isAnswering) {
332 const text = e.message.content
333 .map(b => (b.type === 'text' ? b.text : ''))
334 .join(' ')
335 .replace(/\s+/g, ' ')
336 .trim()
337 if (text) heard(text)
338 }
339 return stored
340 })
341
342 // the turn answering a pat: he stays where he is, glowing, while Claude answers; no world, no scenes
343 on('turn.start', async ($, e, next) => {
344 if (pats.claim(e.text)) {
345 pats.isAnswering = true
346 await sync($)
347 }
348 return next(e)
349 })
350
351 on('turn.complete', async ($, e, next) => {
352 const done = await next(e)
353 // a subagent's turn ends inside the main one: its small Claude reports through SubagentStop
354 if (e.agentId) return done
355 if (pats.isAnswering) {
356 pats.isAnswering = false
357 await sync($)
358 return done
359 }
360 endTurn($, e.reason === 'aborted')
361 await lingerFor($, LINGER_MS)
362 return done
363 })
364}
365
366/**
367 * The band above the prompt: the stage, a ♥ beside it to give Claude a pat (a Raster takes no clicks
368 * of its own: a click reaches the ♥ in the fullscreen terminal; anywhere, ctrl+x tab focuses the band
369 * and p presses it), and between turns the signs to the places beside the hub.
370 */
371function registerBand(on: On) {
372 on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
373 const isOn = await isEnabled($)
374 const rows = Math.min(MAX_ROWS, e.props.maxRows - 1)
375 // always up while on: Claude idles between turns (no model calls then) and dozes off after a while
376 const isLingeringNow = settings.showWhenIdle || (await isLingering($))
377 const isShown = isOn && !e.props.hasSurvey && rows >= MIN_ROWS && (e.props.isWorking || isLingeringNow)
378 // between turns, with places on the ring: one of them may have the band, or the hub shows signs to them
379 const ring = await stops($)
380 const isBetween = ring.length > 1 && !e.props.isWorking && !(await isLingering($))
381 const at = isBetween ? await whereNow($) : null
382 const isAtPlace = at !== null && ring.some(s => s.id === at)
383
384 const elements = $.ui.resolve(e)
385 const Svg = e.surface !== 'terminal' && 'Svg' in elements ? elements.Svg : undefined
386 if (!isShown || isAtPlace || (e.surface !== 'terminal' && !Svg)) {
387 hideBand(e.surface)
388 stage.routeSigns = null
389 return next(e)
390 }
391 const route = isBetween ? routeOf(ring, null) : null
392 stage.routeSigns = route ? { left: route.left?.name ?? null, right: route.right?.name ?? null } : null
393
394 const columns = Math.max(20, Math.min(512, e.props.bodyColumns - 5))
395 const { Box, Button } = elements
396 let picture
397 if (Svg) {
398 picture = (
399 <Svg
400 source={desktopChunk(e.requestId, Math.min(columns, 160), rows)}
401 alt="A little Claude acting out what the agent is doing"
402 {...(getSvgMode() === 'frame' ? { isInteractive: true } : {})}
403 />
404 )
405 } else {
406 if (!('Raster' in elements)) return next(e)
407 const { Raster } = elements
408 picture = <Raster key={RASTER_KEY} columns={columns} rows={rows} cells={terminalCells(e.requestId, columns, rows)} />
409 }
410 return (
411 <Box flexDirection="row">
412 {picture}
413 <Box flexDirection="column" paddingLeft={1}>
414 <Button key={PET_KEY} plain hotkey="p" onPress={() => undefined}>♥</Button>
415 {route?.left ? <Button key={SIGN_LEFT} plain hotkey="a" onPress={() => undefined}>◂</Button> : null}
416 {route?.right ? <Button key={SIGN_RIGHT} plain hotkey="d" onPress={() => undefined}>▸</Button> : null}
417 </Box>
418 </Box>
419 )
420 })
421}
422hooks/activity.ts 104 lines1// What the agent's main-thread tool calls mean to the comic beyond the director's log: the cue over
2// Claude's head as one starts, the activity canned scenes act out, the moments the stage shows at once
3// (a commit's flag, a push's balloon, the task trail), and failures, which cloud the sky.
4
5import type { Weather } from './backdrop'
6import type { Activity } from './canned'
7import { cellText } from './canvas'
8import { stage } from './runtime'
9import { clip } from './scene'
10import type { Stage } from './stage'
11
12const WEATHER_MS = 180_000 // failures this recent cloud the sky
13const TEST_RUN = /\b(?:jest|vitest|pytest|mocha|rspec|ctest|tox|phpunit)\b|\b(?:cargo|go|bun|deno|dotnet|mvn|gradle|npm|pnpm|yarn)\s+(?:run\s+)?test\b|\bplugin test\b|\bmake (?:test|check)\b/
14
15/** Which mark each tool puts over Claude's head as it starts. */
16export const CUES: Record<string, Parameters<Stage['cue']>[0]> = {
17 Read: 'read', NotebookRead: 'read',
18 Grep: 'search', Glob: 'search',
19 Edit: 'edit', Write: 'edit', NotebookEdit: 'edit',
20 Bash: 'run', PowerShell: 'run',
21 WebFetch: 'web', WebSearch: 'web',
22}
23
24let failTimes: number[] = [] // recent failures: they bring clouds, and rain
25let tasksMade = 0 // TaskCreate calls this list
26const tasksDone = new Set<string>()
27
28const baseName = (path: string) => clip(cellText(path.split(/[\\/]/).pop() ?? path), 20)
29
30/**
31 * One main-thread tool call, finished: `act` gets the activity it was for canned scenes, and the stage
32 * shows its moments (git, the task trail) at once.
33 */
34export function observe(e: Record<string, unknown>, ran: { isError?: boolean; deny?: string }, act: (a: Activity) => void) {
35 const str = (k: string) => (typeof e[k] === 'string' ? (e[k] as string) : '')
36 const isFailed = ran.isError === true || ran.deny !== undefined
37 const fail = (label?: string) => {
38 failTimes.push(Date.now())
39 act({ kind: 'fail', label })
40 }
41 switch (String(e.tool)) {
42 case 'Read': case 'NotebookRead':
43 return isFailed ? fail(baseName(str('file_path'))) : act({ kind: 'read', label: baseName(str('file_path')) })
44 case 'Edit': case 'Write': case 'NotebookEdit':
45 return isFailed ? fail(baseName(str('file_path'))) : act({ kind: 'edit', label: baseName(str('file_path')) })
46 case 'Grep': case 'Glob':
47 return act({ kind: 'search', label: clip(cellText(str('pattern')), 20) })
48 case 'WebFetch': case 'WebSearch':
49 return isFailed ? fail() : act({ kind: 'web' })
50 case 'Agent':
51 return act({ kind: 'helper' })
52 case 'TodoWrite': {
53 const todos = Array.isArray(e.todos) ? (e.todos as { status?: unknown }[]) : []
54 const done = todos.filter(t => t?.status === 'completed').length
55 stage.progress = todos.length ? { done, total: todos.length } : null
56 return
57 }
58 case 'TaskCreate':
59 if (!isFailed) tasksMade++
60 return showTasks()
61 case 'TaskUpdate': {
62 const id = str('taskId') || str('id')
63 if (!isFailed && id && e.status === 'completed') tasksDone.add(id)
64 return showTasks()
65 }
66 case 'Bash': case 'PowerShell': {
67 const command = str('command')
68 if (/\bgit\s+commit\b/.test(command) && !isFailed) {
69 stage.gitMoment('commit')
70 return act({ kind: 'commit' })
71 }
72 if (/\bgit\s+push\b/.test(command) && !isFailed) {
73 stage.gitMoment('push')
74 return act({ kind: 'push' })
75 }
76 if (TEST_RUN.test(command)) {
77 if (isFailed) failTimes.push(Date.now())
78 else failTimes = [] // green again: the sky clears
79 return act({ kind: 'test', ok: !isFailed })
80 }
81 return isFailed ? fail() : act({ kind: 'run' })
82 }
83 }
84 if (isFailed) fail()
85}
86
87function showTasks() {
88 if (tasksMade > 0) stage.progress = { done: Math.min(tasksDone.size, tasksMade), total: tasksMade }
89}
90
91/** A new turn: a finished task list is done with; one still under way carries on into it. */
92export function clearFinishedTasks() {
93 if (!stage.progress || stage.progress.done < stage.progress.total) return
94 stage.progress = null
95 tasksMade = 0
96 tasksDone.clear()
97}
98
99/** Clear, cloudy after a failure, rain after several: the last few minutes' work, in the sky. */
100export function weatherAt(now: number): Weather {
101 failTimes = failTimes.filter(t => now - t < WEATHER_MS)
102 return failTimes.length >= 3 ? 'rain' : failTimes.length ? 'cloudy' : 'clear'
103}
104hooks/band.ts 107 lines1// The stage on screen. The terminal draws the band as a Raster, blitted every frame. The desktop app and
2// VS Code draw no Raster: there the band is an SVG that plays a chunk of frames by itself. Once a
3// chunk, the stage is stepped through the next one and the band redrawn with it, so the stage leads
4// the clock by up to a chunk and what happens shows up to that much later than in the terminal.
5
6import type { EngineInterface } from 'claude-code'
7
8import type { Canvas } from './canvas'
9import { stage } from './runtime'
10import { fitChunk } from './svg'
11
12const FRAME_MS = 50
13const CHUNK_MS = 1000
14const SVG_MODE_KEY = 'svgMode'
15/** The Raster's key, for blits. */
16export const RASTER_KEY = 'stage'
17
18/** 'image' draws the SVG as a picture; 'frame' in a sandboxed frame (the SMIL route the API documents). */
19export type SvgMode = 'image' | 'frame'
20
21type Mount = { requestId: string; columns: number; rows: number }
22
23let terminal: Mount | null = null
24let isBlitting = false
25let desktop: Mount | null = null
26let desktopSvg: string | null = null
27let desktopSize = ''
28let svgMode: SvgMode = 'image'
29
30/** Starts the clocks that draw the band, and reads back how the desktop draws it. */
31export async function startBand($: EngineInterface) {
32 $.clock.every(FRAME_MS, () => drawFrame($))
33 $.clock.every(CHUNK_MS, () => drawChunk($))
34 const stored = await $.store.get(SVG_MODE_KEY)
35 if (stored === 'image' || stored === 'frame') svgMode = stored
36}
37
38export function getSvgMode(): SvgMode {
39 return svgMode
40}
41
42export async function setSvgMode($: EngineInterface, mode: SvgMode) {
43 svgMode = mode
44 await $.store.set(SVG_MODE_KEY, mode)
45}
46
47/** The terminal shows the band at this size: the cells of the frame now. */
48export function terminalCells(requestId: string, columns: number, rows: number): string {
49 terminal = { requestId, columns, rows }
50 return stage.frame(columns, rows)
51}
52
53/** The desktop shows the band at this size: the chunk of frames for it, built afresh when the size changed. */
54export function desktopChunk(requestId: string, columns: number, rows: number): string {
55 desktop = { requestId, columns, rows }
56 const size = `${columns}x${rows}`
57 if (!desktopSvg || size !== desktopSize) {
58 desktopSize = size
59 buildChunk()
60 }
61 return desktopSvg!
62}
63
64/** The surface shows something else: its drawing stops. */
65export function hideBand(surface: string) {
66 if (surface === 'terminal') terminal = null
67 else {
68 desktop = null
69 desktopSvg = null
70 }
71}
72
73/** Every frame: the stage steps to now, and the terminal's band is blitted. */
74function drawFrame($: EngineInterface) {
75 // while the desktop draws the band, the stage runs ahead of the clock in chunks: never step it back
76 if (desktop && !terminal) return
77 stage.step(Date.now())
78 if (!terminal || isBlitting) return
79 const { requestId, columns, rows } = terminal
80 isBlitting = true
81 $.ui.blit({ requestId, key: RASTER_KEY, cells: stage.frame(columns, rows) })
82 .catch(() => undefined)
83 .finally(() => {
84 isBlitting = false
85 })
86}
87
88/** Every chunk: the desktop's next chunk is built and the band redrawn with it. */
89function drawChunk($: EngineInterface) {
90 if (!desktop || terminal) return
91 buildChunk()
92 $.ui.invalidate('ui.render')
93}
94
95/** Steps the stage through the next chunk and makes its frames one SVG. */
96function buildChunk() {
97 if (!desktop) return
98 const { columns, rows } = desktop
99 const start = Math.max(Date.now(), stage.time + FRAME_MS)
100 const frames: Canvas[] = []
101 for (let t = start; t < start + CHUNK_MS; t += FRAME_MS) {
102 stage.step(t)
103 frames.push(stage.frameCanvas(columns, rows))
104 }
105 desktopSvg = fitChunk(frames, FRAME_MS).svg
106}
107hooks/demo.ts 66 lines1// The tour /comic-demo plays: every mood once, then every action, each beat
2// captioned with what it is meant to show.
3
4import type { Beat, Mood, Scene } from './scene'
5
6const MOOD_TOUR: [Exclude<Mood, 'neutral'>, string][] = [
7 ['happy', '^ ^ eyes, a music note, sparkles'],
8 ['proud', '^ ^ eyes, a star, lots of sparkles'],
9 ['love', '^ ^ eyes, a heart, hearts floating up'],
10 ['sad', 'drooping eyes, rain cloud, dusty colour, slumped, tears'],
11 ['angry', 'slanted eyes, anger mark, red, shaking, steam'],
12 ['surprised', 'big round eyes, "!"'],
13 ['confused', 'uneven eyes, "?", looking both ways'],
14 ['sleepy', 'closed eyes, Z, z’s drifting up, slow breathing'],
15 ['focused', 'small eyes under a determined brow, "..."'],
16 ['worried', 'sweat drop, trembling'],
17]
18
19const MOOD_SECS = 3.5
20
21/** What each mood is meant to show, for captions. */
22export const MOOD_SHOWS: Record<string, string> = Object.fromEntries(MOOD_TOUR)
23
24/** The beat /comic-feel plays: one mood, acted out for five seconds with its caption. */
25export function feelBeat(mood: Exclude<Mood, 'neutral'>): Beat {
26 return { do: 'emote', mood, secs: 5, caption: `${mood} - ${MOOD_SHOWS[mood]}` }
27}
28
29export function demoScene(): Scene {
30 const n = MOOD_TOUR.length
31 const beats: Beat[] = [
32 { do: 'walk', to: 22, caption: 'Comic tour: every mood, then every action' },
33 ...MOOD_TOUR.map(([mood, shows], i): Beat => ({
34 do: 'emote', mood, secs: MOOD_SECS, caption: `mood ${i + 1}/${n}: ${mood} - ${shows}`,
35 })),
36 { do: 'read', secs: 3, caption: 'action: read - holds an open book, eyes down, a page turns' },
37 { do: 'type', at: 'pc', secs: 3, caption: 'action: type - walks to the computer, arms alternate, cursor races' },
38 { do: 'carry', at: 'box', caption: 'action: carry - lifts the crate overhead' },
39 { do: 'run', to: 92, caption: 'action: run - fast legs, dust behind' },
40 { do: 'drop', caption: 'action: drop - sets the crate down where he stands' },
41 { do: 'look', at: 'bug', react: '!', caption: 'action: look - walks to a prop, faces it, "!" or "?"' },
42 { do: 'squash', at: 'bug', caption: 'action: squash - jumps on it, it vanishes in a puff' },
43 { do: 'dig', secs: 2, caption: 'action: dig - bobs and throws dirt behind him' },
44 { do: 'jump', caption: 'action: jump' },
45 { do: 'wave', caption: 'action: wave - one arm up and down, happy eyes' },
46 { do: 'shrug', caption: 'action: shrug - both arms up, squinting' },
47 { do: 'dance', secs: 3, caption: 'action: dance - hops, turns, swaps arms, sparkles' },
48 { do: 'say', text: 'This is a speech bubble: up to 110 characters, wrapped to fit.', secs: 4, caption: 'action: say' },
49 { do: 'think', text: 'And this is a thought bubble.', secs: 3, caption: 'action: think' },
50 { do: 'celebrate', caption: 'action: celebrate - arms up, hops, sparkles. End of tour!' },
51 ]
52 return {
53 setting: 'meadow',
54 mood: 'neutral',
55 props: [
56 { id: 'pc', kind: 'computer', x: 72 },
57 { id: 'box', kind: 'crate', x: 45 },
58 { id: 'bug', kind: 'bug', x: 58 },
59 ],
60 beats,
61 }
62}
63
64/** Roughly how long the tour runs, with room for the walks between beats. */
65export const DEMO_MS = (MOOD_TOUR.length * MOOD_SECS + 52) * 1000
66hooks/director.ts 403 lines1// The director: what the agent does each turn goes into a log, and about when the stage runs dry the
2// next scene is asked of the model (or, as /config's director setting has it, taken from the canned
3// library) and queued on the stage. The session's world is set up by its first scene and carried from
4// turn to turn; only the director changes it, within the session's limits.
5
6import type { EngineInterface, ModelUsage } from 'claude-code'
7
8import { weatherAt } from './activity'
9import { cannedFirst, cannedInterlude, cannedScene, cannedWrap } from './canned'
10import type { Activity } from './canned'
11import { cellText } from './canvas'
12import { MAX_INTERLUDES, addTiming, blendLatency, emptyTimings, formatTimings, nextAsk } from './pacing'
13import { pats } from './pets'
14import { SYSTEM, buildPrompt, varietyNotes } from './prompt'
15import { settings, stage } from './runtime'
16import { clip, parseScene } from './scene'
17import type { Scene, Setting, Stamp } from './scene'
18import type { StageWorld } from './stage'
19import { isEnabled } from './state'
20import { addUsage, asTally, emptyTally, formatStats, today } from './usage'
21import { changesLeft, followWorld, limitChanges, noChanges } from './world'
22import type { SessionWorld } from './world'
23
24const STILL_RUNNING_MS = 4000 // a tool running this long is told to the director before it ends
25const LOG_LINES = 40
26const RECENT_SCENES = 6 // for the variety notes
27const MAX_GOAL = 300
28
29/** The turn under way: what the person asked, and what the agent has done. */
30const turn = {
31 goal: null as string | null,
32 log: [] as string[],
33 /** Log lines not staged yet, and when the oldest of them happened. */
34 fresh: 0,
35 firstFreshAt: undefined as number | undefined,
36 lastActivity: 0,
37 isRunning: false,
38 /** Its first scene is still to be staged: the model stages it, in the session's world. */
39 isOpening: false,
40 isWrapPending: false,
41 /** Interludes asked for since the last new activity. */
42 interludes: 0,
43 /** What the agent did since the last staged scene, for canned scenes. */
44 acts: [] as Activity[],
45 /** The agent's latest remark to the person. */
46 lastSaid: undefined as string | undefined,
47}
48
49/** The session's world: set up by its first scene, then changed only by the director, now and then. */
50const session = {
51 world: null as SessionWorld | null,
52 /** The settings it has been in, oldest first. */
53 settings: [] as Setting[],
54 /** The stage shows it (not the hub, not the demo's world). */
55 isWorldShown: false,
56 /** What the director changed of it so far. */
57 changes: noChanges(),
58}
59
60/** The director's own bookkeeping. */
61const desk = {
62 /** Bumped by each new turn (and each new place): an answer asked for an older one is dropped. */
63 epoch: 0,
64 /** The epoch of the request under way, if any. */
65 askingIn: null as number | null,
66 lastAsk: 0,
67 /** Requests in a row that brought no scene, and the back-off after them. */
68 failures: 0,
69 retryAfter: 0,
70 /** While the demo or a /comic-feel plays, the director waits. */
71 pausedUntil: 0,
72 hasLoggedError: false,
73 previous: null as Scene | null,
74 recent: [] as Scene[],
75 /** The model's recent answer time; the first answers correct it. */
76 latencyMs: 7000,
77 timings: emptyTimings(),
78 tally: emptyTally(),
79 /** Scenes the model handed over this session. */
80 answered: 0,
81}
82
83/** The main thread's tool calls under way, to tell the director about long ones before they end. */
84const running = new Map<string, { what: string; since: number; isTold: boolean }>()
85
86/** What a request is for, and what it was asked with. */
87type Request = {
88 kind: Stamp['kind']
89 /** The session's world as the stage has it; none before the session's first scene. */
90 world: StageWorld | undefined
91 isInterlude: boolean
92 isTurnOpening: boolean
93 /** The activity it stages, for canned scenes; and the log lines not staged before it. */
94 acts: Activity[]
95 fresh: number
96 /** When its oldest activity happened, and what the stage expected to have left as it was asked. */
97 activity: number | undefined
98 expectedLeftMs: number
99}
100
101/** Sets the director up as the module loads: its first latency guess, and what it learns from the stage. */
102export function startDirector() {
103 desk.latencyMs = settings.model === 'haiku' ? 4000 : 7000
104 stage.onPlay = scene => {
105 if (scene.stamp) desk.timings = addTiming(desk.timings, scene.stamp, Date.now())
106 }
107 // what plays is what the session keeps: a transformed prop, a new hat, new scenery
108 stage.onWorldChange = shown => {
109 if (!session.isWorldShown || !session.world) return
110 const { world, moved } = followWorld(session.world, shown)
111 session.world = world
112 if (moved) {
113 session.settings = [...session.settings, world.setting].slice(-RECENT_SCENES)
114 desk.epoch++ // what was being staged for the old place is dropped
115 }
116 }
117}
118
119/** A turn is under way (not the answer to a pat). */
120export function isTurnRunning(): boolean {
121 return turn.isRunning
122}
123
124/** A line for the director's log: new activity. */
125export function note(line: string) {
126 turn.log.push(line)
127 turn.log = turn.log.slice(-LOG_LINES)
128 if (turn.fresh === 0) turn.firstFreshAt = Date.now()
129 turn.fresh++
130 turn.lastActivity = Date.now()
131 turn.interludes = 0
132}
133
134/** An activity for the canned scenes. */
135export function act(a: Activity) {
136 turn.acts.push(a)
137}
138
139/** The agent said something to the person: the director hears it, and canned scenes may repeat it. */
140export function heard(text: string) {
141 note(`the agent said: ${text.slice(0, 220)}`)
142 turn.lastSaid = clip(cellText(text), 120)
143 act({ kind: 'said', text: clip(cellText(text), 60) })
144}
145
146/** A main-thread tool call began; a long one is told before it ends. */
147export function toolStarted(id: string, what: string) {
148 running.set(id, { what, since: Date.now(), isTold: false })
149}
150
151export function toolEnded(id: string) {
152 running.delete(id)
153}
154
155/** A new turn: the person asked for `text`. The session's world carries on; only the first turn sets one up. */
156export function beginTurn($: EngineInterface, text: string) {
157 stage.attention = null
158 desk.epoch++
159 desk.retryAfter = 0
160 desk.lastAsk = 0
161 turn.goal = text.slice(0, MAX_GOAL)
162 turn.log = []
163 turn.acts = []
164 turn.lastSaid = undefined
165 turn.fresh = 0
166 turn.isWrapPending = false
167 turn.isRunning = true
168 turn.isOpening = session.world !== null
169 note(`the person asked: ${turn.goal}`)
170 // something to see at once: at home he heads for the door, elsewhere (idle, or asleep) he stops to think
171 const isLeaving = stage.leaveHome()
172 // back from home (or the demo): the session's world loads as he steps in, as he left it
173 if (session.world && !session.isWorldShown) {
174 stage.queue(worldScene(session.world, [{ do: 'ponder', secs: 1.5 }]))
175 session.isWorldShown = true
176 } else if (!isLeaving && stage.idleMs > 0) stage.interject([{ do: 'ponder', secs: 2 }])
177 askSoon($)
178}
179
180/** The person added to the running turn: the same story goes on. */
181export function addToTurn(text: string) {
182 note(`the person added: ${text.slice(0, MAX_GOAL)}`)
183}
184
185/**
186 * The turn is over. Finished, its wrap-up is asked for at once. Stopped by the person, what was asked
187 * for the stopped work is dropped, and a shrug in the turn's world says so (no model needed).
188 */
189export function endTurn($: EngineInterface, isAborted: boolean) {
190 turn.isRunning = false
191 stage.attention = null
192 if (!isAborted) {
193 turn.isWrapPending = true
194 askSoon($)
195 return
196 }
197 desk.epoch++
198 turn.fresh = 0
199 turn.firstFreshAt = undefined
200 turn.isWrapPending = false
201 turn.acts = []
202 if (session.world) stage.queue(cannedWrap(stage.world(), undefined, true, Math.random))
203}
204
205/** The director waits `ms` (the demo, a /comic-feel). */
206export function pauseFor(ms: number) {
207 desk.pausedUntil = Date.now() + ms
208}
209
210/** The stage left the session's world (for the demo's); the next turn takes him back to it. */
211export function leaveWorld() {
212 session.isWorldShown = false
213}
214
215/** A /clear is a new conversation: its first turn sets up a new world. */
216export function forgetWorld() {
217 session.world = null
218 session.changes = noChanges()
219}
220
221/** /comic-stats: the tokens the director spent, this session and today, and how long its scenes took. */
222export async function stats($: EngineInterface): Promise<string> {
223 const day = today()
224 const tally = asTally(await $.store.get(`usage:${day}`))
225 return `${formatStats(settings.model, desk.tally, tally, day)}\n\n${formatTimings(desk.timings, desk.latencyMs, desk.answered)}`
226}
227
228/** Once a second: home after a long idle, the sky, and the next scene if it is time to ask for one. */
229export async function tick($: EngineInterface) {
230 tellRunning()
231 const now = Date.now()
232 // between turns, a long idle takes him home through the door
233 if (!turn.isRunning && stage.wantsHome) {
234 stage.goHome()
235 session.isWorldShown = false
236 }
237 stage.ambience = { hour: new Date(now).getHours(), weather: weatherAt(now) }
238 if (isAsking() || now < desk.pausedUntil || pats.isAnswering) return
239 if (!(await isEnabled($)) || isAsking()) return
240 const request = nextRequest(now)
241 if (!request) return
242 if (isCanned(request.kind, request.isTurnOpening) || now < desk.retryAfter) return stageCanned(request)
243 await askModel($, request, now)
244}
245
246/** Asks now rather than at the next tick: a new turn, or its end, should not wait a second. */
247function askSoon($: EngineInterface) {
248 $.clock.after(0, () => tick($).catch(() => undefined))
249}
250
251function isAsking(): boolean {
252 return desk.askingIn === desk.epoch
253}
254
255/** A tool still going after a few seconds (a long build, a test run) is news before its result is. */
256function tellRunning() {
257 const now = Date.now()
258 for (const r of running.values()) {
259 if (r.isTold || now - r.since < STILL_RUNNING_MS) continue
260 r.isTold = true
261 note(`still running, no result yet: ${r.what}`)
262 }
263}
264
265/** What to ask for now, if anything; asking takes the turn's unstaged activity with it. */
266function nextRequest(now: number): Request | null {
267 const remainingMs = stage.remainingMs
268 const untilFreeMs = stage.untilFreeMs
269 const hasWorld = session.world !== null
270 // a canned scene is ready at once: it is asked for as the stage runs dry, not a model's latency ahead
271 const isCannedNext = isCanned(!hasWorld ? 'first' : turn.isWrapPending ? 'wrap' : 'scene', turn.isOpening) || now < desk.retryAfter
272 const ask = nextAsk({
273 now, pace: settings.pace, fresh: turn.fresh, lastAsk: desk.lastAsk, lastActivity: turn.lastActivity,
274 isTurnRunning: turn.isRunning, isWrapPending: turn.isWrapPending, isWorldless: !hasWorld || turn.isOpening,
275 interludes: turn.interludes, remainingMs, untilFreeMs, latencyMs: isCannedNext ? 0 : desk.latencyMs,
276 })
277 if (!ask) return null
278 const isInterlude = ask === 'interlude'
279 if (isInterlude) turn.interludes++
280 turn.isWrapPending = false
281 desk.lastAsk = now
282 // after the session's first scene, scenes play in its world; before it, the first sets one up
283 const world = hasWorld ? stage.world() : undefined
284 const kind: Stamp['kind'] = ask === 'wrap' ? 'wrap' : isInterlude ? 'interlude' : world ? 'scene' : 'first'
285 const isTurnOpening = turn.isOpening && kind === 'scene'
286 if (kind !== 'interlude') turn.isOpening = false
287 const request: Request = {
288 kind, world, isInterlude, isTurnOpening, acts: turn.acts, fresh: turn.fresh,
289 activity: isInterlude ? undefined : turn.firstFreshAt,
290 expectedLeftMs: isInterlude ? remainingMs : untilFreeMs,
291 }
292 turn.acts = []
293 turn.fresh = 0
294 turn.firstFreshAt = undefined
295 return request
296}
297
298/**
299 * Whether a scene of this kind is canned under /config's director setting. Hybrid has the model
300 * stage the session's world, each turn's opening scene in it, and each wrap-up.
301 */
302function isCanned(kind: Stamp['kind'], isTurnOpening = false): boolean {
303 if (settings.director === 'off') return true
304 return settings.director === 'hybrid' && ((kind === 'scene' && !isTurnOpening) || kind === 'interlude')
305}
306
307/** Asks the model for the scene; with no usable answer a canned one plays instead, and the model rests a while. */
308async function askModel($: EngineInterface, r: Request, now: number) {
309 const interlude = r.isInterlude
310 ? { n: turn.interludes, quietSecs: Math.round((now - turn.lastActivity) / 1000), isLast: turn.interludes === MAX_INTERLUDES }
311 : undefined
312 const prompt = buildPrompt({
313 goal: turn.goal, log: turn.log, fresh: r.fresh, previous: desk.previous, finished: r.kind === 'wrap', interlude, world: r.world,
314 changesLeft: changesLeft(session.changes),
315 variety: varietyNotes(desk.recent, Math.random, session.settings, session.world?.setting),
316 })
317 const mine = desk.epoch
318 desk.askingIn = mine
319 stage.pondering = true
320 let isStaged = false
321 try {
322 const asked = Date.now()
323 const answer = await $.model.complete({ model: settings.model, system: [{ text: SYSTEM, cache: true }], prompt, maxTokens: 1500, effort: 'low', timeoutMs: 45000 })
324 const answeredAt = Date.now()
325 countUsage($, answer.usage).catch(() => undefined) // bookkeeping: the scene does not wait on the store
326 if (answer.isAnswered) desk.latencyMs = blendLatency(desk.latencyMs, answeredAt - asked)
327 // a new turn began while the model worked: this scene belongs to the old one
328 if (mine !== desk.epoch) return
329 if (!answer.isAnswered) return logOnce($, `no scene (${answer.reason})`)
330 const parsed = parseScene(answer.text, r.world, { changes: 'director' })
331 if ('error' in parsed) return logOnce($, `unusable scene (${parsed.error})`)
332 // the director owns the world, within the session's limits
333 const { scene, used } = limitChanges(parsed, session.changes)
334 session.changes = used
335 stageScene(scene, r.isInterlude, { kind: r.kind, activity: r.activity, asked, answered: answeredAt, expectedLeftMs: r.expectedLeftMs })
336 isStaged = true
337 desk.failures = 0
338 desk.hasLoggedError = false
339 } catch (err) {
340 logOnce($, `director failed (${err instanceof Error ? err.message : String(err)})`)
341 } finally {
342 if (desk.askingIn === mine) {
343 desk.askingIn = null
344 stage.pondering = false
345 }
346 if (!isStaged && mine === desk.epoch) {
347 desk.failures++
348 desk.retryAfter = Date.now() + Math.min(60_000, 1_000 * 2 ** desk.failures) // 2s, 4s, 8s ... a minute
349 stageCanned(r)
350 }
351 }
352}
353
354/** A canned scene for the request; none for a wrap-up of a turn that never got a world. */
355function stageCanned(r: Request) {
356 const scene = cannedFor(r)
357 if (scene) stageScene(scene, r.isInterlude)
358}
359
360function cannedFor({ kind, world, acts }: Request): Scene | null {
361 if (kind === 'first') return cannedFirst(turn.goal ?? '', session.settings, Math.random)
362 if (!world) return null
363 if (kind === 'scene') return cannedScene(acts, world, Math.random)
364 if (kind === 'interlude') return cannedInterlude(world, turn.interludes, Math.random)
365 return cannedWrap(world, turn.lastSaid, false, Math.random)
366}
367
368/** Queues a scene: the session's first sets up its world. A model's scene carries its timings. */
369function stageScene(scene: Scene, isInterlude: boolean, stamp?: Stamp) {
370 if (session.world) scene.setting = session.world.setting
371 else {
372 session.settings = [...session.settings, scene.setting].slice(-RECENT_SCENES)
373 session.world = { setting: scene.setting, props: scene.props.map(p => ({ ...p })), hat: scene.hat ?? 'none' }
374 session.isWorldShown = true
375 }
376 desk.previous = scene
377 desk.recent = [...desk.recent, scene].slice(-RECENT_SCENES)
378 if (stamp) {
379 scene.stamp = stamp
380 desk.answered++
381 }
382 scene.isNews = !isInterlude
383 stage.queue(scene)
384}
385
386/** A scene that loads the session's world as it stands, with a few beats to arrive on. */
387function worldScene(world: SessionWorld, beats: Scene['beats']): Scene {
388 return { setting: world.setting, mood: 'neutral', props: world.props.map(p => ({ ...p })), hat: world.hat, beats }
389}
390
391/** One line per run of failures: the next scene that lands lets the next failure be told. */
392function logOnce($: EngineInterface, why: string) {
393 if (!desk.hasLoggedError) $.ui.log(`agent-comic: ${why}`)
394 desk.hasLoggedError = true
395}
396
397/** Adds a call's tokens to this session's tally and to today's, which is kept across sessions. */
398async function countUsage($: EngineInterface, usage: ModelUsage) {
399 desk.tally = addUsage(desk.tally, usage)
400 const key = `usage:${today()}`
401 await $.store.set(key, addUsage(asTally(await $.store.get(key)), usage))
402}
403hooks/hub.ts 60 lines1// The hub: Claude's own place, where the session opens. It keeps the keepsakes Claude
2// adds with the comic's tool, across sessions, and has the door to each turn's world.
3
4import { cellText } from './canvas'
5import { HUB_KINDS } from './hubart'
6import type { HubKind } from './hubart'
7
8export type HubItem = { kind: HubKind; label: string; at: number }
9
10export const MAX_HUB_ITEMS = 6 // the hub keeps the newest six; a seventh retires the oldest
11export const MAX_HUB_LABEL = 16
12export const HUB_STORE_KEY = 'hub'
13export const HUB_TOOL = 'hub_add'
14
15/** The tool Claude calls, as `$.tool.register` takes it: deferred, so it costs nothing until looked up. */
16export const HUB_TOOL_SPEC = {
17 name: HUB_TOOL,
18 description:
19 'Add a small keepsake to the agent-comic hub, the little home scene shown above the prompt when Claude Code starts. ' +
20 'Use it rarely: only to remember a real milestone the person would be glad to see again (a hard bug finally fixed, ' +
21 'a feature shipped, a long refactor done, tests green after a struggle). At most one per session; never for routine work.',
22 inputSchema: {
23 type: 'object',
24 properties: {
25 kind: { type: 'string', enum: [...HUB_KINDS], description: 'trophy or medal for wins, plant or flower for growth, lantern for insight, banner for a release, gem for a rare find, statue for a big milestone' },
26 label: { type: 'string', description: `What it remembers, at most ${MAX_HUB_LABEL} characters (e.g. "auth bug slain", "v2 shipped")` },
27 },
28 required: ['kind', 'label'],
29 additionalProperties: false,
30 },
31 isDeferred: true,
32} as const
33
34/** A keepsake from the tool's input, or why not. */
35export function hubItemFrom(input: unknown, at: number): HubItem | { error: string } {
36 const i = (input ?? {}) as { kind?: unknown; label?: unknown }
37 if (!HUB_KINDS.includes(i.kind as HubKind)) return { error: `kind must be one of: ${HUB_KINDS.join(', ')}` }
38 const label = typeof i.label === 'string' ? [...cellText(i.label)].slice(0, MAX_HUB_LABEL).join('').trim() : ''
39 if (!label) return { error: 'label must be a few words' }
40 return { kind: i.kind as HubKind, label, at }
41}
42
43/** The stored keepsakes, read back safely: anything malformed is left out. */
44export function asHubItems(v: unknown): HubItem[] {
45 if (!Array.isArray(v)) return []
46 const items: HubItem[] = []
47 for (const raw of v) {
48 const at = typeof raw?.at === 'number' && Number.isFinite(raw.at) ? raw.at : 0
49 const item = hubItemFrom(raw, at)
50 if (!('error' in item)) items.push(item)
51 }
52 return items.slice(-MAX_HUB_ITEMS)
53}
54
55/** The hub with `item` added, and the keepsake it retired to make room, if any. */
56export function addHubItem(items: readonly HubItem[], item: HubItem): { items: HubItem[]; retired?: HubItem } {
57 const all = [...items, item]
58 return { items: all.slice(-MAX_HUB_ITEMS), retired: all.length > MAX_HUB_ITEMS ? all[0] : undefined }
59}
60hooks/pets.ts 54 lines1// A pat for Claude (the ♥ beside the band, or /comic-pet): hearts at once, and a headpat sent as the
2// person's own message, which Claude answers. While he answers it the comic stays as it is.
3
4import type { EngineInterface } from 'claude-code'
5
6import { stage } from './runtime'
7
8const LINES = [
9 'Here, have a headpat. You are doing amazing!',
10 '*pats your head* You are doing great, Claude.',
11 'Headpat delivery! Thanks for all the help today.',
12 'Here is a little headpat. Keep it up!',
13 '*gentle headpat* Proud of you.',
14 'Have a headpat, you have earned it!',
15 'Headpat break! You are doing wonderfully.',
16 '*pat pat* Great work so far.',
17]
18
19class Pats {
20 /** Claude is answering a pat: no world is set up for it, no scenes are staged. */
21 isAnswering = false
22 private pending: string[] = [] // headpats sent, their turns not begun yet
23 private lastLine = -1
24
25 /** The next pat's message, never the same one twice running; its turn is told apart by it. */
26 send(): string {
27 let i = Math.floor(Math.random() * LINES.length)
28 if (i === this.lastLine) i = (i + 1) % LINES.length
29 this.lastLine = i
30 this.pending.push(LINES[i]!)
31 return LINES[i]!
32 }
33
34 /** True when a turn beginning with `text` answers one of the pats sent (it is crossed off). */
35 claim(text: string): boolean {
36 const i = this.pending.indexOf(text)
37 if (i < 0) return false
38 this.pending.splice(i, 1)
39 return true
40 }
41}
42
43export const pats = new Pats()
44
45/**
46 * A pat: hearts at once, and the headpat sent as the person's message. Sent from a timer, once the hook
47 * that asked has returned: a prompt made inside a command would wait on the turn the command holds.
48 */
49export function givePat($: EngineInterface) {
50 stage.pet()
51 const text = pats.send()
52 $.clock.after(0, () => $.prompt.submit({ text, asUser: true }).catch(() => undefined))
53}
54hooks/places.ts 70 lines1// The comic's world beyond the hub: places other plugins add through $.comic, on a ring that
2// starts at the hub. Wooden signs at the band's edges lead from one stop to the next.
3
4import type { ComicKit, ComicPlace, ComicSide, ComicStop } from '../types'
5import { cellText } from './canvas'
6import { clip } from './scene'
7import { HATS_ART, P, SIGN, TINTS, claude } from './sprites'
8import type { Pose } from './sprites'
9
10export const COMIC_VERSION = 1
11export const HUB: ComicStop = { id: null, name: 'Hub' }
12export const ALIVE_MS = 5000 // a place silent this long has stopped drawing: Claude comes home
13const MAX_NAME = 16
14const MAX_ID = 64
15
16/** A place as a plugin gave it, made safe to draw; null when it is no place. */
17export function asPlace(v: unknown): ComicPlace | null {
18 const p = v as { id?: unknown; name?: unknown } | null
19 if (!p || typeof p.id !== 'string' || typeof p.name !== 'string') return null
20 const id = p.id.trim().slice(0, MAX_ID)
21 const name = clip(cellText(p.name.trim()), MAX_NAME)
22 return id && name ? { id, name } : null
23}
24
25/** The ring with `place` on it (renamed if it was), the hub first, the places by id so signs never jump. */
26export function withPlace(ring: readonly ComicStop[], place: ComicPlace): ComicStop[] {
27 const places = ring.filter((s): s is ComicPlace => s.id !== null && s.id !== place.id)
28 return [HUB, ...[...places, place].sort((a, b) => (a.id < b.id ? -1 : a.id > b.id ? 1 : 0))]
29}
30
31/** The ring without the place `id`. */
32export function withoutPlace(ring: readonly ComicStop[], id: string): ComicStop[] {
33 return [HUB, ...ring.filter(s => s.id !== null && s.id !== id)]
34}
35
36/**
37 * The signs from `here`: its neighbours on the ring. With the hub alone there are none; with one
38 * place, a single sign each way between them, so no stop shows the same sign on both sides.
39 */
40export function routeOf(ring: readonly ComicStop[], here: string | null): { left: ComicStop | null; right: ComicStop | null } {
41 const stops = ring.length ? ring : [HUB]
42 const i = Math.max(0, stops.findIndex(s => s.id === here))
43 if (stops.length < 2) return { left: null, right: null }
44 if (stops.length === 2) return i === 0 ? { left: null, right: stops[1]! } : { left: stops[0]!, right: null }
45 return { left: stops[(i - 1 + stops.length) % stops.length]!, right: stops[(i + 1) % stops.length]! }
46}
47
48/** The side Claude comes in from after following the sign on side `dir`: the other one. */
49export const enteringFrom = (dir: ComicSide): ComicSide => (dir === 1 ? -1 : 1)
50
51/** The comic's art as plain data, for places to draw the same Claude. */
52export function kit(): ComicKit {
53 const pose = (p: Partial<Pose>): string[] =>
54 claude({ face: 'ahead', back: 'down', front: 'down', walk: 0, airborne: false, crouch: false, left: false, ...p })
55 return {
56 claude: {
57 stand: pose({}),
58 blink: pose({ face: 'blink' }),
59 happy: pose({ face: 'happy', back: 'up', front: 'up' }),
60 asleep: pose({ face: 'shut', crouch: true }),
61 wave: pose({ face: 'happy', front: 'up' }),
62 walk: [0, 1, 2, 3].map(walk => pose({ face: 'right', walk })),
63 palette: { ...TINTS.normal },
64 },
65 hats: Object.fromEntries(Object.entries(HATS_ART).map(([k, h]) => [k, { rows: [...h.rows], palette: { ...h.palette }, sit: h.sit }])),
66 sign: { ...SIGN },
67 palette: { ...P },
68 }
69}
70hooks/prompt.ts 230 lines1// What the director tells the model: the system prompt with the scene language, each request built from
2// the turn's log and the world as it is, and the log lines that tool calls become.
3
4import { HATS, MOODS, PROP_KINDS, SETTINGS } from './scene'
5import type { Scene } from './scene'
6import type { WorldChangeCounts } from './world'
7
8/** The system prompt: the scene language and how to stage with it. Cached across calls. */
9export const SYSTEM = `You are the director of a tiny animated comic strip shown in a terminal while an AI coding agent works.
10The star is the agent itself: a small orange pixel creature ("Claude") who walks around a little world, inspects things and remarks on what it finds.
11Each time you are called you get a log of what the agent just did (files read, commands run, searches, its own remarks) and you stage ONE short scene (about 6-15 seconds) that turns the latest activity into a visual metaphor.
12
13Reply with ONLY a JSON object, no prose, no code fence:
14{
15 "setting": one of ${SETTINGS.map(s => `"${s}"`).join(', ')},
16 "mood": one of ${MOODS.map(m => `"${m}"`).join(', ')} (Claude's mood for the whole scene),
17 "hat": one of ${HATS.map(h => `"${h}"`).join(', ')} (first scene of the session only; later, change it with the hat beat),
18 "props": [ { "id": "short-id", "kind": one of ${PROP_KINDS.map(k => `"${k}"`).join(', ')}, "x": 0-100, "label": "optional, max 22 chars" } ],
19 "beats": [ ... ]
20}
21
22Beats run in order:
23 {"do":"walk","to":0-100} {"do":"run","to":0-100} (run kicks up dust: urgency, excitement)
24 {"do":"look","at":"<prop id>","react":"!" or "?"} (walks over to the prop by itself)
25 {"do":"say","text":"aim for 40-80 chars, never over 100"}
26 {"do":"think","text":"aim for 40-80 chars, never over 100"}
27 {"do":"emote","mood":"<mood>","secs":2} (a passing feeling: surprised at a find, worried at a risk, angry at a failure, love for nice code)
28 {"do":"read","secs":3} (holds an open book: reading files or docs)
29 {"do":"type","at":"<computer prop id>"} (walks to it and types: running commands, editing)
30 {"do":"carry","at":"<prop id>"} then later {"do":"drop"} (lifts a prop overhead and sets it down where Claude stands: moving or refactoring)
31 {"do":"plant_sign","label":"max 22 chars","x":0-100,"id":"optional short id"} (hammers a new sign into the ground: mark a finding, a file, a TODO)
32 {"do":"pull_sign","at":"<sign id>"} (pulls a sign out of the ground and it vanishes: done, fixed, or wrong after all)
33 {"do":"ponder","secs":3} (stands and contemplates: a "..." bubble, looks one way, then the other)
34 {"do":"transform","at":"<prop id>","into":"<prop kind>","label":"optional"} (lifts it overhead, a puff of magic smoke, it becomes the new thing for good)
35 {"do":"hat","hat":"<hat>"} (a puff over his head and he wears another hat, for good)
36 {"do":"travel","setting":"<setting>","props":[{"kind":"<prop kind>","label":"optional"}, ... up to 4],"hat":"optional"}
37 (a door appears, he walks through it into new scenery with these props; always the LAST beat of its scene)
38 {"do":"dance"} {"do":"wave"} {"do":"shrug"} {"do":"dig"} {"do":"jump"} {"do":"celebrate"} {"do":"wait","secs":1}
39
40Guidelines:
41- Unhurried. HARD LIMIT: 7 beats per scene (9 for an interlude); 5 is often best. At most 4 props, one idea per scene. Claude is calm and thoughtful,
42 not busy: after picking something up, putting it down or finding something, give him a moment (ponder, wait, or a short emote)
43 before the next thing. Fewer, deliberate actions beat many quick ones.
44- Spread props out (x values at least 15 apart). Leave room near x=0 where Claude may stand.
45- Whimsy over literalness: this is a storybook world, not an office. For each piece of work pick a surprising but fitting metaphor in any setting.
46 The obvious one (a library for reading code) is allowed only now and then. Ideas, each one of many:
47 reading or exploring code: a forest of signposts named after the files; beachcombing scrolls washed up by the sea; lamp-lit inscriptions in a cave; a sign on the moon.
48 searching: digging for a chest in the desert or on the beach; lifting rocks to peek under them; hunting with a lamp at night.
49 running commands or tests: typing at a computer planted somewhere odd (a dune, the moon, a beach) and waiting for its verdict.
50 a bug or an error: a bug crawls out from behind a crate, rock or mushroom; Claude jumps back, surprised or worried.
51 fixing it: stand over the bug and cheer; or carry the crate it hid behind to a better spot.
52 writing or editing files: stacking crates, carrying a scroll to its sign, planting a flag.
53 refactoring or moving code: carrying props from one place to another and setting them down in a new order.
54 web research: a scroll from the sea, a signal from a far planet. a long wait: night, a lamp, sitting by a mushroom, dozing.
55- One world per session, and you own it. The session's FIRST scene sets it up: a setting, a hat and exactly 4 props that belong
56 together as one small place (a desert dig site: cactus, chest, rock, a sign; a night camp: lamp, crate, scroll, flag). Pick a
57 place that can hold a whole session of work. Every later scene gets the world as it now is in the request: do not send "props"
58 or "hat" then, refer to the props by their ids. Carrying a prop to another spot is fine; squashing is not (props never vanish).
59- Change the world rarely, as a beat of the story, when the WORK changes, never just for variety:
60 transform a prop when the kind of work shifts (a scroll becomes a computer as reading turns into running tests; a crate
61 becomes a chest once the bug is found); hat when the session's spirit changes (tophat for a finished feature, nightcap for
62 a long slog, miner when the digging starts); travel only when the session moves on to clearly different work, and only at a
63 turn's start or end. Most scenes change nothing. The request says how many changes are left this session; never use more.
64- Signs are notes in the world, on top of the 4 props: when something concrete is found (a cause, a number, a file, a TODO),
65 plant_sign it right there with a short label (aim for 14 characters or fewer: long boards crowd the strip);
66 pull_sign one that is done or turned out wrong. At most 2 planted signs stand at once; they stay until pulled.
67- A hat fits the place and the spirit of the work: wizard (library, night, space, deep reading),
68 miner (cave, digging, searching), straw (beach, desert, meadow), tophat (a proud or festive moment), nightcap (night, long waits),
69 or none. It stays on until a hat beat changes it.
70- A "sign" shows its label on a board: use it for file names, commands, or search terms the agent is working on (e.g. "auth.ts", "npm test").
71- Props are toys, not scenery: every scene has at least TWO interactions with its props (look at, carry and drop, type at, dig beside),
72 ideally a tiny story: find something, react to it, do something about it.
73- Use "read" at most once per scene, and not in two scenes in a row. Prefer carry, drop, type, dig, run and the gestures.
74- The setting is chosen once per session: its first scene picks it, every later scene stays in it.
75 Vary the moods, actions and stories instead. Follow the variety notes in each request.
76- Give Claude feelings: pick a scene mood that fits the work, and use at least one emote, action or gesture (wave, shrug, dance) per scene so the strip stays lively. Vary them between scenes.
77- Speech is Claude remarking on REAL findings from the log: concrete, short, a little witty, first person. Never invent facts that are not in the log.
78- Continuity lives in the story: the place and its props carry over from turn to turn, so new turns can call back to earlier ones.`
79
80/** The world as the request shows it: the props by id, what is gone, what Claude wears. */
81export type PromptWorld = { setting: string; props: readonly { id: string; kind: string; label?: string; x: number }[]; gone: readonly string[]; hat?: string }
82
83export type PromptArgs = {
84 /** What the person asked the agent this turn. */
85 goal: string | null
86 /** The turn's log, oldest first; its last `fresh` lines are not staged yet. */
87 log: readonly string[]
88 fresh: number
89 previous: Scene | null
90 /** The turn is over: stage its wrap-up. */
91 finished: boolean
92 interlude?: Interlude
93 variety?: Variety
94 /** The session's world, once its first scene set it up. */
95 world?: PromptWorld
96 /** World changes the director may still make this session. */
97 changesLeft?: WorldChangeCounts
98}
99
100/** A quiet stretch: the `n`th interlude, `quietSecs` since the last activity; the last one sends Claude to sleep. */
101type Interlude = { n: number; quietSecs: number; isLast: boolean }
102
103export function buildPrompt(args: PromptArgs): string {
104 const older = args.log.slice(0, Math.max(0, args.log.length - args.fresh))
105 const latest = args.log.slice(Math.max(0, args.log.length - args.fresh))
106 const parts = [
107 `The person asked the agent: ${args.goal ?? '(unknown)'}`,
108 older.length ? `Earlier activity:\n${older.slice(-12).join('\n')}` : '',
109 args.interlude
110 ? interludeAsk(args.interlude)
111 : `Latest activity (stage THIS):\n${latest.join('\n') || '(the agent is thinking)'}`,
112 args.previous
113 ? `Previous scene: setting=${args.previous.setting}, mood=${args.previous.mood}, props=${args.previous.props.map(p => `${p.kind}${p.label ? `(${p.label})` : ''}`).join(', ') || 'none'}`
114 : 'This is the first scene.',
115 args.world ? worldAsk(args.world, args.changesLeft) : 'This is the FIRST scene of the session: set up its world (setting, hat and 4 related props). It carries over to every later turn.',
116 args.variety ? varietyAsk(args.variety, Boolean(args.interlude)) : '',
117 args.finished
118 ? 'The agent has just FINISHED its turn. Stage a short wrap-up scene: Claude sums up the outcome in one remark and celebrates or shrugs as fits.'
119 : '',
120 ]
121 return parts.filter(Boolean).join('\n\n')
122}
123
124/** What the recent scenes leaned on, so the next one can lean elsewhere. */
125export type Variety = { recentSettings: string[]; overused: string[]; suggest: string; banned?: string; locked?: string }
126
127/**
128 * Reads the last few scenes for the actions they used most, and the settings of
129 * recent turns (`settings`, oldest first; the scenes' own when absent) for a setting to try.
130 * `locked` is the session's setting once its first scene picked one.
131 */
132export function varietyNotes(
133 recent: readonly Scene[],
134 rand: () => number = Math.random,
135 settings?: readonly string[],
136 locked?: string,
137): Variety {
138 const recentSettings = [...(settings ?? recent.map(s => s.setting))]
139 const counts = new Map<string, number>()
140 for (const scene of recent.slice(-4)) for (const b of scene.beats) counts.set(b.do, (counts.get(b.do) ?? 0) + 1)
141 const overused = [...counts].filter(([, n]) => n >= 3).sort((a, b) => b[1] - a[1]).map(([act, n]) => `${act} x${n}`)
142 const lately = new Set(recentSettings.slice(-3))
143 const fresh = SETTINGS.filter(s => !lately.has(s))
144 const pool = fresh.length ? fresh : [...SETTINGS]
145 const suggest = pool[Math.floor(rand() * pool.length)]!
146 const [a, b] = recentSettings.slice(-2)
147 return { recentSettings, overused, suggest, banned: a !== undefined && a === b ? a : undefined, locked }
148}
149
150function varietyAsk(v: Variety, isInterlude: boolean): string {
151 const lines = ['Variety notes:']
152 if (v.locked) {
153 lines.push(`- the setting is fixed for this session: "${v.locked}". Stay in it; vary mood, actions and stories instead`)
154 } else {
155 if (v.recentSettings.length) lines.push(`- settings of recent turns, oldest first: ${v.recentSettings.join(', ')}`)
156 lines.push('- this is the first scene of the session: it picks the setting for the whole session')
157 }
158 if (!isInterlude && !v.locked) {
159 lines.push(`- suggested setting this time: ${v.suggest} (use it unless it truly cannot fit the work)`)
160 if (v.banned) lines.push(`- do NOT use "${v.banned}" this time: the last two turns used it`)
161 }
162 if (v.overused.length) lines.push(`- used a lot lately, so go easy on them: ${v.overused.join(', ')}`)
163 return lines.join('\n')
164}
165
166function worldAsk(w: PromptWorld, left?: WorldChangeCounts): string {
167 const props = w.props.map(p => `${p.id} = ${p.kind}${p.label ? ` "${p.label}"` : ''} at x=${p.x}`).join('; ')
168 const world = `The world as it is now (do NOT send "props" or "hat"): setting ${w.setting}; Claude wears: ${w.hat ?? 'none'}; props: ${props || 'none left'}` +
169 (w.gone.length ? `; gone: ${w.gone.join(', ')}` : '') + '. Use these ids.'
170 if (!left) return world
171 return `${world}
172World changes left this session (use only when the work really changes): transform ${left.transform}, hat ${left.hat}, travel ${left.travel}.`
173}
174
175/** What to stage when nothing new has happened for a while but the agent is still at work. */
176function interludeAsk(i: Interlude): string {
177 if (i.isLast) {
178 return `No new activity for ${i.quietSecs}s; the agent is still busy. Stage a short scene in the same setting where Claude, ` +
179 'still waiting, grows drowsy: a yawn-like remark, then {"do":"emote","mood":"sleepy","secs":4}. Invent no findings.'
180 }
181 return `INTERLUDE ${i.n}: no new activity for ${i.quietSecs}s, but the agent is still working (thinking, or a long command). ` +
182 "Continue the previous scene's story in the same setting with 5-8 unhurried beats, pauses included (ponder, wait), so the strip does not stall: Claude keeps busy - " +
183 'rereading or pacing, typing, carrying something, thinking aloud about what IS in the log, a small gesture, a light joke about the wait. ' +
184 'Chain varied actions. Invent no findings and do not repeat the previous remarks.'
185}
186
187/** Cut to `n` characters, on one line. */
188const cut = (s: string, n: number) => (s.length > n ? s.slice(0, n - 1) + '…' : s).replace(/\s+/g, ' ')
189
190/** One log line for a tool call, from its input and how it ended. */
191export function describeCall(e: Record<string, unknown>, outcome: { isError?: boolean; deny?: string; result?: unknown }): string {
192 const tool = String(e.tool)
193 const s = (k: string) => (typeof e[k] === 'string' ? (e[k] as string) : '')
194 let what: string
195 switch (tool) {
196 case 'Read': what = `read ${s('file_path')}`; break
197 case 'Edit': what = `edited ${s('file_path')}`; break
198 case 'Write': what = `wrote ${s('file_path')}`; break
199 case 'Bash': what = `ran \`${cut(s('command'), 80)}\``; break
200 case 'Grep': what = `searched for "${cut(s('pattern'), 40)}"${s('path') ? ` in ${s('path')}` : ''}`; break
201 case 'Glob': what = `listed files matching ${s('pattern')}`; break
202 case 'WebFetch': what = `fetched ${s('url')}`; break
203 case 'WebSearch': what = `searched the web for "${cut(s('query'), 50)}"`; break
204 case 'Agent': what = `sent a helper agent: ${cut(s('description') || s('prompt'), 60)}`; break
205 default: {
206 const args = JSON.stringify(Object.fromEntries(Object.entries(e).filter(([k]) => !['tool', 'tool_use_id', 'agentId'].includes(k))))
207 what = `used ${tool} ${cut(args ?? '', 70)}`
208 }
209 }
210 if (e.agentId) what = `(helper) ${what}`
211 if (outcome.deny) return `${what} -> blocked`
212 const result = summarize(outcome.result)
213 if (outcome.isError) return `${what} -> FAILED${result ? `: ${result}` : ''}`
214 return result ? `${what} -> ${result}` : what
215}
216
217/** A tool's result in a few words: its output, or its content. */
218function summarize(result: unknown): string {
219 if (result === undefined || result === null) return ''
220 let text: string
221 if (typeof result === 'string') text = result
222 else {
223 const r = result as Record<string, unknown>
224 text = typeof r.stdout === 'string' || typeof r.stderr === 'string'
225 ? `${r.stdout ?? ''} ${r.stderr ?? ''}`
226 : typeof r.content === 'string' ? r.content : (JSON.stringify(result) ?? '')
227 }
228 return cut(text.trim(), 140)
229}
230hooks/runtime.ts 28 lines1// What the parts of the comic share in this load of the module: the stage, and the /config settings.
2
3import type { PluginOptions } from 'claude-code'
4
5import { PACES } from './beats'
6import { Stage } from './stage'
7
8/**
9 * Who stages the scenes: the model stages every one (full); the session's world, each turn's opening
10 * and its wrap-up, with canned scenes between (hybrid); or nobody, everything canned (off).
11 */
12export type DirectorMode = 'full' | 'hybrid' | 'off'
13
14export type Settings = { model: 'sonnet' | 'haiku'; pace: keyof typeof PACES; showWhenIdle: boolean; director: DirectorMode }
15
16export const settings: Settings = { model: 'sonnet', pace: 'calm', showWhenIdle: true, director: 'hybrid' }
17
18export const stage = new Stage()
19
20/** Takes /config's values as the module (re)loads; anything unexpected keeps the default. */
21export function applySettings(options: PluginOptions) {
22 settings.model = options.model === 'haiku' ? 'haiku' : 'sonnet'
23 settings.pace = options.pace === 'normal' || options.pace === 'lively' ? options.pace : 'calm'
24 settings.showWhenIdle = options.showWhenIdle !== false
25 settings.director = options.director === 'full' || options.director === 'off' ? options.director : 'hybrid'
26 stage.pace = PACES[settings.pace]
27}
28hooks/scene.ts 233 lines1// The scene language the director writes (and the canned library too): a setting, a mood, props on
2// the ground, and beats the Claude figure performs one after another. parseScene holds a reply to it.
3
4import { cellText } from './canvas'
5import { clamp } from './util'
6
7export const SETTINGS = ['meadow', 'forest', 'cave', 'night', 'desert', 'library', 'space', 'beach'] as const
8export type Setting = (typeof SETTINGS)[number]
9
10export const PROP_KINDS = [
11 'sign', 'tree', 'rock', 'chest', 'bug', 'crate', 'scroll', 'flag',
12 'lamp', 'books', 'computer', 'cactus', 'mushroom',
13] as const
14export type PropKind = (typeof PROP_KINDS)[number]
15
16export const MOODS = [
17 'neutral', 'happy', 'proud', 'love', 'sad', 'angry', 'surprised', 'confused', 'sleepy', 'focused', 'worried',
18] as const
19export type Mood = (typeof MOODS)[number]
20
21export type Prop = { id: string; kind: PropKind; x: number; label?: string }
22
23export type Beat = BeatAction & { caption?: string }
24
25export type BeatAction =
26 | { do: 'walk'; to: number }
27 | { do: 'run'; to: number }
28 | { do: 'say'; text: string; secs?: number }
29 | { do: 'think'; text: string; secs?: number }
30 | { do: 'look'; at: string; react?: '!' | '?' }
31 | { do: 'squash'; at: string }
32 | { do: 'transform'; at: string; into: PropKind; label?: string }
33 | { do: 'plant_sign'; id: string; label: string; x: number }
34 | { do: 'pull_sign'; at: string }
35 | { do: 'carry'; at: string }
36 | { do: 'drop' }
37 | { do: 'type'; at?: string; secs?: number }
38 | { do: 'read'; secs?: number }
39 | { do: 'emote'; mood: Mood; secs?: number }
40 | { do: 'dance'; secs?: number }
41 | { do: 'wave' }
42 | { do: 'shrug' }
43 | { do: 'jump' }
44 | { do: 'dig'; secs?: number }
45 | { do: 'celebrate' }
46 | { do: 'ponder'; secs?: number }
47 | { do: 'wait'; secs: number }
48 | { do: 'hat'; hat: Hat }
49 | { do: 'travel'; setting: Setting; props: Prop[]; hat?: Hat }
50
51export const HATS = ['none', 'wizard', 'miner', 'straw', 'tophat', 'nightcap'] as const
52export type Hat = (typeof HATS)[number]
53
54export type Scene = {
55 setting: Setting
56 mood: Mood
57 props: Prop[]
58 beats: Beat[]
59 hat?: Hat
60 /** It plays in the world on stage (its setting and props, as they now are), not a world of its own. */
61 continues?: boolean
62 /** When the director staged it, for the latency figures; scenes made locally have none. */
63 stamp?: Stamp
64 /** It stages new activity (or the turn's end), so the scene playing may give way to it at a pause. */
65 isNews?: boolean
66}
67
68export type Stamp = {
69 kind: 'first' | 'scene' | 'interlude' | 'wrap'
70 /** The oldest activity it stages; none for an interlude. */
71 activity?: number
72 asked: number
73 answered: number
74 /** What the stage expected to have left to play when it was asked for (ms). */
75 expectedLeftMs: number
76}
77
78const MAX_PROPS = 4
79const MAX_BEATS = 9 // the strip stays calm: anything past this is dropped
80export const MAX_SPEECH = 110
81const MAX_LABEL = 22
82const MAX_ID = 20
83/** Where a new place's props stand, left to right (0..100). */
84export const PROP_SLOTS = [24, 44, 64, 84] as const
85const str = (v: unknown, max: number) => (typeof v === 'string' ? clip(cellText(v), max) : '')
86
87/** Cuts at a word boundary and marks the cut, so a remark never ends mid-word. */
88export function clip(text: string, max: number): string {
89 if (text.length <= max) return text
90 const cut = text.slice(0, max - 1)
91 const space = cut.lastIndexOf(' ')
92 return (space > max * 0.6 ? cut.slice(0, space) : cut).replace(/[\s,;:.-]+$/, '') + '…'
93}
94const num = (v: unknown, fallback: number) => (typeof v === 'number' && Number.isFinite(v) ? v : fallback)
95const secs = (v: unknown, lo: number, hi: number) => (v === undefined ? undefined : clamp(num(v, lo), lo, hi))
96const isMood = (v: unknown): v is Mood => MOODS.includes(v as Mood)
97
98/**
99 * Who may change the session's world in a scene played in it: `none` (canned scenes: transform,
100 * hat and travel are dropped) or `director` (it may transform a prop, swap the hat, or travel).
101 * Squashing a prop is never allowed in a world: the world keeps its props.
102 */
103export type WorldChanges = 'none' | 'director'
104
105/**
106 * Pulls the first JSON object out of a reply and holds it to the language. Given the
107 * session's `world`, the scene plays in it: its own setting and props are ignored, and
108 * what may change the world follows `changes`. A travel beat ends the scene.
109 */
110export function parseScene(
111 reply: string,
112 world?: { setting: Setting; props: readonly Prop[] },
113 opts: { changes?: WorldChanges } = {},
114): Scene | { error: string } {
115 const mayChange = !world || opts.changes === 'director'
116 const start = reply.indexOf('{')
117 const end = reply.lastIndexOf('}')
118 if (start < 0 || end <= start) return { error: 'no JSON object in the reply' }
119
120 let raw: any // untrusted JSON: every field is checked below before it is used
121 try {
122 raw = JSON.parse(reply.slice(start, end + 1))
123 } catch (err) {
124 return { error: `bad JSON: ${String(err).slice(0, 80)}` }
125 }
126
127 const setting: Setting = world?.setting ?? (SETTINGS.includes(raw?.setting) ? raw.setting : 'meadow')
128 const mood: Mood = isMood(raw?.mood) ? raw.mood : 'neutral'
129 // the hat comes with the world: a later scene of the turn keeps the one Claude already wears
130 const hat: Hat | undefined = world ? undefined : HATS.includes(raw?.hat) ? raw.hat : 'none'
131
132 const props: Prop[] = []
133 for (const p of world ? [] : Array.isArray(raw?.props) ? raw.props.slice(0, MAX_PROPS) : []) {
134 if (!PROP_KINDS.includes(p?.kind)) continue
135 const id = str(p.id, MAX_ID) || `p${props.length}`
136 const label = str(p.label, MAX_LABEL) || undefined
137 props.push({ id, kind: p.kind, x: clamp(num(p.x, 50), 0, 100), label })
138 }
139 if (world) props.push(...world.props.map(p => ({ ...p })))
140 const ids = new Set(props.map(p => p.id))
141 const signs = new Set(props.filter(p => p.kind === 'sign').map(p => p.id))
142
143 const beats: Beat[] = []
144 for (const b of Array.isArray(raw?.beats) ? raw.beats.slice(0, MAX_BEATS) : []) {
145 switch (b?.do) {
146 case 'walk':
147 case 'run':
148 beats.push({ do: b.do, to: clamp(num(b.to, 50), 0, 100) })
149 break
150 case 'say':
151 case 'think': {
152 const text = str(b.text, MAX_SPEECH)
153 if (text) beats.push({ do: b.do, text, secs: secs(b.secs, 1, 8) })
154 break
155 }
156 case 'look':
157 if (ids.has(b.at)) beats.push({ do: 'look', at: b.at, react: b.react === '!' || b.react === '?' ? b.react : undefined })
158 break
159 case 'squash':
160 case 'carry':
161 if (b.do === 'squash' && world) break
162 if (ids.has(b.at)) beats.push({ do: b.do, at: b.at })
163 break
164 case 'plant_sign': {
165 const label = str(b.label, MAX_LABEL)
166 if (!label) break
167 // a fresh id, so later beats (and scenes) can look at or pull this sign
168 let id = str(b.id, MAX_ID) || 'note'
169 for (let n = 2; ids.has(id); n++) id = `${str(b.id, MAX_ID - 2) || 'note'}${n}`
170 ids.add(id)
171 signs.add(id)
172 beats.push({ do: 'plant_sign', id, label, x: clamp(num(b.x, 50), 0, 100) })
173 break
174 }
175 case 'pull_sign':
176 if (signs.has(b.at)) beats.push({ do: 'pull_sign', at: b.at })
177 break
178 case 'transform':
179 if (mayChange && ids.has(b.at) && PROP_KINDS.includes(b.into)) {
180 beats.push({ do: 'transform', at: b.at, into: b.into, label: str(b.label, MAX_LABEL) || undefined })
181 }
182 break
183 case 'type':
184 beats.push({ do: 'type', at: ids.has(b.at) ? b.at : undefined, secs: secs(b.secs, 1, 5) })
185 break
186 case 'emote':
187 if (isMood(b.mood)) beats.push({ do: 'emote', mood: b.mood, secs: secs(b.secs, 1, 5) })
188 break
189 case 'read':
190 case 'dance':
191 beats.push({ do: b.do, secs: secs(b.secs, 1, 5) })
192 break
193 case 'sleep': // sleeping is the sleepy mood, not an action of its own
194 beats.push({ do: 'emote', mood: 'sleepy', secs: secs(b.secs, 1, 5) ?? 4 })
195 break
196 case 'ponder':
197 beats.push({ do: 'ponder', secs: secs(b.secs, 1.5, 6) })
198 break
199 case 'drop':
200 case 'wave':
201 case 'shrug':
202 case 'jump':
203 case 'celebrate':
204 beats.push({ do: b.do })
205 break
206 case 'dig':
207 beats.push({ do: 'dig', secs: secs(b.secs, 1, 4) })
208 break
209 case 'wait':
210 beats.push({ do: 'wait', secs: clamp(num(b.secs, 1), 0.3, 4) })
211 break
212 case 'hat':
213 if (mayChange && HATS.includes(b.hat)) beats.push({ do: 'hat', hat: b.hat })
214 break
215 case 'travel': {
216 if (!world || !mayChange || !SETTINGS.includes(b.setting) || b.setting === world.setting) break
217 const props: Prop[] = []
218 for (const p of Array.isArray(b.props) ? b.props.slice(0, MAX_PROPS) : []) {
219 if (!PROP_KINDS.includes(p?.kind)) continue
220 props.push({ id: `${p.kind}${props.length}`, kind: p.kind, x: PROP_SLOTS[props.length]!, label: str(p.label, MAX_LABEL) || undefined })
221 }
222 beats.push({ do: 'travel', setting: b.setting, props, hat: HATS.includes(b.hat) ? b.hat : undefined })
223 break
224 }
225 }
226 // through the door, the scene is over: anything after it belonged to the old place
227 if (beats[beats.length - 1]?.do === 'travel') break
228 }
229 if (beats.length === 0) return { error: 'the scene has no usable beats' }
230
231 return { setting, mood, props, beats, hat, continues: world ? true : undefined }
232}
233hooks/state.ts 119 lines1// The comic's $.state, which places read (types/index.d.ts): whether the comic is on, what the band is
2// doing, and where Claude is on the ring of places. And the moves along that ring (places.ts).
3
4import { atom, read, update } from 'claude-code'
5import type { EngineInterface } from 'claude-code'
6
7import type { ComicPlace, ComicSide, ComicState, ComicStop } from '../types'
8import { ALIVE_MS, HUB, enteringFrom, routeOf, withPlace, withoutPlace } from './places'
9import { settings } from './runtime'
10
11// read and written only in this file, as the state scan requires: other modules use the functions below
12const enabled = atom({ plugin: 'agent-comic', key: 'enabled' } as const, true)
13/** The band stays up a while after a turn (and through a /comic-demo or a /comic-feel). */
14const lingering = atom({ plugin: 'agent-comic', key: 'lingering' } as const, false)
15const bandState = atom({ plugin: 'agent-comic', key: 'state' } as const, 'hidden' as ComicState)
16const here = atom({ plugin: 'agent-comic', key: 'here' } as const, null as string | null)
17const cameFrom = atom({ plugin: 'agent-comic', key: 'cameFrom' } as const, null as ComicSide | null)
18const ring = atom({ plugin: 'agent-comic', key: 'places' } as const, [HUB] as ComicStop[])
19
20/** When each place last said it was drawing. */
21const aliveAt = new Map<string, number>()
22
23/**
24 * Tells the places what the band is doing; the comic itself never reads it. `isWorking`: a turn
25 * (or the answer to a pat) is under way.
26 */
27export async function syncState($: EngineInterface, isWorking: () => boolean) {
28 const isOn = await read($, enabled)
29 const isStaying = await read($, lingering)
30 const state: ComicState = !isOn ? 'hidden'
31 : isWorking() ? 'working'
32 : isStaying ? 'wrapping'
33 : settings.showWhenIdle ? 'idle' : 'hidden'
34 // read as stored, not with the atom's initial: other plugins see only what was written
35 if ((await $.state.get({ plugin: 'agent-comic', key: 'state' })).value !== state) await update($, bandState, () => state)
36}
37
38export async function isEnabled($: EngineInterface): Promise<boolean> {
39 return read($, enabled)
40}
41
42export async function setEnabled($: EngineInterface, isOn: boolean) {
43 await update($, enabled, () => isOn)
44}
45
46export async function isLingering($: EngineInterface): Promise<boolean> {
47 return read($, lingering)
48}
49
50export async function setLingering($: EngineInterface, isOn: boolean) {
51 await update($, lingering, () => isOn)
52}
53
54/** The ring of stops, the hub first. */
55export async function stops($: EngineInterface): Promise<ComicStop[]> {
56 return read($, ring)
57}
58
59/** Where Claude is between turns: null for the hub, else a place's id. */
60export async function whereNow($: EngineInterface): Promise<string | null> {
61 return read($, here)
62}
63
64/** The signs from where he is now. */
65export async function routeNow($: EngineInterface) {
66 return routeOf(await read($, ring), await read($, here))
67}
68
69/** Whether `id` is a place on the ring. */
70async function isOnRing($: EngineInterface, id: string): Promise<boolean> {
71 return (await read($, ring)).some(s => s.id === id)
72}
73
74/** A place signs on (or is renamed). */
75export async function addPlace($: EngineInterface, place: ComicPlace) {
76 await update($, ring, r => withPlace(r, place))
77}
78
79/** A place signs off; Claude comes home to the hub if he was there. */
80export async function removePlace($: EngineInterface, id: string) {
81 await update($, ring, r => withoutPlace(r, id))
82 aliveAt.delete(id)
83 if ((await read($, here)) === id) await goTo($, null, null)
84}
85
86/** A place says it is still drawing; one the ring lost (the comic reloaded) is added back. */
87export async function placeAlive($: EngineInterface, place: ComicPlace) {
88 if (!(await isOnRing($, place.id))) await addPlace($, place)
89 aliveAt.set(place.id, await $.clock.now())
90}
91
92/** Claude goes to a place on the ring (null: the hub), in from side `from`; an id not on it is ignored. */
93export async function goTo($: EngineInterface, id: string | null, from: ComicSide | null) {
94 if (id !== null && !(await isOnRing($, id))) return
95 if (id !== null) aliveAt.set(id, await $.clock.now())
96 // the side first, so the place reads it as it takes over
97 await update($, cameFrom, () => from)
98 await update($, here, () => id)
99}
100
101/** Follows the sign on side `dir`, if there is one. */
102export async function stepTo($: EngineInterface, dir: ComicSide) {
103 const route = await routeNow($)
104 const to = dir === -1 ? route.left : route.right
105 if (to) await goTo($, to.id, enteringFrom(dir))
106}
107
108/** A place that stopped drawing (it failed, or was turned off) sends Claude home to the hub. */
109export async function checkPlace($: EngineInterface) {
110 const id = await read($, here)
111 if (id === null) return
112 if (!(await isOnRing($, id))) return goTo($, null, null)
113 const now = await $.clock.now()
114 const last = aliveAt.get(id)
115 // it draws only while the band is idle: until then, and on the way in, it has its grace
116 if ((await read($, bandState)) !== 'idle' || last === undefined) return void aliveAt.set(id, now)
117 if (now - last > ALIVE_MS) await goTo($, null, null)
118}
119