MCP server, agent skill and CLI for automating a running Godot game

Playwright, but for game engines.
**Drive your running Godot game from outside the engine.** Click real buttons, read real node state, capture real frames and diff them against saved baselines.
One Go binary. Two frontends over the same live connection:
See it work: examples/minimal-game is one command. Clone it and watch an agent click a button in a real running Godot scene, then assert the result.
Status: beta, pre-1.0. Prebuilt binaries for Linux, macOS (Intel and Apple Silicon) and Windows. Tool schemas and the wire protocol may still change between minor versions.
# 1. Get the binary (Linux shown; macOS and Windows builds are on the same page)
curl -fsSLo godot-stagehand \
https://github.com/mrf/godot-stagehand/releases/latest/download/godot-stagehand-linux-amd64
chmod +x godot-stagehand
# 2. Install the addon into your Godot project (idempotent)
./godot-stagehand setup /path/to/your/godot/project
# 3. Run your game with Stagehand on
godot --path /path/to/your/project --stagehand
setup prints the MCP client config snippet and the command to run your game. Your game then prints a one-session auth token. Keep it private, and give it to godot_connect.
Rather not use a terminal? Enable the addon in Project → Project Settings → Plugins, then click Setup… in the editor toolbar. That wizard downloads the binary, writes the config, and tests the connection. Either path is walked through step by step in the Quickstart.
/plugin marketplace add mrf/godot-stagehand
/plugin install godot-stagehand@godot-stagehand
The plugin brings the MCP server (it downloads the matching release binary on first start), the agent skill, and godot-stagehand on the Bash tool's PATH. Enable it in your Godot project's .claude/settings.json rather than user-wide, and remove any hand-written godot-stagehand MCP entry first, or every tool appears twice.
In the terminal, /stagehand-view opens a pane with the last frame Claude captured. kitty and Ghostty show it as a full picture. Other terminals, and anything inside tmux, show a coarse grid of coloured blocks instead, because Claude Code draws pictures only where the terminal supports kitty-style images. The Desktop app shows the frame's size and capture time.
From an MCP client (Claude Code, Claude Desktop, Cursor, anything speaking MCP):
{
"mcpServers": {
"godot-stagehand": {
"command": "/absolute/path/to/godot-stagehand"
}
}
}
From a terminal or a CI job:
export STAGEHAND_AUTH_TOKEN=<the token this Godot session printed>
godot-stagehand find --port 26788 'class:Button' --properties text
godot-stagehand run scenarios/menu-smoke.json --out-dir ci-artifacts
run executes a declarative list of launch, action, wait and assertion steps against a real Godot build and exits nonzero on failure. Exit 5 means a real regression. --out-dir collects report.json, junit.xml, rpc-trace.json, godot.log, screenshots and diff images.
Stagehand binds to 127.0.0.1 and rejects every command until the peer supplies the session token, but it is a dev control plane, not a hardened endpoint. Read the security boundary before you expose anything.
| Quickstart | Install and first command, step by step |
| Tool reference | Every MCP tool, and what to build with them |
| CLI and scenario runner | Commands, scenario format, exit codes, CI recipes |
| Selectors | Targeting nodes by path, name, class, group, text, role |
| Configuration | Flags, env vars, timeouts, running several agents at once |
| Security boundary | Auth, remote binding, unsafe methods |
| Architecture | How the addon, the binary and your client fit together |
| Compatibility | Godot 4.3 to 4.7, and why not 4.2 |
| Troubleshooting | When it won't connect, or the screenshots are black |
| Comparison | Versus editor-automation tools and in-engine test frameworks |
| Visual regression | Baselines, diffing, and the CI gate contract |
| Agent skill | Drop-in skill file that teaches an agent the whole workflow |
| Windows / WSL | Bridging Godot on Windows with a client in WSL |
go vet ./... # lint
go test ./... # Go tests (no Godot needed)
# Scenario runner against a real headless Godot
GODOT_BIN=/path/to/godot go test -tags=godot -run '^TestScenarioRunner' .
# GDScript unit suite (GdUnit4, headless, needs Godot 4.6+)
GODOT_BIN=/path/to/godot ./scripts/run-gdscript-tests.sh
Read the GDScript testing guide for the suite layout and strict-mode rules, the addon sync contract before editing any copy of the addon, and the error model before adding a handler that can fail.
MIT. See LICENSE.
hooks/register.ts 438 lines1// The godot-stagehand mod (docs/design/claude-code-plugin.md, D7): a status
2// band above the prompt and a /stagehand-view pane with the last game frame.
3//
4// It only observes. The tool.call hook passes every call on unchanged and
5// reads the results of Claude's own Stagehand calls; it never calls the server
6// itself, because $.mcp.call fires tool.call again and, inside a turn, needs a
7// permission grant (design Q7). Only the pane's buttons call the server, from
8// outside a turn. The MCP server and the skill work without this mod.
9import type { EngineInterface, On } from 'claude-code'
10import { decodePng, type Pixels } from './png.js'
11import { encodeCells, halfBlockCells, rasterGrid, thumbnail } from './raster.js'
12
13const SERVER = 'plugin:godot-stagehand:stagehand'
14const TOOL_PREFIX = 'mcp__plugin_godot-stagehand_stagehand__'
15const PANE_ID = 'stagehand-view'
16// The pane's frame element, an Image or a Raster; the key the probe blits.
17const FRAME_KEY = 'frame'
18// The Image element takes PNGs of at most 2 MiB decoded.
19const IMAGE_LIMIT_BYTES = 2 * 1024 * 1024
20// godot_connect's defaults, for a successful call that left them out.
21const DEFAULT_INSTANCE = 'default'
22const DEFAULT_HOST = '127.0.0.1'
23const DEFAULT_PORT = 26700
24
25interface Instance {
26 id: string
27 state: string
28 host: string
29 port: number
30}
31
32interface Frame {
33 png: string
34 bytes: number
35 width: number
36 height: number
37 capturedAt: Date
38 // At most 512 px on the long side, for a Raster; the full decode is dropped.
39 // Undefined when the decoder rejected the frame or no Raster can need it.
40 thumbnail: Pixels | undefined
41 // The Raster last drawn from it, kept until the pane's size changes.
42 raster?: { columns: number; rows: number; cells: string }
43 // $.ui.blit probes made while it was the frame drawn.
44 probes: number
45}
46
47// State lives in module variables: the band rebuilds from the next Stagehand
48// call, so nothing has to survive a reload.
49const instances = new Map<string, Instance>()
50let frame: Frame | undefined
51let paneError: string | undefined
52
53// How the pane draws a frame on the terminal (design D7, "Frame fallback").
54// `Image` draws pixels only where the terminal can (kitty, Ghostty) and its alt
55// elsewhere, such as inside tmux. Which one it does is known only once the
56// Image is mounted: $.ui.blit with the same source then answers {} or a deny
57// naming the alt. So the pane starts `probing`, settles on `image` for the
58// session when a blit is taken, and on `raster` (half blocks) when one is
59// denied. A refused call leaves it on `image`, as the pane drew before.
60let frameMode: 'probing' | 'image' | 'raster' = 'probing'
61let probeInFlight = false
62// A blit made in the same pass as the drawing finds nothing mounted yet: on
63// 2.1.288 it answers 'no Image of its own is mounted under key "frame" in
64// stagehand-view', and a blit from the next drawing gets the real answer about
65// 25 ms later. That deny alone means "ask again".
66const NOT_MOUNTED = 'is mounted under key'
67const MAX_PROBES = 8
68// Under a frame drawn as blocks. Claude Code draws pictures in kitty and
69// Ghostty; inside tmux it never does (README, "Claude Code").
70const BLOCKS_WHY =
71 "Blocks, because this terminal can't show pictures here. kitty or Ghostty, outside tmux, show the full frame."
72
73// ── Reading tool results ────────────────────────────────────────────────────
74
75function asRecord(value: unknown): Readonly<Record<string, unknown>> | undefined {
76 return typeof value === 'object' && value !== null && !Array.isArray(value)
77 ? (value as Readonly<Record<string, unknown>>)
78 : undefined
79}
80
81function stringField(record: Readonly<Record<string, unknown>> | undefined, key: string): string | undefined {
82 const value = record?.[key]
83 return typeof value === 'string' ? value : undefined
84}
85
86function numberField(record: Readonly<Record<string, unknown>> | undefined, key: string): number | undefined {
87 const value = record?.[key]
88 return typeof value === 'number' && Number.isFinite(value) ? value : undefined
89}
90
91function parseJSON(text: string | undefined): Readonly<Record<string, unknown>> | undefined {
92 if (text === undefined) return undefined
93 try {
94 return asRecord(JSON.parse(text))
95 } catch {
96 // Not every result is JSON (godot_connect answers in prose); not ours to read.
97 return undefined
98 }
99}
100
101// What a successful call left for the model: its text, and its content blocks.
102interface Observed {
103 text: string | undefined
104 blocks: readonly unknown[]
105}
106
107// A tool.call result as core gives it: `{ result, text }`, or `isError` / `deny`.
108function fromToolCall(result: unknown): Observed | undefined {
109 const record = asRecord(result)
110 if (record === undefined || record['isError'] === true || record['deny'] !== undefined) return undefined
111 const inner = record['result']
112 const text = stringField(record, 'text') ?? (typeof inner === 'string' ? inner : undefined)
113 return { text, blocks: Array.isArray(inner) ? inner : [] }
114}
115
116// A $.mcp.call result: `{ content, isError }`.
117function fromMcpCall(result: unknown): Observed | undefined {
118 const record = asRecord(result)
119 if (record === undefined || record['isError'] === true) return undefined
120 const content = record['content']
121 const blocks: readonly unknown[] = Array.isArray(content) ? content : []
122 const texts = blocks.flatMap((block) => {
123 const text = stringField(asRecord(block), 'text')
124 return text === undefined ? [] : [text]
125 })
126 return { text: texts.length > 0 ? texts.join('\n') : undefined, blocks }
127}
128
129function replaceInstances(list: unknown, stateOf: (item: Readonly<Record<string, unknown>>) => string | undefined): void {
130 if (!Array.isArray(list)) return
131 instances.clear()
132 for (const entry of list) {
133 const item = asRecord(entry)
134 const id = stringField(item, 'id')
135 const host = stringField(item, 'host')
136 const port = numberField(item, 'port')
137 const state = item === undefined ? undefined : stateOf(item)
138 if (id !== undefined && host !== undefined && port !== undefined && state !== undefined) {
139 instances.set(id, { id, state, host, port })
140 }
141 }
142}
143
144// PNG width and height from the IHDR chunk: bytes 16-23 of the file, which
145// are base64 characters 0-31.
146function pngSize(png: string): { width: number; height: number } {
147 const alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
148 const bytes: number[] = []
149 for (let i = 0; i + 3 < 32 && i + 3 < png.length; i += 4) {
150 const n = [0, 1, 2, 3].reduce((acc, k) => acc * 64 + Math.max(0, alphabet.indexOf(png.charAt(i + k))), 0)
151 bytes.push((n >> 16) & 0xff, (n >> 8) & 0xff, n & 0xff)
152 }
153 const word = (at: number): number =>
154 ((bytes[at] ?? 0) * 0x1000000) + ((bytes[at + 1] ?? 0) << 16) + ((bytes[at + 2] ?? 0) << 8) + (bytes[at + 3] ?? 0)
155 return { width: word(16), height: word(20) }
156}
157
158function decodedLength(base64: string): number {
159 const padding = base64.endsWith('==') ? 2 : base64.endsWith('=') ? 1 : 0
160 return Math.floor((base64.length * 3) / 4) - padding
161}
162
163// Decodes a frame once, as it arrives, never while drawing. Not when it is
164// over the Image limit, which keeps the text summary, nor once the terminal
165// has drawn an Image, since no Raster will be drawn then.
166function thumbnailOf(png: string, bytes: number): Pixels | undefined {
167 if (bytes > IMAGE_LIMIT_BYTES || frameMode === 'image') return undefined
168 try {
169 const decoded = decodePng(Uint8Array.fromBase64(png))
170 return decoded.kind === 'decoded' ? thumbnail(decoded.pixels) : undefined
171 } catch {
172 // Not base64, or out of memory: the frame keeps its text summary.
173 return undefined
174 }
175}
176
177function frameFrom(blocks: readonly unknown[]): Frame | undefined {
178 for (const entry of blocks) {
179 const block = asRecord(entry)
180 if (stringField(block, 'type') !== 'image') continue
181 // Claude Code hands MCP images on in the Messages API shape
182 // ({ source: { type: 'base64', media_type, data } }); accept the MCP shape too.
183 const source = asRecord(block?.['source'])
184 const png = stringField(source, 'data') ?? stringField(block, 'data')
185 const mime = stringField(source, 'media_type') ?? stringField(block, 'mimeType')
186 if (png === undefined || mime !== 'image/png') continue
187 const bytes = decodedLength(png)
188 return { png, bytes, ...pngSize(png), capturedAt: new Date(), thumbnail: thumbnailOf(png, bytes), probes: 0 }
189 }
190 return undefined
191}
192
193// Updates the module state from one successful Stagehand call. Returns
194// whether anything a drawing shows changed.
195function observe(tool: string, args: Readonly<Record<string, unknown>>, observed: Observed): boolean {
196 switch (tool) {
197 case 'godot_status': {
198 const report = parseJSON(observed.text)
199 if (report === undefined) return false
200 replaceInstances(report['instances'], (item) => stringField(item, 'state'))
201 return true
202 }
203 case 'godot_list_instances': {
204 const report = parseJSON(observed.text)
205 if (report === undefined) return false
206 replaceInstances(report['instances'], (item) =>
207 item['connected'] === true ? 'connected' : 'disconnected',
208 )
209 return true
210 }
211 case 'godot_launch': {
212 const launched = parseJSON(observed.text)
213 const host = stringField(launched, 'host')
214 const port = numberField(launched, 'port')
215 if (host === undefined || port === undefined) return false
216 const id = stringField(launched, 'instance_id') ?? DEFAULT_INSTANCE
217 instances.set(id, { id, state: 'connected', host, port })
218 return true
219 }
220 case 'godot_connect': {
221 // godot_connect answers in prose, so read the call's own arguments.
222 const id = stringField(args, 'instance_id') ?? DEFAULT_INSTANCE
223 const host = stringField(args, 'host') ?? DEFAULT_HOST
224 const port = numberField(args, 'port') ?? DEFAULT_PORT
225 instances.set(id, { id, state: 'connected', host, port })
226 return true
227 }
228 case 'godot_disconnect': {
229 const id = stringField(args, 'instance_id')
230 return id !== undefined && instances.delete(id)
231 }
232 case 'godot_screenshot': {
233 const captured = frameFrom(observed.blocks)
234 if (captured === undefined) return false
235 frame = captured
236 return true
237 }
238 default:
239 return false
240 }
241}
242
243// ── Drawing ─────────────────────────────────────────────────────────────────
244
245function statusLine(): string | undefined {
246 const connected = [...instances.values()].filter((instance) => instance.state === 'connected')
247 const [only] = connected
248 if (only === undefined) return undefined
249 const address = (instance: Instance): string => `${instance.id} ${instance.host}:${String(instance.port)}`
250 if (connected.length === 1) return `stagehand · ${address(only)} · connected`
251 return `stagehand · ${String(connected.length)} connected · ${connected.map(address).join(', ')}`
252}
253
254function describeSize(bytes: number): string {
255 return bytes >= 1024 * 1024 ? `${(bytes / (1024 * 1024)).toFixed(1)} MiB` : `${String(Math.ceil(bytes / 1024))} KiB`
256}
257
258function clock(date: Date): string {
259 const two = (n: number): string => String(n).padStart(2, '0')
260 return `${two(date.getHours())}:${two(date.getMinutes())}:${two(date.getSeconds())}`
261}
262
263// Terminal cells are about twice as tall as they are wide.
264function imageCells(width: number, height: number, maxColumns: number, maxRows: number): { columns: number; rows: number } {
265 const clamp = (n: number, max: number): number => Math.max(1, Math.min(255, max, Math.round(n)))
266 const aspect = width > 0 && height > 0 ? height / width : 9 / 16
267 let columns = clamp(maxColumns, maxColumns)
268 let rows = clamp((columns * aspect) / 2, maxRows)
269 if ((columns * aspect) / 2 > maxRows) columns = clamp((rows * 2) / aspect, maxColumns)
270 rows = clamp(rows, maxRows)
271 return { columns, rows }
272}
273
274// The Raster cells for a frame in a columns × rows grid, from its thumbnail.
275function rasterOf(shown: Frame, small: Pixels, columns: number, rows: number): string {
276 if (shown.raster?.columns !== columns || shown.raster.rows !== rows) {
277 shown.raster = { columns, rows, cells: encodeCells(halfBlockCells(small, columns, rows)) }
278 }
279 return shown.raster.cells
280}
281
282// Asks whether the terminal drew the Image's pixels by blitting it the source
283// it already has. Started while drawing and not awaited there; a deny for an
284// Image not mounted yet asks again from the next drawing.
285async function probeImage($: EngineInterface, drawn: Frame): Promise<void> {
286 if (probeInFlight || drawn.probes >= MAX_PROBES) return
287 probeInFlight = true
288 drawn.probes++
289 let deny: string | undefined
290 try {
291 const answer = await $.ui.blit({ requestId: PANE_ID, key: FRAME_KEY, source: { png: drawn.png } })
292 deny = answer.deny
293 } catch {
294 // The call itself was refused (another mod, or no blit in this build):
295 // keep the Image for this frame.
296 drawn.probes = MAX_PROBES
297 return
298 } finally {
299 probeInFlight = false
300 }
301 if (deny === undefined) {
302 frameMode = 'image'
303 return
304 }
305 if (!deny.includes(NOT_MOUNTED)) frameMode = 'raster'
306 // Draw again: as a Raster, or as the Image with the next probe.
307 $.ui.invalidate('ui.render')
308}
309
310// ── Pane buttons: the only server calls, made outside a turn ────────────────
311
312async function callFromPane($: EngineInterface, tool: 'godot_screenshot' | 'godot_status'): Promise<void> {
313 try {
314 const observed = fromMcpCall(await $.mcp.call(SERVER, tool, {}))
315 paneError = observed === undefined ? `${tool} failed; ask Claude to check the game.` : undefined
316 if (observed !== undefined) observe(tool, {}, observed)
317 } catch (error) {
318 paneError = error instanceof Error ? error.message : String(error)
319 }
320 $.ui.invalidate('ui.render')
321}
322
323// ── Hooks ───────────────────────────────────────────────────────────────────
324
325export function register(on: On): void {
326 on('tool.call', async ($, e, next) => {
327 const result = await next(e)
328 if (e.tool.startsWith(TOOL_PREFIX)) {
329 const observed = fromToolCall(result)
330 const args = asRecord(e) ?? {}
331 if (observed !== undefined && observe(e.tool.slice(TOOL_PREFIX.length), args, observed)) {
332 $.ui.invalidate('ui.render')
333 }
334 }
335 return result
336 })
337
338 on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
339 const line = statusLine()
340 if (line === undefined || e.props.hasSurvey) return next(e)
341 const { Box, Text } = $.ui.resolve(e)
342 // Keep what the mods after this one drew.
343 const theirs = await next(e)
344 return Box({
345 flexDirection: 'column',
346 children: [Text({ dimColor: true, wrap: 'truncate-end', children: [line] }), theirs],
347 })
348 })
349
350 on('ui.render', { component: 'Pane' }, async ($, e, next) => {
351 if (e.requestId !== PANE_ID) return next(e)
352 const { Box, Text, Button } = $.ui.resolve(e)
353
354 const rows = [
355 Text({ bold: true, wrap: 'truncate-end', children: [statusLine() ?? 'stagehand · no game connected'] }),
356 ]
357 if (frame === undefined) {
358 rows.push(Text({ dimColor: true, children: ['No frame yet. Press r, or ask Claude for a screenshot.'] }))
359 } else {
360 const summary = `${String(frame.width)}×${String(frame.height)} frame, ${describeSize(frame.bytes)}, captured ${clock(frame.capturedAt)}`
361 const maxRows = Math.max(1, e.props.scroll.bodyRows - 4)
362 const { thumbnail: small } = frame
363 if (e.surface !== 'terminal' || frame.bytes > IMAGE_LIMIT_BYTES || (frameMode === 'raster' && small === undefined)) {
364 const why =
365 e.surface !== 'terminal'
366 ? 'this app cannot draw it'
367 : frame.bytes > IMAGE_LIMIT_BYTES
368 ? 'too large to draw here'
369 : 'this terminal cannot draw it'
370 rows.push(Text({ children: [`Last ${summary}: ${why}; ask Claude for a screenshot to see it.`] }))
371 } else if (frameMode === 'raster' && small !== undefined) {
372 // Only the terminal's element table has Raster and Image (the Desktop app has neither).
373 const { Raster } = $.ui.resolve(e)
374 const grid = rasterGrid(small.width, small.height, e.props.bodyColumns, maxRows)
375 rows.push(Raster({ key: FRAME_KEY, ...grid, cells: rasterOf(frame, small, grid.columns, grid.rows) }))
376 rows.push(Text({ dimColor: true, children: [summary] }))
377 rows.push(Text({ dimColor: true, children: [BLOCKS_WHY] }))
378 } else {
379 const { Image } = $.ui.resolve(e)
380 const cells = imageCells(frame.width, frame.height, e.props.bodyColumns, maxRows)
381 // The alt text stands in for the picture until the probe has switched
382 // a terminal that cannot draw one to the Raster, right above the summary.
383 rows.push(Image({ key: FRAME_KEY, source: { png: frame.png }, ...cells, alt: 'Last game frame' }))
384 rows.push(Text({ dimColor: true, children: [summary] }))
385 if (frameMode === 'probing') void probeImage($, frame)
386 }
387 }
388 if (paneError !== undefined) rows.push(Text({ color: 'error', children: [paneError] }))
389 rows.push(
390 Box({
391 flexDirection: 'row',
392 columnGap: 3,
393 children: [
394 Button({
395 key: 'refresh',
396 label: 'Refresh frame',
397 hotkey: 'r',
398 plain: true,
399 onPress: () => {
400 void callFromPane($, 'godot_screenshot')
401 },
402 }),
403 Button({
404 key: 'status',
405 label: 'Re-read status',
406 hotkey: 's',
407 plain: true,
408 onPress: () => {
409 void callFromPane($, 'godot_status')
410 },
411 }),
412 ],
413 }),
414 )
415 return Box({ flexDirection: 'column', children: rows })
416 })
417
418 on('command.run', { command: 'stagehand-view' }, async ($) => {
419 await $.ui.open({ id: PANE_ID, title: 'Stagehand', focus: true, closeOnEscape: true })
420 return {}
421 })
422
423 // Last, and guarded: $.command.register throws on a taken name, and the
424 // band above must keep working when it does.
425 on('session.start', async ($, e, next) => {
426 try {
427 await $.command.register({
428 name: 'stagehand-view',
429 description: 'Show the last game frame Claude captured and the Stagehand connection',
430 immediate: true,
431 })
432 } catch {
433 // Another plugin or the user owns /stagehand-view; the band still works.
434 }
435 return next(e)
436 })
437}
438hooks/png.ts 385 lines1// PNG decoding for the pane's frame fallback (docs/design/claude-code-plugin.md,
2// D7 "Frame fallback"): 8-bit RGB and RGBA, non-interlaced, which is what
3// Godot's save_png_to_buffer writes. A mod has no Node APIs and no
4// DecompressionStream, so this carries its own zlib inflate (RFC 1950, 1951).
5//
6// decodePng never throws: any PNG it cannot read, or a damaged one, comes back
7// as an `unsupported` result with the reason.
8
9export interface Pixels {
10 readonly width: number
11 readonly height: number
12 // Bytes per pixel: 3 for RGB, 4 for RGBA. Rows are packed, top row first.
13 readonly channels: 3 | 4
14 readonly data: Uint8Array
15}
16
17export type PngResult =
18 | { readonly kind: 'decoded'; readonly pixels: Pixels }
19 | { readonly kind: 'unsupported'; readonly reason: string }
20
21// Why a PNG or zlib stream was refused. Only decodePng's callers see the text.
22export class PngError extends Error {}
23
24// The largest frame decoded, in pixels: a 3840×2160 screenshot fits.
25export const MAX_PIXELS = 1 << 23
26
27export function decodePng(png: Uint8Array): PngResult {
28 try {
29 return { kind: 'decoded', pixels: decode(png) }
30 } catch (error) {
31 const reason = error instanceof PngError ? error.message : `the decoder failed: ${String(error)}`
32 return { kind: 'unsupported', reason }
33 }
34}
35
36// ── PNG ─────────────────────────────────────────────────────────────────────
37
38const SIGNATURE = [137, 80, 78, 71, 13, 10, 26, 10]
39
40interface Header {
41 width: number
42 height: number
43 channels: 3 | 4
44}
45
46function decode(png: Uint8Array): Pixels {
47 if (png.length < SIGNATURE.length || SIGNATURE.some((byte, i) => png[i] !== byte)) {
48 throw new PngError('not a PNG file')
49 }
50 const view = new DataView(png.buffer, png.byteOffset, png.byteLength)
51 let header: Header | undefined
52 const idat: Uint8Array[] = []
53 for (let pos = SIGNATURE.length; ; ) {
54 if (pos + 12 > png.length) throw new PngError('the PNG file ends before its IEND chunk')
55 const length = view.getUint32(pos)
56 const type = String.fromCharCode(...png.subarray(pos + 4, pos + 8))
57 const end = pos + 8 + length
58 if (end + 4 > png.length) throw new PngError(`the ${type} chunk runs past the end of the file`)
59 if (crc32(png.subarray(pos + 4, end)) !== view.getUint32(end)) {
60 throw new PngError(`the ${type} chunk fails its CRC check`)
61 }
62 const data = png.subarray(pos + 8, end)
63 if (header === undefined) {
64 if (type !== 'IHDR') throw new PngError('the PNG file does not start with IHDR')
65 header = readHeader(data)
66 } else if (type === 'IDAT') {
67 idat.push(data)
68 } else if (type === 'IEND') {
69 return pixelsOf(header, concat(idat))
70 } else if (type !== 'PLTE' && (type.charCodeAt(0) & 0x20) === 0) {
71 // An unknown critical chunk changes how the image reads; PLTE in a
72 // truecolour image is only a suggested palette.
73 throw new PngError(`the PNG file has a critical ${type} chunk this decoder does not read`)
74 }
75 pos = end + 4
76 }
77}
78
79function readHeader(data: Uint8Array): Header {
80 if (data.length !== 13) throw new PngError('the IHDR chunk is not 13 bytes')
81 const view = new DataView(data.buffer, data.byteOffset, data.byteLength)
82 const width = view.getUint32(0)
83 const height = view.getUint32(4)
84 const [depth, colourType, compression, filter, interlace] = data.subarray(8)
85 if (colourType !== 2 && colourType !== 6) {
86 throw new PngError(`colour type ${String(colourType)} is not supported (8-bit RGB or RGBA only)`)
87 }
88 if (depth !== 8) throw new PngError(`bit depth ${String(depth)} is not supported (8-bit RGB or RGBA only)`)
89 if (compression !== 0 || filter !== 0) throw new PngError('the PNG uses an unknown compression or filter method')
90 if (interlace !== 0) throw new PngError('interlaced PNGs are not supported')
91 if (width === 0 || height === 0) throw new PngError('the PNG has no pixels')
92 if (width * height > MAX_PIXELS) {
93 throw new PngError(`${String(width)}×${String(height)} is over the ${String(MAX_PIXELS)}-pixel limit`)
94 }
95 return { width, height, channels: colourType === 6 ? 4 : 3 }
96}
97
98function concat(parts: readonly Uint8Array[]): Uint8Array {
99 const whole = new Uint8Array(parts.reduce((sum, part) => sum + part.length, 0))
100 let at = 0
101 for (const part of parts) {
102 whole.set(part, at)
103 at += part.length
104 }
105 return whole
106}
107
108// Undoes each row's filter (PNG spec, section 9). A filtered row is its filter
109// type byte, then `stride` bytes.
110function pixelsOf({ width, height, channels }: Header, stream: Uint8Array): Pixels {
111 const stride = width * channels
112 const raw = inflate(stream, height * (stride + 1))
113 const data = new Uint8Array(stride * height)
114 // The row above the first is all zeros.
115 const zeros = new Uint8Array(stride)
116 for (let y = 0; y < height; y++) {
117 const filter = raw[y * (stride + 1)]
118 const line = raw.subarray(y * (stride + 1) + 1, (y + 1) * (stride + 1))
119 const row = data.subarray(y * stride, (y + 1) * stride)
120 const up = y > 0 ? data.subarray((y - 1) * stride, y * stride) : zeros
121 // Uint8Array stores wrap modulo 256, as the filters need.
122 switch (filter) {
123 case 0:
124 row.set(line)
125 break
126 case 1:
127 for (let i = 0; i < stride; i++) row[i] = (line[i] ?? 0) + (i >= channels ? (row[i - channels] ?? 0) : 0)
128 break
129 case 2:
130 for (let i = 0; i < stride; i++) row[i] = (line[i] ?? 0) + (up[i] ?? 0)
131 break
132 case 3:
133 for (let i = 0; i < stride; i++) {
134 row[i] = (line[i] ?? 0) + (((i >= channels ? (row[i - channels] ?? 0) : 0) + (up[i] ?? 0)) >> 1)
135 }
136 break
137 case 4:
138 // Paeth, inlined: a call per byte costs about 20 times as much in the
139 // mod worker (measured on 2.1.288: 700 ms against 35 ms for 6 MB).
140 for (let i = 0; i < stride; i++) {
141 const a = i >= channels ? (row[i - channels] ?? 0) : 0
142 const b = up[i] ?? 0
143 const c = i >= channels ? (up[i - channels] ?? 0) : 0
144 // |p - a|, |p - b| and |p - c| for p = a + b - c.
145 const pa = b > c ? b - c : c - b
146 const pb = a > c ? a - c : c - a
147 const pc = a + b > c + c ? a + b - c - c : c + c - a - b
148 row[i] = (line[i] ?? 0) + (pa <= pb && pa <= pc ? a : pb <= pc ? b : c)
149 }
150 break
151 default:
152 throw new PngError(`row ${String(y)} has unknown filter type ${String(filter)}`)
153 }
154 }
155 return { width, height, channels, data }
156}
157
158const CRC_TABLE = Uint32Array.from({ length: 256 }, (_, n) => {
159 let c = n
160 for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1
161 return c >>> 0
162})
163
164function crc32(bytes: Uint8Array): number {
165 let c = 0xffffffff
166 for (const byte of bytes) c = (CRC_TABLE[(c ^ byte) & 0xff] ?? 0) ^ (c >>> 8)
167 return (c ^ 0xffffffff) >>> 0
168}
169
170// ── zlib inflate ────────────────────────────────────────────────────────────
171
172const LENGTH_BASE = [3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258]
173const LENGTH_EXTRA = [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0]
174const DISTANCE_BASE = [
175 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
176 8193, 12289, 16385, 24577,
177]
178const DISTANCE_EXTRA = [0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13]
179// The order a dynamic block lists its code-length code lengths in.
180const CODE_LENGTH_ORDER = [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15]
181const END_OF_BLOCK = 256
182
183// A canonical Huffman code as a lookup table indexed by the next `bits` input
184// bits: each entry is `symbol << 4 | code length`, and 0 where no code is.
185interface Huffman {
186 table: Uint32Array
187 bits: number
188}
189
190function huffman(lengths: Uint8Array): Huffman {
191 const counts = new Uint16Array(16)
192 let bits = 0
193 for (const length of lengths) {
194 counts[length] = (counts[length] ?? 0) + 1
195 bits = Math.max(bits, length)
196 }
197 let left = 1
198 for (let length = 1; length <= 15; length++) {
199 left = left * 2 - (counts[length] ?? 0)
200 if (left < 0) throw new PngError('the zlib stream has an over-subscribed Huffman code')
201 }
202 const next = new Uint16Array(16)
203 for (let length = 1; length < 15; length++) next[length + 1] = ((next[length] ?? 0) + (counts[length] ?? 0)) << 1
204 const table = new Uint32Array(1 << bits)
205 lengths.forEach((length, symbol) => {
206 if (length === 0) return
207 const code = next[length] ?? 0
208 next[length] = code + 1
209 // Deflate packs codes from their most significant bit, and the reader
210 // takes bits least significant first, so the table is indexed reversed.
211 let reversed = 0
212 for (let k = 0; k < length; k++) reversed |= ((code >> k) & 1) << (length - 1 - k)
213 for (let index = reversed; index < table.length; index += 1 << length) table[index] = (symbol << 4) | length
214 })
215 return { table, bits }
216}
217
218let fixed: [Huffman, Huffman] | undefined
219
220function fixedCodes(): [Huffman, Huffman] {
221 if (fixed === undefined) {
222 const lengths = new Uint8Array(288)
223 lengths.fill(8, 0, 144)
224 lengths.fill(9, 144, 256)
225 lengths.fill(7, 256, 280)
226 lengths.fill(8, 280, 288)
227 fixed = [huffman(lengths), huffman(new Uint8Array(30).fill(5))]
228 }
229 return fixed
230}
231
232// Reads a deflate stream's bits, least significant first. Past the end it
233// reads zeros and throws as soon as one of them is used.
234class BitReader {
235 private pos: number
236 private buffer = 0
237 private count = 0
238 private padding = 0
239
240 constructor(
241 private readonly bytes: Uint8Array,
242 start: number,
243 ) {
244 this.pos = start
245 }
246
247 read(n: number): number {
248 this.fill(n)
249 const value = this.buffer & ((1 << n) - 1)
250 this.drop(n)
251 return value
252 }
253
254 symbol({ table, bits }: Huffman): number {
255 this.fill(bits)
256 const entry = table[this.buffer & (table.length - 1)] ?? 0
257 const length = entry & 15
258 if (length === 0) throw new PngError('the zlib stream has an invalid Huffman code')
259 this.drop(length)
260 return entry >>> 4
261 }
262
263 // Skips to the next byte boundary.
264 align(): void {
265 this.drop(this.count & 7)
266 }
267
268 private fill(n: number): void {
269 while (this.count < n) {
270 if (this.pos < this.bytes.length) {
271 this.buffer |= (this.bytes[this.pos] ?? 0) << this.count
272 this.pos++
273 } else {
274 this.padding++
275 }
276 this.count += 8
277 }
278 }
279
280 private drop(n: number): void {
281 this.buffer >>>= n
282 this.count -= n
283 // The padding is the top of the buffer: it has been read once fewer bits
284 // are left than it holds.
285 if (this.count < this.padding * 8) throw new PngError('the zlib stream ends early')
286 }
287}
288
289// Inflates a zlib stream that must hold exactly `length` bytes.
290export function inflate(stream: Uint8Array, length: number): Uint8Array {
291 const [cmf = 0, flg = 0] = stream
292 if ((cmf & 15) !== 8 || cmf >> 4 > 7 || ((cmf << 8) | flg) % 31 !== 0) throw new PngError('bad zlib header')
293 if (flg & 0x20) throw new PngError('the zlib stream asks for a preset dictionary')
294 const out = new Uint8Array(length)
295 let at = 0
296 const bits = new BitReader(stream, 2)
297 for (let last = false; !last; ) {
298 last = bits.read(1) === 1
299 const type = bits.read(2)
300 if (type === 0) {
301 bits.align()
302 const size = bits.read(16)
303 if ((size ^ 0xffff) !== bits.read(16)) throw new PngError('a stored zlib block has a bad length')
304 if (at + size > length) throw new PngError('the zlib stream holds more data than the image')
305 for (let k = 0; k < size; k++) out[at++] = bits.read(8)
306 continue
307 }
308 if (type === 3) throw new PngError('the zlib stream has a reserved block type')
309 const [literals, distances] = type === 1 ? fixedCodes() : dynamicCodes(bits)
310 for (;;) {
311 const symbol = bits.symbol(literals)
312 if (symbol < END_OF_BLOCK) {
313 if (at >= length) throw new PngError('the zlib stream holds more data than the image')
314 out[at++] = symbol
315 continue
316 }
317 if (symbol === END_OF_BLOCK) break
318 // A length code, its extra bits, then a distance code and its extra bits.
319 const lengthBase = LENGTH_BASE[symbol - 257]
320 if (lengthBase === undefined) throw new PngError('the zlib stream has an invalid length code')
321 const size = lengthBase + bits.read(LENGTH_EXTRA[symbol - 257] ?? 0)
322 const distanceCode = bits.symbol(distances)
323 const distanceBase = DISTANCE_BASE[distanceCode]
324 if (distanceBase === undefined) throw new PngError('the zlib stream has an invalid distance code')
325 const distance = distanceBase + bits.read(DISTANCE_EXTRA[distanceCode] ?? 0)
326 if (distance > at) throw new PngError('a zlib back-reference reaches before the start')
327 if (at + size > length) throw new PngError('the zlib stream holds more data than the image')
328 if (distance >= size) {
329 out.copyWithin(at, at - distance, at - distance + size)
330 at += size
331 } else {
332 // Overlapping: byte by byte repeats the last `distance` bytes.
333 for (const end = at + size; at < end; at++) out[at] = out[at - distance] ?? 0
334 }
335 }
336 }
337 if (at !== length) throw new PngError(`the image data is ${String(at)} bytes, not ${String(length)}`)
338 bits.align()
339 const adler = ((bits.read(8) << 24) | (bits.read(8) << 16) | (bits.read(8) << 8) | bits.read(8)) >>> 0
340 if (adler !== adler32(out)) throw new PngError('the zlib stream fails its Adler-32 check')
341 return out
342}
343
344function dynamicCodes(bits: BitReader): [Huffman, Huffman] {
345 const literalCount = bits.read(5) + 257
346 const distanceCount = bits.read(5) + 1
347 const codeLengthCount = bits.read(4) + 4
348 if (literalCount > 286 || distanceCount > 30) throw new PngError('a zlib block declares too many codes')
349 const codeLengths = new Uint8Array(19)
350 for (let i = 0; i < codeLengthCount; i++) codeLengths[CODE_LENGTH_ORDER[i] ?? 0] = bits.read(3)
351 const codeLengthCode = huffman(codeLengths)
352 const lengths = new Uint8Array(literalCount + distanceCount)
353 for (let i = 0; i < lengths.length; ) {
354 const symbol = bits.symbol(codeLengthCode)
355 if (symbol < 16) {
356 lengths[i++] = symbol
357 continue
358 }
359 if (symbol === 16 && i === 0) throw new PngError('a zlib block repeats a code length before the first')
360 const value = symbol === 16 ? (lengths[i - 1] ?? 0) : 0
361 const repeat = symbol === 16 ? 3 + bits.read(2) : symbol === 17 ? 3 + bits.read(3) : 11 + bits.read(7)
362 if (i + repeat > lengths.length) throw new PngError('a zlib block repeats past its code lengths')
363 lengths.fill(value, i, i + repeat)
364 i += repeat
365 }
366 if (lengths[END_OF_BLOCK] === 0) throw new PngError('a zlib block has no end-of-block code')
367 return [huffman(lengths.subarray(0, literalCount)), huffman(lengths.subarray(literalCount))]
368}
369
370function adler32(bytes: Uint8Array): number {
371 let a = 1
372 let b = 0
373 // 5552 bytes is the most that can be summed before the sums need reducing.
374 for (let start = 0; start < bytes.length; start += 5552) {
375 const end = Math.min(start + 5552, bytes.length)
376 for (let i = start; i < end; i++) {
377 a += bytes[i] ?? 0
378 b += a
379 }
380 a %= 65521
381 b %= 65521
382 }
383 return ((b << 16) | a) >>> 0
384}
385hooks/raster.ts 114 lines1// Half-block drawing for the pane's frame fallback (docs/design/claude-code-plugin.md,
2// D7 "Frame fallback"). A frame is box-filtered to a cell grid, two pixels per
3// cell: each cell is ▀ with the top pixel as its foreground and the bottom
4// pixel as its background. A cell is about twice as tall as it is wide, so the
5// two pixels are about square.
6import type { Pixels } from './png.js'
7
8// The thumbnail kept per frame, so a resized pane redraws without the full frame.
9export const THUMBNAIL_SIDE = 512
10// The largest Raster Claude Code draws.
11const MAX_COLUMNS = 512
12const MAX_ROWS = 256
13const UPPER_HALF = 0x2580
14const SPACE = 0x20
15// A Raster colour that means the terminal's own default.
16const DEFAULT_COLOUR = 0x01000000
17
18const clamp = (n: number, low: number, high: number): number => Math.min(high, Math.max(low, n))
19
20// RGB pixels of `source` box-filtered to width × height: each output pixel is
21// the mean of the source pixels it covers, RGBA composited over black first.
22function resample(source: Pixels, width: number, height: number): Uint8Array {
23 const { channels, data } = source
24 const span = (i: number, from: number, to: number): [number, number] => {
25 const start = Math.floor((i * from) / to)
26 return [start, Math.max(start + 1, Math.floor(((i + 1) * from) / to))]
27 }
28 const columns = Array.from({ length: width }, (_, ox) => span(ox, source.width, width))
29 const out = new Uint8Array(width * height * 3)
30 let o = 0
31 for (let oy = 0; oy < height; oy++) {
32 const [y0, y1] = span(oy, source.height, height)
33 for (const [x0, x1] of columns) {
34 let r = 0
35 let g = 0
36 let b = 0
37 for (let y = y0; y < y1; y++) {
38 const end = (y * source.width + x1) * channels
39 for (let at = (y * source.width + x0) * channels; at < end; at += channels) {
40 const alpha = channels === 4 ? (data[at + 3] ?? 0) : 255
41 r += (data[at] ?? 0) * alpha
42 g += (data[at + 1] ?? 0) * alpha
43 b += (data[at + 2] ?? 0) * alpha
44 }
45 }
46 const total = (y1 - y0) * (x1 - x0) * 255
47 out[o++] = Math.round(r / total)
48 out[o++] = Math.round(g / total)
49 out[o++] = Math.round(b / total)
50 }
51 }
52 return out
53}
54
55// The frame at most `side` pixels on its long side, aspect ratio kept, as RGB.
56export function thumbnail(pixels: Pixels, side = THUMBNAIL_SIDE): Pixels {
57 const scale = Math.min(1, side / Math.max(pixels.width, pixels.height))
58 const width = Math.max(1, Math.round(pixels.width * scale))
59 const height = Math.max(1, Math.round(pixels.height * scale))
60 return { width, height, channels: 3, data: resample(pixels, width, height) }
61}
62
63// The cell grid the pane draws a width × height frame in: all the columns it
64// may use, and as many rows as that width needs, within what it may use.
65export function rasterGrid(
66 width: number,
67 height: number,
68 maxColumns: number,
69 maxRows: number,
70): { columns: number; rows: number } {
71 const columns = clamp(maxColumns, 1, MAX_COLUMNS)
72 const rows = clamp(Math.ceil((columns * height) / width / 2), 1, clamp(maxRows, 1, MAX_ROWS))
73 return { columns, rows }
74}
75
76// Every cell of a columns × rows Raster, row-major [codePoint, foreground,
77// background] triplets: the image fitted with its aspect ratio kept and
78// centred in whole cells. The cells around it are blank.
79export function halfBlockCells(image: Pixels, columns: number, rows: number): Uint32Array {
80 const scale = Math.min(columns / image.width, (rows * 2) / image.height)
81 const width = clamp(Math.round(image.width * scale), 1, columns)
82 const height = clamp(Math.round((image.height * scale) / 2), 1, rows) * 2
83 const rgb = resample(image, width, height)
84 const left = Math.floor((columns - width) / 2)
85 const top = Math.floor((rows - height / 2) / 2)
86 const colour = (x: number, y: number): number => {
87 const at = (y * width + x) * 3
88 return ((rgb[at] ?? 0) << 16) | ((rgb[at + 1] ?? 0) << 8) | (rgb[at + 2] ?? 0)
89 }
90 const words = new Uint32Array(columns * rows * 3)
91 for (let row = 0; row < rows; row++) {
92 for (let column = 0; column < columns; column++) {
93 const x = column - left
94 const y = (row - top) * 2
95 const inside = x >= 0 && x < width && y >= 0 && y < height
96 words.set(
97 inside ? [UPPER_HALF, colour(x, y), colour(x, y + 1)] : [SPACE, DEFAULT_COLOUR, DEFAULT_COLOUR],
98 (row * columns + column) * 3,
99 )
100 }
101 }
102 return words
103}
104
105// A Raster's `cells`: padded base64 of the triplets as little-endian u32s.
106export function encodeCells(words: Uint32Array): string {
107 const bytes = new Uint8Array(words.length * 4)
108 const view = new DataView(bytes.buffer)
109 words.forEach((word, i) => {
110 view.setUint32(i * 4, word, true)
111 })
112 return bytes.toBase64()
113}
114