Orchestrate lean headless Claude workers (Haiku scouts, Sonnet coders and reviewers) with the cw CLI, and watch them live in a pixel-art side pane

Claude Code plugin. The main session (Opus) leads; cheap headless workers do the reading and the coding.
orchestrate skill — the playbook: scout → spec → coder → reviewer → verify, fleets, permissions, cost rules.cw CLI (bin/, on the Bash PATH) — starts one claude -p worker with a ~3k-token cold start.scout = Haiku, read-only (+ web with -w). coder = Sonnet, edits and runs tests (auto mode, risky calls come back as requests). reviewer = Sonnet, read-only, no web: a fresh context reads a diff that cw inlines and reports BLOCKER / SUGGEST lines with file:line.cwgo (run one worker, notify when it finishes or asks), cwwait (recovery waiter), cwls, cwopen, cwwt (one git worktree per writer), cwkill./crew opens it; it also opens itself when a worker starts.ctx 64%).+128 −14 lines, ✓ test / ✗ test, and its cost. ✦ after the effort pips: Jev chose the effort.5h ~3% estimates its share of the 5-hour limit (the window's rise since the session began, split by spend between lead and crew).notes, steps, report and test tabs. c copies its resume command, b goes back./plugin install cw-crew --marketplace memoksin/cw-crew
Answer y to add the marketplace, then pick a scope.
winget install -e --id Git.Git
winget install -e --id jqlang.jq
winget install -e --id Anthropic.ClaudeCode
winget install -e --id BurntSushi.ripgrep.MSVC # optional, faster scout searches
winget install -e --id sharkdp.fd # optional
Git for Windows brings Git Bash (Claude Code's Bash tool), perl and git.
claude and the /plugin install line above.%USERPROFILE%\.claude\settings.json: { "env": { "CLAUDE_CODE_GIT_BASH_PATH": "C:\\Program Files\\Git\\bin\\bash.exe" } }
cw scout <<< "Reply ok. No tools.". The last line must contain rc=0.Update later with winget upgrade --all and claude plugin update cw-crew@cw-crew.
jq, see Windows.claude, jq, perl, git on PATH. rg and fd help scouts but are optional.CLAUDE_CODE_NO_FLICKER=1, outside tmux) and ≥110 columns. Otherwise it sits above the prompt. Sprites need a terminal with an image protocol; others get half-blocks.details › button per worker sits under it. Install the plugin from a terminal at user scope; the desktop session loads it.Ask Claude to delegate ("use workers", /orchestrate). By hand:
cw scout -f src/app.ts <<< "List every caller of parseConfig with file:line."
cwgo api coder -W api -T 'npm test' -- specs/common.md specs/api.md
# run cwgo in the background: it waits for its worker and prints the report or question
cwwait # recovery: fires when any unreported worker finishes (use with cwgo -d)
cwgo api.rv reviewer -W api -- specs/api.md # review worktree api's changes
cw reviewer -B main <<< "Focus: auth." # review this branch since main
| Var | Default | What | |
|---|---|---|---|
CW_SCOUT_MODEL / CW_CODER_MODEL / CW_REVIEWER_MODEL | claude-haiku-5-5 / claude-sonnet-5-5 / claude-sonnet-5-5 | worker models | |
CW_MAX_TURNS | 80 | coder turn limit | |
CW_TIMEOUT | 3600 coder / 1200 scout, reviewer | seconds | |
CW_REVIEW_MAX | 60000 | characters of diff a reviewer gets inline; the rest it reads itself | |
CW_LOG_DIR | ~/.claude/cw-runs | run logs (the pane reads them too) | |
CW_FLEET | $CW_LOG_DIR/fleet/<repo> | fleet dir | |
CW_WT_ROOT | ../<repo>-wt | worktree root | |
CW_JEV | 0 | 1 = Jev (OpenRouter) picks worker effort per task. Sends the first 20k characters of each task to OpenRouter. Off: role default (scout low, coder medium) | |
OPENROUTER_API_KEY / CW_JEV_KEYCHAIN | — | key for CW_JEV=1; on macOS a keychain service name works instead of the env key | |
CW_KILL_ALLOW | — | colon-separated command prefixes cwkill may also stop | |
CW_ACCEPT_FAIL_RE | `^\s*(FAIL\b(?!:? *0\b)\ | SCRIPT ERROR)` | Perl regex: a -T run that exits 0 but prints a matching line is accept=FAIL(output). Empty turns it off |
Set them in ~/.claude/settings.json under env.
claude --plugin-dir . # run from this folder
claude plugin validate .
claude plugin test .
tests/cw.sh # bin/cw against a fake claude (no model call)
tools/gen_frames.sh # rebuild frames/ after changing hooks/creatures.ts (needs bun + Pillow)
MIT
hooks/register.tsx 422 lines1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, Register } from 'claude-code'
3
4import { FRAME_MS, frameFile, imageSource, lookKey } from './creatures'
5import {
6 buildWorkers, CARD, clock, drawDetail, drawScene, encode, isActive, isVisible, LABEL, msysToWin, PANE as PANE_BG, parseEvents, sceneRows, sceneSvg,
7 SPRITE_COLS, SPRITE_ROWS, type Meta, type Run, type Spot, type State, type Totals, type Worker,
8} from './scene'
9import type { Tab } from '../types'
10
11const PANE = 'cw-crew'
12const DAY = 86_400_000
13// cw touches <run>.hb every 30 s while its process lives: a staler one means cw was killed before .done.
14const STALE_MS = 90_000
15const DIED = 137
16const slots = atom({ plugin: 'cw-crew', key: 'slots' } as const, 0)
17const selected = atom({ plugin: 'cw-crew', key: 'selected' } as const, '')
18const tab = atom({ plugin: 'cw-crew', key: 'tab' } as const, 'notes' as Tab)
19const TABS: Tab[] = ['notes', 'steps', 'report', 'test']
20const NOTES = 4, STEPS = 10, REPORT_CHARS = 2400, TEST_LINES = 20
21const css = (c: number) => `#${(c & 0xffffff).toString(16).padStart(6, '0')}`
22const TEXT = '#e6e6f0', DIM = '#8a8fa3', GOOD = '#7bd88f', BAD = '#ff5c5c'
23type Tracked = Run & { size: number; final: boolean }
24
25// Module state: a reload starts it over and the next poll rebuilds it from the run files.
26let dir = ''
27let session = ''
28let metas = new Map<string, Meta | null>()
29let runs = new Map<string, Tracked>()
30let workers: Worker[] = []
31let mounted: { cols: number; rows: number; maxRows: number; images: boolean; keys: Set<string> } | undefined
32// Sprites are Images until the terminal shows it draws their alt instead (no image protocol,
33// tmux): a blit of a mounted Image is then denied, and the pane falls back to half-blocks.
34let images = true
35let refused = 0
36let shown = new Map<string, string>()
37let seen = new Map<string, State>()
38let status: string | undefined
39let opened = false
40let polling = false
41let lastKick = 0
42// Surfaces with no Raster (desktop, editor, mobile) get the scene as an Svg, redrawn by poll() while shown.
43let svgAt = 0
44let svgKick = 0
45// PNG frames as base64, read once each; a session sees a few dozen of the 650.
46const pngs = new Map<string, string>()
47// Detail view: the open worker's live notes (its assistant text) and final report, refreshed by poll().
48let selKey = ''
49let detail: { key: string; size: number; notes: string[]; report?: string; test?: string } = { key: '', size: -1, notes: [] }
50let detailKick = 0
51// The lead's own spend and its 5-hour readings (session.measure), to weigh the crew's share of that limit.
52let leadCost = 0
53let five: { first: number; last: number } | undefined
54let totals: Totals = {}
55
56function readText($: EngineInterface, name: string) {
57 return $.fs.read(`${dir}/${name}`).catch(() => undefined)
58}
59
60async function poll($: EngineInterface) {
61 if (polling) return
62 polling = true
63 try {
64 const sid = await $.session.id()
65 if (sid !== session) {
66 session = sid
67 metas = new Map(); runs = new Map(); seen = new Map()
68 }
69 const now = await $.clock.now()
70 const entries = await $.fs.list(dir).catch(() => [])
71 const byName = new Map(entries.map(en => [en.name, en]))
72
73 for (const en of entries) {
74 if (!en.name.endsWith('.meta')) continue
75 const id = en.name.slice(0, -'.meta'.length)
76 if (!metas.has(id)) {
77 if (now - en.mtimeMs > DAY) { metas.set(id, null); continue }
78 const text = await readText($, en.name)
79 let meta: Meta | undefined
80 try { meta = text ? (JSON.parse(text) as Meta) : undefined } catch { meta = undefined }
81 if (!meta) continue
82 // A resumed/restarted lead gets a new session id: keep showing the workers still running from before.
83 const hb = byName.get(`${id}.hb`)
84 const live = !byName.has(`${id}.done`) && (hb ? now - hb.mtimeMs < STALE_MS
85 : now / 1000 - meta.start < (meta.tmo ?? 3600) + 2400) // no .hb (older cw): + cw's acceptance run
86 metas.set(id, meta.session === session || live ? meta : null)
87 }
88 const meta = metas.get(id)
89 if (!meta) continue
90 const run = runs.get(id) ?? { id, meta, events: [], size: -1, final: false }
91 if (run.final) {
92 // The lead closed the request without a resume (cwopen -x): lower the hand.
93 if (run.question !== undefined && !byName.has(`${id}.ask`)) runs = new Map(runs).set(id, { ...run, question: undefined })
94 continue
95 }
96 const ev = byName.get(`${id}.events`)
97 const done = byName.get(`${id}.done`)
98 let next: Tracked = run
99 // The events file is complete once .done exists, so read it one last time then.
100 if (ev && (ev.size !== run.size || done)) {
101 next = { ...next, events: parseEvents((await readText($, ev.name)) ?? ''), size: ev.size }
102 }
103 if (done) {
104 const rc = Number.parseInt((await readText($, done.name)) ?? '', 10)
105 const question = byName.has(`${id}.ask`) ? (await readText($, `${id}.ask`))?.trim() : undefined
106 next = { ...next, rc: Number.isNaN(rc) ? 1 : rc, doneAt: done.mtimeMs, question, final: true }
107 } else {
108 // Not final: a heartbeat that resumes (laptop woke up) brings the worker back.
109 const hb = byName.get(`${id}.hb`)
110 const died = !!hb && now - hb.mtimeMs > STALE_MS
111 if (died !== (next.rc === DIED)) next = died ? { ...next, rc: DIED, doneAt: hb.mtimeMs } : { ...next, rc: undefined, doneAt: undefined }
112 }
113 if (next !== run || !runs.has(id)) runs = new Map(runs).set(id, next)
114 }
115
116 const all = buildWorkers([...runs.values()], now)
117 announce($, all)
118 const spent = all.reduce((s, w) => s + (w.cost ?? 0), 0)
119 // Workers draw on the same account: the 5-hour window moved by this much since the session began,
120 // and the crew's part of it is taken as its part of the money spent.
121 const moved = five ? five.last - five.first : 0
122 totals = { cost: spent || undefined, limit: spent && moved > 0 ? (moved * spent) / (spent + leadCost) : undefined }
123 const visible = all.filter(w => isVisible(w, now))
124 const grew = visible.length !== workers.length
125 workers = visible
126 if (grew) await update($, slots, () => visible.length)
127
128 const active = all.filter(isActive).length
129 const asking = all.filter(w => w.state === 'ask').length
130 const text = active ? `⚒ ${active} working${asking ? ` · ${asking} asking` : ''}`
131 : asking ? `? ${asking} waiting for an answer` : undefined
132 if (text !== status) { status = text; $.ui.status(text) }
133
134 if (active && !opened) {
135 opened = true
136 const res = await $.ui.open(paneArgs())
137 if (!res.isPlaced) $.ui.toast('cw-crew: workers running, open the pane with /crew')
138 }
139 // A pane hidden behind a tab drops its Raster; ask for a redraw now and then so the animation resumes.
140 if (!mounted && opened && now - lastKick > 2000) { lastKick = now; $.ui.invalidate('ui.render') }
141 // ponytail: whole-Svg redraw per poll, no per-frame blit there; fine for a handful of workers.
142 else if (!selKey && now - svgAt < 5000 && now - svgKick >= (active ? 400 : 2000)) { svgKick = now; $.ui.invalidate('ui.render') }
143 if (selKey) {
144 await refreshDetail($, all, byName)
145 // The limits tick with the clock: redraw a live worker's detail view each second.
146 if (all.some(w => w.key === selKey && isActive(w)) && now - detailKick >= 1000) { detailKick = now; $.ui.invalidate('ui.render') }
147 }
148 } finally {
149 polling = false
150 }
151}
152
153// The open worker's newest run: its stream (.jsonl) holds the notes, its result (.json) the report.
154async function refreshDetail($: EngineInterface, all: Worker[], byName: Map<string, { size: number }>) {
155 const w = all.find(x => x.key === selKey)
156 const id = w?.runIds.at(-1)
157 if (!w || !id) return
158 const size = byName.get(`${id}.jsonl`)?.size ?? 0
159 if (detail.key === w.key && detail.size === size && (w.end === undefined || detail.report !== undefined)) return
160 const notes: string[] = []
161 for (const line of ((await readText($, `${id}.jsonl`)) ?? '').split('\n')) {
162 if (!line.includes('"type":"assistant"')) continue
163 try {
164 const m = JSON.parse(line) as { message?: { content?: { type: string; text?: string }[] } }
165 for (const c of m.message?.content ?? []) if (c.type === 'text' && c.text?.trim()) notes.push(c.text.trim())
166 } catch { /* a line still being written */ }
167 }
168 let report: string | undefined, test: string | undefined
169 if (w.end !== undefined) {
170 try { report = ((JSON.parse((await readText($, `${id}.json`)) ?? '{}') as { result?: string }).result ?? '').trim() } catch { report = '' }
171 test = (await readText($, `${id}.accept`))?.trimEnd().split('\n').slice(-TEST_LINES).join('\n')
172 }
173 detail = { key: w.key, size, notes: notes.slice(-NOTES), report, test }
174 $.ui.invalidate('ui.render')
175}
176
177function openDetail($: EngineInterface, key: string) {
178 selKey = key
179 detail = { key: '', size: -1, notes: [] }
180 mounted = undefined
181 const w = workers.find(x => x.key === key)
182 void update($, tab, () => (w?.end !== undefined ? 'report' : 'notes'))
183 void update($, selected, () => key)
184}
185
186// Each tool step with how it came back: tool results follow their calls in order.
187function stepsOf(w: Worker) {
188 const out: { t: number; tool: string; arg: string; res?: string }[] = []
189 let next = 0
190 for (const ev of w.runIds.flatMap(id => runs.get(id)?.events ?? [])) {
191 if (ev.e === 'tool') out.push({ t: ev.t, tool: ev.tool ?? '', arg: ev.arg ?? '' })
192 else if ((ev.e === 'ok' || ev.e === 'error' || ev.e === 'denied') && out[next]) out[next++]!.res = ev.e
193 else if (ev.e === 'init') next = out.length
194 }
195 return out.slice(-STEPS)
196}
197
198// A drawn scene as one Svg, the sprites' PNG frames inlined; half-block pixels if a frame will not read.
199async function svgOf($: EngineInterface, draw: (images: boolean) => { rows: number; words: Uint32Array; spots: Spot[] }, cols: number) {
200 let { rows, words, spots } = draw(true)
201 const sprites = []
202 for (const s of spots) {
203 const file = frameFile(s.look)
204 let base64 = pngs.get(file)
205 if (base64 === undefined) {
206 base64 = await $.fs.read(`${$.plugin.root}/frames/${file}`, { as: 'bytes' }).then(r => r.base64, () => '')
207 pngs.set(file, base64)
208 }
209 if (base64) sprites.push({ x: s.x, y: s.y, base64 })
210 }
211 let svg = sceneSvg(words, cols, rows, sprites)
212 if (sprites.length < spots.length || svg.length > 131_072) { ({ rows, words } = draw(false)); svg = sceneSvg(words, cols, rows) }
213 return svg
214}
215
216// Ask for the rows the scene needs (room for two workers once any run), not the default third of the screen.
217const paneArgs = () => ({ id: PANE, title: 'Crew', rows: sceneRows(workers.length && Math.max(2, workers.length), 60), columns: 60 })
218
219function announce($: EngineInterface, all: Worker[]) {
220 // One state per key (the last run wins): two entries with one key would flip-flop and toast every poll.
221 for (const w of new Map(all.map(w => [w.key, w])).values()) {
222 const before = seen.get(w.key)
223 seen.set(w.key, w.state)
224 if (before === w.state || (before === undefined && w.end !== undefined)) continue
225 if (w.state === 'ask') $.ui.toast(`? ${w.name} asks: ${w.question ?? ''}`, { timeoutMs: 8000 })
226 else if (w.state === 'blocked') $.ui.toast(`! ${w.name} blocked: ${w.arg}`)
227 else if (w.state === 'done') $.ui.toast(`✓ ${w.name} (${w.role}) done`)
228 else if (w.state === 'failed') $.ui.toast(`✗ ${w.name} (${w.role}) failed`)
229 }
230}
231
232async function paint($: EngineInterface) {
233 const at = mounted
234 const root = $.plugin.root
235 if (!at || sceneRows(workers.length, at.cols, at.maxRows) !== at.rows) return
236 const { words, spots } = drawScene(workers, at.cols, await $.clock.now(), at.maxRows, at.images, totals)
237 const res = await $.ui.blit({ requestId: PANE, key: 'crew', cells: encode(words) })
238 if (res.deny) { mounted = undefined; return }
239 // The cells went in, so the pane is mounted: an Image refused now is one drawing its alt.
240 for (const s of spots) {
241 const key = lookKey(s.look)
242 if (!at.keys.has(s.key) || shown.get(s.key) === key) continue
243 const img = await $.ui.blit({ requestId: PANE, key: s.key, source: imageSource(s.look, root) })
244 if (img.deny) {
245 if (/alt|placeholder|unsupported/i.test(img.deny) || ++refused >= 6) {
246 images = false
247 mounted = undefined
248 $.ui.log(`cw-crew: no images here (${img.deny}); half-block sprites`)
249 $.ui.invalidate('ui.render')
250 }
251 return
252 }
253 refused = 0
254 shown.set(s.key, key)
255 }
256}
257
258export const register: Register = on => {
259 on('session.start', async ($, e, next) => {
260 session = await $.session.id()
261 const home = (await $.env.get('HOME')) || (await $.env.get('USERPROFILE')) || ''
262 dir = msysToWin((await $.env.get('CW_LOG_DIR')) || `${home}/.claude/cw-runs`).replace(/\\/g, '/')
263 await $.command.register({ name: 'crew', description: 'Open the cw worker pane (scouts, coders, reviewers)' })
264 $.clock.every(400, () => void poll($).catch(err => $.ui.log(`cw-crew poll: ${String(err)}`)))
265 $.clock.every(FRAME_MS, () => void paint($).catch(() => { mounted = undefined }))
266 return next(e)
267 })
268
269 // The engine docks a pane on the right only in the fullscreen layout from 110 columns; else it sits above the prompt.
270 on('command.run', { command: 'crew' }, async ($, e) => {
271 opened = true
272 // A reload with the pane open can refuse the first blits before the pane mounts; /crew retries PNG sprites.
273 images = true
274 refused = 0
275 mounted = undefined
276 await $.ui.open(paneArgs())
277 const { isFullscreen, columns } = e.presentation
278 // The layout hints are the terminal's; the desktop places the pane itself.
279 const where = (await $.env.get('CLAUDE_CODE_ENTRYPOINT')) === 'claude-desktop' ? ''
280 : !isFullscreen
281 ? ' It sits above the prompt: the right-side pane needs the fullscreen layout (CLAUDE_CODE_NO_FLICKER=1, outside tmux).'
282 : columns < 110 ? ` It sits above the prompt: the right-side pane needs a terminal of at least 110 columns (now ${columns}).` : ''
283 return { text: `Crew pane opened.${where}` }
284 })
285
286 on('session.measure', async ($, e, next) => {
287 leadCost = e.cost?.usd ?? leadCost
288 const pct = e.rateLimits.find(r => r.kind === 'five_hour')?.percentUsed
289 // A drop means the window rolled over: count from there.
290 if (pct !== undefined) five = !five || pct < five.last ? { first: pct, last: pct } : { ...five, last: pct }
291 return next(e)
292 })
293
294 on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
295 await read($, slots)
296 const sel = await read($, selected)
297 const open = sel ? workers.find(w => w.key === sel) : undefined
298 const terminal = e.surface === 'terminal'
299 if (open) {
300 mounted = undefined // paint() must not blit the scene over the detail view
301 const { Box, Text, Button } = $.ui.resolve(e)
302 const now = await $.clock.now()
303 const current = await read($, tab)
304 const cols = Math.max(46, Math.min(terminal ? 512 : 138, e.props.bodyColumns))
305 let hero
306 if (e.surface === 'terminal') {
307 const { Image, Raster } = $.ui.resolve(e)
308 const d = drawDetail(open, cols, now, images)
309 hero = (
310 <Box width={cols} height={d.rows}>
311 <Raster key="detail" columns={cols} rows={d.rows} cells={encode(d.words)} />
312 {d.spots.map(s => (
313 <Box position="absolute" top={s.y} left={s.x} width={SPRITE_COLS} height={SPRITE_ROWS} backgroundColor={css(CARD)}>
314 <Image key={`d${s.key}`} source={imageSource(s.look, $.plugin.root)} columns={SPRITE_COLS} rows={SPRITE_ROWS} alt={s.alt} />
315 </Box>
316 ))}
317 </Box>
318 )
319 } else {
320 const { Svg } = $.ui.resolve(e)
321 hero = <Svg key="detail" source={await svgOf($, im => drawDetail(open, cols, now, im), cols)} alt={`${open.name} ${LABEL[open.state]}`} />
322 }
323 const ago = (t: number) => clock(Math.max(0, now - t))
324 const ready = detail.key === open.key
325 const body =
326 current === 'notes' ? (!ready ? [<Text color={DIM}>reading…</Text>]
327 : detail.notes.length === 0 ? [<Text color={DIM}>no notes yet</Text>]
328 : detail.notes.map(n => <Text color={TEXT} wrap="wrap">{n.slice(0, 400)}</Text>))
329 : current === 'steps' ? (() => {
330 const steps = stepsOf(open)
331 return steps.length === 0 ? [<Text color={DIM}>none yet</Text>] : steps.map(st => (
332 <Text wrap="truncate-end">
333 <Text color={st.res === 'ok' ? GOOD : st.res ? BAD : DIM}>{st.res === 'ok' ? '✓' : st.res ? '✗' : '·'} </Text>
334 <Text color={DIM}>{ago(st.t).padStart(5)} </Text>
335 <Text color={TEXT}>{st.tool} </Text><Text color={DIM}>{st.arg}</Text>
336 </Text>
337 ))
338 })()
339 : current === 'report' ? [open.end === undefined ? <Text color={DIM}>still working</Text>
340 : !ready || detail.report === undefined ? <Text color={DIM}>reading…</Text>
341 : <Text color={TEXT} wrap="wrap">{detail.report ? detail.report.slice(0, REPORT_CHARS) : 'no report (timed out or killed)'}</Text>]
342 : [open.accept === undefined ? <Text color={DIM}>{open.end === undefined && open.state !== 'test' ? 'runs after the work' : 'no acceptance command'}</Text>
343 : <Text color={open.accept.ok ? GOOD : BAD}>{open.accept.ok ? '✓ passed' : `✗ failed${open.accept.rc !== undefined ? ` (rc ${open.accept.rc})` : ''}`}</Text>,
344 ...(ready && detail.test ? [<Text color={DIM} wrap="wrap">{detail.test}</Text>] : [])]
345 const resume = open.sid ? `cw ${open.role} -r ${open.sid}` : ''
346 return (
347 <Box flexDirection="column" backgroundColor={css(PANE_BG)} gap={1}>
348 <Box flexDirection="row" gap={1} paddingX={1}>
349 <Button key="back" hotkey="b" onPress={() => { selKey = ''; mounted = undefined; void update($, selected, () => '') }}>‹ back</Button>
350 {resume && <Button key="copy" hotkey="c" onPress={p => void $.ui.copy({ text: resume, surface: p.surface })
351 .then(r => $.ui.toast(r.isCopied ? `copied: ${resume}` : 'could not copy'))}>copy resume</Button>}
352 </Box>
353 {hero}
354 <Box flexDirection="column" paddingX={1}>
355 {open.state === 'ask' && open.question && <Text color="#ffe8a3" wrap="wrap">? {open.question}</Text>}
356 <Text color={DIM} wrap="wrap">{open.task.slice(0, 600)}</Text>
357 </Box>
358 <Box flexDirection="row" gap={2} paddingX={1}>
359 {TABS.map(t => (
360 <Button key={`tab-${t}`} plain onPress={() => void update($, tab, () => t)}>
361 <Text color={t === current ? TEXT : DIM} bold={t === current} underline={t === current}>{t}</Text>
362 </Button>
363 ))}
364 </Box>
365 <Box flexDirection="column" paddingX={1}>{body}</Box>
366 </Box>
367 )
368 }
369 if (sel) { selKey = ''; void update($, selected, () => '') } // the worker left the crew
370 if (!terminal) {
371 const { Box, Button, Svg, Text } = $.ui.resolve(e)
372 const now = await $.clock.now()
373 svgAt = now
374 const cols = Math.max(46, Math.min(138, e.props.bodyColumns))
375 const svg = await svgOf($, im => drawScene(workers, cols, now, 256, im, totals), cols)
376 const alt = workers.length ? workers.map(w => `${w.name} ${w.role} ${LABEL[w.state]}`).join(', ') : 'no workers'
377 return (
378 <Box flexDirection="column" gap={1}>
379 {svg.length <= 131_072 ? <Svg key="crew" source={svg} alt={alt} />
380 : workers.map(w => <Text>{w.name} · {w.role} · {LABEL[w.state]}</Text>)}
381 {workers.length > 0 && (
382 <Box flexDirection="row" gap={1} flexWrap="wrap">
383 {workers.map(w => <Button key={`open-${w.key}`} onPress={() => openDetail($, w.key)}>{w.name} ›</Button>)}
384 </Box>
385 )}
386 </Box>
387 )
388 }
389 const { Box, Button, Image, Raster, Text } = $.ui.resolve(e)
390 const cols = Math.max(24, Math.min(512, e.props.bodyColumns))
391 // Draw every card, even past the pane's height: the engine scrolls a body taller than its window.
392 // Only the 256-row hard cap still folds workers into one-line rows.
393 const maxRows = 256
394 const { rows, words, spots, hits } = drawScene(workers, cols, await $.clock.now(), maxRows, images, totals)
395 mounted = { cols, rows, maxRows, images, keys: new Set(spots.map(s => s.key)) }
396 const raster = <Raster key="crew" columns={cols} rows={rows} cells={encode(words)} />
397 // Each card's name is a Button over the same text: a click opens its detail view.
398 // Not `h`: JSX compiles to the global h(), which a parameter of that name would shadow.
399 const buttons = hits.map(hit => (
400 <Box position="absolute" top={hit.y} left={hit.x}>
401 <Button key={`open-${hit.key}`} plain onPress={() => openDetail($, hit.key)}>
402 <Text color={css(hit.color)} backgroundColor={css(CARD)}>{hit.label}</Text>
403 </Button>
404 </Box>
405 ))
406 if (!images) return <Box width={cols} height={rows}>{raster}{buttons}</Box>
407 // Each sprite an Image over the blank cells the scene left for it; paint() swaps its frames.
408 shown = new Map(spots.map(s => [s.key, lookKey(s.look)]))
409 return (
410 <Box width={cols} height={rows}>
411 {raster}
412 {spots.map(s => (
413 <Box position="absolute" top={s.y} left={s.x} width={SPRITE_COLS} height={SPRITE_ROWS} backgroundColor={css(CARD)}>
414 <Image key={s.key} source={imageSource(s.look, $.plugin.root)} columns={SPRITE_COLS} rows={SPRITE_ROWS} alt={s.alt} />
415 </Box>
416 ))}
417 {buttons}
418 </Box>
419 )
420 })
421}
422hooks/creatures.ts 974 lines1// The crew's creatures: a round owl per scout, a plum owl in glasses per reviewer, a baby dragon per coder
2// (purple and crowned on Opus).
3// Drawn in code at 60x32 pixels, 4x the old 15x8 half-block sprites each way, for terminals that
4// show images; the same frame downsampled to 15x8 half-blocks for the ones that draw cells only.
5// Frames step every FRAME_MS; motion is eased over long loops so nothing jumps more than a pixel or two.
6
7import type { Role, State } from './scene'
8
9export type Pose = State | 'sleep'
10export const CLEAR = 0x02000000
11export const BIG_W = 60, BIG_H = 32
12// Hi-res pixels per logical pixel in the image frames.
13export const BIG_S = 2
14export const SMALL_W = 15, SMALL_H = 8
15export const FRAME_MS = 125
16// A see-through black (gen_frames.py writes it with alpha) so the shadow suits any terminal background.
17export const SHADOW = 0x03000000
18
19const OUT = 0x2a2140
20const EYE = 0x1f1833, IRIS = 0x4a4fa8, SHINE = 0xffffff, BLUSH = 0xff9cc2, TONGUE = 0xff6f91
21const TEAR = 0x8fd3ff
22const CONFETTI = [0xff6b6b, 0xffd166, 0x06d6a0, 0x4dabf7, 0xcc5de8, 0xffffff]
23
24// Drawn in logical pixels; `s` hi-res pixels per logical one, so curves and outlines come out finer
25// while every shape keeps its logical size and place.
26export class Canvas {
27 px: Uint32Array
28 readonly pw: number; readonly ph: number
29 constructor(readonly w: number, readonly h: number, readonly s = 1) {
30 this.pw = w * s; this.ph = h * s
31 this.px = new Uint32Array(this.pw * this.ph).fill(CLEAR)
32 }
33 at(x: number, y: number) {
34 const i = Math.floor(x * this.s + 1e-6), j = Math.floor(y * this.s + 1e-6)
35 return i >= 0 && j >= 0 && i < this.pw && j < this.ph ? this.px[j * this.pw + i] ?? CLEAR : CLEAR
36 }
37 dot(i: number, j: number, c: number, on?: number) {
38 if (i < 0 || j < 0 || i >= this.pw || j >= this.ph) return
39 if (on !== undefined && this.px[j * this.pw + i] !== on) return
40 this.px[j * this.pw + i] = c
41 }
42 // One logical pixel: an s x s block, placed to the hi-res pixel.
43 put(x: number, y: number, c: number, on?: number) {
44 const i0 = Math.floor(x * this.s + 1e-6), j0 = Math.floor(y * this.s + 1e-6)
45 for (let j = 0; j < this.s; j++) for (let i = 0; i < this.s; i++) this.dot(i0 + i, j0 + j, c, on)
46 }
47 rect(x: number, y: number, w: number, h: number, c: number) {
48 const i0 = Math.floor(x * this.s + 1e-6), j0 = Math.floor(y * this.s + 1e-6)
49 for (let j = 0; j < Math.round(h * this.s); j++) for (let i = 0; i < Math.round(w * this.s); i++) this.dot(i0 + i, j0 + j, c)
50 }
51 // Every hi-res pixel whose centre lies in the ellipse; `keep` (in logical units) limits it to some of them.
52 oval(cx: number, cy: number, rx: number, ry: number, c: number, keep?: (x: number, y: number) => boolean) {
53 const s = this.s
54 for (let j = Math.floor((cy - ry) * s); j <= Math.ceil((cy + ry) * s); j++) {
55 for (let i = Math.floor((cx - rx) * s); i <= Math.ceil((cx + rx) * s); i++) {
56 const dx = ((i + 0.5) / s - cx) / rx, dy = ((j + 0.5) / s - cy) / ry
57 if (dx * dx + dy * dy <= 1 && (!keep || keep(i / s, j / s))) this.dot(i, j, c)
58 }
59 }
60 }
61 // An oval with a dark rim of its own, so it reads over a body of a near colour.
62 rim(cx: number, cy: number, rx: number, ry: number, c: number) {
63 this.oval(cx, cy, rx + 1, ry + 1, OUT)
64 this.oval(cx, cy, rx, ry, c)
65 }
66 tri(ax: number, ay: number, bx: number, by: number, cx: number, cy: number, c: number) {
67 const side = (px: number, py: number, x0: number, y0: number, x1: number, y1: number) =>
68 (px - x1) * (y0 - y1) - (x0 - x1) * (py - y1)
69 const s = this.s
70 for (let j = Math.floor(Math.min(ay, by, cy) * s); j <= Math.ceil(Math.max(ay, by, cy) * s); j++) {
71 for (let i = Math.floor(Math.min(ax, bx, cx) * s); i <= Math.ceil(Math.max(ax, bx, cx) * s); i++) {
72 const px = (i + 0.5) / s, py = (j + 0.5) / s
73 const d1 = side(px, py, ax, ay, bx, by), d2 = side(px, py, bx, by, cx, cy), d3 = side(px, py, cx, cy, ax, ay)
74 if (!((d1 < 0 || d2 < 0 || d3 < 0) && (d1 > 0 || d2 > 0 || d3 > 0))) this.dot(i, j, c)
75 }
76 }
77 }
78 line(x0: number, y0: number, x1: number, y1: number, c: number, thick = 1) {
79 const n = Math.max(1, Math.ceil(Math.max(Math.abs(x1 - x0), Math.abs(y1 - y0)) * this.s))
80 for (let k = 0; k <= n; k++) {
81 const x = x0 + ((x1 - x0) * k) / n, y = y0 + ((y1 - y0) * k) / n
82 this.rect(x, y, thick, thick, c)
83 }
84 }
85 stamp(rows: string[], pal: Record<string, number>, ox: number, oy: number, k = 1) {
86 rows.forEach((row, y) => {
87 for (let x = 0; x < row.length; x++) {
88 const c = pal[row[x] ?? '.']
89 if (c !== undefined) this.rect(ox + x * k, oy + y * k, k, k, c)
90 }
91 })
92 }
93 // A one hi-res pixel dark edge around everything drawn so far: the sticker look.
94 outline(c: number) {
95 const src = this.px.slice(), W = this.pw, H = this.ph
96 const at = (x: number, y: number) => (x < 0 || y < 0 || x >= W || y >= H ? CLEAR : src[y * W + x])
97 for (let y = 0; y < H; y++) for (let x = 0; x < W; x++) {
98 if (src[y * W + x] !== CLEAR) continue
99 if (at(x - 1, y) !== CLEAR || at(x + 1, y) !== CLEAR || at(x, y - 1) !== CLEAR || at(x, y + 1) !== CLEAR) {
100 this.px[y * W + x] = c
101 }
102 }
103 }
104 over(o: Canvas) {
105 for (let i = 0; i < this.px.length; i++) if ((o.px[i] ?? CLEAR) !== CLEAR) this.px[i] = o.px[i] ?? CLEAR
106 }
107}
108
109const mix = (a: number, b: number, k: number) => {
110 const ch = (s: number) => Math.round(((a >> s) & 255) * (1 - k) + ((b >> s) & 255) * k)
111 return (ch(16) << 16) | (ch(8) << 8) | ch(0)
112}
113// One smooth cycle over `n` frames: 0 at frame 0, 1 halfway, back to 0.
114const cyc = (f: number, n: number) => 0.5 - 0.5 * Math.cos((2 * Math.PI * f) / n)
115const ease = (t: number) => (t <= 0 ? 0 : t >= 1 ? 1 : t * t * (3 - 2 * t))
116const dim = (c: number) => mix(c, 0x000000, 0.3)
117const rnd = (a: number, b: number) => {
118 const x = Math.sin(a * 12.9898 + b * 78.233) * 43758.5453
119 return x - Math.floor(x)
120}
121
122type Pal = {
123 body: number; shade: number; light: number; belly: number; mark: number
124 wing: number; face: number; beak: number; horn: number
125}
126const OWL: Pal = {
127 body: 0x63c9cf, shade: 0x3d9cad, light: 0xb4f0ea, belly: 0xfff3da, mark: 0xe8cf9f,
128 wing: 0x4aa3bd, face: 0xeafaf6, beak: 0xffa938, horn: 0x3d9cad,
129}
130const REVIEW_OWL: Pal = {
131 body: 0xe58fb4, shade: 0xb9628f, light: 0xffd1e3, belly: 0xfff3da, mark: 0xe8b8c8,
132 wing: 0xc66f9c, face: 0xfff0f5, beak: 0xffa938, horn: 0xb9628f,
133}
134const DRAGON: Pal = {
135 body: 0xffab52, shade: 0xe27c2f, light: 0xffd79c, belly: 0xfff0c8, mark: 0xf0c084,
136 wing: 0xff6f5e, face: 0xffab52, beak: 0, horn: 0xfff4dc,
137}
138const DRAGON_OPUS: Pal = {
139 body: 0xb59cff, shade: 0x8a6fe3, light: 0xe0d6ff, belly: 0xfff0fa, mark: 0xe6c6ef,
140 wing: 0xff8fcf, face: 0xb59cff, beak: 0, horn: 0xfff4dc,
141}
142
143type Arm = 'down' | 'up' | 'wave' | 'hold' | 'type' | 'chin' | 'point'
144type Eyes = 'open' | 'wide' | 'closed' | 'happy' | 'dizzy' | 'squeeze' | 'sad'
145type Mouth = 'smile' | 'open' | 'o' | 'frown' | 'flat'
146type Body = {
147 x: number; y: number; squash: number; look: [number, number]
148 eyes: Eyes; mouth: Mouth; left: Arm; right: Arm; phase: number
149 hat?: 'crown' | 'nightcap' | 'shell'; glasses?: boolean; flap: number
150}
151type Frame = { cx: number; cy: number; top: number; bottom: number; rx: number; ry: number; eyY: number }
152
153const owl = (role: Role) => role !== 'coder'
154const palOf = (role: Role, opus: boolean) => role === 'scout' ? OWL : role === 'reviewer' ? REVIEW_OWL : opus ? DRAGON_OPUS : DRAGON
155
156function frameOf(b: Body): Frame {
157 const top = 8 + b.y + b.squash, bottom = 30.5 + b.y
158 const cy = (top + bottom) / 2, ry = (bottom - top) / 2
159 return { cx: 16 + b.x, cy, top, bottom, rx: 12.5 + b.squash * 0.5, ry, eyY: cy - 3.5 }
160}
161
162function eye(c: Canvas, x: number, y: number, kind: Eyes, look: [number, number], phase: number, side: number, lid: number) {
163 const ix = Math.floor(x), iy = Math.floor(y)
164 switch (kind) {
165 case 'open':
166 case 'wide':
167 case 'sad': {
168 const r = kind === 'wide' ? 3.5 : 3.1
169 const lx = x + look[0], ly = y + look[1]
170 c.oval(lx, ly, r, r + 0.6, EYE)
171 c.oval(lx, ly + 1.8, r - 0.9, 1.6, IRIS, (px, py) => c.at(px, py) === EYE)
172 c.rect(Math.floor(lx - 1.7), Math.floor(ly - 2.3), 2, 2, SHINE)
173 c.put(lx + 1.1, ly + 1.2, SHINE)
174 if (kind === 'wide') c.put(lx + 1.4, ly - 2.2, SHINE)
175 if (kind === 'sad') {
176 // a heavy lid slanting down to the outside
177 for (let yy = iy - 5; yy <= iy; yy++) for (let xx = ix - 4; xx <= ix + 4; xx++) {
178 const cut = iy - 1 + (xx - ix) * side * 0.4
179 if (yy < cut) for (const on of [EYE, IRIS, SHINE]) c.put(xx, yy, lid, on)
180 }
181 c.line(ix - 3, iy - 1 - 3 * side * 0.4, ix + 3, iy - 1 + 3 * side * 0.4, EYE)
182 }
183 break
184 }
185 case 'closed':
186 for (const [dx, dy] of [[-2, 0], [-1, 1], [0, 1], [1, 1], [2, 0]] as const) c.put(ix + dx, iy + dy, EYE)
187 break
188 case 'happy':
189 for (const [dx, dy] of [[-2, 1], [-2, 2], [-1, 0], [0, -1], [1, 0], [2, 1], [2, 2]] as const) c.put(ix + dx, iy + dy, EYE)
190 break
191 case 'squeeze':
192 for (const [dx, dy] of [[-2, -2], [-1, -1], [0, 0], [-1, 1], [-2, 2], [-1, -2], [0, -1], [1, 0], [0, 1], [-1, 2]] as const) {
193 c.put(ix + dx * -side, iy + dy, EYE)
194 }
195 break
196 case 'dizzy':
197 for (let t = 0; t < 4 * Math.PI; t += 0.12) {
198 const r = 0.3 + t * 0.26
199 c.put(x + r * Math.cos(t * side + phase), y + 0.3 + r * Math.sin(t * side + phase), EYE)
200 }
201 break
202 }
203}
204
205function body(c: Canvas, role: Role, pal: Pal, b: Body) {
206 const { cx, cy, top, bottom, rx, ry, eyY } = frameOf(b)
207 if (role === 'coder') {
208 // the tail curls out behind, to the right
209 const wag = Math.sin((b.phase * Math.PI) / 8) * 0.8
210 for (let t = 0; t <= 1.0001; t += 0.05) {
211 const r = 3 - 1.7 * t
212 c.oval(cx + 8 + 8.5 * t, bottom - 3 - 9 * t * t + wag * t, r, r, pal.body)
213 }
214 c.tri(cx + 14.5, bottom - 13 + wag, cx + 18.5, bottom - 15 + wag, cx + 17, bottom - 10 + wag, pal.wing)
215 // bat wings behind the shoulders
216 for (const s of [-1, 1]) {
217 c.tri(cx + s * 7, cy - 6, cx + s * 15.6, cy - 12 - b.flap, cx + s * 10, cy + 1, pal.wing)
218 c.tri(cx + s * 11, cy - 4, cx + s * 15.6, cy - 12 - b.flap, cx + s * 15, cy - 1, pal.wing)
219 }
220 } else {
221 for (const s of [-1, 1]) c.tri(cx + s * 4.5, top + 3, cx + s * 10.5, top - 4.5, cx + s * 11.5, top + 6, pal.horn)
222 }
223
224 c.oval(cx, cy, rx, ry, pal.shade)
225 c.oval(cx - 0.6, cy - 0.9, rx - 1.1, ry - 0.9, pal.body)
226 c.oval(cx - 6, top + 3.6, 3.6, 1.7, pal.light)
227 c.oval(cx, bottom - 5.8, 7.6, 5.4, pal.belly)
228 if (owl(role)) {
229 for (const [mx, my] of [[-4, -5], [1, -5], [-2, -2.5], [3, -2.5]] as const) {
230 const x = Math.floor(cx + mx), y = Math.floor(bottom + my)
231 c.put(x, y, pal.mark); c.put(x + 1, y + 1, pal.mark); c.put(x + 2, y, pal.mark)
232 }
233 for (const s of [-1, 1]) c.oval(cx + s * 5.5, eyY + 0.4, 5.9, 5.3, pal.face)
234 } else {
235 for (const dy of [-6.5, -3.5]) c.line(cx - 6, bottom + dy, cx + 5, bottom + dy, pal.mark)
236 for (const y of [bottom - 6.5, bottom - 3.5]) for (let x = cx - 8; x <= cx + 8; x++) {
237 if (c.at(x, y) === pal.mark && (c.at(x, y - 1) !== pal.belly || c.at(x, y + 1) !== pal.belly)) c.put(x, y, pal.belly)
238 }
239 for (const s of [-1, 1]) c.tri(cx + s * 4.5, top + 2.2, cx + s * 8.5, top - 5, cx + s * 8.6, top + 2.8, pal.horn)
240 }
241
242 // feet
243 for (const s of [-1, 1]) {
244 if (owl(role)) c.oval(cx + s * 5, bottom, 2.6, 1.3, pal.beak)
245 else c.oval(cx + s * 6, bottom - 0.3, 3, 1.6, pal.shade)
246 }
247
248 for (const s of [-1, 1]) c.oval(cx + s * 8.6, eyY + 4.2, 1.8, 1, BLUSH)
249 for (const [s, x] of [[-1, cx - 5.5], [1, cx + 5.5]] as const) eye(c, x, eyY, b.eyes, b.look, (b.phase * Math.PI) / 8, s, pal.face)
250 if (b.glasses) {
251 for (const s of [-1, 1]) {
252 const gx = cx + s * 5.5
253 c.oval(gx, eyY, 4.9, 4.9, OUT, (x, y) => {
254 const dx = x + 0.5 - gx, dy = y + 0.5 - eyY
255 return dx * dx + dy * dy > 3.9 * 3.9
256 })
257 }
258 c.line(cx - 1, eyY - 1, cx, eyY - 1, OUT)
259 }
260
261 const my = Math.floor(eyY + 3)
262 const mx = Math.floor(cx)
263 if (owl(role)) {
264 if (b.mouth === 'open' || b.mouth === 'o') {
265 c.rect(mx - 2, my, 4, 1, pal.beak); c.rect(mx - 2, my + 1, 4, 2, EYE)
266 c.put(mx - 2, my + 1, pal.beak); c.put(mx + 1, my + 1, pal.beak); c.rect(mx - 1, my + 3, 2, 1, pal.beak)
267 if (b.mouth === 'open') c.rect(mx - 1, my + 2, 2, 1, TONGUE)
268 } else {
269 c.rect(mx - 2, my, 4, 1, pal.beak); c.rect(mx - 1, my + 1, 2, 1, pal.beak)
270 if (b.mouth === 'frown') c.rect(mx - 1, my + 2, 2, 1, mix(pal.beak, EYE, 0.3))
271 }
272 } else {
273 c.put(mx - 2, my - 1, pal.shade); c.put(mx + 1, my - 1, pal.shade)
274 const y = my + 1
275 if (b.mouth === 'smile') {
276 for (const [dx, dy] of [[-3, 0], [-2, 1], [-1, 0], [0, 0], [1, 1], [2, 0]] as const) c.put(mx + dx, y + dy, EYE)
277 } else if (b.mouth === 'open') {
278 c.oval(cx, y + 1.2, 2.4, 1.9, EYE)
279 c.oval(cx, y + 2.4, 1.6, 0.8, TONGUE, (px, py) => c.at(px, py) === EYE)
280 c.put(mx - 2, y, SHINE)
281 } else if (b.mouth === 'o') {
282 c.oval(cx, y + 0.8, 1.3, 1.4, EYE)
283 } else if (b.mouth === 'frown') {
284 for (const [dx, dy] of [[-2, 1], [-1, 0], [0, 0], [1, 1]] as const) c.put(mx + dx, y + dy, EYE)
285 } else {
286 c.rect(mx - 1, y, 2, 1, EYE)
287 }
288 }
289
290 if (b.hat === 'crown') {
291 c.stamp([
292 'Y...YY...Y',
293 'YY.YYYY.YY',
294 'YYYYPPYYYY',
295 'yyyyyyyyyy',
296 ], { Y: 0xffd447, y: 0xe0a422, P: 0xff5fa2 }, mx - 5, Math.floor(top) - 4)
297 } else if (b.hat === 'nightcap') {
298 const t = Math.floor(top)
299 c.tri(mx - 8, t + 2, mx + 8, t + 2, mx + 11, t - 6, 0x6c7bff)
300 c.tri(mx - 2, t - 1, mx + 6, t - 1, mx + 11, t - 6, 0x8f9bff)
301 c.rect(mx - 8, t + 1, 17, 2, 0xf4f1ff)
302 c.oval(mx + 12, t - 6.5, 2.2, 2.2, 0xf4f1ff)
303 } else if (b.hat === 'shell') {
304 const t = Math.floor(top)
305 // the top of the eggshell, its broken edge jagged
306 c.oval(cx, t + 2, 7, 5, 0xfff6e6, (x, y) => y < t + 1 || (y === t + 1 && x % 2 === 0))
307 c.oval(cx - 3, t - 1, 1.2, 0.8, pal.body)
308 }
309}
310
311function arm(c: Canvas, role: Role, pal: Pal, b: Body, side: number, kind: Arm) {
312 const { cx, cy, eyY } = frameOf(b)
313 // owls have wings, dragons stubby paws: smaller, in the body's shade
314 const col = owl(role) ? pal.wing : pal.shade
315 const k = owl(role) ? 1 : 0.75
316 const s = side
317 const limb = (x: number, y: number, rx: number, ry: number) => c.rim(x, y, rx * k, ry * k, col)
318 switch (kind) {
319 case 'down': limb(cx + s * (owl(role) ? 11.2 : 10), cy + 3, 2.5, 4.8); break
320 case 'up': limb(cx + s * 12.4, cy - 8.5, 2.3, 4.5); break
321 case 'wave':
322 if (b.phase % 8 < 4) limb(cx + s * 12.4, cy - 8.5, 2.3, 4.5)
323 else limb(cx + s * 13.8, cy - 7, 2.3, 4.2)
324 break
325 case 'hold': limb(cx + s * 12.6, cy + 3, 4.6, 2.3); break
326 case 'type': limb(cx + s * 12.2, cy + 4.5 - (Math.floor(b.phase / 2) % 2 ? 1.5 : 0), 4.2, 2.2); break
327 case 'chin': c.rim(cx + s * 4.5, eyY + 7, 2.2, 1.6, col); break
328 case 'point':
329 limb(cx + s * 11.5, cy - 2, 2.4, 3.2)
330 limb(cx + s * 13.8, cy - 6.5, 2.2, 2.4)
331 c.oval(cx + s * 11.5, cy - 2, 2.4 * k, 3.2 * k, col)
332 break
333 }
334}
335
336function sparkle(c: Canvas, x: number, y: number, size: number, col = 0xffffff) {
337 if (size <= 0) return
338 c.put(x, y, col)
339 for (let k = 1; k <= size; k++) {
340 const t = k === size ? mix(col, 0x8888aa, 0.35) : col
341 c.put(x + k, y, t); c.put(x - k, y, t); c.put(x, y + k, t); c.put(x, y - k, t)
342 }
343}
344
345function star(c: Canvas, x: number, y: number) {
346 c.stamp(['..y..', '.yyy.', 'yyWyy', '.yyy.', '.y.y.'], { y: 0xffe066, W: 0xfffbe0 }, Math.floor(x) - 2, Math.floor(y) - 2)
347}
348
349const Z5 = ['#####', '...#.', '..#..', '.#...', '#####']
350const Z4 = ['####', '..#.', '.#..', '####']
351const QUESTION = ['.###.', '#...#', '...#.', '..#..', '..#..', '.....', '..#..']
352
353// Which frame a state shows at `now`: `seed` puts each worker's loop at its own phase.
354// Counts are frames of FRAME_MS. An intro plays once from the state's start; then the loop runs,
355// or, with no loop, the intro's last frame holds.
356export const LOOP: Record<Pose, number> = {
357 boot: 0, resumed: 0, think: 32, read: 48, write: 48, bash: 32, web: 32, test: 32,
358 blocked: 16, error: 32, ask: 32, done: 1, failed: 1, sleep: 32,
359}
360export const INTRO: Partial<Record<Pose, number>> = { boot: 12, resumed: 12, blocked: 8, done: 16, failed: 8 }
361export const BLINKS: Pose[] = ['think', 'read', 'write', 'bash', 'web', 'test', 'ask']
362// Working creatures breathe on a 2 s cycle; every loop above is a multiple of it.
363const BREATHE: Pose[] = ['think', 'read', 'write', 'bash', 'web', 'test', 'ask', 'error', 'blocked']
364export type Look = { role: Role; opus: boolean; state: Pose; frame: number; blink: boolean }
365
366export function lookAt(role: Role, model: string, state: Pose, now: number, stateAt: number, seed: number): Look {
367 // Only coders wear the Opus crown: frames/ holds no crowned owls.
368 const opus = role === 'coder' && /opus/i.test(model)
369 const tick = Math.floor(now / FRAME_MS) + seed
370 const intro = INTRO[state] ?? 0, loop = LOOP[state]
371 const step = Math.floor(Math.max(0, now - stateAt) / FRAME_MS)
372 const frame = step < intro ? step : loop ? intro + (loop > 1 ? tick % loop : 0) : intro - 1
373 const blink = BLINKS.includes(state) && tick % 31 === 0
374 return { role, opus, state, frame, blink }
375}
376export const lookKey = (l: Look) => `${l.role}${l.opus ? '+' : ''}:${l.state}:${l.frame}${l.blink ? 'b' : ''}`
377export const frameCount = (state: Pose) => (INTRO[state] ?? 0) + LOOP[state]
378
379export function drawLook({ role, opus, state, frame: f, blink }: Look): Canvas {
380 const pal = palOf(role, opus)
381 const c = new Canvas(BIG_W, BIG_H, BIG_S)
382 const fx = new Canvas(BIG_W, BIG_H, BIG_S)
383 const b: Body = {
384 x: 0, y: 0, squash: 0, look: [0, 0], eyes: 'open', mouth: 'smile', left: 'down', right: 'down',
385 phase: f, hat: opus ? 'crown' : undefined, flap: 0,
386 }
387 let creature = true
388 let mid: () => void = () => {}
389 let front: () => void = () => {}
390
391 switch (state) {
392 case 'boot': {
393 if (f <= 6) {
394 creature = false
395 const ox = [0, 0, -1, 0, 1, 0, -1][f] ?? 0
396 c.oval(16 + ox, 19.5, 10.5, 12.5, 0xfff6e6)
397 c.oval(17.5 + ox, 21, 9, 11, 0xf1e2c8, (x, y) => (x - 16 - ox) * 0.6 + (y - 19.5) > 6)
398 for (const [x, y, rx, ry] of [[11.5, 14, 2.2, 1.6], [20.5, 23, 2.8, 2.1], [12.5, 26, 1.6, 1.3], [21.5, 12, 1.4, 1.1]] as const) {
399 c.oval(x + ox, y, rx, ry, pal.body)
400 }
401 c.oval(12.5 + ox, 11, 1.4, 2.6, 0xffffff)
402 const crack: [number, number][] = [[6, 17], [8, 20], [10, 16], [13, 21], [15, 17], [18, 21], [21, 16], [24, 20], [26, 17]]
403 const n = Math.max(0, Math.floor((f - 1) * 1.6))
404 for (let i = 0; i < Math.min(n, crack.length - 1); i++) {
405 const p = crack[i], q = crack[i + 1]
406 if (p && q) c.line(p[0] + ox, p[1], q[0] + ox, q[1], OUT)
407 }
408 if (f >= 3) for (let i = 0; i < 3; i++) sparkle(fx, 36 + rnd(i, f) * 20, 4 + rnd(f, i) * 22, 1, i % 2 ? pal.body : 0xffffff)
409 } else {
410 const out = f >= 10
411 b.eyes = out ? 'happy' : 'wide'
412 b.mouth = out ? 'open' : 'o'
413 b.left = out ? 'up' : 'down'; b.right = out ? 'up' : 'down'
414 b.y = f === 10 ? -1.5 : f === 11 ? -0.5 : 0
415 if (out) b.hat = 'shell'
416 front = () => {
417 if (!out) {
418 // the lower half of the shell still around the belly, the cap flying off up and to the right
419 c.oval(16, 23, 12.5, 9, 0xfff6e6, (x, y) => y >= 26 + (x % 2))
420 for (let x = 4; x <= 28; x++) c.put(x, 25 + (x % 2), OUT)
421 const t = ease((f - 6) / 3)
422 const tx = 30 + 16 * t, ty = 9 - 7 * t
423 c.oval(tx, ty + 3, 6, 4, 0xfff6e6, (_, y) => y < ty + 4)
424 c.oval(tx - 2, ty + 1.5, 1.5, 1, pal.body)
425 } else {
426 c.oval(40, 29.5, 4, 2.5, 0xfff6e6, (_, y) => y >= 29)
427 c.oval(50, 30, 3, 2, 0xfff6e6, (_, y) => y >= 30)
428 }
429 for (let i = 0; i < 5; i++) sparkle(fx, 34 + rnd(i, f) * 24, 3 + rnd(f, i) * 24, 1 + ((i + f) % 2), [0xffffff, 0xffe066, pal.body][i % 3])
430 }
431 }
432 break
433 }
434
435 case 'think': {
436 b.look = [0.6 + 0.5 * Math.sin((f * Math.PI) / 16), -1]; b.right = 'chin'; b.mouth = 'flat'
437 mid = () => {
438 const dy = Math.round(cyc(f, 32))
439 for (const [x, y, rx, ry] of [[41.5, 8.5, 5, 4.5], [48, 6.5, 6, 5.2], [54.5, 8.5, 4.6, 4.2], [45, 12, 5.5, 3.2], [51.5, 12, 5.5, 3.2]] as const) {
440 c.oval(x, y + dy, rx, ry, 0xf4f1ff)
441 }
442 c.oval(34.5, 18.5, 1.6, 1.6, 0xf4f1ff)
443 c.oval(37.5, 15 + dy * 0.5, 2.2, 2.1, 0xf4f1ff)
444 // the dots light one a second, each fading in
445 for (let i = 0; i < 3; i++) c.rect(42 + i * 5, 8 + dy, 3, 3, mix(0xd5d0ea, 0x6a5acd, ease((f - 8 * i - 5) / 3)))
446 }
447 break
448 }
449
450 case 'read': {
451 // the eyes follow the highlighted line down the left page, then the right, then the page turns
452 const line = Math.min(7, Math.floor(f / 5))
453 b.look = [line < 4 ? 0.2 : 1.4, 0.4 + (line % 4) * 0.35]; b.glasses = true; b.right = 'hold'; b.mouth = 'flat'
454 mid = () => {
455 c.rect(31, 16, 27, 14, OUT)
456 c.rect(32, 27, 25, 2, 0xc4664d)
457 c.rect(32, 17, 12, 10, 0xfffaf0); c.rect(45, 17, 11, 10, 0xfffaf0)
458 c.rect(44, 17, 1, 10, 0xd9cbb2); c.rect(43, 17, 1, 10, 0xece2cf)
459 for (let i = 0; i < 4; i++) {
460 for (const [x0, w0, k] of [[33, 9, 0], [46, 9, 1]] as const) {
461 const len = 5 + Math.floor(rnd(i + k * 4, 0) * (w0 - 4))
462 c.rect(x0, 18 + i * 2 + 1, len, 1, f < 40 && line === i + k * 4 ? 0x4d9bf0 : 0xa7adbf)
463 }
464 }
465 const turn = f >= 41 && f <= 46 ? Math.floor((f - 41) / 2) : -1
466 if (turn >= 0) {
467 const x = [46, 43, 35][turn] ?? 46, w = turn === 1 ? 2 : 9, y = turn === 1 ? 10 : 14
468 c.rect(x - 1, y - 1, w + 2, 27 - y + 1, OUT)
469 c.rect(x, y, w, 27 - y, 0xfff3dd)
470 }
471 }
472 break
473 }
474
475 case 'write':
476 case 'bash': {
477 const code: [number, number, number][][] = [
478 [[0, 3, 0xff7aa2], [4, 5, 0x7cc7ff], [10, 2, 0xc9c9e6]],
479 [[2, 4, 0x7ee0a1], [7, 6, 0xffd166]],
480 [[2, 3, 0xff7aa2], [6, 7, 0x7cc7ff]],
481 [[4, 8, 0xc9c9e6], [13, 2, 0xffd166]],
482 [[0, 1, 0xc9c9e6]],
483 ]
484 if (state === 'write') {
485 // types the snippet out over ~4 s, then rests with the cursor blinking
486 const budget0 = Math.floor(f * 1.25)
487 const typing = budget0 < 41
488 b.right = typing ? 'type' : 'hold'
489 mid = () => {
490 c.rect(34, 6, 22, 18, OUT)
491 c.rect(35, 7, 20, 16, 0x3b4252)
492 c.rect(36, 8, 18, 14, 0x1e2230)
493 let budget = budget0
494 code.forEach((segs, row) => {
495 for (const [x, w, col] of segs) {
496 const shown = Math.max(0, Math.min(w, budget))
497 budget -= w
498 c.rect(37 + x, 10 + row * 2, shown, 1, col)
499 if (shown > 0 && shown < w) c.rect(37 + x + shown, 9 + row * 2, 1, 2, 0xffffff)
500 }
501 })
502 if (!typing && f % 8 < 4) c.rect(39, 17, 1, 2, 0xffffff)
503 c.rect(31, 24, 28, 5, OUT)
504 c.rect(32, 25, 26, 3, 0xc5ccd8)
505 for (let x = 33; x < 57; x += 2) c.put(x, 26, 0x8f99aa)
506 c.rect(36, 24, 18, 1, 0x8f99aa)
507 if (typing) for (let i = 0; i < 3; i++) {
508 const ph = (f + i * 5) % 16
509 fx.rect(38 + i * 7, 5 - ph * 0.35, 2, 1, [0xff7aa2, 0x7ee0a1, 0x7cc7ff][i] ?? 0xffffff)
510 }
511 }
512 b.look = [1, 0.2 + Math.min(4, Math.floor(budget0 / 9)) * 0.25]
513 } else {
514 // a line every second scrolls up; the prompt types between them
515 const s = Math.floor(f / 8), inLine = f % 8
516 const typed = Math.min(3, Math.floor(inLine / 2))
517 b.look = [1, 0.6]; b.right = inLine < 6 ? 'type' : 'hold'
518 mid = () => {
519 c.rect(33, 2, 26, 22, OUT)
520 c.rect(34, 3, 24, 3, 0x4c566a)
521 c.put(36, 4, 0xff5f56); c.put(38, 4, 0xffbd2e); c.put(40, 4, 0x27c93f)
522 c.rect(34, 6, 24, 17, 0x0d1117)
523 for (let row = 0; row < 4; row++) {
524 const k = (row + s) % 4
525 const len = 6 + Math.floor(rnd(k, 3) * 14)
526 c.rect(36, 8 + row * 3, len, 1, k % 3 === 0 ? 0x81c784 : 0x8b949e)
527 }
528 c.stamp(['#..', '.#.', '#..'], { '#': 0x81c784 }, 36, 19)
529 c.rect(40, 20, typed * 2, 1, 0xe6edf3)
530 if (f % 8 < 4) c.rect(40 + typed * 2, 19, 2, 3, 0xe6edf3)
531 c.rect(31, 25, 24, 5, OUT)
532 c.rect(32, 26, 22, 3, 0x9aa5b1)
533 for (let x = 33; x < 53; x += 2) c.put(x, 27, 0x6b7584)
534 }
535 }
536 break
537 }
538
539 case 'web': {
540 b.look = [1, -1]; b.right = 'point'; b.mouth = 'o'
541 mid = () => {
542 const gx = 47, gy = 13, r = 8.5
543 c.oval(gx, gy, r + 1, r + 1, OUT)
544 c.oval(gx, gy, r, r, 0x3a86ff, (x, y) => {
545 const nx = (x + 0.5 - gx) / r, ny = (y + 0.5 - gy) / r
546 const lon = Math.asin(Math.max(-1, Math.min(1, nx / Math.sqrt(Math.max(0.0001, 1 - ny * ny))))) + (f * Math.PI) / 16
547 const lat = Math.asin(ny)
548 const land = Math.sin(lon * 2 + 1) * Math.cos(lat * 2.5) + Math.sin(lon * 3 + lat * 3) * 0.6 > 0.45
549 if (land) c.put(x, y, nx > 0.55 ? 0x3a9e5c : 0x52d17c)
550 return !land
551 })
552 c.oval(gx, gy, r, r, 0x2a64c8, (x, y) => c.at(x, y) === 0x3a86ff && (x + 0.5 - gx) / r > 0.55)
553 c.rect(gx - 4, gy - 6, 2, 2, 0xd8ecff)
554 c.rect(gx - 1, gy + 10, 2, 3, 0x9aa5b1)
555 c.rect(gx - 5, gy + 13, 10, 2, 0x9aa5b1)
556 const arcs = 1 + Math.min(2, Math.floor((f % 16) / 5))
557 for (let k = 0; k < arcs; k++) {
558 const rr = 3 + k * 2.5
559 const col = k === arcs - 1 ? dim(0x4dd0e1) : 0x4dd0e1
560 for (let a = -0.2; a <= Math.PI / 2 + 0.2; a += 0.08) fx.put(gx + 4 + rr * Math.cos(a - Math.PI / 2), gy - 6 + rr * Math.sin(a - Math.PI / 2), col)
561 }
562 }
563 break
564 }
565
566 case 'test': {
567 // a clipboard of checks ticking green one by one; the row being run pulses yellow
568 const row = Math.min(4, Math.floor((f + 1) / 7))
569 b.look = [1, -0.4 + Math.min(3, row) * 0.45]; b.glasses = true; b.right = 'hold'; b.mouth = row >= 4 ? 'smile' : 'flat'
570 mid = () => {
571 c.rect(34, 3, 23, 28, OUT)
572 c.rect(35, 4, 21, 26, 0xc68a4f)
573 c.rect(37, 7, 17, 21, 0xfffaf0)
574 c.rect(41, 1, 9, 4, OUT)
575 c.rect(42, 2, 7, 2, 0x9aa5b1)
576 for (let i = 0; i < 4; i++) {
577 const y = 8 + i * 5
578 const done = i < row, now = i === row
579 c.rect(38, y, 5, 5, OUT)
580 c.rect(39, y + 1, 3, 3, done ? 0xd7f5df : now ? mix(0xfff3c4, 0xffd166, cyc(f, 4)) : 0xffffff)
581 if (done) c.stamp(['..#', '#.#', '.#.'], { '#': 0x2e9e4f }, 39, y + 1)
582 c.rect(44, y + 2, 5 + Math.floor(rnd(i, 1) * 5), 1, done ? 0x6b7584 : 0xa7adbf)
583 }
584 if (row >= 4) for (let k = 0; k < 3; k++) sparkle(fx, 36 + rnd(k, 9) * 20, 2 + rnd(9, k) * 6, (f + k) % 3 ? 1 : 2, k % 2 ? 0x7bd88f : 0xffffff)
585 }
586 break
587 }
588
589 case 'resumed': {
590 // the answer lands: two little hops under a lighting bulb
591 b.eyes = 'wide'; b.mouth = 'open'; b.left = 'up'; b.right = 'up'
592 b.y = -2.5 * Math.sin((Math.PI * (f % 6)) / 6)
593 b.flap = f % 4 < 2 ? 1 : 0
594 mid = () => {
595 const gx = 47, gy = 11
596 const lit = ease(f / 4)
597 c.oval(gx, gy, 7.2, 7.4, mix(0xd8dce6, 0xffe066, lit))
598 c.oval(gx + 1.5, gy + 1.5, 5.5, 5.5, mix(0xb8bdca, 0xffd23f, lit), (x, y) => (x - gx) + (y - gy) > 3)
599 c.oval(gx - 2.5, gy - 3, 1.4, 2.2, 0xfffbe0)
600 c.line(gx - 2, gy + 2, gx - 1, gy + 4, 0xff9f1c); c.line(gx - 1, gy + 4, gx, gy + 2, 0xff9f1c)
601 c.line(gx, gy + 2, gx + 1, gy + 4, 0xff9f1c)
602 c.rect(gx - 4, gy + 7, 8, 6, OUT)
603 c.rect(gx - 3, gy + 7, 6, 5, 0xb0b8c4)
604 c.rect(gx - 3, gy + 8, 6, 1, 0x7f889a); c.rect(gx - 3, gy + 10, 6, 1, 0x7f889a)
605 const len = f < 3 ? 0 : 1 + Math.min(2, Math.floor((f - 3) / 2))
606 for (let k = 0; k < 8; k++) {
607 if (k === 2) continue
608 const a = (k * Math.PI) / 4 - Math.PI / 2
609 for (let d = 0; d < len; d++) fx.put(gx + Math.cos(a) * (10 + d), gy + Math.sin(a) * (10 + d), 0xfff3b0)
610 }
611 }
612 break
613 }
614
615 case 'ask': {
616 b.eyes = 'wide'; b.look = [1, -1]; b.mouth = 'open'; b.right = 'wave'
617 mid = () => {
618 const dy = Math.round(cyc(f, 32))
619 c.oval(47, 11 + dy, 10, 9.5, 0xfffaf0)
620 c.tri(36.5, 13 + dy, 40, 17 + dy, 33, 21 + dy, 0xfffaf0)
621 c.stamp(QUESTION, { '#': 0xff9f1c }, 42, 4 + dy, 2)
622 const tw = f % 16
623 if (tw >= 2 && tw <= 5) sparkle(fx, 57, 2, tw === 3 || tw === 4 ? 2 : 1, 0xffd166)
624 if (tw >= 10 && tw <= 12) sparkle(fx, 36, 3, 1, 0xffd166)
625 }
626 break
627 }
628
629 case 'blocked': {
630 b.eyes = 'squeeze'; b.mouth = 'frown'
631 if (f < 8) b.x = [-1, 1, -1, 1, -0.6, 0.6, -0.3, 0][f] ?? 0
632 const g = Math.max(0, f - 8)
633 mid = () => {
634 const gx = 47, gy = 13
635 c.oval(gx, gy, 9, 9, OUT)
636 c.oval(gx, gy, 8, 8, f < 8 ? 0xff4d5e : mix(0xd93a4b, 0xff4d5e, cyc(g, 16)))
637 c.rect(gx - 6, gy - 1, 12, 3, 0xffffff)
638 const fr = frameOf(b)
639 const ph = (g + 10) % 16
640 fx.oval(fr.cx + 10, fr.top + 3 + ph * 0.35, 1.2, 1.7, TEAR)
641 fx.put(fr.cx + 9.6, fr.top + 2 + ph * 0.35, TEAR)
642 }
643 break
644 }
645
646 case 'error': {
647 // a slow dizzy spin: half the usual phase rate
648 b.eyes = 'dizzy'; b.mouth = 'flat'; b.phase = f / 2
649 b.x = 0.8 * Math.sin((2 * Math.PI * f) / 32)
650 mid = () => {
651 c.tri(47, 3, 36, 22.5, 58, 22.5, OUT)
652 c.tri(47, 5.5, 38, 21.5, 56, 21.5, mix(0xff9f43, 0xffc078, cyc(f, 32)))
653 c.rect(46, 10, 2, 6, OUT); c.rect(46, 17, 2, 2, OUT)
654 const fr = frameOf(b)
655 for (let k = 0; k < 3; k++) {
656 const a = (f * Math.PI) / 16 + (k * 2 * Math.PI) / 3
657 star(fx, fr.cx + 11 * Math.cos(a), fr.top - 0.5 + 2.2 * Math.sin(a))
658 }
659 }
660 break
661 }
662
663 case 'done': {
664 if (f < 16) {
665 // two hops, a squash on each landing, confetti drifting down
666 const h = f % 8
667 b.eyes = 'happy'; b.mouth = 'open'; b.left = 'up'; b.right = 'wave'
668 b.y = -3 * Math.sin((Math.PI * h) / 8)
669 b.squash = h === 0 ? 1 : 0
670 b.flap = f % 4 < 2 ? 2 : 0
671 front = () => {
672 for (let i = 0; i < 16; i++) {
673 const x = rnd(i, 7) * 60 + Math.sin((f + i) * 0.6) * 1.2, y = (rnd(i, 3) * 32 + f) % 32
674 const col = CONFETTI[i % CONFETTI.length] ?? 0xffffff
675 if ((i + Math.floor(f / 2)) % 2) fx.rect(x, y, 2, 1, col)
676 else fx.rect(x, y, 1, 2, col)
677 }
678 }
679 } else {
680 b.eyes = 'happy'; b.mouth = 'smile'
681 mid = () => {
682 const gx = 46, gy = 15
683 c.oval(gx, gy, 8, 8, 0x5cd67a)
684 c.oval(gx + 1, gy + 1, 6.5, 6.5, 0x43bd62, (x, y) => (x - gx) + (y - gy) > 4)
685 c.line(41, 15, 44, 18, 0xffffff, 2); c.line(44, 18, 50, 11, 0xffffff, 2)
686 sparkle(fx, 56, 4, 2, 0xffffff); sparkle(fx, 36, 5, 1, 0xfff3b0)
687 }
688 }
689 break
690 }
691
692 case 'failed': {
693 // sinks down over a second, then holds
694 b.eyes = 'sad'; b.mouth = 'frown'; b.squash = ease(Math.min(f, 7) / 7)
695 mid = () => {
696 const gx = 46, gy = 15
697 c.oval(gx, gy, 8, 8, 0xff5c6c)
698 c.oval(gx + 1, gy + 1, 6.5, 6.5, 0xe5485a, (x, y) => (x - gx) + (y - gy) > 4)
699 c.line(42, 11, 49, 18, 0xffffff, 2); c.line(49, 11, 42, 18, 0xffffff, 2)
700 const fr = frameOf(b)
701 for (const [s, off] of [[-1, 0], [1, 3]] as const) {
702 const ph = Math.min(f, 7 + off) - off
703 if (ph >= 0) fx.rect(fr.cx + s * 5.5 + (s < 0 ? -3 : 2), fr.eyY + 3 + Math.min(ph, 4) * 0.8, 1, 2, TEAR)
704 }
705 }
706 break
707 }
708
709 case 'sleep': {
710 b.eyes = 'closed'; b.mouth = 'o'; b.hat = 'nightcap'
711 b.squash = 0.2 + 0.9 * cyc(f, 32)
712 front = () => {
713 const fr = frameOf(b)
714 const r = 0.9 + 2.2 * cyc(f, 32)
715 fx.oval(fr.cx + 4.5, fr.eyY + 6.5 - r * 0.3, r, r, 0xbfe9ff)
716 fx.put(fr.cx + 4 - r * 0.4, fr.eyY + 5.5 - r * 0.6, 0xffffff)
717 for (let k = 0; k < 3; k++) {
718 const p = ((f + k * 11) % 32) / 32
719 const col = mix(0xc6b3ff, 0x2a2d3d, p * 0.9)
720 fx.stamp(k === 0 ? Z4 : Z5, { '#': col }, Math.floor(35 + k * 7 + p * 4), Math.floor(21 - k * 7 - p * 5))
721 }
722 }
723 break
724 }
725 }
726
727 if (BREATHE.includes(state)) b.squash += 0.7 * cyc(f, 16)
728 if (blink && (b.eyes === 'open' || b.eyes === 'wide')) b.eyes = 'closed'
729 if (role === 'reviewer') b.glasses = true
730 if (creature) {
731 body(c, role, pal, b)
732 mid()
733 arm(c, role, pal, b, -1, b.left)
734 arm(c, role, pal, b, 1, b.right)
735 front()
736 }
737 c.outline(OUT)
738 c.over(fx)
739 // A soft shadow that shrinks as the creature leaves the ground.
740 const out = new Canvas(BIG_W, BIG_H, BIG_S)
741 const lift = Math.max(0, -b.y)
742 out.oval(creature ? frameOf(b).cx : 16, 31.2, 11.5 - lift * 1.4, 1.6, SHADOW)
743 out.over(c)
744 return out
745}
746
747// ---------- the half-block fallback: 15x8, a small hand-made creature and the props as icons ----------
748
749const SMALL_BODY: Record<Role, string[]> = {
750 scout: [
751 '.h....h.',
752 '.hBBBBh.',
753 'BFFBBFFB',
754 'BFFBBFFB',
755 'BBByyBBB',
756 'WBccccBW',
757 'WBccccBW',
758 '..o..o..',
759 ],
760 reviewer: [
761 '.h....h.',
762 '.hBBBBh.',
763 'BggBBggB',
764 'BFFggFFB',
765 'BBByyBBB',
766 'WBccccBW',
767 'WBccccBW',
768 '..o..o..',
769 ],
770 coder: [
771 'H......H',
772 'wHBBBBHw',
773 'wBBBBBBw',
774 '.BBBBBB.',
775 '.BBBBBB.',
776 '.BccccBt',
777 '.BccccBt',
778 '..d..d..',
779 ],
780}
781
782const ICON = {
783 ask: ['.##.', '#..#', '..#.', '.#..', '....', '.#..'],
784 bang: ['#', '#', '#', '.', '#'],
785 check: ['....#', '...#.', '#.#..', '.#...'],
786 cross: ['#...#', '.#.#.', '..#..', '.#.#.', '#...#'],
787 bulb: ['.###.', '#####', '#####', '.###.', '.###.'],
788 globe: ['.###.', '#####', '#####', '#####', '.###.'],
789 bubble: ['.#####.', '#######', '.#####.'],
790 stop: ['.###.', '#####', '#...#', '#####', '.###.'],
791 warn: ['..#..', '.###.', '.#.#.', '#####'],
792 z: ['###', '..#', '.#.', '###'],
793}
794const LAND = ['01100011', '11110011', '01110001', '00110110', '00011100']
795
796export function drawSmall({ role, opus, state, frame: big, blink }: Look): Canvas {
797 // The icons keep their own short cycles at half the big frames' rate.
798 const f = state === 'boot' ? (big < 7 ? Math.floor((big * 5) / 7) : big < 10 ? 5 : 7)
799 : state === 'done' ? (big < 16 ? big >> 1 : 8)
800 : big >> 1
801 const p = new Canvas(SMALL_W, SMALL_H)
802 const pal = palOf(role, opus)
803 const theme = role === 'scout' ? 0x4fd1c5 : role === 'reviewer' ? 0xff8fb8 : opus ? 0xb59cff : 0xffb347
804 const colors: Record<string, number> = {
805 h: pal.horn, H: pal.horn, B: pal.body, F: pal.face, y: pal.beak, c: pal.belly, o: pal.beak,
806 w: pal.wing, t: pal.body, d: pal.shade, g: OUT,
807 }
808 const celebrating = state === 'done' && f < 8
809 const ox = state === 'blocked' && f < 2 ? f : 0
810 const oy = celebrating && f % 4 >= 1 && f % 4 <= 3 ? -1 : 0
811
812 if (state === 'boot' && f < 5) {
813 // the egg, cracking
814 p.stamp(['..##..', '.####.', '######', '######', '######', '.####.'], { '#': 0xfff6e6 }, 1 + (f === 1 ? -1 : f === 3 ? 1 : 0), 1)
815 p.put(2, 3, pal.body); p.put(5, 5, pal.body)
816 if (f >= 2) for (let x = 1; x < 1 + (f - 1) * 2 && x < 7; x++) p.put(x, 3 + (x % 2), OUT)
817 if (f >= 2) p.put(9 + (f * 3) % 5, (f * 5) % 7, 0xffffff)
818 return p
819 }
820
821 p.stamp(SMALL_BODY[role], colors, ox, oy)
822 if (opus) { p.put(ox + 3, oy, 0xffd447); p.put(ox + 4, oy, 0xffd447) }
823 if (state === 'sleep') { p.put(ox + 2, oy, 0x6c7bff); p.put(ox + 3, oy, 0x6c7bff); p.put(ox + 4, oy, 0x6c7bff); p.put(ox + 5, oy, 0xf4f1ff) }
824 if (state === 'boot') { p.put(ox + 2, oy, 0xfff6e6); p.put(ox + 3, oy, 0xfff6e6); p.put(ox + 4, oy, 0xfff6e6); p.put(ox + 5, oy, 0xfff6e6) }
825
826 // eyes: one dark pixel each, a lid line when shut
827 const eyeRow = oy + 3
828 const shut = blink || state === 'sleep' || state === 'blocked' || (state === 'done') || (state === 'boot' && f === 7)
829 const up = state === 'think' || state === 'ask' || state === 'web' || state === 'resumed'
830 const dx = state === 'read' || state === 'write' || state === 'bash' || state === 'test' ? 1 : 0
831 for (const x of [2, 5]) {
832 if (state === 'error') p.put(ox + x, eyeRow, f % 2 ? 0xff8a65 : EYE)
833 else if (shut) { p.put(ox + x - 1, eyeRow, EYE); p.put(ox + x, eyeRow, EYE) }
834 else p.put(ox + x + (x === 2 ? dx : 0) - (x === 5 && dx ? 0 : 0), eyeRow - (up ? 1 : 0), EYE)
835 if (state === 'failed') p.put(ox + x, eyeRow + 1 + (f % 2), TEAR)
836 }
837 if (state !== 'failed' && role === 'coder') { p.put(ox + 1, oy + 4, BLUSH); p.put(ox + 6, oy + 4, BLUSH) }
838 if (role === 'coder' && (state === 'done' || state === 'ask' || state === 'resumed')) { p.put(ox + 3, oy + 4, EYE); p.put(ox + 4, oy + 4, EYE) }
839
840 const limb = owl(role) ? pal.wing : pal.shade
841 const armUp = (x: number) => { p.put(ox + x, oy + 2, limb); p.put(ox + x, oy + 3, limb) }
842 const armDown = (x: number) => { p.put(ox + x, oy + 5, limb); p.put(ox + x, oy + 6, limb) }
843 armDown(0)
844
845 switch (state) {
846 case 'write':
847 case 'bash': {
848 p.put(7, 5 - (f % 2), limb)
849 if (state === 'bash') {
850 for (let y = 0; y < 6; y++) for (let x = 9; x < 15; x++) p.put(x, y, y === 0 ? 0x4c566a : 0x0d1117)
851 p.put(10, 2, 0x81c784); p.put(11, 3, 0x81c784); p.put(10, 4, 0x81c784)
852 if (f % 2 === 0) p.put(13, 4, 0xe6edf3)
853 for (let x = 9; x < 14; x++) p.put(x, 7, 0x9aa5b1)
854 } else {
855 for (let y = 1; y < 6; y++) for (let x = 9; x < 15; x++) p.put(x, y, y === 1 || x === 9 || x === 14 ? 0x3b4252 : 0x1e2230)
856 for (let i = 0; i < 3; i++) p.put(10 + i, 2 + i, [0xff7aa2, 0x7ee0a1, 0x7cc7ff][(i + f) % 3] ?? theme)
857 for (let x = 8; x < 15; x++) p.put(x, 6, 0xc5ccd8)
858 p.put(10 + (f % 4), 0, theme)
859 }
860 break
861 }
862 case 'read':
863 p.put(7, 5, limb)
864 for (let y = 3; y <= 7; y++) for (let x = 8; x <= 14; x++) p.put(x, y, x === 11 ? 0xd9cbb2 : 0xfffaf0)
865 for (const y of [4, 6]) {
866 const hot = Math.floor(f / 4) % 2
867 p.put(9, y, hot && y === 4 ? 0x4d9bf0 : 0xa7adbf); p.put(12, y, 0xa7adbf); p.put(13, y, y === 6 && !hot ? 0x4d9bf0 : 0xa7adbf)
868 }
869 break
870 case 'test':
871 p.put(7, 5, limb)
872 for (let y = 1; y < 8; y++) for (let x = 9; x < 15; x++) p.put(x, y, x === 9 || x === 14 || y === 1 || y === 7 ? 0xc68a4f : 0xfffaf0)
873 p.put(11, 0, 0x9aa5b1); p.put(12, 0, 0x9aa5b1)
874 for (let i = 0; i < 3; i++) {
875 const y = 2 + i * 2
876 p.put(10, y, f % 4 > i ? 0x43bd62 : f % 4 === i ? 0xffd166 : 0xa7adbf)
877 p.put(11, y, 0xa7adbf); p.put(12, y, 0xa7adbf)
878 }
879 break
880 case 'web':
881 armUp(7)
882 ICON.globe.forEach((row, y) => {
883 for (let x = 0; x < row.length; x++) if (row[x] === '#') {
884 const land = LAND[y]?.[(x + f) % 8] === '1'
885 p.put(9 + x, 1 + y, land ? 0x52d17c : 0x3a86ff)
886 }
887 })
888 p.put(f % 4 < 2 ? 14 : 13, 0, 0x4dd0e1)
889 break
890 case 'ask':
891 if (f % 4 < 2) armUp(7); else { p.put(7, 1, limb); p.put(7, 2, limb) }
892 p.stamp(ICON.ask, { '#': 0xffd166 }, 10, f % 4 < 2 ? 0 : 1)
893 break
894 case 'resumed':
895 armUp(7); armUp(0)
896 p.stamp(ICON.bulb.slice(0, 3), { '#': 0xffe066 }, 10, 0)
897 p.stamp(ICON.bulb.slice(3), { '#': 0x9aa5b1 }, 10, 3)
898 if (f % 2) { p.put(9, 0, 0xfff3b0); p.put(14, 1, 0xfff3b0); p.put(9, 2, 0xfff3b0) }
899 break
900 case 'blocked':
901 armDown(7)
902 p.stamp(ICON.stop, { '#': f < 2 || f % 4 < 2 ? 0xff4d5e : 0xd93a4b }, 10, 1)
903 p.put(12, 3, 0xffffff); p.put(11, 3, 0xffffff); p.put(13, 3, 0xffffff)
904 p.put(ox + 7, 1 + (f % 3), TEAR)
905 break
906 case 'error':
907 armDown(7)
908 p.stamp(ICON.warn, { '#': 0xff9f43 }, 10, 2)
909 p.put(12, 3, OUT)
910 p.put(ox + 1 + (f % 6), 0, 0xffe066)
911 break
912 case 'done':
913 if (celebrating) {
914 armUp(0); armUp(7)
915 for (let i = 0; i < 10; i++) {
916 const x = Math.floor(rnd(i, 7) * 15), y = Math.floor((rnd(i, 3) * 8 + f) % 8)
917 if (p.at(x, y) === CLEAR) p.put(x, y, CONFETTI[i % CONFETTI.length] ?? 0xffffff)
918 }
919 } else {
920 armDown(7)
921 p.stamp(ICON.check, { '#': 0x7bd88f }, 10, 2)
922 if (f % 16 < 2) p.put(14, 0, 0xffffff)
923 }
924 break
925 case 'failed':
926 armDown(7)
927 p.stamp(ICON.cross, { '#': 0xff5c6c }, 10, 1)
928 break
929 case 'sleep': {
930 armDown(7)
931 p.stamp(ICON.z, { '#': 0xb39ddb }, 9, 4)
932 if (f % 8 >= 3) p.stamp(ICON.z, { '#': 0x8f7fbf }, 12, 0)
933 break
934 }
935 case 'boot':
936 armUp(0); armUp(7)
937 p.put(10, 6, 0xfff6e6); p.put(11, 7, 0xfff6e6); p.put(12, 7, 0xfff6e6)
938 p.put(9 + (f % 3) * 2, 1, 0xffffff)
939 break
940 default: {
941 // think: paw at the chin, a thought bubble filling dot by dot
942 p.put(6, 4, limb)
943 p.put(8, 3, 0xe6e6f0)
944 p.stamp(ICON.bubble, { '#': 0xf4f1ff }, 8, 0)
945 const lit = Math.floor(f / 4)
946 for (let i = 0; i < 3; i++) p.put(9 + i * 2, 1, i < lit ? 0x6a5acd : 0xc8c8d8)
947 }
948 }
949 return p
950}
951
952// Frames are pure in their Look, so each is drawn once; a long session sees a few hundred.
953const BIG = new Map<string, Canvas>()
954const SMALL = new Map<string, Canvas>()
955const cached = <T>(m: Map<string, T>, key: string, make: () => T): T => {
956 const hit = m.get(key)
957 if (hit) return hit
958 if (m.size > 800) m.clear()
959 const v = make()
960 m.set(key, v)
961 return v
962}
963export const bigSprite = (l: Look) => cached(BIG, lookKey(l), () => drawLook(l))
964export const smallSprite = (l: Look) => cached(SMALL, lookKey(l), () => drawSmall(l))
965
966// Every distinct frame is a small PNG under frames/ (made by tools/gen_frames.sh); the terminal reads the
967// file itself and a source equal to the last one sends nothing, so a blit carries only a path.
968export const frameFile = (l: Look) => `${l.role}${l.opus ? '_opus' : ''}-${l.state}-${l.frame}${l.blink ? 'b' : ''}.png`
969export const imageSource = (l: Look, root: string) => ({ file: `${root}/frames/${frameFile(l)}`, format: 'png' as const })
970
971export const ALL_POSES: Pose[] = [
972 'boot', 'resumed', 'think', 'read', 'write', 'bash', 'web', 'test', 'blocked', 'error', 'ask', 'done', 'failed', 'sleep',
973]
974hooks/scene.ts 744 lines1// Pure drawing: cw run files -> worker states -> one Raster of text and half-block pixel art,
2// or of text alone with each sprite listed for an Image laid over it.
3
4import { CLEAR, FRAME_MS, SMALL_H, SMALL_W, lookAt, smallSprite, type Canvas, type Look } from './creatures'
5
6export type Role = 'scout' | 'coder' | 'reviewer'
7export type Kind = 'read' | 'write' | 'bash' | 'web'
8export type State =
9 | 'boot' | 'resumed' | 'think' | Kind | 'test' | 'blocked' | 'error' | 'ask' | 'done' | 'failed'
10
11export type Ev = {
12 e: string; t: number; tool?: string; arg?: string
13 ok?: boolean; sub?: string; sid?: string; turns?: number; denied?: number; out?: number
14 ctx?: number; mid?: string // assistant steps: context size, message id
15 cost?: number; cin?: number; nin?: number; win?: number // result: USD, cached / new input tokens, context window
16 add?: number; del?: number; files?: number; rc?: number // diff; accept_end
17}
18export type Meta = {
19 role: Role; model: string; session: string; resume: string; task: string
20 start: number; tmo: number; web: boolean; pid: number; effort?: string; effort_src?: string
21 name?: string // fleet name from cwgo (CW_NAME): shown instead of a generated one
22 effort_p?: string; maxt?: number; branch?: string; wt?: string
23 cont?: boolean // an auto-continue after the turn limit
24}
25export type Run = { id: string; meta: Meta; events: Ev[]; rc?: number; doneAt?: number; question?: string }
26
27export type Worker = {
28 key: string; role: Role; model: string; name: string; task: string; effort: string
29 start: number; runStart: number; resumed: boolean
30 state: State; stateAt: number; arg: string; trail: Kind[]; times: number[]; lastAt: number; tmo: number
31 blocked: number; question?: string; end?: number; turns: number; out: number
32 runIds: string[] // the chain's runs, oldest first: the detail view reads their files
33 effortSrc: string; effortP: string; branch: string; wt: string; sid: string
34 runTurns: number; maxTurns: number; conts: number // the turn limit holds per run
35 ctx: number; win: number // the newest step's context, the model's window
36 cost?: number; cin: number; nin: number
37 add: number; del: number; files: number
38 accept?: { ok: boolean; rc?: number }
39}
40
41const NAMES: Record<Role, string[]> = {
42 scout: ['KIRI', 'SORA', 'MOCHI', 'YUZU', 'HOSHI', 'NORI', 'TOFU', 'MISO', 'KOJI', 'UME'],
43 coder: ['BOLT', 'RIVET', 'PIXEL', 'FORGE', 'GIZMO', 'BYTE', 'FLUX', 'SPARK', 'COG', 'WELD'],
44 reviewer: ['LENS', 'OPAL', 'IRIS', 'SAGE', 'QUILL', 'PRISM', 'ONYX', 'JADE', 'RUNE', 'ECHO'],
45}
46
47const READ_CMD = /^\s*(rg|fd|eza|ls|wc|head|tail|cat|bat|grep|find|sed -n|git (log|show|diff|status|blame))\b/
48
49export function kindOf(tool: string, arg: string): Kind {
50 if (tool === 'Read' || tool === 'Grep' || tool === 'Glob') return 'read'
51 if (tool === 'Edit' || tool === 'Write' || tool === 'MultiEdit' || tool === 'NotebookEdit') return 'write'
52 if (tool === 'WebFetch' || tool === 'WebSearch') return 'web'
53 return READ_CMD.test(arg) ? 'read' : 'bash'
54}
55
56export function parseEvents(text: string): Ev[] {
57 const out: Ev[] = []
58 for (const line of text.split('\n')) {
59 if (!line.trim()) continue
60 try { out.push(JSON.parse(line)) } catch { /* a half-written last line; read again next poll */ }
61 }
62 return out
63}
64
65type RunView = Pick<Worker, 'state' | 'stateAt' | 'arg' | 'blocked' | 'end' | 'turns' | 'out' | 'lastAt'
66 | 'runTurns' | 'ctx' | 'win' | 'cost' | 'cin' | 'nin' | 'add' | 'del' | 'files' | 'accept'> & { trail: Kind[]; times: number[] }
67
68const ACCEPT_MS = 1_830_000 // cw's CW_ACCEPT_TMO default (1800 s) plus slack
69
70export function runState(run: Run, now: number): RunView {
71 const start = run.meta.start * 1000
72 const trail: Kind[] = [], times: number[] = []
73 let arg = '', lastTool: Ev | undefined, lastDenied: Ev | undefined, lastError: Ev | undefined
74 let result: Ev | undefined, accept: Ev | undefined, accepted: Ev | undefined, blocked = 0
75 let ctx = 0, add = 0, del = 0, files = 0
76 const mids = new Set<string>()
77 for (const ev of run.events) {
78 if (ev.ctx) ctx = ev.ctx
79 if (ev.mid) mids.add(ev.mid)
80 if (ev.e === 'tool') {
81 lastTool = ev
82 arg = ev.arg ?? ''
83 trail.push(kindOf(ev.tool ?? '', arg))
84 times.push(ev.t)
85 } else if (ev.e === 'denied') { lastDenied = ev; blocked++ }
86 else if (ev.e === 'error') lastError = ev
87 else if (ev.e === 'result') result = ev
88 // A resume replays the old session's result before its own init: only a result after the last init ends the run
89 else if (ev.e === 'init') result = undefined
90 else if (ev.e === 'accept') accept = ev
91 else if (ev.e === 'accept_end') accepted = ev
92 else if (ev.e === 'diff') { add += ev.add ?? 0; del += ev.del ?? 0; files += ev.files ?? 0 }
93 }
94 const lastAt = run.events[run.events.length - 1]?.t ?? start
95 const base = {
96 arg, trail, times, blocked, lastAt, turns: result?.turns ?? 0, out: result?.out ?? 0,
97 runTurns: result?.turns ?? mids.size, ctx, win: result?.win ?? 0, cost: result?.cost,
98 cin: result?.cin ?? 0, nin: result?.nin ?? 0, add, del, files,
99 accept: accepted ? { ok: accepted.ok !== false, rc: accepted.rc } : undefined,
100 }
101 // cw auto-continues a turn-limited run without writing .done: that result is not the end
102 const continuing = result?.sub === 'error_max_turns' && run.rc === undefined
103 // cw runs the acceptance command after the result and writes .done only when it ends
104 if (accept && !accepted && run.rc === undefined && now - accept.t < ACCEPT_MS) {
105 return { ...base, state: 'test', stateAt: accept.t }
106 }
107 if ((result && !continuing) || run.rc !== undefined) {
108 const end = accepted?.t ?? result?.t ?? run.doneAt ?? now
109 const ok = !!result?.ok && (run.rc ?? 0) === 0 && accepted?.ok !== false
110 const state: State = run.question && ok ? 'ask' : ok ? 'done' : 'failed'
111 return { ...base, state, stateAt: end, end }
112 }
113 if (now > start + (run.meta.tmo + 30) * 1000) return { ...base, state: 'failed', stateAt: now, end: now }
114 const last = run.events[run.events.length - 1]
115 if (run.meta.resume && now - start < 1600) return { ...base, state: 'resumed', stateAt: start }
116 if (!last || now - start < 1500) return { ...base, state: 'boot', stateAt: start }
117 if (lastDenied && now - lastDenied.t < 4000) return { ...base, state: 'blocked', stateAt: lastDenied.t }
118 if (lastError && now - lastError.t < 2500) return { ...base, state: 'error', stateAt: lastError.t }
119 if (lastTool && (last === lastTool || now - lastTool.t < 1500)) {
120 return { ...base, state: trail[trail.length - 1] ?? 'bash', stateAt: lastTool.t }
121 }
122 return { ...base, state: 'think', stateAt: last.t }
123}
124
125// One worker per chain of runs: a run started with `-r <sid>` continues the worker whose run ended with that sid.
126export function buildWorkers(runs: Run[], now: number): Worker[] {
127 const sorted = [...runs].sort((a, b) => a.meta.start - b.meta.start || a.id.localeCompare(b.id))
128 const bySid = new Map<string, Worker>()
129 const workers: Worker[] = []
130 const used: Record<Role, number> = { scout: 0, coder: 0, reviewer: 0 }
131 // A live run learns its model's context window from any finished run of that model.
132 const windows = new Map<string, number>()
133 for (const run of sorted) for (const ev of run.events) if (ev.win) windows.set(run.meta.model, ev.win)
134 for (const run of sorted) {
135 const view = runState(run, now)
136 const prev = run.meta.resume ? bySid.get(run.meta.resume) : undefined
137 const role: Role = run.meta.role === 'coder' || run.meta.role === 'reviewer' ? run.meta.role : 'scout'
138 // A resume started under its own fleet name (cwgo NAME -r sid) is a new job on the same creature:
139 // show that name, task and clock, as cwls does.
140 const renamed = !!prev && !!run.meta.name && run.meta.name !== prev.name
141 const w: Worker = {
142 key: prev?.key ?? run.id,
143 role,
144 model: run.meta.model,
145 effort: run.meta.effort ?? '',
146 name: renamed ? run.meta.name! : prev?.name ?? (run.meta.name || NAMES[role][used[role]++ % NAMES[role].length] + (used[role] > 10 ? String(Math.ceil(used[role] / 10)) : '')),
147 task: renamed ? run.meta.task : prev?.task ?? run.meta.task,
148 start: renamed ? run.meta.start * 1000 : prev?.start ?? run.meta.start * 1000,
149 runStart: run.meta.start * 1000,
150 tmo: run.meta.tmo,
151 resumed: !!prev,
152 ...view,
153 trail: [...(prev?.trail ?? []), ...view.trail],
154 times: [...(prev?.times ?? []), ...view.times],
155 blocked: (prev?.blocked ?? 0) + view.blocked,
156 turns: (prev?.turns ?? 0) + view.turns,
157 out: (prev?.out ?? 0) + view.out,
158 question: view.state === 'ask' ? run.question : undefined,
159 runIds: [...(prev?.runIds ?? []), run.id],
160 effortSrc: run.meta.effort_src ?? '', effortP: run.meta.effort_p ?? '',
161 branch: run.meta.branch || prev?.branch || '', wt: run.meta.wt || prev?.wt || '',
162 sid: [...run.events].reverse().find(ev => ev.sid)?.sid ?? prev?.sid ?? '',
163 maxTurns: run.meta.maxt ?? (role === 'coder' ? 80 : role === 'reviewer' ? 20 : 40),
164 conts: (prev?.conts ?? 0) + (run.meta.cont ? 1 : 0),
165 // A resume continues the same conversation: until its first step the context is the last run's.
166 ctx: view.ctx || prev?.ctx || 0,
167 win: view.win || prev?.win || windows.get(run.meta.model) || (/\[1m\]/i.test(run.meta.model) ? 1_000_000 : 200_000),
168 cost: prev?.cost === undefined && view.cost === undefined ? undefined : (prev?.cost ?? 0) + (view.cost ?? 0),
169 cin: (prev?.cin ?? 0) + view.cin, nin: (prev?.nin ?? 0) + view.nin,
170 add: (prev?.add ?? 0) + view.add, del: (prev?.del ?? 0) + view.del, files: (prev?.files ?? 0) + view.files,
171 }
172 const at = prev ? workers.indexOf(prev) : -1
173 if (at >= 0) workers[at] = w
174 else workers.push(w)
175 // A run that dies before its result (killed, timeout) never maps its sid, so the next resume
176 // of the same sid still finds `prev`; point it at the newest run or two workers share a key.
177 if (prev) for (const [k, v] of bySid) if (v === prev) bySid.set(k, w)
178 // init carries the sid too, so a run that timed out before its result still chains its resume.
179 const sid = [...run.events].reverse().find(ev => ev.sid)?.sid
180 if (sid) bySid.set(sid, w)
181 }
182 return workers
183}
184
185export const KEEP_MS = 120_000
186export const isVisible = (w: Worker, now: number) =>
187 w.end === undefined || w.state === 'ask' || now - w.end < KEEP_MS
188export const isActive = (w: Worker) => w.end === undefined
189
190// ---------- pixels ----------
191
192const DEF = 0x01000000
193// A sprite fills MW x MH cells: one 60x32 Image where the terminal shows pictures, else
194// 15x8 half-block pixels (one pixel = one half-block, no scaling). Creature left, props right.
195const MW = SMALL_W, MH = SMALL_H / 2
196
197export const THEME: Record<Role, number> = { scout: 0x4fd1c5, coder: 0xffb347, reviewer: 0xff8fb8 }
198const OPUS_THEME = 0xb59cff
199
200const hash = (s: string) => {
201 let h = 7
202 for (let i = 0; i < s.length; i++) h = (h * 31 + s.charCodeAt(i)) >>> 0
203 return h % 997
204}
205const dim = (c: number, k: number) =>
206 (Math.round(((c >> 16) & 255) * k) << 16) | (Math.round(((c >> 8) & 255) * k) << 8) | Math.round((c & 255) * k)
207const mix = (a: number, b: number, k: number) => {
208 const ch = (s: number) => Math.round(((a >> s) & 255) * (1 - k) + ((b >> s) & 255) * k)
209 return (ch(16) << 16) | (ch(8) << 8) | ch(0)
210}
211// 0..1..0 once every `ms`: colours breathe instead of blinking.
212const pulse = (now: number, ms: number) => 0.5 - 0.5 * Math.cos((2 * Math.PI * (now % ms)) / ms)
213
214// Where a sprite goes in the scene: `key` names its Image, `look` the frame it shows.
215export type Spot = { key: string; x: number; y: number; look: Look; alt: string }
216export const SPRITE_COLS = MW, SPRITE_ROWS = MH
217
218// ---------- cells ----------
219
220export class Grid {
221 glyph: Uint32Array; fg: Uint32Array; bg: Uint32Array
222 constructor(public w: number, public h: number, bg = DEF) {
223 this.glyph = new Uint32Array(w * h).fill(0x20)
224 this.fg = new Uint32Array(w * h).fill(DEF)
225 this.bg = new Uint32Array(w * h).fill(bg)
226 }
227 // No `bg`: the cell keeps the one it has, so text and pixels sit on a filled panel.
228 put(x: number, y: number, ch: string, fg: number, bg?: number) {
229 if (x < 0 || y < 0 || x >= this.w || y >= this.h) return
230 const i = y * this.w + x
231 this.glyph[i] = ch.codePointAt(0) ?? 0x20
232 this.fg[i] = fg
233 if (bg !== undefined) this.bg[i] = bg
234 }
235 fill(x: number, y: number, w: number, h: number, bg: number) {
236 for (let j = y; j < y + h; j++) for (let i = x; i < x + w; i++) this.put(i, j, ' ', DEF, bg)
237 }
238 text(x: number, y: number, s: string, fg: number, max = this.w - x, bg?: number) {
239 const chars = [...s]
240 for (let i = 0; i < Math.min(chars.length, max); i++) this.put(x + i, y, chars[i] ?? ' ', fg, bg)
241 return Math.max(0, Math.min(chars.length, max))
242 }
243 // A rounded chip: half-circle caps around the text, the text on the chip's colour.
244 pill(x: number, y: number, s: string, fg: number, bg: number, max = this.w - x) {
245 if (max < 3) return 0
246 this.put(x, y, '▐', bg)
247 const n = this.text(x + 1, y, s, fg, max - 2, bg)
248 this.put(x + 1 + n, y, '▌', bg)
249 return n + 2
250 }
251 pixels(p: Canvas, x0: number, y0: number) {
252 for (let r = 0; r < p.h / 2; r++) for (let x = 0; x < p.w; x++) {
253 const top = p.px[r * 2 * p.w + x] ?? CLEAR, bot = p.px[(r * 2 + 1) * p.w + x] ?? CLEAR
254 if (top === CLEAR && bot === CLEAR) continue
255 if (top === CLEAR) this.put(x0 + x, y0 + r, '▄', bot)
256 else if (bot === CLEAR) this.put(x0 + x, y0 + r, '▀', top)
257 else if (top === bot) this.put(x0 + x, y0 + r, '█', top)
258 else this.put(x0 + x, y0 + r, '▀', top, bot)
259 }
260 }
261 words(): Uint32Array {
262 const out = new Uint32Array(this.w * this.h * 3)
263 for (let i = 0; i < this.w * this.h; i++) {
264 out[i * 3] = this.glyph[i] ?? 0x20; out[i * 3 + 1] = this.fg[i] ?? DEF; out[i * 3 + 2] = this.bg[i] ?? DEF
265 }
266 return out
267 }
268}
269
270export const encode = (words: Uint32Array): string =>
271 (new Uint8Array(words.buffer) as Uint8Array & { toBase64(): string }).toBase64()
272
273export const LABEL: Record<State, string> = {
274 boot: 'waking up', resumed: 'answered', think: 'thinking', read: 'reading', write: 'writing',
275 bash: 'command', web: 'on the web', test: 'testing', blocked: 'blocked', error: 'error', ask: 'asking',
276 done: 'done', failed: 'failed',
277}
278export const STATE_COLOR: Record<State, number> = {
279 boot: 0xffffff, resumed: 0xffe082, think: 0xb39ddb, read: 0x64b5f6, write: 0xffb347, bash: 0x81c784,
280 web: 0x4dd0e1, test: 0x9be7ff, blocked: 0xff6b6b, error: 0xff8a65, ask: 0xffd166, done: 0x7bd88f, failed: 0xff5c5c,
281}
282const KIND_COLOR: Record<Kind, number> = { read: 0x64b5f6, write: 0xffb347, bash: 0x81c784, web: 0x4dd0e1 }
283const EFFORT: Record<string, [number, number]> = { low: [1, 0x81c784], medium: [2, 0xffd166], high: [3, 0xff8a65] }
284const SPIN = '⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏'
285// The pane paints its own background and each worker is a filled card on it. The sprite frames are
286// transparent: an Image's box shows one colour even where the terminal letterboxes it (tall cells).
287export const PANE = 0x111122, CARD = 0x222233
288const TEXT = 0xe6e6f0, DIM = 0x8a8fa3, FAINT = 0x4d5162
289// Budgets read as memobar's do: under half green, to 80% yellow, from 80% red.
290const GOOD = 0x7bd88f, WARN = 0xffd166, BAD = 0xff5c5c
291export const level = (f: number) => (f >= 0.8 ? BAD : f >= 0.5 ? WARN : GOOD)
292const BRANCH = 0x9be7ff, JEV = 0xb39ddb
293const BUCKET_MS = 4000
294const QUIET_MS = 45_000
295
296export const CARD_H = 6
297const HEADER_H = 2
298const EMPTY_H = 8
299
300export const perRow = (cols: number) => Math.max(1, Math.min(3, Math.floor(cols / 46)))
301
302// The engine scrolls a pane body taller than its window; past 256 rows the scene folds:
303// as many full cards as fit, the rest as one-line rows, then a "+N" row.
304export type Layout = { rows: number; cards: number; lines: number; more: number }
305export function layout(n: number, cols: number, maxRows = 256): Layout {
306 const cap = Math.max(1, Math.min(256, maxRows))
307 const per = perRow(cols)
308 const full = HEADER_H + (n === 0 ? EMPTY_H : Math.ceil(n / per) * CARD_H)
309 if (full <= cap || n === 0) return { rows: Math.min(full, cap), cards: n, lines: 0, more: 0 }
310 for (let k = Math.ceil(n / per) - 1; k >= 0; k--) {
311 const cards = Math.min(n, k * per)
312 const lines = Math.ceil((n - cards) / per)
313 const rows = HEADER_H + k * CARD_H + lines
314 if (rows <= cap) return { rows, cards, lines, more: 0 }
315 }
316 const lines = Math.max(0, cap - HEADER_H - 1)
317 return { rows: cap, cards: 0, lines, more: n - lines * per }
318}
319export const sceneRows = (n: number, cols: number, maxRows?: number) => layout(n, cols, maxRows).rows
320
321const RANK = (w: Worker) => (w.state === 'ask' ? 0 : !w.end ? 1 : w.state === 'failed' ? 2 : 3)
322
323export const clock = (ms: number) => {
324 const s = Math.max(0, Math.floor(ms / 1000))
325 return `${Math.floor(s / 60)}:${String(s % 60).padStart(2, '0')}`
326}
327// Token counts as memobar writes them: 950, 50.0k, 1.2M.
328export const kilo = (n: number) => (n >= 1e6 ? `${(n / 1e6).toFixed(1)}M` : n >= 1000 ? `${(n / 1000).toFixed(1)}k` : String(Math.round(n)))
329export const usd = (n: number) => (n < 0.01 ? '<$0.01' : `$${n.toFixed(2)}`)
330export const shortModel = (m: string) => /haiku|sonnet|opus|fable/i.exec(m)?.[0].toLowerCase() ?? m
331const shorten = (s: string, n: number) => {
332 const one = s.replace(/\s+/g, ' ').trim()
333 return [...one].length <= n ? one : '…' + [...one].slice(-(n - 1)).join('')
334}
335function wrap(s: string, width: number, lines: number): string[] {
336 const out: string[] = []
337 let cur = ''
338 for (const word of s.replace(/^[#>*\s\d.]*(goal:)?\s*/i, '').split(/\s+/)) {
339 if (!word) continue
340 const next = cur ? `${cur} ${word}` : word
341 if ([...next].length <= width) { cur = next; continue }
342 if (cur) out.push(cur)
343 cur = [...word].slice(0, width).join('')
344 if (out.length === lines) break
345 }
346 if (cur && out.length < lines) out.push(cur)
347 if (out.length === lines && [...out.join(' ')].length < [...s].length - 2) {
348 const last = [...(out[lines - 1] ?? '')]
349 out[lines - 1] = last.slice(0, Math.max(0, width - 1)).join('') + '…'
350 }
351 return out.slice(0, lines)
352}
353
354// MSYS path (/c/Users/x) -> C:/Users/x so $.fs can read it; other paths pass through.
355export const msysToWin = (p: string) => p.replace(/^\/([a-zA-Z])(?=\/|$)/, (_, d: string) => `${d.toUpperCase()}:`)
356
357// A path reads by its file name: the folders dim, the name bright. A command shows whole.
358function target(g: Grid, x: number, y: number, arg: string, max: number, bright: number, faint: number) {
359 if (max < 2 || !arg) return 0
360 const s = shorten(arg, max)
361 const cut = /\s/.test(arg.trim()) ? 0 : Math.max(s.lastIndexOf('/'), s.lastIndexOf('\\')) + 1
362 const n = g.text(x, y, s.slice(0, cut), faint, max)
363 return n + g.text(x + n, y, s.slice(cut), bright, max - n)
364}
365
366// The three limits a run can hit. The turn limit and the clock hold per run; the context is the conversation's.
367export type Gauge = { name: 'context' | 'turns' | 'time'; short: string; f: number; value: string; note: string }
368export function gauges(w: Worker, now: number): Gauge[] {
369 const ms = (w.end ?? now) - w.runStart, tmo = Math.max(1, w.tmo * 1000)
370 const c = w.win ? w.ctx / w.win : 0
371 return [
372 { name: 'context', short: 'ctx', f: c, value: `${Math.round(c * 100)}%`, note: w.ctx ? `${kilo(w.ctx)} / ${kilo(w.win)}` : '' },
373 { name: 'turns', short: 'turns', f: w.runTurns / Math.max(1, w.maxTurns), value: `${w.runTurns}/${w.maxTurns}`, note: w.conts ? `continued ×${w.conts}` : '' },
374 { name: 'time', short: 'time', f: ms / tmo, value: w.end !== undefined ? clock(ms) : `${clock(tmo - ms)} left`, note: `of ${clock(tmo)}` },
375 ]
376}
377const worst = (gs: Gauge[]) => gs.reduce((a, b) => (b.f > a.f ? b : a))
378
379const BARS = '▂▃▅▆▇'
380// Tools per BUCKET_MS bucket, newest on the right, each bar in the colour of its last tool's kind:
381// the worker's rhythm at a glance, and a flat line when it has gone quiet.
382function activity(g: Grid, w: Worker, x: number, y: number, n: number, now: number, fade: number) {
383 if (n <= 0) return
384 const anchor = Math.ceil((w.end ?? now) / BUCKET_MS) * BUCKET_MS
385 const from = anchor - n * BUCKET_MS
386 const count = new Array<number>(n).fill(0), kind = new Array<Kind | undefined>(n)
387 w.times.forEach((t, i) => {
388 const b = Math.floor((t - from) / BUCKET_MS)
389 if (b < 0 || b >= n) return
390 count[b] = (count[b] ?? 0) + 1
391 kind[b] = w.trail[i]
392 })
393 for (let i = 0; i < n; i++) {
394 const t0 = from + i * BUCKET_MS
395 if (t0 + BUCKET_MS < w.start) continue
396 const k = count[i] ?? 0, kd = kind[i]
397 if (!k || !kd) g.put(x + i, y, '▁', mix(FAINT, CARD, 0.45))
398 else g.put(x + i, y, BARS[Math.min(BARS.length - 1, k - 1)] ?? '▇', mix(KIND_COLOR[kd], CARD, fade))
399 }
400}
401
402// A filled panel with rounded corners: quarter blocks on the top and bottom rows, half blocks on the
403// sides, so its edges sit half a cell in and stacked panels get one row of pane between them.
404function panel(g: Grid, x0: number, y0: number, W: number, H: number) {
405 const R = x0 + W - 1, B = y0 + H - 1
406 for (let x = x0 + 1; x < R; x++) { g.put(x, y0, '▄', CARD); g.put(x, B, '▀', CARD) }
407 g.put(x0, y0, '▗', CARD); g.put(R, y0, '▖', CARD); g.put(x0, B, '▝', CARD); g.put(R, B, '▘', CARD)
408 for (let y = y0 + 1; y < B; y++) { g.put(x0, y, '▐', CARD); g.put(R, y, '▌', CARD) }
409 g.fill(x0 + 1, y0 + 1, W - 2, H - 2, CARD)
410}
411
412type Place = (look: Look, x: number, y: number, alt: string) => void
413// Where a card's name is: a Button laid over it opens the worker's detail view.
414export type Hit = { key: string; x: number; y: number; label: string; color: number }
415
416const iconOf = (w: Worker, f: number) =>
417 w.state === 'done' ? '✓' : w.state === 'failed' ? '✗' : w.state === 'ask' ? '?'
418 : w.state === 'blocked' || w.state === 'error' ? '!' : SPIN[f % SPIN.length] ?? ' '
419const themeOf = (w: Worker) => (/opus/i.test(w.model) ? OPUS_THEME : THEME[w.role])
420
421function card(g: Grid, w: Worker, x0: number, y0: number, W: number, now: number, place: Place, hits?: Hit[]) {
422 const f = Math.floor(now / FRAME_MS)
423 const theme = themeOf(w)
424 const sc = STATE_COLOR[w.state]
425 const over = w.end !== undefined && w.state !== 'ask'
426 // A finished card steps back: its words sink toward the panel.
427 const fade = over ? 0.4 : 0
428 const ink = (c: number) => mix(c, CARD, fade)
429 const accent =
430 w.state === 'ask' ? mix(dim(sc, 0.5), sc, pulse(now, 1600))
431 : w.state === 'blocked' || w.state === 'error' ? mix(dim(sc, 0.45), sc, pulse(now, 700))
432 : over ? mix(sc, CARD, 0.45)
433 : mix(dim(theme, 0.75), theme, pulse(now + hash(w.key) * 37, 2400))
434 const gs = gauges(w, now)
435 const top = worst(gs)
436
437 panel(g, x0, y0, W, CARD_H)
438 const R = x0 + W - 1, B = y0 + CARD_H - 1
439 for (let y = y0 + 1; y < B; y++) g.put(x0, y, '▐', accent)
440
441 // The bottom edge fills as a bar: while it works, the limit closest to running out in its budget
442 // colour; the countdown until a finished card leaves; full and breathing while a question waits.
443 let frac = 0, bar = GOOD
444 if (w.state === 'ask') { frac = 1; bar = mix(dim(sc, 0.55), sc, pulse(now, 1600)) }
445 else if (over) { frac = 1 - (now - (w.end ?? now)) / KEEP_MS; bar = mix(sc, CARD, 0.72) }
446 else { frac = top.f; bar = mix(level(top.f), CARD, top.f >= 0.8 ? 0.1 : top.f >= 0.5 ? 0.35 : 0.6) }
447 const inner = W - 2
448 const fill = Math.round(Math.max(0, Math.min(1, frac)) * inner)
449 for (let i = 0; i < fill; i++) g.put(x0 + 1 + i, B, '▀', bar)
450
451 place(lookAt(w.role, w.model, w.state, now, w.stateAt, hash(w.key)), x0 + 2, y0 + 1, `${w.name} ${LABEL[w.state]}`)
452
453 const X = x0 + MW + 4, TW = R - X - 1
454 if (TW < 8) return
455 const row = (i: number) => y0 + 1 + i
456
457 // 1: who: name (it opens the details), model, effort; the clock on the right
458 const elapsed = clock((w.end ?? now) - w.start)
459 const clockX = R - 1 - elapsed.length
460 g.text(clockX, row(0), elapsed, over ? ink(DIM) : TEXT)
461 let x = X + g.text(X, row(0), w.name, ink(theme), clockX - X - 1)
462 hits?.push({ key: w.key, x: X, y: row(0), label: w.name, color: ink(theme) })
463 const room = () => clockX - x - 2
464 if (room() > 2) x += g.text(x, row(0), ' ›', ink(DIM), room())
465 if (room() > 7) x += 2 + g.text(x + 2, row(0), shortModel(w.model), ink(DIM), room() - 2)
466 const eff = EFFORT[w.effort]
467 if (eff && room() > 4) {
468 x += 1
469 for (let i = 0; i < 3; i++) g.put(x + i, row(0), i < eff[0] ? '●' : '○', i < eff[0] ? ink(eff[1]) : mix(FAINT, CARD, 0.3))
470 x += 3
471 // ✦: Jev chose the effort, not the role default
472 if (w.effortSrc === 'jev' && room() > 1) x += g.text(x, row(0), '✦', ink(JEV))
473 }
474 if (w.resumed && room() > 2) g.put(x + 1, row(0), '↻', ink(0xffe082))
475
476 // 2: what it is doing now and on what; once over, what it left behind
477 g.put(X, row(1), iconOf(w, f), ink(sc))
478 let lx = X + 2 + g.text(X + 2, row(1), LABEL[w.state], ink(sc), TW - 2)
479 const end = X + TW
480 const quiet = !w.end ? now - w.lastAt : 0
481 if (over) {
482 if ((w.add || w.del) && end - lx > 8) {
483 lx += 2 + g.text(lx + 2, row(1), `+${w.add}`, ink(GOOD))
484 lx += 1 + g.text(lx + 1, row(1), `−${w.del}`, ink(BAD))
485 }
486 if (w.accept && end - lx > 7) lx += 2 + g.text(lx + 2, row(1), w.accept.ok ? '✓ test' : '✗ test', ink(w.accept.ok ? GOOD : BAD))
487 } else if (quiet > QUIET_MS && w.state === 'think') {
488 g.text(lx, row(1), ` · quiet ${clock(quiet)}`, mix(WARN, CARD, 0.25 * pulse(now, 2000)), end - lx)
489 } else if (w.arg && w.state !== 'ask' && end - lx > 6) {
490 lx += 1 + g.text(lx + 1, row(1), '·', FAINT)
491 target(g, lx + 1, row(1), w.arg, end - lx - 1, ink(0xc9d6e6), ink(0x6d7891))
492 }
493
494 // 3–4: the question while one waits; else the task, then the rhythm and what needs an eye
495 if (w.state === 'ask' && w.question) {
496 wrap(w.question, TW, 2).forEach((line, i) => g.text(X, row(2 + i), line, 0xffe8a3))
497 return
498 }
499 let tx = X
500 if (w.wt && TW > 20) tx += 2 + g.text(X, row(2), `⎇ ${w.wt}`, ink(BRANCH), 16)
501 wrap(w.task, X + TW - tx, 1).forEach(line => g.text(tx, row(2), line, ink(DIM)))
502
503 const flags: [string, number][] = []
504 if (over) flags.push([w.cost !== undefined ? usd(w.cost) : `${w.turns} turns`, ink(DIM)])
505 else {
506 if (w.blocked) flags.push([`! ${w.blocked}`, 0xff9e9e])
507 if (top.f >= 0.5) flags.push([`${top.short} ${top.value}`, level(top.f)])
508 }
509 let rx = X + TW
510 for (const [s, c] of flags.reverse()) {
511 rx -= [...s].length
512 g.text(rx, row(3), s, c)
513 rx -= 2
514 }
515 const strip = rx - X
516 if (strip >= 6) activity(g, w, X, row(3), strip, now, fade)
517}
518
519function line(g: Grid, w: Worker, x0: number, y: number, W: number, now: number) {
520 const sc = STATE_COLOR[w.state]
521 const R = x0 + W - 1
522 const elapsed = clock((w.end ?? now) - w.start)
523 g.text(R - elapsed.length, y, elapsed, w.end ? DIM : TEXT)
524 const end = R - elapsed.length - 1
525 let x = x0 + 1
526 g.put(x, y, iconOf(w, Math.floor(now / FRAME_MS)), sc); x += 2
527 x += g.text(x, y, w.name, themeOf(w), end - x)
528 x += 1 + g.text(x + 1, y, LABEL[w.state], sc, end - x - 1)
529 const rest = w.state === 'ask' ? (w.question ?? '') : w.arg || w.task
530 if (end - x > 4) g.text(x + 1, y, shorten(rest, end - x - 2), DIM)
531}
532
533// What the whole crew has cost, and its rough share of the 5-hour limit (from the lead's readings).
534export type Totals = { cost?: number; limit?: number }
535
536function header(g: Grid, ws: Worker[], now: number, totals: Totals) {
537 // the crew's colours drift through the title's diamond and the rule's travelling glow
538 const hues = [0x4fd1c5, 0x64b5f6, 0xb39ddb, 0xffb347, 0xffd166]
539 const t = (now / 1600) % hues.length
540 const hue = mix(hues[Math.floor(t)] ?? 0x4fd1c5, hues[(Math.floor(t) + 1) % hues.length] ?? 0x4fd1c5, t % 1)
541 g.put(1, 0, '◆', hue)
542 let x = 3 + g.text(3, 0, 'CREW', TEXT)
543 const active = ws.filter(w => !w.end).length
544 const asking = ws.filter(w => w.state === 'ask').length
545 const done = ws.filter(w => w.state === 'done').length
546 const failed = ws.filter(w => w.state === 'failed').length
547 const chips: [string, number, boolean][] = [
548 [`● ${active}`, GOOD, active > 0], [`? ${asking}`, WARN, asking > 0],
549 [`✓ ${done}`, GOOD, done > 0], [`✗ ${failed}`, BAD, failed > 0],
550 ]
551 // right: the crew's activity over the last two minutes, then what it has spent
552 const SPAN = 12, BK = 10_000
553 const from = Math.ceil(now / BK) * BK - SPAN * BK
554 const per = new Array<number>(SPAN).fill(0)
555 for (const w of ws) for (const tt of w.times) {
556 const b = Math.floor((tt - from) / BK)
557 if (b >= 0 && b < SPAN) per[b] = (per[b] ?? 0) + 1
558 }
559 const money = totals.cost !== undefined && totals.cost > 0 ? usd(totals.cost) : ''
560 const share = totals.limit !== undefined && totals.limit >= 0.5 ? `5h ~${Math.round(totals.limit)}%` : ''
561 let right = g.w - 1
562 if (share) { right -= [...share].length; g.text(right, 0, share, DIM); right -= 2 }
563 if (money) { right -= [...money].length; g.text(right, 0, money, TEXT); right -= 2 }
564 if (!active && !asking) x += 1 + g.text(x + 1, 0, 'idle', DIM)
565 for (const [s, c, on] of chips) {
566 if (!on) continue
567 if (x + 1 + [...s].length + 2 >= right - 1) break
568 x += 1 + g.pill(x + 1, 0, s, c === WARN ? mix(c, 0xffffff, 0.2 * pulse(now, 1600)) : c, mix(PANE, c, 0.16))
569 }
570 // the counts first; the sparkline takes what room is left
571 const n = Math.min(SPAN, right - x - 2)
572 if (ws.length && n >= 6) {
573 const most = Math.max(1, ...per)
574 per.slice(SPAN - n).forEach((k, i) => g.put(right - n + i, 0, k ? (BARS[Math.min(BARS.length - 1, Math.ceil((k / most) * BARS.length) - 1)] ?? '▇') : '▁',
575 k ? mix(0x4fd1c5, 0xb39ddb, i / n) : FAINT))
576 }
577 const head = ((now / 18) % (g.w + 30)) - 15
578 for (let i = 0; i < g.w; i++) {
579 const d = Math.abs(i - head)
580 g.put(i, 1, '─', d < 10 ? mix(0x24262f, hue, 0.7 * (1 - d / 10) ** 2) : 0x24262f)
581 }
582}
583
584// `images`: leave each sprite's cells blank and list it in `spots`, for an Image laid over them.
585// `hits`: where each card's name is, for a Button laid over it.
586export function drawScene(
587 ws: Worker[], cols: number, now: number, maxRows?: number, images = false, totals: Totals = {},
588): { rows: number; words: Uint32Array; spots: Spot[]; hits: Hit[] } {
589 const fit = layout(ws.length, cols, maxRows)
590 const rows = fit.rows
591 const g = new Grid(cols, rows, PANE)
592 const spots: Spot[] = []
593 const hits: Hit[] = []
594 const place: Place = (look, x, y, alt) => {
595 if (images) spots.push({ key: `s${spots.length}`, x, y, look, alt })
596 else g.pixels(smallSprite(look), x, y)
597 }
598 header(g, ws, now, totals)
599 if (ws.length === 0) {
600 panel(g, 0, HEADER_H, cols, EMPTY_H)
601 // The reviewer joins when its label fits a third of the pane.
602 const crew: Role[] = cols >= 60 ? ['scout', 'coder', 'reviewer'] : ['scout', 'coder']
603 const slot = Math.floor(cols / crew.length)
604 for (const [i, role] of crew.entries()) {
605 const model = role === 'scout' ? 'haiku' : 'sonnet'
606 const cx = Math.max(0, i * slot + Math.floor((slot - MW) / 2))
607 place(lookAt(role, model, 'sleep', now, 0, i * 5), cx, HEADER_H + 1, `${role} asleep`)
608 const label = `${role} · ${model}`
609 g.text(Math.max(0, i * slot + Math.floor((slot - label.length) / 2)), HEADER_H + 1 + MH, label, dim(THEME[role], 0.8))
610 }
611 const msg = 'no workers · /orchestrate wakes them'
612 g.text(Math.max(0, Math.floor((cols - [...msg].length) / 2)), HEADER_H + MH + 2, msg, FAINT)
613 return { rows, words: g.words(), spots, hits }
614 }
615 const per = perRow(cols)
616 const W = Math.floor(cols / per)
617 const cw = per > 1 ? W - 1 : W
618 // Overflowing: questions and live workers keep the cards, finished ones drop to lines first.
619 const list = fit.cards < ws.length ? [...ws].sort((a, b) => RANK(a) - RANK(b)) : ws
620 list.slice(0, fit.cards).forEach((w, i) => card(g, w, (i % per) * W, HEADER_H + Math.floor(i / per) * CARD_H, cw, now, place, hits))
621 const top = HEADER_H + Math.ceil(fit.cards / per) * CARD_H
622 list.slice(fit.cards, fit.cards + fit.lines * per)
623 .forEach((w, i) => line(g, w, (i % per) * W, top + Math.floor(i / per), W, now))
624 if (fit.more > 0) {
625 const msg = `+${fit.more} more · enlarge the pane`
626 g.text(Math.max(0, Math.floor((cols - [...msg].length) / 2)), rows - 1, msg, DIM)
627 }
628 return { rows, words: g.words(), spots, hits }
629}
630
631// The detail view's head: the worker's card, then a panel of its three limits as bars and its numbers.
632export const DETAIL_ROWS = CARD_H + 7
633export function drawDetail(w: Worker, cols: number, now: number, images = false): { rows: number; words: Uint32Array; spots: Spot[] } {
634 const g = new Grid(cols, DETAIL_ROWS, PANE)
635 const spots: Spot[] = []
636 const place: Place = (look, x, y, alt) => {
637 if (images) spots.push({ key: `s${spots.length}`, x, y, look, alt })
638 else g.pixels(smallSprite(look), x, y)
639 }
640 card(g, w, 0, 0, cols, now, place)
641 const y0 = CARD_H
642 panel(g, 0, y0, cols, 7)
643 const R = cols - 1
644 const VW = Math.min(24, Math.max(10, cols - 30))
645 const vx = R - 1 - VW, bx = 12, bw = vx - 2 - bx
646 gauges(w, now).forEach((ga, i) => {
647 const y = y0 + 1 + i
648 g.text(3, y, ga.name, DIM)
649 const c = level(ga.f)
650 const n = Math.round(Math.max(0, Math.min(1, ga.f)) * bw)
651 for (let k = 0; k < bw; k++) g.put(bx + k, y, k < n ? '━' : '─', k < n ? c : FAINT)
652 const v = g.text(vx, y, ga.value, TEXT, VW)
653 if (ga.note) g.text(vx + v + 2, y, ga.note, DIM, VW - v - 2)
654 })
655 const cache = w.cin + w.nin ? Math.round((100 * w.cin) / (w.cin + w.nin)) : undefined
656 const chosen = w.effortSrc === 'jev' ? /\d+/.exec(w.effortP.split(' ').find(p => p[0] === w.effort[0]) ?? '')?.[0] : undefined
657 const effort = w.effort + (w.effortSrc === 'jev' ? ` · jev${chosen ? ` ${chosen}%` : ''}` : w.effortSrc === 'flag' ? ' · set' : '')
658 // Only what is known: cost, cache and output arrive with the run's result.
659 const stats: [string, string | false, number][][] = [
660 [['cost', w.cost !== undefined && usd(w.cost), TEXT], ['cache', cache !== undefined && `${cache}%`, TEXT],
661 ['out', w.out > 0 && kilo(w.out), TEXT], ['blocked', w.blocked > 0 && String(w.blocked), 0xff9e9e]],
662 [['effort', effort, w.effortSrc === 'jev' ? JEV : TEXT], ['branch', w.wt || w.branch, BRANCH],
663 ['diff', w.files > 0 && `+${w.add} −${w.del} · ${w.files} files`, TEXT]],
664 ]
665 stats.forEach((items, i) => {
666 let x = 3
667 const y = y0 + 4 + i
668 for (const [k, v, c] of items) {
669 if (!v) continue
670 if (x + k.length + 2 + [...v].length > R - 1) break
671 x += g.text(x, y, k, DIM) + 1
672 x += g.text(x, y, v, c) + 3
673 }
674 })
675 return { rows: DETAIL_ROWS, words: g.words(), spots }
676}
677
678// ---------- svg (surfaces with no Raster: desktop, editor, mobile) ----------
679
680// One cell is CW x CH; each half-block pixel (CW x CH/2) comes out square. Every cell splits into
681// 2x2 quarters so ▀▄█▌▐ map to rects, merged into runs and one path per colour; other glyphs are text.
682const CW = 6, CH = 12
683const hex = (c: number) => `#${(c & 0xffffff).toString(16).padStart(6, '0')}`
684const esc = (s: string) => s.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>')
685const QUARTERS: Record<number, number> = {
686 0x2580: 0b1100, 0x2584: 0b0011, 0x2588: 0b1111, 0x258c: 0b1010, 0x2590: 0b0101,
687 0x2596: 0b0010, 0x2597: 0b0001, 0x2598: 0b1000, 0x259d: 0b0100,
688}
689
690// `sprites`: PNG frames laid over the blank cells drawScene(images = true) left, as data URIs.
691export type SvgSprite = { x: number; y: number; base64: string }
692export function sceneSvg(words: Uint32Array, cols: number, rows: number, sprites: SvgSprite[] = [], scale = 1.5): string {
693 const q = new Int32Array(cols * 2 * rows * 2).fill(-1)
694 const texts: string[] = []
695 for (let y = 0; y < rows; y++) {
696 // Runs end at spaces: a surface may collapse them, and textLength would then stretch the rest.
697 let run = '', runX = 0, runFg = -1
698 const flush = () => {
699 if (run) {
700 const n = [...run].length
701 texts.push(`<text x="${runX * CW}" y="${y * CH + 9.5}" fill="${hex(runFg)}" textLength="${n * CW}" lengthAdjust="spacingAndGlyphs">${esc(run)}</text>`)
702 }
703 run = ''; runFg = -1
704 }
705 for (let x = 0; x < cols; x++) {
706 const i = (y * cols + x) * 3
707 const g = words[i] ?? 0x20, fg = words[i + 1] ?? DEF, bg = words[i + 2] ?? DEF
708 const fill = (mask: number, c: number) => {
709 if (c === DEF) return
710 for (let k = 0; k < 4; k++) if (mask & (8 >> k)) q[(y * 2 + (k >> 1)) * cols * 2 + x * 2 + (k & 1)] = c & 0xffffff
711 }
712 fill(0b1111, bg)
713 const mask = QUARTERS[g]
714 if (mask !== undefined) { fill(mask, fg === DEF ? TEXT : fg); flush(); continue }
715 const c = fg === DEF ? TEXT : fg & 0xffffff
716 if (g === 0x20) { flush(); continue }
717 if (run && c !== runFg) flush()
718 if (!run) { runX = x; runFg = c }
719 run += String.fromCodePoint(g)
720 }
721 flush()
722 }
723 const paths = new Map<number, string>()
724 const W = cols * 2
725 for (let j = 0; j < rows * 2; j++) {
726 for (let i = 0; i < W;) {
727 const c = q[j * W + i] ?? -1
728 let k = i + 1
729 while (k < W && q[j * W + k] === c) k++
730 if (c >= 0) {
731 const w = ((k - i) * CW) / 2
732 paths.set(c, `${paths.get(c) ?? ''}M${(i * CW) / 2} ${(j * CH) / 2}h${w}v${CH / 2}h-${w}z`)
733 }
734 i = k
735 }
736 }
737 const vw = cols * CW, vh = rows * CH
738 return `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${vw} ${vh}" width="${vw * scale}" height="${vh * scale}">` +
739 `<rect width="${vw}" height="${vh}" rx="6" fill="${hex(PANE)}"/>` +
740 [...paths].map(([c, d]) => `<path fill="${hex(c)}" d="${d}"/>`).join('') +
741 sprites.map(s => `<image x="${s.x * CW}" y="${s.y * CH}" width="${MW * CW}" height="${MH * CH}" style="image-rendering:pixelated" href="data:image/png;base64,${s.base64}"/>`).join('') +
742 `<g font-family="ui-monospace,Menlo,Consolas,monospace" font-size="10">${texts.join('')}</g></svg>`
743}
744types/index.d.ts 12 lines1export type Slots = number
2/** The worker key whose detail view is open; '' = the crew scene. */
3export type Selected = string
4/** The detail view's open tab. */
5export type Tab = 'notes' | 'steps' | 'report' | 'test'
6
7declare module 'claude-code' {
8 interface PluginState {
9 'cw-crew': { slots: Slots; selected: Selected; tab: Tab }
10 }
11}
12