SLOPSHOPPER

Glass

A desktop-app look for Claude Code's terminal: colored shell commands in prose, a Bottom line card, content-fit code cards, borderless tables, gutter marks…

bandspinnerrowsguardcommandtoast
★ 16v0.16.0MITupdated 2026-10-25rashedInt32/glass
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · glass
╭──────────────────────╮ ◆ You · 8:53 AM ───────────────────────────────────────────────────────────────────────────│ glass │ fix the failing auth test and add an audit log call │ 1 call failed · Bash │ ╰──────────────────────╯ ⏺ Read(src/auth.ts) ⎿ Read 6 lines │ ├─ ✓ Edit src/auth.ts ⏺ Bash(bun test) ⎿ 3 pass, 1 fail Done. I made refresh reject expired claims and added an audit call. › /fold ⎿ glass: Folded 1 turn. /unfold opens them again. ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Your message
◆ You · 8:53 AM ───────────────────────────────────────────────────────────────────────────────────… fix the failing auth test and add an audit log call
Claude's reply
Done. I made refresh reject expired claims and added an audit call.
Tool row
│ ├─ ✓ Edit src/auth.ts
README

glass

A desktop-app look for Claude Code's terminal transcript, as a mod.

https://github.com/user-attachments/assets/365252bf-4b60-49c3-902b-b8e127592d28

Palettes

The same turn under each palette: pick one with /config under Glass.

<table> <tr> <td><strong>tarnish</strong> glass's own. Metals aging: copper for what is happening now, the verdigris it weathers to for what has settled, brass strings, steel paths, tarnished silver for flags. Placed in OKLCH.<br><br><img src="docs/shots/tarnish.png" alt="the demo turn under the tarnish palette"></td> </tr> <tr> <td><strong>overprint</strong> glass's own. Risograph inks on black paper: fluorescent pink, aqua, yellow, orange, violet; the card tints are an ink overprinted on black. Loud by design.<br><br><img src="docs/shots/overprint.png" alt="the demo turn under the overprint palette"></td> </tr> <tr> <td><strong>ironbow</strong> glass's own. The thermal camera gradient, heat for activity: yellow verb, orange builtins, magenta flags, violet strings, cold-blue paths; done is cold, so the dots are blue.<br><br><img src="docs/shots/ironbow.png" alt="the demo turn under the ironbow palette"></td> </tr> <tr> <td><strong>lagoon</strong> glass's own. Daylight shallows: turquoise lead, sky, hibiscus flags, sun-yellow strings, sand paths, white-sand text. The bright one.<br><br><img src="docs/shots/lagoon.png" alt="the demo turn under the lagoon palette"></td> </tr> <tr> <td><strong>iris</strong> glass's own. The flower: indigo petals lead, leaf-underside teal, honey strings, orchid flags, sky paths; the neutrals carry an indigo cast.<br><br><img src="docs/shots/iris.png" alt="the demo turn under the iris palette"></td> </tr> <tr> <td><strong>tangerine</strong> glass's own. A warm lead on water's cool set: tangerine verb and tool names, water's cyan band and builtins, crimson's pink for your row and flags, lemon strings, periwinkle paths.<br><br><img src="docs/shots/tangerine.png" alt="the demo turn under the tangerine palette"></td> </tr> <tr> <td><strong>prism</strong> glass's own. A starship prompt's rainbow, each color in its segment's role: coral for you, orange paths, steel-cyan strings with coral JSON keys, emerald builtins, a blue verb, purple for Claude and the prompt box; neon green done, red failed.<br><br><img src="docs/shots/prism.png" alt="the demo turn under the prism palette"></td> </tr> <tr> <td><strong>prism-light</strong> glass's own, for a light terminal. prism by role on GitHub Light: each neon and pastel taken down along its own hue to 4.5:1, the yellow as a dark gold.<br><br><img src="docs/shots/prism-light.png" alt="the demo turn under the prism-light palette"></td> </tr> <tr> <td><strong>tangerine-light</strong> glass's own, for a light terminal. tangerine by role on GitHub Light: orange verb, cyan band, pink for you, the lemon strings as a dark gold.<br><br><img src="docs/shots/tangerine-light.png" alt="the demo turn under the tangerine-light palette"></td> </tr> <tr> <td><strong>tidepool</strong> (default) my nvim theme, mapped by role.<br><br><img src="docs/shots/tidepool.png" alt="the demo turn under the tidepool palette"></td> </tr> <tr> <td><strong>water</strong> Empryo's own proxysoul-water tokens.<br><br><img src="docs/shots/water.png" alt="the demo turn under the water palette"></td> </tr> <tr> <td><strong>crimson</strong> Empryo's crimson world, "the heart", from empryo.com's CSS.<br><br><img src="docs/shots/crimson.png" alt="the demo turn under the crimson palette"></td> </tr> <tr> <td><strong>codex</strong> One Dark.<br><br><img src="docs/shots/codex.png" alt="the demo turn under the codex palette"></td> </tr> </table>

What it draws

  • Commands in color. Inside backticks and in plain prose: command, subcommand, flag, string, path, operator, number, variable, each in its own color. In prose a command paints only with evidence (git push --follow-tags paints, make sure the build passes does not).
  • Paths and links anywhere. src/main.rs:42:7 with its line number in the number color, README.md, .gitignore, ~/.config/app.toml. URLs underlined; https links are real OSC 8 links.
  • A Bottom line card. A reply opening with Bottom line (or Bottom line:) and Verified: / Issue: / Fix: rows becomes a tinted card with a thin bar and colored labels. Forms while streaming, never flickers.
  • Gutter marks. A ▎ beside any paragraph that asks something of you: a question, an instruction, a risk, or a thing Claude did not do. Off for turns whose prompt asked for writing.
  • Private notes. A paragraph opening with Private or Privately draws italic and quiet.
  • Code cards. Fences on a tinted card sized to the code, a quiet language header, a line count and gutter past eight lines. glass's own highlighter does the coloring, in the palette's code keys; a shell fence takes the same colors as a command in prose.
  • Diff cards. An Edit, Write or file-changing Bash result as a rounded card with the file in its top border, ╭─ SPEC.md +1 -1 ───╮: one number column, + and - rows on a quiet tint, one context line each side, the code painted the same way, the frame on the tree trunk.
  • Headings, lists, quotes, tables. Bold colored headings with no rules, • ◦ ☐ ☑ markers, a quote bar, borderless tables with aligned columns and right-aligned numbers. A table a little too wide squeezes its widest column instead of falling back to boxes.
  • Turn headers. ◆ You · 1:11 PM ──── as one titled rule over your prompt, then ◉ Claude · 1:14 PM once the turn starts, with a dots line under it: one dot per tool call, grouped by tool, green, a red ✗ for a failure, hollow while running, then Bash ×3 · Read ×2. Once done the line reads 5 actions · 2 edits · 1 failed. /fold tucks finished trees away and /unfold opens them.
  • A tool tree. While a turn runs, every call is one row: ├─ ✓ Bash git status · 3 lines with its wall time at the right, ○ while it runs, ✗ in red when it fails. A Bash command keeps its colors once done; other arguments step down to a quiet color, and paths draw relative to the project. Rows light under the pointer. The engine's folded runs name what they read: ├─ ▸ Read ×2 SPEC.md · render.ts. Bash output is painted, three lines then a count. A finished agent is one row.
  • Background band. While subagents run, a rounded frame above the prompt lists them with a face, model and effort, current tool, tokens and the file they last touched, five at a time. The chevron folds it to one strip of faces. A view at the end of each row opens that agent's transcript in the main view (Claude Code 2.1.300 or newer); the row in view reads back.
  • Event rows. A background task's notification draws as one tree row with its duration; a message from another agent draws as one muted row.
  • Summary rows. A compaction summary ends on a quiet · summary mark, as the engine's own does.
  • Server tool rows. A tool the API ran inside the request (the advisor) has no tool call of its own; glass draws it after the reply as a quiet tree row with its duration.
  • Themes. The diff card and the mode word under the prompt take the active theme's own slots, so they match the engine's panels under any theme. /glass-theme writes a theme built from the current palette to ~/.claude/themes/glass-<palette>.json; pick it in /theme (the engine lets a plugin select only its built-in themes). Then the prompt box, mode words, permission prompts and diff panels take the palette too. Switching the palette while a glass theme is active rewrites the file. Your own theme files are never touched.
  • Notifications. A native notification when a background agent finishes after its turn ended, or a turn ends with failed calls. The engine already notifies when a turn finishes, so glass does not. Off with the notify option under Glass in /config.
  • Fold and Copy. A chevron at the right of the dots line folds that turn's tree; ⧉ Copy takes the finished answer to the clipboard. /fold and /unfold do the same from the keyboard.

Every width is measured the way the engine measures cells, so emoji and CJK in tables stay aligned.

Install

claude plugin marketplace add rashedInt32/glass
claude plugin install glass@glass

Claude Code 2.1.295 or newer. On an older engine glass still loads: the notification falls back to a toast, summary and server tool rows need props that older engines do not send, and the rest is unchanged.

Restart Claude Code. Pick a palette with /config under Glass: tidepool (default), tarnish, overprint, ironbow, lagoon, iris, tangerine and prism (glass's own), prism-light and tangerine-light (glass's own, for a light terminal), water (Empryo's own proxysoul-water tokens), crimson (Empryo's crimson world, "the heart", from empryo.com's own CSS) or codex. Every palette but the two -light ones assumes a dark terminal. The light pair is drawn for GitHub Light (#ffffff) and keeps 4.5:1 text on One Light, Solarized Light and Catppuccin Latte too; on Latte the card tint reads as the ground. Run /glass-theme after picking one so the engine's own panels take a light base.

To try it from a clone without installing:

claude --plugin-dir /path/to/glass

Design

SPEC.md is the contract: every element, its exact tree and colors, and the directions that were tried and rejected, with reasons. Settled through a design panel and an investigation against how Claude Desktop, the Codex app and T3 Code render chat.

The tidepool palette maps a neovim theme of the same name by role: strings olive, numbers and inline code pine, commands iris, builtins foam, paths gold, links mint.

Development

claude plugin validate .
npx -p typescript tsc -p .   # after the engine has laid .claude-plugin/types
claude plugin test .         # tests/*.test.ts, run in the engine's own sandbox
LC_ALL=C grep -rn '[^ -~]' hooks/   # must print nothing

scripts/check.sh runs all four and checks that both manifests carry the same version. scripts/demo-dump.sh before|after writes the text dumps DEMO.md compares, from tests/demo.test.ts. bun scripts/show.ts paints the fixtures before and after in the terminal, and bun scripts/readme-shots.ts shoots the palette screenshots above with headless Chrome; both draw through scripts/paint.ts. CI runs it on every push and pull request, without tsc: the types only exist once the engine has loaded the plugin.

Every non-ASCII glyph is built from a code point in hooks/glyphs.ts. Literals outside ASCII are forbidden in hooks/: the tool path that writes files has dropped private-use glyphs before.

License

MIT

Source 14 files
hooks/register.ts 778 lines
1import { atom, read, update } from 'claude-code'
2import type { Elements, EngineInterface, RenderElement, Register } from 'claude-code'
3
4import type { GlassAgent, GlassCall, GlassPrompt, GlassServerTool, GlassTurn } from '../types'
5import { MAX_PAINTED_LINES, cleanHint, renderHint, clockCells, fmtToolTime, isEditTool, toolText, setCwd, renderAgentLaunch, renderBand, renderBashResult, renderDiff, renderEventRow, renderGroupRow, renderMessageRow, renderNoOutput, renderServerToolRows, renderSkillLoad, renderToolError, renderToolOutput, renderTreeRow, renderUserRow } from './chrome'
6import type { ChangedFile, Hunk } from './chrome'
7import { G } from './glyphs'
8import { parseMarkdown } from './markdown'
9import type { Block } from './markdown'
10import { PALETTES, paletteNameOf, paletteNamed } from './palette'
11import type { Palette, PaletteName } from './palette'
12import { themeFileName, themeFor, themeJson, themeSetting } from './theme'
13import { writeIntent } from './prose'
14import { renderReply } from './render'
15
16// The turns this session, newest last. A user row finds its own turn in
17// here: a `read` while a render hook runs subscribes that row, so every
18// `update` draws every user row again, and each must still find its data.
19const turns = atom({ plugin: 'glass', key: 'turns' } as const, [] as GlassTurn[])
20// the prompts the person submitted, newest last: a user row finds its turn
21// by text, and the assistant header appears once the turn starts
22const prompts = atom({ plugin: 'glass', key: 'prompts' } as const, [] as GlassPrompt[])
23// every main-loop call by turn: the dots line, the tree's times, and which
24// rows a folded turn hides
25const calls = atom({ plugin: 'glass', key: 'calls' } as const, {} as Record<string, GlassCall[]>)
26// subagents still running, for the band above the prompt
27const agents = atom({ plugin: 'glass', key: 'agents' } as const, [] as GlassAgent[])
28const band = atom({ plugin: 'glass', key: 'band' } as const, 'open' as 'open' | 'closed')
29// the main-loop turn now running, or null between turns. State, not module
30// memory: a hot reload mid-turn rebuilds the module but the host keeps this,
31// so an agent finishing inside that turn is not mistaken for one that
32// finished after it (review finding, 0.5.1)
33const liveTurn = atom({ plugin: 'glass', key: 'liveTurn' } as const, null as string | null)
34
35const HISTORY = 48
36// finished replies whose parse is kept for their redraws
37const PARSED_MAX = 64
38const ANSWER_MAX = 20000
39
40const ESC = String.fromCodePoint(0x1b)
41// the engine shows this many output lines before folding the rest behind ctrl+o
42// tools whose row never carries a body: a run of them packs without air rows
43const COMPACT = new Set(['Read'])
44
45// Live things, ticked once a second: main-loop calls still running (their
46// row's clock is a Raster the ticker blits, no redraw) and subagents still
47// running (the status line under the prompt). Module state, read by no
48// render hook, so a tick redraws nothing in the transcript (2026-10-04).
49const liveCalls = new Map<string, { tool: string; t0: number }>()
50let ticker: { cancel: () => void } | null = null
51
52async function tick($: EngineInterface, p: Palette): Promise<void> {
53  const now = await $.clock.now()
54  for (const [id, c] of liveCalls) {
55    void $.ui.blit({ requestId: id, key: 'clock', cells: clockCells(now - c.t0, p.meta) }).catch(() => undefined)
56  }
57  // nothing runs: the ticker stops (no status line: the owner found it noise
58  // under the prompt, 2026-10-04)
59  if (liveCalls.size === 0) {
60    ticker?.cancel()
61    ticker = null
62  }
63}
64
65// A native notification for what the engine stays silent on (0.5.0): the
66// engine's own idle notification covers a finished turn, so glass never
67// notifies at turn end. On an engine without `$.ui.notify`, or a channel
68// that did not send, the text is a toast instead. Never called from a
69// render hook, a timer, or on hearing a notification.
70// `$.ui.notify` is typed from 2.1.295 on; the call is spelled at the call
71// site (the validator asks for `$.noun.event(...)`), typed through a cast of
72// `$`, and an engine without it throws into the toast fallback.
73type Notifier = { ui: { notify: (text: string, options?: { title?: string }) => Promise<{ isSent: boolean }> } }
74async function notifyPerson($: EngineInterface, text: string): Promise<void> {
75  try {
76    const r = await ($ as unknown as Notifier).ui.notify(text, { title: 'glass' })
77    if (r.isSent) return
78  } catch {
79    // no notify on this engine, or the channel failed: the toast below
80  }
81  try {
82    $.ui.toast(text)
83  } catch {
84    // a notification is never worth a failed hook
85  }
86}
87
88// Puts an agent's transcript in the main view, or the main conversation
89// back (0.10.0). `$.ui.view` is typed from 2.1.300 on; the call is spelled
90// at the call site through a cast of `$`, as notifyPerson's is (the
91// validator refuses `$.ui` bound to a value). A `deny` (the agent is gone,
92// the view moved, no view on this surface) and an engine without the method
93// both end in a toast: a press is never worth a failed hook.
94type Viewer = { ui: { view: (v: { agentId?: string }) => Promise<{ deny?: string } | undefined> } }
95async function showView($: EngineInterface, v: { agentId?: string }): Promise<void> {
96  let text: string | null = null
97  try {
98    const r = await ($ as unknown as Viewer).ui.view(v)
99    if (r?.deny) text = `glass: ${r.deny}`
100  } catch {
101    text = 'glass: viewing an agent needs Claude Code 2.1.300 or newer'
102  }
103  if (text === null) return
104  try {
105    $.ui.toast(text)
106  } catch {
107    // a toast is never worth a failed hook
108  }
109}
110
111// Writes a palette's theme to ~/.claude/themes/glass-<palette>.json and
112// selects it (0.5.0). The one file glass writes outside its own folder:
113// the directory comes from HOME, the name from the closed palette list, the
114// content is serialised from hex-checked values. An existing entry under
115// that name that is not a regular file (a link, a directory) is left alone.
116// The owner's own theme files are never touched. Returns the line to show.
117// The engine prefixes a command's answer with the plugin's name, so the
118// lines carry none. The engine's `theme` row takes only its built-in names
119// from a plugin (seen 2.1.296: `takes one of: auto, dark, light, ...`), so
120// the select step is tried and, when refused, the answer names the one
121// settings.json line that selects a custom theme.
122async function installTheme($: EngineInterface, name: PaletteName): Promise<string> {
123  const home = await $.env.get('HOME')
124  if (!home || !home.startsWith('/')) return 'HOME is not set, so no theme was written'
125  const dir = `${home}/.claude/themes`
126  const file = themeFileName(name)
127  const shown = `~/.claude/themes/${file}`
128  try {
129    const hit = (await $.fs.list(dir)).find(x => x.name === file)
130    if (hit && (hit.isLink || hit.kind !== 'file')) return `${shown} is not a regular file; nothing written`
131  } catch {
132    // no themes directory yet: the write creates it
133  }
134  try {
135    await $.fs.write(`${dir}/${file}`, themeJson(themeFor(PALETTES[name], name)))
136  } catch {
137    return `could not write ${shown}`
138  }
139  const setting = themeSetting(name)
140  const byHand = `wrote ${shown}. A plugin cannot select a custom theme, so pick glass-${name} in /theme.`
141  try {
142    const r = await $.config.set({ key: 'theme', value: setting })
143    if (r.deny) return byHand
144  } catch {
145    return byHand
146  }
147  return `theme glass-${name} on (${shown})`
148}
149
150// A Bash call's body as glass draws it, or null where the engine's stays.
151// Drawn under the ToolUse row from its own `output` (2026-10-04): calls run
152// in parallel drew their row with no ToolResult under it, so the body went
153// missing; the ToolResult row then draws nothing where this is non-null.
154function bashBody(t: Elements['terminal'], p: Palette, output: unknown, isErrored: boolean, cols: number): RenderElement | null {
155  if (isErrored) {
156    if (typeof output !== 'string' || output.trim() === '') return null
157    return renderToolOutput(t, p, output.replace(/\s+$/, '').split('\n'), { columns: cols, maxLines: MAX_PAINTED_LINES })
158  }
159  const out = output as { stdout?: unknown; stderr?: unknown; interrupted?: unknown; bashEditDiff?: unknown } | undefined
160  if (!out || typeof out !== 'object' || typeof out.stdout !== 'string' || out.interrupted === true) return null
161  const stderr = typeof out.stderr === 'string' ? out.stderr : ''
162  const text = [out.stdout, stderr].filter(s => s.trim() !== '').join('\n').replace(/\s+$/, '')
163  const lines = text === '' ? [] : text.split('\n')
164  const diff = out.bashEditDiff as { files?: unknown; moreFiles?: unknown } | undefined
165  const files = Array.isArray(diff?.files)
166    ? (diff!.files as ChangedFile[]).filter(f => f && typeof f.filePath === 'string' && Array.isArray(f.hunks)).map(f => ({ ...f, hunks: f.hunks.filter(h => h && typeof h.oldStart === 'number' && typeof h.newStart === 'number' && Array.isArray(h.lines)) }))
167    : []
168  if (files.length > 0) {
169    const moreFiles = typeof diff?.moreFiles === 'number' ? diff.moreFiles : 0
170    return renderBashResult(t, p, lines, files, { maxLines: MAX_PAINTED_LINES, moreFiles, columns: cols })
171  }
172  if (text === '') return renderNoOutput(t, p)
173  if (text.includes(ESC)) return null
174  return renderToolOutput(t, p, lines, { columns: cols, maxLines: MAX_PAINTED_LINES })
175}
176
177// one main-loop call recorded under its turn, replacing an earlier record
178// of the same id
179async function setCall($: EngineInterface, turnId: string, call: GlassCall) {
180  await update($, calls, r => {
181    const record = { ...(r ?? {}) }
182    const list = record[turnId] ?? []
183    const i = list.findIndex(c => c.id === call.id)
184    record[turnId] = i < 0 ? [...list, call] : [...list.slice(0, i), call, ...list.slice(i + 1)]
185    return record
186  })
187}
188
189export const register: Register = (on, options) => {
190  const opts = (options ?? {}) as { palette?: unknown; notify?: unknown }
191  // the palette follows /config live: every hook reads this binding at
192  // draw time, and the config.set hook below swaps it (rows already drawn
193  // keep their colors until something redraws them)
194  let palette = paletteNamed(opts.palette)
195  let paletteName = paletteNameOf(opts.palette)
196  // notifications (0.5.0): on unless the option says otherwise; follows /config live
197  let notifyOn = opts.notify !== false
198  // gutter marks are off for a turn whose prompt asked for writing: the
199  // reply is then the thing itself and asks nothing of the reader
200  let marks = true
201  // the slash commands this session has, for the band's `/tasks` hint
202  let commands = new Set<string>()
203  // the names and types of subagents this session spawned: their folded
204  // `Message from` rows hide, since the finished row says the same
205  const spawned = new Set<string>()
206  // Tree rows read these module records, never an atom: a read in a render
207  // hook subscribes the row, and every write then redraws every row of the
208  // turn, which strands duplicate rows above the viewport (2026-10-03).
209  const callTurn = new Map<string, string>()
210  const callMs = new Map<string, number>()
211  // rows of a group the engine unfolded: no ToolResult of their own, so the
212  // ToolUse hook draws an Edit's or a Write's card under the row
213  const grouped = new Set<string>()
214  // each turn's main-loop calls in order, and whether Claude wrote text
215  // since the call before: the air rule below reads both
216  const turnOrder = new Map<string, { id: string; tool: string; afterText: boolean }[]>()
217  let textSinceCall = false
218  // /fold and /expand: module state like the records above, so a render
219  // hook reads them without subscribing; a hot reload opens everything again
220  let foldedTurns = new Set<string>()
221  let expandAllNow = false
222  // the module records keep the turns the atoms keep: past HISTORY turns
223  // the oldest turn's calls go, so a long session does not grow them forever
224  const forgetOldTurns = () => {
225    for (const [old, list] of turnOrder) {
226      if (turnOrder.size <= HISTORY) break
227      turnOrder.delete(old)
228      foldedTurns.delete(old)
229      for (const c of list) {
230        callTurn.delete(c.id)
231        callMs.delete(c.id)
232        grouped.delete(c.id)
233      }
234    }
235  }
236  // a finished message redraws on every /fold, resize and palette change:
237  // its parse is kept, the newest few by text
238  const parsed = new Map<string, Block[]>()
239  const parse = (text: string): Block[] => {
240    const hit = parsed.get(text)
241    if (hit) return hit
242    const blocks = parseMarkdown(text)
243    parsed.set(text, blocks)
244    if (parsed.size > PARSED_MAX) parsed.delete(parsed.keys().next().value!)
245    return blocks
246  }
247
248  // the live main-loop turn; a hot reload resets it, which only affects the
249  // totals of the turn that reloaded
250  const live = {
251    turnId: '',
252    // true from turn.start to the main loop's turn.complete: an agent that
253    // finishes outside that window finished after its turn (0.5.0)
254    active: false,
255    startedAt: 0,
256    tools: 0,
257    edits: 0,
258    failed: 0,
259    lastToolId: null as string | null,
260    lastFailedTool: null as string | null,
261    costStart: null as number | null,
262    // tools the API ran inside this turn's requests (0.5.0)
263    serverTools: [] as GlassServerTool[],
264  }
265
266  on('config.set', { key: 'glass.palette' }, async ($, e, next) => {
267    const result = await next(e)
268    palette = paletteNamed(e.value)
269    paletteName = paletteNameOf(e.value)
270    // a glass theme follows the palette (0.5.0); any other theme is left alone
271    try {
272      const row = (await $.config.list()).find(r => r.key === 'theme')
273      if (typeof row?.value === 'string' && row.value.startsWith('custom:glass-')) $.ui.toast('glass: ' + (await installTheme($, paletteName)))
274    } catch {
275      // the theme stays as it was
276    }
277    return result
278  })
279
280  on('command.run', { command: 'glass-theme' }, async $ => ({ text: await installTheme($, paletteName) }))
281
282  on('config.set', { key: 'glass.notify' }, async ($, e, next) => {
283    const result = await next(e)
284    notifyOn = e.value !== false
285    return result
286  })
287
288  on('session.start', async ($, e, next) => {
289    // 0.4.2 to 0.4.5 pinned a status line; clear one a reload left behind
290    $.ui.status(undefined)
291    try {
292      setCwd(await $.session.cwd())
293    } catch {
294      setCwd('')
295    }
296    try {
297      commands = new Set((await $.command.list()).map(c => c.name))
298    } catch {
299      commands = new Set()
300    }
301    await $.command.register({ name: 'fold', description: 'glass: fold the tool trees of every finished turn' })
302    await $.command.register({ name: 'unfold', description: 'glass: open the tool trees of every turn' })
303    await $.command.register({ name: 'expand', description: 'glass: open every folded run of reads and searches' })
304    await $.command.register({ name: 'collapse', description: 'glass: fold the runs of reads and searches again' })
305    await $.command.register({ name: 'glass-theme', description: 'glass: write a theme for the current palette to ~/.claude/themes and select it' })
306    return next(e)
307  })
308  on('command.run', { command: 'expand' }, async $ => {
309    expandAllNow = true
310    $.ui.invalidate('ui.render')
311    return { text: 'Every folded run is open. /collapse folds them again.' }
312  })
313  on('command.run', { command: 'collapse' }, async $ => {
314    expandAllNow = false
315    $.ui.invalidate('ui.render')
316    return { text: 'Runs of reads and searches fold again.' }
317  })
318
319  // ---- folding on demand -------------------------------------------------
320  on('command.run', { command: 'fold' }, async $ => {
321    const ids = ((await read($, turns)) ?? []).map(h => h.turnId)
322    foldedTurns = new Set(ids.slice(-HISTORY))
323    $.ui.invalidate('ui.render')
324    return { text: ids.length ? `Folded ${ids.length} turn${ids.length === 1 ? '' : 's'}. /unfold opens them again.` : 'Nothing to fold yet.' }
325  })
326  on('command.run', { command: 'unfold' }, async $ => {
327    foldedTurns = new Set()
328    $.ui.invalidate('ui.render')
329    return { text: 'Every turn is open.' }
330  })
331
332  // ---- reply renderer ----------------------------------------------------
333  on('ui.render', { component: 'AssistantMessage' }, ($, e, next) => {
334    if (e.surface !== 'terminal') return next(e)
335    const text = e.props.text
336    if (text.trim() === '') return next(e)
337    const t = $.ui.resolve(e)
338    // no bullet: the assistant header under the user row carries it
339    return renderReply(t, parse(text), palette, {
340      first: e.props.isFirstOfReply,
341      columns: e.viewport?.columns ?? 80,
342      marks,
343      // a compaction summary (read-only flag, passed on untouched; typed from
344      // 2.1.295 on, so read loosely for older type layouts)
345      summary: (e.props as { isSummary?: unknown }).isSummary === true,
346    })
347  })
348
349  // ---- user row, assistant header, dots line -----------------------------
350  on('ui.render', { component: 'UserMessage' }, async ($, e, next) => {
351    if (e.surface !== 'terminal') return next(e)
352    const t = $.ui.resolve(e)
353    const kind = e.props.origin.kind
354    // a background task's notification: one tree row, the body under it
355    // when the view is expanded (a short one is expanded from the start)
356    if (kind === 'task-notification') return renderEventRow(t, palette, e.requestId, e.props.text, e.props.task, e.props.isExpanded)
357    // any other row (another agent's message, a scheduled trigger, a
358    // bridge): one muted row; ctrl+o keeps the engine's body
359    if (kind !== 'composer') {
360      if (e.props.isExpanded) return next(e)
361      if (spawned.has(e.props.from?.name ?? '')) return t.Box({ display: 'none', children: [] })
362      return renderMessageRow(t, palette, e.props.from?.name ?? kind)
363    }
364    const text = e.props.text
365    if (text.trim() === '') return next(e)
366    const known = [...((await read($, prompts)) ?? [])].reverse().find(p => p.text === text) ?? null
367    const turnId = known?.turnId ?? null
368    let turn = null
369    if (turnId) {
370      const list = ((await read($, calls)) ?? {})[turnId] ?? []
371      const done = ((await read($, turns)) ?? []).find(h => h.turnId === turnId) ?? null
372      turn = {
373        turnId,
374        calls: list,
375        done,
376      }
377    }
378    const answer = turn?.done?.answer ?? ''
379    return renderUserRow(t, palette, {
380      text,
381      submittedAt: known?.submittedAt ?? null,
382      startedAt: known?.startedAt ?? null,
383      turn,
384      columns: e.viewport?.columns ?? 80,
385      // 0.5.0 (gated on the live press retest): the chevron folds this one
386      // turn, Copy takes the finished answer
387      ...(turnId
388        ? {
389            folded: foldedTurns.has(turnId),
390            onFold: () => {
391              if (foldedTurns.has(turnId)) foldedTurns.delete(turnId)
392              else foldedTurns.add(turnId)
393              $.ui.invalidate('ui.render')
394            },
395            onCopy: answer ? (press: { surface: 'terminal' | 'desktop' | 'vscode' | 'mobile' }) => void $.ui.copy({ text: answer, surface: press.surface }).catch(() => undefined) : null,
396          }
397        : {}),
398    })
399  })
400
401  // ---- tool tree ---------------------------------------------------------
402  on('ui.render', { component: 'ToolUse' }, async ($, e, next) => {
403    if (e.surface !== 'terminal') return next(e)
404    const id = e.props.tool_use_id
405    const turnId = callTurn.get(id)
406    // a folded turn hides its rows; a row of a turn glass never saw stays
407    if (turnId && foldedTurns.has(turnId)) return $.ui.resolve(e).Box({ display: 'none', children: [] })
408    const t = $.ui.resolve(e)
409    const order = turnId ? turnOrder.get(turnId) : undefined
410    const at = order ? order.findIndex(c => c.id === id) : -1
411    // Air above every row, except a bare row that continues a run of the
412    // same bodiless tool with no prose between (Read, Read, Read). A row
413    // after a body, a card, prose or another tool keeps its air (2026-10-04).
414    const air = !(order && at > 0 && COMPACT.has(e.props.tool) && order[at - 1]!.tool === e.props.tool && !order[at]!.afterText)
415    const started = liveCalls.get(id)
416    const clock = e.props.isRunning && started ? clockCells((await $.clock.now()) - started.t0, palette.meta) : undefined
417    const row = renderTreeRow(t, palette, e.props, { durationMs: callMs.get(id) ?? null, air, ...(clock ? { clock } : {}) })
418    if (grouped.has(id) && (e.props.tool === 'Edit' || e.props.tool === 'Write') && !e.props.isRunning && !e.props.isErrored) {
419      const card = editCard(t, palette, e.props.output, e.props.input, e.viewport?.columns ?? 80)
420      if (card) return t.Box({ flexDirection: 'column', children: [row, card] })
421    }
422    if (e.props.tool !== 'Bash' || e.props.isRunning || e.props.output === undefined) return row
423    const body = bashBody(t, palette, e.props.output, e.props.isErrored, e.viewport?.columns ?? 80)
424    return body ? t.Box({ flexDirection: 'column', children: [row, body] }) : row
425  })
426
427  // the engine's folded run of reads and searches: one tree row; /expand
428  // opens every group where it is
429  on('ui.render', { component: 'ToolGroup' }, async ($, e, next) => {
430    if (e.surface !== 'terminal') return next(e)
431    if (e.props.isExpanded) {
432      remember(grouped, e.props.calls)
433      return next(e)
434    }
435    const first = e.props.calls.find((c: { tool_use_id?: string }) => typeof c.tool_use_id === 'string')
436    const turnId = first?.tool_use_id ? callTurn.get(first.tool_use_id) ?? null : null
437    if (turnId && foldedTurns.has(turnId)) return $.ui.resolve(e).Box({ display: 'none', children: [] })
438    const id = e.requestId
439    // open after /expand, or on its own when a call in it failed: a red
440    // mark must never hide behind a count
441    const failed = e.props.calls.some((c: { isErrored?: boolean; isInterrupted?: boolean }) => c.isErrored || c.isInterrupted)
442    if (expandAllNow || failed) {
443      remember(grouped, e.props.calls)
444      return next({ ...e, props: { ...e.props, isExpanded: true } })
445    }
446    const t = $.ui.resolve(e)
447    return renderGroupRow(t, palette, e.props.calls, {
448      isActive: e.props.isActive,
449      key: `expand:${id}`,
450    })
451  })
452
453  // Bash output body, painted. The engine
454  // strips escape codes from a rewritten result, so the body is drawn as
455  // Text, and only when it is short enough that the engine would show it
456  // whole: longer output keeps the engine's collapsed body and ctrl+o.
457  on('ui.render', { component: 'ToolResult' }, async ($, e, next) => {
458    if (e.surface !== 'terminal') return next(e)
459    const turnId = callTurn.get(e.props.tool_use_id)
460    if (turnId && foldedTurns.has(turnId)) return $.ui.resolve(e).Box({ display: 'none', children: [] })
461    // a failed call's reason on the trunk; a failed Bash's body is the ToolUse row's
462    if (e.props.isErrored && e.props.tool !== 'Bash' && typeof e.props.output === 'string') {
463      const reason = e.props.output.replace(/<\/?tool_use_error>/g, '')
464      if (reason.trim() !== '') return renderToolError($.ui.resolve(e), palette, reason)
465    }
466    // an Edit's or a Write's diff, drawn as glass draws it (owner's request, 2026-10-03)
467    if ((e.props.tool === 'Edit' || e.props.tool === 'Write') && !e.props.isErrored) {
468      return editCard($.ui.resolve(e), palette, e.props.output, (e.props as { input?: unknown }).input, e.viewport?.columns ?? 80) ?? next(e)
469    }
470    // a backgrounded agent: one trunked line in place of the engine's body
471    if (e.props.tool === 'Agent' || e.props.tool === 'Task') {
472      const status = (e.props.output as { status?: unknown } | undefined)?.status
473      if (status === 'async_launched' || status === 'remote_launched') return renderAgentLaunch($.ui.resolve(e), palette, status === 'remote_launched')
474      return next(e)
475    }
476    // a loaded skill: one trunked line in place of the engine's body, whose
477    // corner bracket sat off the trunk (2026-10-09)
478    if (e.props.tool === 'Skill' && !e.props.isErrored) return renderSkillLoad($.ui.resolve(e), palette, e.props.output)
479    if (e.props.tool !== 'Bash') return next(e)
480    // a backgrounded command: the same trunked line, not the engine's corner
481    // bracket, which sat off the trunk (2026-10-05)
482    if (typeof (e.props.output as { backgroundTaskId?: unknown } | undefined)?.backgroundTaskId === 'string' && !e.props.isErrored) return renderAgentLaunch($.ui.resolve(e), palette, false)
483    // the ToolUse row draws the body glass owns; this row draws nothing then
484    const body = bashBody($.ui.resolve(e), palette, e.props.output, e.props.isErrored, e.viewport?.columns ?? 80)
485    return body ? $.ui.resolve(e).Box({ display: 'none', children: [] }) : next(e)
486  })
487
488  // ---- the turn's bookkeeping --------------------------------------------
489  on('prompt.submit', async ($, e, next) => {
490    marks = !writeIntent(e.text)
491    const now = await $.clock.now()
492    await update($, prompts, ps => [...(ps ?? []), { text: e.text, submittedAt: now, startedAt: null, turnId: null }].slice(-HISTORY))
493    return next(e)
494  })
495
496  on('turn.start', async ($, e, next) => {
497    // 2.1.299: turn.start also fires for subagents' and teammates' turns; the
498    // live turn is the main loop's (the typings gain agentId with that engine)
499    if ((e as { agentId?: string }).agentId) return next(e)
500    live.turnId = e.turnId
501    live.active = true
502    await update($, liveTurn, () => e.turnId)
503    live.startedAt = await $.clock.now()
504    live.tools = 0
505    live.edits = 0
506    live.failed = 0
507    live.lastToolId = null
508    live.lastFailedTool = null
509    live.serverTools = []
510    live.costStart = null
511    try {
512      live.costStart = (await $.session.usage()).cost?.usd ?? null
513    } catch {
514      live.costStart = null
515    }
516    const { turnId, startedAt } = live
517    // the newest prompt with this text gets its turn, which draws the
518    // assistant header and the dots line under the user row
519    await update($, prompts, ps => {
520      const list = [...(ps ?? [])]
521      for (let i = list.length - 1; i >= 0; i--) {
522        const p = list[i]!
523        if (p.text === e.text && p.turnId === null) {
524          list[i] = { ...p, startedAt, turnId }
525          break
526        }
527      }
528      return list
529    })
530    await update($, calls, r => {
531      const entries = Object.entries(r ?? {}).filter(([k]) => k !== turnId).slice(-(HISTORY - 1))
532      return Object.fromEntries([...entries, [turnId, []]])
533    })
534    // a new turn always shows its tree
535    foldedTurns.delete(turnId)
536    forgetOldTurns()
537    return next(e)
538  })
539
540  on('tool.call', async ($, e, next) => {
541    const main = !e.agentId
542    const id = e.tool_use_id ?? ''
543    const turnId = live.turnId
544    if (main) {
545      live.tools += 1
546      if (id) live.lastToolId = id
547      if (id && turnId) callTurn.set(id, turnId)
548      if (id && turnId) turnOrder.set(turnId, [...(turnOrder.get(turnId) ?? []).filter(c => c.id !== id), { id, tool: e.tool, afterText: textSinceCall }])
549      textSinceCall = false
550      if (id && turnId) await setCall($, turnId, { id, tool: e.tool, status: 'running', ms: null })
551      if (id) liveCalls.set(id, { tool: e.tool, t0: await $.clock.now() })
552      if (!ticker) ticker = $.clock.every(1000, () => void tick($, palette))
553    } else if (e.agentId) {
554      const agentId = e.agentId
555      const stage = toolText(e.tool)
556      const args = e as unknown as Record<string, unknown>
557      const file = typeof args.file_path === 'string' ? args.file_path : typeof args.path === 'string' ? args.path : null
558      void update($, agents, as => (as ?? []).map(a => (a.agentId === agentId ? { ...a, stage, file: file ?? a.file } : a)))
559    }
560    if (isEditTool(e.tool)) live.edits += 1
561    const t0 = await $.clock.now()
562    let r
563    try {
564      r = await next(e)
565    } finally {
566      if (main && id) liveCalls.delete(id)
567    }
568    if (main) {
569      const ms = (await $.clock.now()) - t0
570      if (r.isError) {
571        live.failed += 1
572        live.lastFailedTool = e.tool
573      }
574      if (id) callMs.set(id, ms)
575      if (id) liveCalls.delete(id)
576      if (id && turnId) await setCall($, turnId, { id, tool: e.tool, status: r.isError ? 'failed' : 'ok', ms })
577    }
578    return r
579  })
580
581  // a subagent's model requests: its tokens and effort for the band. The
582  // event streams, so the hook is a generator relaying every chunk; the
583  // stop chunk carries the usage.
584  on('turn.step', async function* ($, e, next) {
585    const stream = next(e)
586    let usage: { input_tokens: number; output_tokens: number; cache_read_input_tokens: number; cache_creation_input_tokens: number } | null = null
587    let step = await stream.next()
588    while (!step.done) {
589      const chunk = step.value
590      if (chunk.kind === 'stop') usage = chunk.usage
591      if (chunk.kind === 'text' && !e.agentId) textSinceCall = true
592      yield chunk
593      step = await stream.next()
594    }
595    // tools the API ran inside this request (the advisor): the step's result
596    // lists them; the main loop's are drawn after the reply (0.5.0)
597    if (!e.agentId) {
598      const result = step.value as unknown as { serverToolUses?: ReadonlyArray<{ id: string; name: string; startedAt: number; endedAt?: number }> } | undefined
599      for (const s of result?.serverToolUses ?? []) {
600        if (typeof s.id !== 'string' || typeof s.name !== 'string' || typeof s.startedAt !== 'number') continue
601        if (live.serverTools.some(x => x.id === s.id)) continue
602        live.serverTools.push({ id: s.id, name: s.name, startedAt: s.startedAt, ...(typeof s.endedAt === 'number' ? { endedAt: s.endedAt } : {}) })
603      }
604    }
605    if (e.agentId) {
606      const agentId = e.agentId
607      const effort = e.effort === undefined ? '' : String(e.effort)
608      const u = usage
609      const used = u ? u.input_tokens + u.cache_read_input_tokens + u.cache_creation_input_tokens + u.output_tokens : 0
610      void update($, agents, as => (as ?? []).map(a => (a.agentId === agentId ? { ...a, effort: effort || a.effort, tokens: a.tokens + used } : a)))
611    }
612    return step.value
613  })
614
615  on('agent.spawn', async ($, e, next) => {
616    const r = await next(e)
617    if (e.subagentType) spawned.add(e.subagentType)
618    if (typeof (e as { name?: unknown }).name === 'string') spawned.add((e as { name: string }).name)
619    if (r.agentId) {
620      const agent: GlassAgent = {
621        agentId: r.agentId,
622        description: e.description,
623        kind: e.subagentType,
624        model: r.model,
625        effort: '',
626        stage: 'thinking' + G.ellipsis,
627        file: '',
628        tokens: 0,
629        startedAt: await $.clock.now(),
630      }
631      await update($, agents, as => [...(as ?? []).filter(a => a.agentId !== agent.agentId), agent])
632    }
633    return r
634  })
635
636  on('turn.complete', async ($, e, next) => {
637    if (e.agentId) {
638      const agentId = e.agentId
639      const done = ((await read($, agents)) ?? []).find(a => a.agentId === agentId)
640      await update($, agents, as => (as ?? []).filter(a => a.agentId !== agentId))
641      // an agent that finished after its turn ended: the engine says nothing,
642      // so glass does (0.5.0); one that finished inside a turn is on screen.
643      // The live turn is read from state, which survives a reload (0.5.1).
644      const mainLive = ((await read($, liveTurn)) ?? null) !== null
645      if (done && !mainLive && notifyOn) {
646        const ms = (await $.clock.now()) - done.startedAt
647        const label = done.description.length > 60 ? done.description.slice(0, 59) + G.ellipsis : done.description
648        await notifyPerson($, ms >= 100 ? `${label} ${G.middot} ${fmtToolTime(ms)}` : label)
649      }
650      return next(e)
651    }
652    const u = e.usage
653    let costUsd: number | null = null
654    if (live.costStart !== null) {
655      try {
656        const now = (await $.session.usage()).cost?.usd
657        if (typeof now === 'number') costUsd = Math.max(0, now - live.costStart)
658      } catch {
659        costUsd = null
660      }
661    }
662    const finishedAt = await $.clock.now()
663    const turn: GlassTurn = {
664      turnId: e.turnId,
665      durationMs: e.durationMs,
666      tools: live.tools,
667      edits: live.edits,
668      failed: live.failed,
669      inTokens: u ? u.input_tokens + u.cache_read_input_tokens + u.cache_creation_input_tokens : 0,
670      cacheTokens: u ? u.cache_read_input_tokens : 0,
671      outTokens: u ? u.output_tokens : 0,
672      costUsd,
673      lastToolId: live.lastToolId,
674      answer: e.answer.slice(0, ANSWER_MAX),
675      startedAt: live.startedAt || finishedAt - e.durationMs,
676      finishedAt,
677      ...(live.serverTools.length ? { serverTools: [...live.serverTools] } : {}),
678    }
679    await update($, turns, h => [...(h ?? []), turn].slice(-HISTORY))
680    live.active = false
681    await update($, liveTurn, () => null)
682    // a turn that ended with failed calls: the engine's idle notification
683    // does not say so (0.5.0)
684    if (live.failed > 0 && notifyOn) {
685      await notifyPerson($, `${live.failed} ${live.failed === 1 ? 'call' : 'calls'} failed${live.lastFailedTool ? ` ${G.middot} ${toolText(live.lastFailedTool)}` : ''}`)
686    }
687    // a finished turn stays open: the tree is the evidence of what the
688    // prompt did (owner's call, 2026-10-03; /fold tucks old turns away)
689    return next(e)
690  })
691
692  // ---- footer ------------------------------------------------------------
693  // The engine's `Baked for 12s` line is dropped by request: the dots line
694  // under the user row carries the counts, and the turn's cost and
695  // tokens stay in state for anything that wants them later.
696  on('ui.render', { component: 'TurnDuration' }, async ($, e, next) => {
697    if (e.surface !== 'terminal') return next(e)
698    const t = $.ui.resolve(e)
699    // the one per-turn row after the reply: it carries the tools the API ran
700    // itself, when the turn had any (0.5.0). It finds its turn by duration,
701    // as the footer did; this read subscribes one row per turn.
702    const list = (await read($, turns)) ?? []
703    let mine: GlassTurn | null = null
704    for (let i = list.length - 1; i >= 0; i--) {
705      if (list[i]!.durationMs === e.props.durationMs) {
706        mine = list[i]!
707        break
708      }
709    }
710    const tools = mine?.serverTools ?? []
711    if (tools.length === 0) return t.Box({ display: 'none', children: [] })
712    return renderServerToolRows(t, palette, tools)
713  })
714
715  // ---- the hint line under the prompt: key reminders dropped ---------------
716  on('ui.render', { component: 'PromptHint' }, ($, e, next) => {
717    if (e.surface !== 'terminal') return next(e)
718    const h = cleanHint(e.props.hint)
719    return h ? renderHint($.ui.resolve(e), palette, h) : next(e)
720  })
721
722  // ---- spinner: the action count while tools run -------------------------
723  on('ui.render', { component: 'Spinner' }, ($, e, next) => {
724    if (e.surface !== 'terminal' || e.props.mode !== 'tool-use' || live.tools === 0) return next(e)
725    const n = live.tools
726    return next({ ...e, props: { ...e.props, suffix: `${G.ellipsis} ${G.middot} ${n} ${n === 1 ? 'action' : 'actions'}` } })
727  })
728
729  // ---- background band ---------------------------------------------------
730  on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
731    if (e.surface !== 'terminal' || e.props.hasSurvey) return next(e)
732    // The band is one site for every plugin: what the plugins beneath draw
733    // stays, under the agents' frame, and alone when no agent runs.
734    const below = await next(e)
735    const list = (await read($, agents)) ?? []
736    if (list.length === 0) return below
737    const t = $.ui.resolve(e)
738    const state = (await read($, band)) ?? 'open'
739    // 0.10.0: `view` puts the agent's transcript in the main view and `back`
740    // returns, through `$.ui.view` (engine 2.1.300) in showView. The site
741    // says which agent is in view.
742    const frame = renderBand(t, palette, {
743      agents: list,
744      now: await $.clock.now(),
745      columns: e.props.bodyColumns,
746      open: state === 'open',
747      onToggle: () => void update($, band, s => (s === 'closed' ? 'open' : 'closed')),
748      tasksCommand: commands.has('tasks') ? 'tasks' : commands.has('bashes') ? 'bashes' : null,
749      viewing: e.props.view?.agentId ?? null,
750      onView: (agentId: string) => void showView($, { agentId }),
751      onBack: () => void showView($, {}),
752    })
753    return t.Box({ flexDirection: 'column', children: [frame, below] })
754  })
755}
756
757/** Keeps the tool_use_ids of an unfolded group's calls. */
758function remember(ids: Set<string>, calls: ReadonlyArray<{ tool_use_id?: string }>): void {
759  for (const c of calls) if (typeof c.tool_use_id === 'string') ids.add(c.tool_use_id)
760}
761
762/**
763 * An Edit's or a Write's result as glass's diff card, null when there is
764 * nothing to draw. A Write that created the file has no patch: its whole
765 * content draws as added lines under `Created`.
766 */
767function editCard(t: Elements['terminal'], palette: Palette, output: unknown, input: unknown, columns: number): RenderElement | null {
768  const out = output as { structuredPatch?: unknown; filePath?: unknown; type?: unknown; content?: unknown } | undefined
769  const patch = out?.structuredPatch
770  const patched = Array.isArray(patch) ? (patch as Hunk[]).filter(h => h && typeof h.oldStart === 'number' && typeof h.newStart === 'number' && Array.isArray(h.lines)) : []
771  const created = patched.length === 0 && out?.type === 'create' && typeof out.content === 'string'
772  const hunks = created ? [{ oldStart: 0, newStart: 1, lines: (out.content as string).replace(/\n$/, '').split('\n').map(l => `+${l}`) }] : patched
773  if (hunks.length === 0) return null
774  const args = input as { file_path?: unknown } | undefined
775  const path = typeof out?.filePath === 'string' ? out.filePath : typeof args?.file_path === 'string' ? args.file_path : ''
776  return renderDiff(t, palette, hunks, { path, columns, ...(created ? { verb: 'Created' } : {}) })
777}
778
hooks/chrome.ts 1169 lines
1// Turn chrome, following SPEC.md "Turn chrome": the user row with its
2// assistant header and dots line, the tool tree, the folded group, event
3// rows and the background band. One glyph
4// family (glyphs.ts), one ruler (width.ts), one hierarchy rule: bright for
5// the live thing, `meta` for the done thing, `faint` for scaffolding,
6// saturated color on marks only.
7import type { Elements, RenderElement, RenderNode, UiPressArgument } from 'claude-code'
8
9import type { GlassAgent, GlassCall, GlassServerTool, GlassTurn } from '../types'
10import { G } from './glyphs'
11import { codeColor, highlightLine, langOf } from './highlight'
12import type { State } from './highlight'
13import { paintLine } from './output'
14import type { Palette } from './palette'
15import { measure } from './render'
16import { shellSpans } from './shell'
17import { THEME } from './theme'
18import { cellWidth, clipPath } from './width'
19
20type Table = Elements['terminal']
21type Press = (e: UiPressArgument) => void
22
23// the API bounds a Text string at this many characters
24const MAX_TEXT = 10000
25
26const EDIT_TOOLS = new Set(['Edit', 'Write', 'NotebookEdit', 'MultiEdit'])
27export function isEditTool(name: string): boolean {
28  return EDIT_TOOLS.has(name)
29}
30
31// `3:31 PM` in the machine's locale
32const clock = new Intl.DateTimeFormat(undefined, { hour: 'numeric', minute: '2-digit' })
33export function clockTime(ms: number): string {
34  return clock.format(ms)
35}
36
37export function fmtDuration(ms: number): string {
38  const s = Math.round(ms / 1000)
39  if (s < 60) return `${s}s`
40  const m = Math.floor(s / 60)
41  if (m < 60) return `${m}m ${String(s % 60).padStart(2, '0')}s`
42  // an hour on: `2h 05m`, so the clock's seven cells still hold it whole
43  return `${Math.floor(m / 60)}h ${String(m % 60).padStart(2, '0')}m`
44}
45
46// a tool's wall time: tenths under ten seconds, whole seconds after
47export function fmtToolTime(ms: number): string {
48  if (ms < 10_000) return `${(ms / 1000).toFixed(1)}s`
49  return fmtDuration(ms)
50}
51
52export function fmtTokens(n: number): string {
53  if (n < 1000) return String(n)
54  if (n < 10_000) return `${(n / 1000).toFixed(1)}k`
55  if (n < 1e6) return `${Math.round(n / 1000)}k`
56  return `${(n / 1e6).toFixed(1)}M`
57}
58
59// Empryo's rule: three decimals under a cent, two from there
60export function fmtCost(usd: number): string {
61  if (usd < 0.01) return `$${usd.toFixed(3)}`
62  return `$${usd.toFixed(2)}`
63}
64
65// a Text string the API accepts: tab and newline are the only controls
66export function safeText(s: string, max = MAX_TEXT): string {
67  const clean = s.replace(/\r\n?/g, '\n').replace(/[\x00-\x08\x0b-\x1f\x7f]/g, '')
68  return clean.length > max ? clean.slice(0, max - 1) + G.ellipsis : clean
69}
70
71// cut to `n` cells with an ellipsis
72export function clip(s: string, n: number): string {
73  if (cellWidth(s) <= n) return s
74  // no room: nothing, not a lone ellipsis a cell past the edge
75  if (n <= 0) return ''
76  let out = ''
77  for (const ch of s) {
78    if (cellWidth(out + ch) > n - 1) break
79    out += ch
80  }
81  return out + G.ellipsis
82}
83
84// pad or cut to exactly `n` cells
85function fit(s: string, n: number): string {
86  const c = clip(s, n)
87  return c + ' '.repeat(Math.max(0, n - cellWidth(c)))
88}
89
90// a path padded or cut to exactly `n` cells, cut in the middle so the file
91// name stays: `hooks/...render.ts`, not `hooks/rend...`
92function fitPath(s: string, n: number): string {
93  const c = clipPath(s, n)
94  return c + ' '.repeat(Math.max(0, n - cellWidth(c)))
95}
96
97// a row of air above a tree row, with the trunk drawn through it so the
98// tree stays one line (the owner wants a blank between runs, 2026-10-03)
99// Tree rows sit 2 cells in from each edge (owner's request, 2026-10-03:
100// the right column was flush with the terminal's edge), the same 2 the
101// prose measure leaves on the right.
102const TREE_INSET = 2
103function spaced(t: Table, p: Palette, row: RenderElement, air = true): RenderElement {
104  return t.Box({ flexDirection: 'column', marginLeft: TREE_INSET, marginRight: TREE_INSET, children: air ? [t.Text({ color: p.faint, children: [G.pipe] }), row] : [row] })
105}
106
107// the session's directory: paths under it draw relative (`SPEC.md`, not
108// the whole home path); set at session.start, empty draws paths whole
109let cwd = ''
110export function setCwd(dir: string): void {
111  cwd = dir.replace(/\/+$/, '')
112}
113export function rel(path: string): string {
114  return cwd && path.startsWith(cwd + '/') ? path.slice(cwd.length + 1) : path
115}
116
117const plural = (n: number, one: string) => `${n} ${n === 1 ? one : one + 's'}`
118const sep = ` ${G.middot} `
119
120// ---- user row ------------------------------------------------------------
121
122export type TurnView = {
123  turnId: string
124  calls: GlassCall[]
125  /** the finished turn, once it is */
126  done: GlassTurn | null
127}
128
129export type UserRow = {
130  text: string
131  submittedAt: number | null
132  /** when the turn for this prompt began; the assistant header follows once known */
133  startedAt: number | null
134  turn: TurnView | null
135  columns: number
136  /** 0.5.0, gated on the live press retest: the turn's tree is folded */
137  folded?: boolean
138  /** a press folds or unfolds this turn's tree; none, no chevron */
139  onFold?: Press | null
140  /** a press copies the turn's answer; none, no Copy */
141  onCopy?: Press | null
142}
143
144// the dots: one per call in call order, grouped by consecutive tool with a
145// space between groups; `ok` green, `err` red, hollow while running. Past
146// DOTS_MAX calls the first DOTS_SHOWN draw and `+N` in `faint` stands for
147// the rest, so the summary after them is never pushed off the row (45
148// calls filled 80 columns with dots, 2026-10-06); the summary keeps every
149// count, failures included.
150const DOTS_MAX = 16
151const DOTS_SHOWN = 12
152function dots(t: Table, p: Palette, calls: GlassCall[]): RenderNode[] {
153  const out: RenderNode[] = []
154  let prev: string | null = null
155  const shown = calls.length > DOTS_MAX ? calls.slice(0, DOTS_SHOWN) : calls
156  for (const c of shown) {
157    if (prev !== null && c.tool !== prev) out.push(t.Text({ children: [' '] }))
158    prev = c.tool
159    const mark = c.status === 'running' ? G.hollow : c.status === 'failed' ? G.cross : G.disc
160    const color = c.status === 'failed' ? p.err : c.status === 'ok' ? p.ok : p.meta
161    // the dot and its tree row light together under the pointer
162    out.push(t.Text({ color, hover: { scope: callScope(c.id), backgroundColor: p.rowHover }, children: [mark] }))
163  }
164  if (shown.length < calls.length) out.push(t.Text({ color: p.faint, children: [` +${calls.length - shown.length}`] }))
165  return out
166}
167
168// `Bash x3 . Read x2`: the tools in first-seen order with their counts
169function toolCounts(calls: GlassCall[]): string {
170  const counts = new Map<string, number>()
171  for (const c of calls) counts.set(c.tool, (counts.get(c.tool) ?? 0) + 1)
172  return [...counts].map(([tool, n]) => (n > 1 ? `${toolText(tool)} ${G.times}${n}` : toolText(tool))).join(sep)
173}
174
175// ---- tool names ----------------------------------------------------------
176
177// MCP tools arrive as `mcp__<server>__<tool>`: the label drops `mcp__` and
178// splits the rest, the server drawn once in `faint` before the name. Servers
179// lose the prefixes Claude Code adds (`plugin_<plugin>_`, `claude_ai_`) and
180// a trailing `_MCP`, and read in kebab case; a name's underscore runs fold
181// to one, or to spaces under NAME_SPACES (owner's request, 2026-10-07:
182// `mcp__figma__get_design_context` read as rules, not a name). The server
183// was `meta` first, which read lighter than the faint subject on water.
184const NAME_SPACES = false
185export type ToolLabel = { server: string | null; name: string }
186export function toolLabel(tool: string): ToolLabel {
187  const m = /^mcp__(.+?)__(.+)$/.exec(tool)
188  if (!m) return { server: null, name: tool.replace(/_+/g, '_') }
189  const server = m[1]!.replace(/^plugin_[^_]+_(?=.)/, '').replace(/^claude_ai_(?=.)/, '').replace(/(?<=.)_mcp$/i, '')
190  const name = NAME_SPACES ? m[2]!.replace(/_+/g, ' ').trim() : m[2]!.replace(/_+/g, '_')
191  return { server: server.toLowerCase().replace(/_+/g, '-'), name: name || m[2]! }
192}
193export function toolText(tool: string): string {
194  const l = toolLabel(tool)
195  return l.server ? `${l.server} ${l.name}` : l.name
196}
197function toolNodes(t: Table, p: Palette, tool: string, bold: boolean): RenderNode[] {
198  const l = toolLabel(tool)
199  const name = t.Text({ color: p.tool, bold, children: [l.name] })
200  return l.server ? [t.Text({ color: p.faint, children: [l.server + ' '] }), name] : [name]
201}
202
203// `<diamond> You . 01:11 PM`, the prompt under it at the measure, then after
204// one blank row the assistant header `<fisheye> Claude . 01:14 PM` and the
205// dots line: the one place a header can sit above both the tool rows and
206// the reply, since the engine fixes the row order. Folded, the dots line
207// reads the tool counts while the turn runs and the totals once it is
208// done.
209export function renderUserRow(t: Table, p: Palette, r: UserRow): RenderElement {
210  const m = measure(r.columns)
211  const rows: RenderElement[] = [
212    // a turn separator: one blank row, a faint rule the measure wide, one
213    // more blank row, so a new prompt stands apart from the reply above
214    // (owner's request, 2026-10-03)
215    // the turn boundary is one titled rule: `<diamond> You . 3:20 PM ---`
216    // to the measure, a blank row above it (proposal 7, 2026-10-04: it
217    // replaces a bare rule with a blank row each side, two rows saved)
218    t.Box({
219      marginTop: 1,
220      children: [
221        t.Text({
222          wrap: 'truncate-end',
223          children: [
224            // name and glyph in one color: a neutral bold name was tried
225            // and the owner wanted the color back (2026-10-11)
226            t.Text({ color: p.accentUser, bold: true, children: [G.diamond + ' You'] }),
227            ...(r.submittedAt === null ? [] : [t.Text({ color: p.meta, children: [sep + clockTime(r.submittedAt)] })]),
228            t.Text({ color: p.faint, children: [' ' + G.rule.repeat(Math.max(1, m - cellWidth(G.diamond + ' You' + (r.submittedAt === null ? '' : sep + clockTime(r.submittedAt))) - 1))] }),
229          ],
230        }),
231      ],
232    }),
233    t.Box({ marginLeft: 2, width: m, children: [t.Text({ wrap: 'wrap', children: [safeText(r.text)] })] }),
234  ]
235  if (r.startedAt !== null) {
236    rows.push(
237      t.Box({
238        marginTop: 1,
239        children: [
240          t.Text({
241            children: [
242              t.Text({ color: p.accent, bold: true, children: [G.fisheye + ' Claude'] }),
243              t.Text({ color: p.meta, children: [sep + clockTime(r.startedAt)] }),
244            ],
245          }),
246        ],
247      }),
248    )
249  }
250  const v = r.turn
251  if (v && v.calls.length > 0) {
252    const summary: RenderNode[] = []
253    if (v.done) {
254      summary.push(plural(v.done.tools, 'action'))
255      if (v.done.edits > 0) summary.push(sep + plural(v.done.edits, 'edit'))
256      if (v.done.failed > 0) summary.push(sep, t.Text({ color: p.err, children: [`${v.done.failed} failed`] }))
257    } else {
258      summary.push(toolCounts(v.calls))
259      const failed = v.calls.filter(c => c.status === 'failed').length
260      if (failed > 0) summary.push(sep, t.Text({ color: p.err, children: [`${failed} failed`] }))
261    }
262    // dots as sibling Texts, so each can light its row (a Text nested in a
263    // Text follows its hover group but cannot heat it)
264    const left = t.Box({
265      flexDirection: 'row',
266      flexShrink: 1,
267      children: [...dots(t, p, v.calls), t.Text({ children: ['  '] }), t.Box({ flexShrink: 1, children: [t.Text({ wrap: 'truncate-end', color: v.done ? p.meta : p.bold, children: summary })] })],
268    })
269    // 0.5.0: the chevron and Copy return as plain Buttons at the right end,
270    // gated on the live press retest (the 0.2 and 0.3 Buttons never
271    // received a press; 2.1.288 fixed button routing). /fold and /unfold
272    // stay the keyboard route. Label only: no children, so the tree
273    // validates on engines before 2.1.295.
274    const controls: RenderNode[] = []
275    if (r.onFold) controls.push(t.Button({ key: `fold:${v.turnId}`, label: r.folded ? G.right : G.down, plain: true, dimColor: true, hover: { backgroundColor: p.rowHover }, onPress: r.onFold }))
276    if (r.onCopy && v.done) controls.push(...(controls.length ? ['  '] : []), t.Button({ key: `copy:${v.turnId}`, label: G.copy + ' Copy', plain: true, dimColor: true, hover: { backgroundColor: p.rowHover }, onPress: r.onCopy }))
277    rows.push(
278      t.Box({
279        key: `dots:${v.turnId}`,
280        flexDirection: 'row',
281        marginLeft: 2,
282        // the same right inset as the tree rows, so the buttons end where
283        // the durations end
284        marginRight: TREE_INSET,
285        justifyContent: 'space-between',
286        hover: { backgroundColor: p.rowHover },
287        children: [
288          t.Box({ flexDirection: 'row', flexShrink: 1, children: [left] }),
289          ...(controls.length ? [t.Box({ flexDirection: 'row', flexShrink: 0, marginLeft: 2, children: controls })] : []),
290        ],
291      }),
292    )
293  }
294  return t.Box({ flexDirection: 'column', children: rows })
295}
296
297// ---- tool tree -----------------------------------------------------------
298
299export type TreeRow = {
300  tool_use_id: string
301  tool: string
302  input: unknown
303  isRunning: boolean
304  isErrored: boolean
305  isInterrupted: boolean
306  output?: unknown
307}
308
309// no `last`: knowing a turn's last call needs a subscription to the turn,
310// so every row draws the tee and the trunk runs on (0.3.10)
311export type TreeOptions = {
312  /** wall time once known */
313  durationMs: number | null
314  /** a trunk row above; false inside a run of the same tool (2026-10-04) */
315  air?: boolean
316  /** while running: the clock's first cells (clockCells); a ticker blits the rest */
317  clock?: string
318}
319
320function str(args: Record<string, unknown>, k: string): string | null {
321  return typeof args[k] === 'string' ? (args[k] as string) : null
322}
323
324// the subject of a row: a Bash command tokenized, live or done (the owner
325// liked the colors on the done row, 2026-10-05); other subjects step down
326// to faint once done
327function subjectNodes(t: Table, p: Palette, tool: string, input: unknown, live: boolean): RenderNode[] {
328  const args = (input ?? {}) as Record<string, unknown>
329  const out: RenderNode[] = []
330  const command = tool === 'Bash' ? str(args, 'command') : null
331  if (command) {
332    const text = safeText(command.replace(/\s*\n\s*/g, ' '), 400)
333    const spans = shellSpans(text, true) ?? [{ text, kind: 'plain' as const }]
334    for (const s of spans) out.push(s.kind === 'plain' ? s.text : t.Text({ color: p[s.kind], children: [s.text] }))
335    return out
336  }
337  const path = str(args, 'file_path') ?? str(args, 'path') ?? str(args, 'notebook_path')
338  const url = str(args, 'url')
339  const other = str(args, 'pattern') ?? str(args, 'query') ?? str(args, 'description') ?? str(args, 'skill') ?? str(args, 'prompt') ?? str(args, 'command')
340  // a done row steps everything after the name down to faint, paths included
341  if (other && !path) out.push(t.Text({ ...(live ? {} : { color: p.faint }), children: [safeText(other.replace(/\s*\n\s*/g, ' '), 200)] }))
342  if (path) out.push(t.Text({ color: live ? p.path : p.faint, children: [safeText(rel(path), 400)] }))
343  if (url) out.push(t.Text({ color: live ? p.url : p.faint, underline: live, children: [safeText(url, 400)] }))
344  if (other && path) out.push(t.Text({ color: live ? p.meta : p.faint, children: [sep + safeText(other.replace(/\s*\n\s*/g, ' '), 200)] }))
345  return out
346}
347
348// lines a Bash result holds, for the `. N lines` tail of a done row
349function outputLines(output: unknown): number | null {
350  if (!output || typeof output !== 'object') return null
351  const o = output as { stdout?: unknown; stderr?: unknown }
352  const text = [o.stdout, o.stderr].filter((s): s is string => typeof s === 'string' && s.trim() !== '').join('\n').replace(/\s+$/, '')
353  return text === '' ? 0 : text.split('\n').length
354}
355
356// The connector and mark that open a tree row, in a box that never shrinks.
357// A Text in a row shrinks with its siblings: when the subject overflows, the
358// row squeezed the two-cell `o ` mark to one cell and the gap after it went
359// (`oBash  cat > ...`, seen 2026-10-05). Only the subject truncates now.
360function rowHead(t: Table, ...cells: RenderElement[]): RenderElement {
361  return t.Box({ flexDirection: 'row', flexShrink: 0, children: cells })
362}
363
364// `|- v Bash  git log --oneline . 3 lines                        0.8s`
365// Connector `faint`, mark in its status color, the name in `tool` (bold
366// while live), the subject truncating (ctrl+o has the whole call), the
367// time at the right. The row lights under the pointer.
368export function renderTreeRow(t: Table, p: Palette, row: TreeRow, o: TreeOptions): RenderElement {
369  const live = row.isRunning
370  const failed = row.isErrored || row.isInterrupted
371  const mark = live ? G.hollow : failed ? G.cross : G.tick
372  // the tick in `ok`: a meta tick was tried and the owner wanted the green
373  // back (2026-10-11)
374  const markColor = live ? p.meta : failed ? p.err : p.ok
375  const subject = subjectNodes(t, p, row.tool, row.input, live)
376  const tail: RenderNode[] = []
377  if (!live && row.tool === 'Bash') {
378    // the count only once the body folds: a three-line body is its own count
379    const n = outputLines(row.output)
380    if (n !== null && n > MAX_PAINTED_LINES) tail.push(t.Text({ color: p.faint, children: [sep + plural(n, 'line')] }))
381  }
382  // under a tenth of a second the time says nothing (`0.0s`): none
383  const right = o.durationMs === null || o.durationMs < 100 ? '' : fmtToolTime(o.durationMs)
384  return spaced(t, p, t.Box({
385    key: `row:${row.tool_use_id}`,
386    flexDirection: 'row',
387    hover: { scope: callScope(row.tool_use_id), backgroundColor: p.rowHover },
388    children: [
389      rowHead(t, t.Text({ color: p.faint, children: [G.tee + G.rule + ' '] }), t.Text({ color: markColor, children: [mark + ' '] })),
390      t.Box({
391        flexGrow: 1,
392        flexShrink: 1,
393        children: [
394          t.Text({
395            wrap: 'truncate-end',
396            children: [...toolNodes(t, p, row.tool, live), ...(subject.length ? ['  ', ...subject] : []), ...tail],
397          }),
398        ],
399      }),
400      ...(live && o.clock && 'Raster' in t
401        ? [t.Box({ flexShrink: 0, marginLeft: 2, children: [t.Raster({ key: 'clock', columns: CLOCK_CELLS, rows: 1, cells: o.clock })] })]
402        : right
403          ? [t.Box({ flexShrink: 0, marginLeft: 2, children: [t.Text({ color: live ? p.meta : p.faint, children: [right] })] })]
404          : []),
405    ],
406  }), o.air ?? true)
407}
408
409// A tool the API ran inside the request (the advisor): no tool.call, no
410// engine row, so the turn's record draws these after the reply (0.5.0).
411// `|- v advisor  ran by the API                                   4.2s`
412// Connector faint, the mark in meta (the engine ran nothing, so not ok's
413// done), the name in `tool`, the note faint, the duration faint as on every
414// finished row; none without an end time. Each row keeps its air row above.
415export function renderServerToolRows(t: Table, p: Palette, tools: ReadonlyArray<GlassServerTool>): RenderElement {
416  const rows = tools.map(s => {
417    const right = s.endedAt === undefined || s.endedAt - s.startedAt < 100 ? '' : fmtToolTime(s.endedAt - s.startedAt)
418    return spaced(t, p, t.Box({
419      key: `server:${s.id}`,
420      flexDirection: 'row',
421      hover: { backgroundColor: p.rowHover },
422      children: [
423        rowHead(t, t.Text({ color: p.faint, children: [G.tee + G.rule + ' '] }), t.Text({ color: p.meta, children: [G.tick + ' '] })),
424        t.Box({
425          flexGrow: 1,
426          flexShrink: 1,
427          children: [t.Text({ wrap: 'truncate-end', children: [...toolNodes(t, p, safeText(s.name, 60), false), '  ', t.Text({ color: p.faint, children: ['ran by the API'] })] })],
428        }),
429        ...(right ? [t.Box({ flexShrink: 0, marginLeft: 2, children: [t.Text({ color: p.faint, children: [right] })] })] : []),
430      ],
431    }))
432  })
433  return t.Box({ flexDirection: 'column', children: rows })
434}
435
436// cells a body row leaves for the trunk column before its content
437const TRUNK = 3
438// painted output lines under a Bash row before the rest folds to a count
439export const MAX_PAINTED_LINES = 3
440
441// A body row under a tree row: the trunk down its left, `h` rows tall,
442// the content indented under the row's mark.
443function trunked(t: Table, p: Palette, h: number, content: RenderNode[]): RenderElement {
444  return t.Box({
445    flexDirection: 'row',
446    marginLeft: TREE_INSET,
447    marginRight: TREE_INSET,
448    children: [
449      t.Box({ width: TRUNK, flexShrink: 0, children: [t.Text({ color: p.faint, children: [Array(Math.max(1, h)).fill(G.pipe).join('\n')] })] }),
450      t.Box({ flexGrow: 1, flexShrink: 1, flexDirection: 'column', children: content }),
451    ],
452  })
453}
454
455// characters of one output line kept: more than any terminal row shows
456const OUTPUT_LINE_MAX = 1000
457
458// a line as a terminal leaves it: a carriage return (a progress bar's
459// `50%\r100%`) starts the line over, so only the last pass shows
460function overstruck(line: string): string {
461  const s = line.replace(/\r+$/, '')
462  return s.slice(s.lastIndexOf('\r') + 1)
463}
464
465export type OutputOptions = {
466  columns: number
467  /** lines past this fold to a `faint` count */
468  maxLines: number
469}
470
471// The engine's Bash result body, redrawn so the output can be painted (the
472// engine strips escape codes from a rewritten result, so colors have to be
473// Text) and so the trunk runs through it: one trunked row per line, the
474// rest folded to `+N lines`. (The dentistry-symbol connector and the engine's own
475// collapsed body for long output were the first design; both broke the
476// tree's line, owner's request 2026-10-03.)
477export function renderToolOutput(t: Table, p: Palette, lines: string[], o: OutputOptions = { columns: 80, maxLines: lines.length }): RenderElement {
478  const shown = lines.slice(0, o.maxLines)
479  // one row per output line, clipped: a long line no longer doubles the
480  // body's height, and ctrl+o has the whole output (2026-10-04)
481  // each line made a string the API takes: no control characters (a `\b`
482  // or a bell refused the whole tree) and cut well past any terminal's
483  // width, since the row clips anyway (a minified JSON line ran 16000)
484  const rows = shown.map(line =>
485    trunked(t, p, 1, [
486      t.Text({
487        wrap: 'truncate-end',
488        children: paintLine(safeText(overstruck(line), OUTPUT_LINE_MAX)).map(s => (s.color ? t.Text({ color: p[s.color], children: [s.text] }) : t.Text({ color: p.meta, children: [s.text] }))),
489      }),
490    ]),
491  )
492  const rest = lines.length - shown.length
493  if (rest > 0) rows.push(trunked(t, p, 1, [t.Text({ color: p.faint, children: [G.ellipsis + ` +${plural(rest, 'line')}`] })]))
494  return t.Box({ flexDirection: 'column', children: rows })
495}
496
497// ---- an Edit's diff ------------------------------------------------------
498
499export type Hunk = { oldStart: number; newStart: number; lines: string[] }
500
501export type DiffOptions = {
502  /** the file's path, for the highlighter's language */
503  path: string
504  /** the terminal's width */
505  columns: number
506  /** `Created` or `Deleted` before the path in the title; absent for an update */
507  verb?: string
508}
509
510// rows a diff body draws before folding the rest into a count
511const MAX_DIFF_ROWS = 200
512const DIFF_MIN = 60
513
514// An Edit's `structuredPatch` as glass draws it, in place of the engine's
515// own diff panel (owner's request, 2026-10-03, after Empryo's card): a
516// rounded `faint` frame on the trunk column, sized to the hunks, one number column (the new
517// number on a kept or added line, the old on a removed one) in `faint`,
518// `+` in `ok` on an `addBg` row, `-` in `err` on a `delBg` row, the code
519// painted by glass's highlighter, an ellipsis row between hunks.
520export function renderDiff(t: Table, p: Palette, hunks: ReadonlyArray<Hunk>, o: DiffOptions): RenderElement {
521  const lang = langOf(o.path)
522  const last = Math.max(1, ...hunks.flatMap(h => [h.oldStart + h.lines.length, h.newStart + h.lines.length]))
523  const digits = String(last).length
524  type Piece = { text: string; color?: string }
525  type Line = { kind: 'add' | 'del' | 'ctx' | 'note'; num: number | null; pieces: Piece[] }
526  const lines: Line[] = []
527  let widest = 0
528  let total = 0
529  let hidden = 0
530  let add = 0
531  let del = 0
532  hunks.forEach((h, i) => {
533    const state: State = { inBlock: false }
534    // one context line before the first change and one after the last;
535    // context between changes stays, and the numbers keep counting
536    const changed = h.lines.map((l, k) => (l[0] === '+' || l[0] === '-' ? k : -1)).filter(k => k >= 0)
537    const lo = changed.length ? changed[0]! - 1 : -Infinity
538    const hi = changed.length ? changed[changed.length - 1]! + 1 : Infinity
539    let k = -1
540    if (i > 0 && total < MAX_DIFF_ROWS) lines.push({ kind: 'note', num: null, pieces: [{ text: G.ellipsis, color: p.faint }] })
541    let old = h.oldStart
542    let cur = h.newStart
543    for (const raw of h.lines) {
544      k++
545      const head = raw[0]
546      const kind = head === '+' ? 'add' : head === '-' ? 'del' : head === '\\' ? 'note' : 'ctx'
547      const num = kind === 'del' ? old : cur
548      if (kind === 'ctx' || kind === 'del') old++
549      if (kind === 'ctx' || kind === 'add') cur++
550      if (kind === 'add') add++
551      if (kind === 'del') del++
552      if (kind === 'ctx' && (k < lo || k > hi)) continue
553      total++
554      if (total > MAX_DIFF_ROWS) {
555        hidden++
556        continue
557      }
558      // tabs expand here: the engine and the terminal disagree on a tab's width
559      const body = safeText(raw.slice(1), 2000).replace(/\t/g, '    ')
560      widest = Math.max(widest, cellWidth(body))
561      if (kind === 'note') {
562        lines.push({ kind, num: null, pieces: [{ text: body, color: p.faint }] })
563        continue
564      }
565      const pieces = highlightLine(body, lang, state).map(s => (s.kind === 'plain' ? { text: s.text } : { text: s.text, color: codeColor(p, s.kind) }))
566      lines.push({ kind, num, pieces })
567    }
568  })
569  if (hidden > 0) lines.push({ kind: 'note', num: null, pieces: [{ text: G.ellipsis + ` +${plural(hidden, 'line')}`, color: p.faint }] })
570
571  const name = safeText(rel(o.path), 400)
572  const counts = (add > 0 ? ` +${add}` : '') + (del > 0 ? ` -${del}` : '')
573  const verb = o.verb ? o.verb + ' ' : ''
574  const cap = Math.max(20, o.columns - 2 * TREE_INSET)
575  const width = Math.min(cap, Math.max(DIFF_MIN, widest + digits + 3 + 4, cellWidth(verb + name + counts) + 8))
576  // inside the frame: a border and a padding cell each side
577  const inner = width - 4
578  const gutter = digits + 3
579  const room = Math.max(1, inner - gutter)
580
581  // The frame is drawn by glass, row by row, so the file can sit in the top
582  // border, `SPEC.md +1 -1` between the arcs (owner's pick, 2026-10-03; an absolute
583  // title over a Box border is clipped by the engine). glass breaks every
584  // code line at the room itself, so the engine never wraps inside the card
585  // and each row carries its own two edges: no glyph column guesses a height.
586  const edge = (s: string) => t.Text({ color: p.faint, children: [s] })
587  const out: RenderElement[] = []
588  const fixed = 3 + cellWidth(verb + counts) + 3
589  const shown = o.path ? clipPath(name, Math.max(4, width - fixed)) : ''
590  const titleW = o.path ? cellWidth(verb + shown + counts) + 1 : 0
591  out.push(
592    t.Text({
593      children: [
594        edge(G.arcTL + G.rule + (o.path ? ' ' : '')),
595        ...(o.path
596          ? [
597              ...(verb ? [t.Text({ color: p.meta, children: [verb] })] : []),
598              t.Text({ color: p.path, children: [shown] }),
599              ...(add > 0 ? [' ', t.Text({ color: THEME.success, children: [`+${add}`] })] : []),
600              ...(del > 0 ? [' ', t.Text({ color: THEME.error, children: [`-${del}`] })] : []),
601              ' ',
602            ]
603          : []),
604        edge(G.rule.repeat(Math.max(1, width - 3 - (o.path ? 1 : 0) - titleW)) + G.arcTR),
605      ],
606    }),
607  )
608  for (const l of lines) {
609    // 0.5.0: the tints are the active theme's diff slots, so the card
610    // matches the engine's own diff panels; 0.5.3: the marks take the
611    // theme's success and error (the diff*Word slots are the engine's
612    // word-level backgrounds, not text colors). A glass theme sets these to
613    // the palette's addBg, delBg, ok and err.
614    const bg = l.kind === 'add' ? THEME.diffAdded : l.kind === 'del' ? THEME.diffRemoved : undefined
615    const mark = l.kind === 'add' ? '+' : l.kind === 'del' ? '-' : ' '
616    const markColor = l.kind === 'add' ? THEME.success : l.kind === 'del' ? THEME.error : p.faint
617    chunk(l.pieces, room).forEach((part, n) => {
618      const used = part.reduce((w, x) => w + cellWidth(x.text), 0)
619      const head: RenderNode[] =
620        n === 0 && l.num !== null
621          ? [t.Text({ color: bg ? p.meta : p.faint, children: [String(l.num).padStart(digits) + ' '] }), t.Text({ color: markColor, children: [mark + ' '] })]
622          : [' '.repeat(gutter)]
623      out.push(
624        t.Box({
625          flexDirection: 'row',
626          children: [
627            edge(G.pipe + ' '),
628            t.Box({
629              width: inner,
630              flexShrink: 0,
631              ...(bg ? { backgroundColor: bg } : {}),
632              children: [
633                t.Text({
634                  wrap: 'truncate-end',
635                  children: [...head, ...part.map(x => (x.color ? t.Text({ color: x.color, children: [x.text] }) : x.text)), ' '.repeat(Math.max(0, room - used))],
636                }),
637              ],
638            }),
639            edge(' ' + G.pipe),
640          ],
641        }),
642      )
643    })
644  }
645  out.push(edge(G.arcBL + G.rule.repeat(width - 2) + G.arcBR))
646  // the card sits on the trunk column: its left edge is the trunk
647  return t.Box({ marginLeft: TREE_INSET, marginRight: TREE_INSET, width, flexDirection: 'column', children: out })
648}
649
650// colored pieces cut into rows of at most `w` cells, by the engine's ruler
651function chunk(pieces: ReadonlyArray<{ text: string; color?: string }>, w: number): { text: string; color?: string }[][] {
652  const rows: { text: string; color?: string }[][] = [[]]
653  let used = 0
654  for (const piece of pieces) {
655    let buf = ''
656    for (const ch of piece.text) {
657      const cw = cellWidth(ch)
658      if (used + cw > w && used > 0) {
659        if (buf) rows[rows.length - 1]!.push({ ...piece, text: buf })
660        rows.push([])
661        buf = ''
662        used = 0
663      }
664      buf += ch
665      used += cw
666    }
667    if (buf) rows[rows.length - 1]!.push({ ...piece, text: buf })
668  }
669  return rows
670}
671
672// ---- a Bash result that changed files ------------------------------------
673
674export type ChangedFile = { filePath: string; hunks: Hunk[]; created?: true; deleted?: true }
675
676export type BashResultOptions = {
677  /** the painted body shows this many lines before folding the rest */
678  maxLines: number
679  moreFiles: number
680  columns: number
681}
682
683// A Bash result whose command rewrote files: the output body as the
684// standalone one draws (folded past `maxLines` to a `faint` count), then
685// per file, after one trunked row of air, a header `Updated <path> +a -b` and the
686// same rounded diff card an Edit gets (owner's request, 2026-10-03: the
687// engine's own panel for these was the one pink thing left).
688export function renderBashResult(t: Table, p: Palette, lines: string[], files: ReadonlyArray<ChangedFile>, o: BashResultOptions): RenderElement {
689  const rows: RenderElement[] = []
690  const air = () => trunked(t, p, 1, [t.Text({ children: [''] })])
691  if (lines.length > 0) rows.push(renderToolOutput(t, p, lines, { columns: o.columns, maxLines: o.maxLines }))
692  for (const f of files) {
693    const verb = f.created ? 'Created' : f.deleted ? 'Deleted' : undefined
694    rows.push(air())
695    // the card's top border names the file; a change with no hunks keeps a header line
696    if (f.hunks.length > 0) {
697      rows.push(renderDiff(t, p, f.hunks, { path: f.filePath, columns: o.columns, ...(verb ? { verb } : {}) }))
698      continue
699    }
700    rows.push(
701      trunked(t, p, 1, [
702        t.Text({
703          wrap: 'truncate-end',
704          children: [
705            t.Text({ color: p.meta, children: [(verb ?? 'Updated') + ' '] }),
706            t.Text({ color: p.path, children: [safeText(rel(f.filePath), 400)] }),
707          ],
708        }),
709      ]),
710    )
711  }
712  if (o.moreFiles > 0) {
713    rows.push(air())
714    rows.push(trunked(t, p, 1, [t.Text({ color: p.faint, children: [G.ellipsis + ` +${o.moreFiles} more file${o.moreFiles === 1 ? '' : 's'}`] })]))
715  }
716  return t.Box({ flexDirection: 'column', children: rows })
717}
718
719// ---- folded group --------------------------------------------------------
720
721export type GroupCall = { tool: string; input?: unknown; isRunning: boolean; isErrored: boolean; isInterrupted: boolean }
722
723export type GroupOptions = {
724  isActive: boolean
725  /** the row's key, which its hover tint needs; null draws it untinted */
726  key: string | null
727}
728
729// `|- > Read x3  a.ts . b.ts [1 edit]`, all `faint`, the mark in `meta`; a
730// failed count in `err`; a live group ends in an ellipsis. No fold button:
731// a Button in a transcript row never received its press live (2026-10-03),
732// so /expand opens every group. Each MCP server takes a line of its own,
733// named once at its head, under one hover (owner's request, 2026-10-07).
734export function renderGroupRow(t: Table, p: Palette, calls: ReadonlyArray<GroupCall>, o: GroupOptions): RenderElement {
735  const runs = new Map<string, GroupCall[]>()
736  for (const c of calls) {
737    const server = toolLabel(c.tool).server ?? ''
738    const run = runs.get(server)
739    if (run) run.push(c)
740    else runs.set(server, [c])
741  }
742  const lines = [...runs].map(([server, run]) => groupLine(t, p, server, run, o.isActive && (runs.size === 1 || run.some(c => c.isRunning))))
743  return spaced(t, p, t.Box({
744    ...(o.key ? { key: `group:${o.key}`, hover: { backgroundColor: p.rowHover } } : {}),
745    flexDirection: 'column',
746    children: lines,
747  }))
748}
749
750function groupLine(t: Table, p: Palette, server: string, calls: GroupCall[], live: boolean): RenderElement {
751  const edits = calls.filter(c => isEditTool(c.tool)).length
752  const failed = calls.filter(c => c.isErrored || c.isInterrupted).length
753  // what the run touched: the tools with counts, then each subject once
754  const counts = new Map<string, number>()
755  for (const c of calls) {
756    const name = toolLabel(c.tool).name
757    counts.set(name, (counts.get(name) ?? 0) + 1)
758  }
759  const tools = [...counts].map(([tool, n]) => (n > 1 ? `${tool} ${G.times}${n}` : tool)).join(sep)
760  const subjects = [...new Set(calls.map(c => {
761    const a = (c.input ?? {}) as Record<string, unknown>
762    const s = str(a, 'file_path') ?? str(a, 'path') ?? str(a, 'pattern') ?? str(a, 'query') ?? str(a, 'url') ?? clip((str(a, 'command') ?? '').replace(/\s+/g, ' '), 60)
763    return safeText(rel(s).replace(/\s+/g, ' '), 200)
764  }).filter(s => s !== ''))]
765  const parts: RenderNode[] = server ? [t.Text({ color: p.faint, children: [server + ' '] })] : []
766  parts.push(t.Text({ color: p.tool, children: [tools] }))
767  if (subjects.length) parts.push('  ' + subjects.join(sep))
768  if (edits > 0) parts.push(sep + plural(edits, 'edit'))
769  if (failed > 0) parts.push(sep, t.Text({ color: p.err, children: [`${failed} failed`] }))
770  const tail = live ? sep + `${calls.filter(c => c.isRunning).length} running` + G.ellipsis : ''
771  return t.Box({
772    flexDirection: 'row',
773    children: [
774      rowHead(t, t.Text({ color: p.faint, children: [G.tee + G.rule + ' '] }), t.Text({ color: p.meta, children: [G.right + ' '] })),
775      t.Box({ flexShrink: 1, children: [t.Text({ wrap: 'truncate-end', color: p.faint, children: [...parts, tail] })] }),
776    ],
777  })
778}
779
780// ---- events after the turn -----------------------------------------------
781
782export type EventTask = { status?: string; durationMs?: number }
783
784// a background task's notification as one tree row:
785// `|- v Agent "Research Empryo" finished                         1m 12s`
786// A Box with a hover style must carry a key, or the validator refuses the
787// whole tree and the engine draws its own row. The key is the message's
788// own id: two notifications with the same first line must not share one.
789// Every event row draws the tee, as tree rows do: knowing the last needs a
790// subscription to the session's messages.
791export function renderEventRow(t: Table, p: Palette, id: string, text: string, task: EventTask | undefined, expanded = false): RenderElement {
792  const linesAll = text.split('\n')
793  const at = linesAll.findIndex(l => l.trim() !== '')
794  const first = safeText(linesAll[at] ?? '', 400)
795  const rest = expanded ? safeText(linesAll.slice(at + 1).join('\n').trim(), MAX_TEXT) : ''
796  const status = (task?.status ?? '').toLowerCase()
797  const failed = /fail|error|kill|cancel/.test(status)
798  // under a tenth of a second the time says nothing, as on a tree row
799  const right = typeof task?.durationMs === 'number' && task.durationMs >= 100 ? fmtToolTime(task.durationMs) : ''
800  // `Agent "Count hook source lines" finished` draws as a tool row
801  const agent = /^Agent "(.+)" \w+/.exec(first)
802  const row = spaced(t, p, t.Box({
803    key: `event:${id}`,
804    flexDirection: 'row',
805    hover: { backgroundColor: p.rowHover },
806    children: [
807      rowHead(t, t.Text({ color: p.faint, children: [G.tee + G.rule + ' '] }), t.Text({ color: failed ? p.err : p.ok, children: [(failed ? G.cross : G.tick) + ' '] })),
808      t.Box({ flexGrow: 1, flexShrink: 1, children: [t.Text({ wrap: 'truncate-end', color: p.meta, children: agent ? [t.Text({ color: p.tool, children: ['Agent'] }), '  ' + agent[1]!] : [first] })] }),
809      ...(right ? [t.Box({ flexShrink: 0, marginLeft: 2, children: [t.Text({ color: p.faint, children: [right] })] })] : []),
810    ],
811  }))
812  if (rest === '') return row
813  // the rest of the notification hangs off the trunk as a Bash body does,
814  // one row per line, clipped (a body with no trunk sat off the column)
815  const body = rest.split('\n').map(l => t.Text({ wrap: 'truncate-end', color: p.meta, children: [l] }))
816  return t.Box({
817    flexDirection: 'column',
818    children: [row, trunked(t, p, body.length, body)],
819  })
820}
821
822// a message another agent sent, folded: `|- . Message from @Explore` in
823// `private`; no key hint at the right (0.5.3: the hint line and the group
824// rows gave theirs up, this was the last)
825export function renderMessageRow(t: Table, p: Palette, name: string): RenderElement {
826  return spaced(t, p, t.Box({
827    key: `message:${name}`,
828    flexDirection: 'row',
829    hover: { backgroundColor: p.rowHover },
830    children: [
831      rowHead(t, t.Text({ color: p.faint, children: [G.tee + G.rule + ' '] }), t.Text({ color: p.faint, children: [G.ring + ' '] })),
832      t.Box({ flexGrow: 1, flexShrink: 1, children: [t.Text({ wrap: 'truncate-end', color: p.private, children: [`Message from @${safeText(name, 80)}`] })] }),
833    ],
834  }))
835}
836
837// ---- background band -----------------------------------------------------
838
839const BAND_ROWS = 5
840const COL_NAME = 20
841const COL_MODEL = 22
842const COL_STAGE = 14
843const COL_TOKENS = 8
844// the view and back labels are one width, so a row is the band wide either way
845const VIEW_LABEL = 'view'
846const BACK_LABEL = 'back'
847const VIEW_CELLS = 1 + VIEW_LABEL.length
848
849// `view` on an agent's row, `back` on the one in view: a plain dim Button in
850// a keyed Box, as the chevron is (a hover with no keyed Box around it makes
851// the engine refuse the tree)
852function viewButton(t: Table, p: Palette, agentId: string, inView: boolean, onPress: () => void): RenderElement {
853  const key = `band:view:${agentId}`
854  return t.Box({ key, children: [t.Button({ key, label: inView ? BACK_LABEL : VIEW_LABEL, plain: true, dimColor: true, hover: { backgroundColor: p.rowHover }, onPress })] })
855}
856
857export type BandOptions = {
858  agents: GlassAgent[]
859  now: number
860  columns: number
861  open: boolean
862  onToggle: Press | null
863  /** the slash command that lists tasks, when the session has one */
864  tasksCommand: string | null
865  /**
866   * 0.10.0: opens an agent's transcript in the main view (`$.ui.view`,
867   * engine 2.1.300); absent or null, no row draws a button
868   */
869  onView?: ((agentId: string) => void) | null
870  /** the agent whose transcript is in view (`e.props.view.agentId`), if any */
871  viewing?: string | null
872  /** returns to the main conversation; the row in view draws `back` */
873  onBack?: (() => void) | null
874}
875
876// the agent's face: eyes level while it thinks, lowered while it reads
877function face(a: GlassAgent): string {
878  const eye = G.disc
879  const mouth = a.stage.startsWith('thinking') ? G.smile : G.down
880  return `(${eye}${mouth}${eye})`
881}
882
883function shortModel(model: string): string {
884  return model.replace(/^claude-/, '').replace(/-\d{8}$/, '')
885}
886
887// A rounded frame the band's width, the title in its top edge and the
888// oldest agent's elapsed time at the right; one row per live agent, newest
889// last, five at most and `+N more`; the bottom edge carries the hint.
890// Closed, one strip: the title, the faces, the newest agent's stage.
891export function renderBand(t: Table, p: Palette, o: BandOptions): RenderElement {
892  const { agents, now } = o
893  // the engine draws its `[-]` collapse mark over the band's top-right
894  // cells; the frame stops four short of it (2026-10-04)
895  const w = Math.max(40, o.columns - 4)
896  const oldest = agents.reduce((n, a) => Math.min(n, a.startedAt), now)
897  const elapsed = fmtDuration(Math.max(0, now - oldest))
898  const titleText = `background${sep}${agents.length}`
899  // the chevron's hover tint needs a keyed Box around it: without one the
900  // engine refuses the whole tree and draws nothing, so the band was
901  // invisible from 0.5.2 to 0.5.3 (found in the debug log, 2026-10-12)
902  const chevron = o.onToggle
903    ? t.Box({ key: 'band:chevron', children: [t.Button({ key: 'band:toggle', label: o.open ? G.down : G.right, plain: true, dimColor: true, hover: { backgroundColor: p.rowHover }, onPress: o.onToggle })] })
904    : t.Text({ color: p.accent, children: [o.open ? G.down : G.right] })
905  const title = t.Text({
906    children: [
907      t.Text({ color: p.accent, children: [G.dotted + ' '] }),
908      t.Text({ color: p.accent, bold: true, children: ['background'] }),
909      t.Text({ color: p.meta, children: [sep] }),
910      t.Text({ color: p.accent, bold: true, children: [String(agents.length)] }),
911      ' ',
912    ],
913  })
914
915  if (!o.open) {
916    // `- o background . 3 v - (o_o) (o_o)  Research Empryo . thinking... ----- 1m 25s -`
917    // the fill is measured from the strings around it, so the strip is
918    // exactly the band wide
919    const newest = agents[agents.length - 1]!
920    const lead = `${G.rule} `
921    const titleStr = `${G.dotted} background${sep}${agents.length} `
922    const mid = ` ${G.rule} `
923    const tail = ` ${elapsed} ${G.rule}`
924    const fixedFor = (faces: string) => cellWidth(lead + titleStr) + 1 + cellWidth(mid + faces) + 2 + 1 + cellWidth(tail)
925    // a narrow terminal drops the oldest faces, all of them if it must, so
926    // 16 cells stay for the name and the fill; the name then takes what is
927    // left but one
928    let shown = agents.slice(-BAND_ROWS)
929    while (shown.length > 0 && w - fixedFor(shown.map(face).join(' ')) < 16) shown = shown.slice(1)
930    const faces = shown.map(face).join(' ')
931    const fixed = fixedFor(faces)
932    const room = w - fixed
933    const name = clip(`${a11(newest.description)}${sep}${newest.stage}`, room >= 16 ? room - 8 : Math.max(0, room - 1))
934    const fill = Math.max(1, w - fixed - cellWidth(name))
935    return t.Box({
936      flexDirection: 'row',
937      width: w,
938      children: [
939        t.Text({ color: p.accent, children: [lead] }),
940        title,
941        chevron,
942        t.Text({ color: p.accent, children: [mid] }),
943        t.Text({ color: p.warn, children: [faces] }),
944        t.Text({ color: p.meta, children: [`  ${name} `] }),
945        t.Text({ color: p.accent, children: [G.rule.repeat(fill)] }),
946        t.Text({ color: p.meta, children: [` ${elapsed} `] }),
947        t.Text({ color: p.accent, children: [G.rule] }),
948      ],
949    })
950  }
951
952  // the top edge: arc, rule, the title, rules to the elapsed time, arc
953  const topUsed = cellWidth(`${G.arcTL}${G.rule} ${G.dotted} background${sep}${agents.length} `) + 1 + 1 + cellWidth(` ${elapsed} ${G.rule}${G.arcTR}`)
954  const top = t.Box({
955    flexDirection: 'row',
956    children: [
957      t.Text({ color: p.accent, children: [G.arcTL + G.rule + ' '] }),
958      title,
959      chevron,
960      t.Text({ color: p.accent, children: [' ' + G.rule.repeat(Math.max(1, w - topUsed))] }),
961      t.Text({ color: p.meta, children: [` ${elapsed} `] }),
962      t.Text({ color: p.accent, children: [G.rule + G.arcTR] }),
963    ],
964  })
965  // the frame and the model column stay accent: a faint frame was tried
966  // and the owner wanted the color back (2026-10-11)
967  const edge = (s: string) => t.Text({ color: p.accent, children: [s] })
968  const inner = w - 4
969  const shown = agents.slice(-BAND_ROWS)
970  const more = agents.length - shown.length
971  const cols = bandColumns(inner, o.onView ? VIEW_CELLS : 0)
972  const rows = shown.map(a => {
973    const modelText = `${shortModel(a.model)}${a.effort ? sep + a.effort : ''}`
974    const inView = o.viewing === a.agentId
975    const onView = o.onView
976    const press = inView ? () => o.onBack?.() : () => onView?.(a.agentId)
977    return t.Box({
978      flexDirection: 'row',
979      children: [
980        edge(G.pipe + ' '),
981        t.Text({
982          children: [
983            t.Text({ color: p.warn, children: [G.diamond + ' ' + face(a) + ' '] }),
984            t.Text({ color: inView ? p.accent : p.bold, bold: true, children: [fit(a11(a.description), cols.name)] }),
985            ' ',
986            t.Text({ color: p.accent, children: [fit(modelText, cols.model)] }),
987            ' ',
988            t.Text({ color: p.meta, children: [fit(a.stage, cols.stage)] }),
989            ' ',
990            t.Text({ color: p.meta, children: [fit(a.tokens > 0 ? fmtTokens(a.tokens) : '', cols.tokens)] }),
991            ' ',
992            t.Text({ color: p.faint, children: [fitPath(rel(a.file), cols.file)] }),
993          ],
994        }),
995        ...(onView ? [t.Text({ children: [' '] }), viewButton(t, p, a.agentId, inView, press)] : []),
996        edge(' ' + G.pipe),
997      ],
998    })
999  })
1000  if (more > 0) {
1001    rows.push(
1002      t.Box({
1003        flexDirection: 'row',
1004        children: [edge(G.pipe + ' '), t.Text({ color: p.faint, children: [fit(`  +${more} more`, inner)] }), edge(' ' + G.pipe)],
1005      }),
1006    )
1007  }
1008  const hint = 'They outlive this turn'
1009  const cmd = o.tasksCommand ? `/${o.tasksCommand}` : ''
1010  const bottomUsed = 2 + 1 + cellWidth(hint) + 1 + (cmd ? cellWidth(cmd) + 2 : 0) + 2
1011  const bottom = t.Box({
1012    flexDirection: 'row',
1013    children: [
1014      t.Text({ color: p.accent, children: [G.arcBL + G.rule + ' '] }),
1015      t.Text({ color: p.faint, children: [hint + ' '] }),
1016      t.Text({ color: p.accent, children: [G.rule.repeat(Math.max(1, w - bottomUsed))] }),
1017      ...(cmd ? [t.Text({ color: p.meta, children: [` ${cmd} `] })] : []),
1018      t.Text({ color: p.accent, children: [G.rule + G.arcBR] }),
1019    ],
1020  })
1021  return t.Box({ flexDirection: 'column', width: w, children: [top, ...rows, bottom] })
1022}
1023
1024// A band row's column widths inside `inner` cells: the diamond, a space,
1025// the five-cell face and a space (8), then name, model, stage, tokens and
1026// file with one space after each of the first four. The file takes what is
1027// left; on a narrow terminal the model gives up cells first, then the
1028// name, the tokens column, the stage, and the name and model again, so a
1029// row never outgrows its frame.
1030function bandColumns(inner: number, extra = 0): { name: number; model: number; stage: number; tokens: number; file: number } {
1031  const c = { name: COL_NAME, model: COL_MODEL, stage: COL_STAGE, tokens: COL_TOKENS }
1032  let over = 8 + 4 + extra + c.name + c.model + c.stage + c.tokens - inner
1033  const give = (k: keyof typeof c, min: number) => {
1034    const d = Math.max(0, Math.min(over, c[k] - min))
1035    c[k] -= d
1036    over -= d
1037  }
1038  give('model', 8)
1039  give('name', 8)
1040  give('tokens', 0)
1041  give('stage', 6)
1042  give('model', 1)
1043  give('name', 1)
1044  return { ...c, file: Math.max(0, -over) }
1045}
1046
1047// a description as one printable line
1048function a11(s: string): string {
1049  return safeText(s.replace(/\s+/g, ' ').trim(), 120)
1050}
1051
1052// A backgrounded Agent's result, in place of the engine's body (its corner
1053// bracket broke the trunk, 2026-10-04): one trunked line in `faint`.
1054export function renderAgentLaunch(t: Table, p: Palette, remote: boolean): RenderElement {
1055  const text = remote ? `running remotely${sep}/tasks` : `running in the background${sep}${G.arrowDown} to manage`
1056  return trunked(t, p, 1, [t.Text({ color: p.faint, wrap: 'truncate-end', children: [text] })])
1057}
1058
1059// A Bash command that printed nothing, in place of the engine's body (its
1060// corner bracket broke the trunk, 2026-10-06): one trunked line in `faint`.
1061export function renderNoOutput(t: Table, p: Palette): RenderElement {
1062  return trunked(t, p, 1, [t.Text({ color: p.faint, wrap: 'truncate-end', children: ['(No output)'] })])
1063}
1064
1065// A loaded skill, in place of the engine's body (its corner bracket sat off
1066// the trunk, 2026-10-09): one trunked line in `faint`, with the engine's
1067// tool count and model where it gives them. A forked skill draws as an
1068// Agent's launch.
1069export function renderSkillLoad(t: Table, p: Palette, output: unknown): RenderElement {
1070  const o = (output && typeof output === 'object' ? output : {}) as { status?: unknown; background?: unknown; allowedTools?: unknown; model?: unknown }
1071  if (o.status === 'forked') return o.background === true ? renderAgentLaunch(t, p, false) : trunked(t, p, 1, [t.Text({ color: p.faint, children: ['done'] })])
1072  const parts = ['skill loaded']
1073  if (Array.isArray(o.allowedTools) && o.allowedTools.length > 0) parts.push(`${plural(o.allowedTools.length, 'tool')} allowed`)
1074  if (typeof o.model === 'string' && o.model !== '') parts.push(safeText(o.model, 80))
1075  return trunked(t, p, 1, [t.Text({ color: p.faint, wrap: 'truncate-end', children: [parts.join(sep)] })])
1076}
1077
1078// A failed non-Bash call's error, in place of the engine's body (its corner
1079// bracket broke the trunk, 2026-10-06): the reason's first line in `err`,
1080// the rest a `faint` count; ctrl+o has it whole.
1081export function renderToolError(t: Table, p: Palette, text: string): RenderElement {
1082  const lines = text.split('\n').map(l => l.trim()).filter(l => l !== '')
1083  const rows = [trunked(t, p, 1, [t.Text({ color: p.err, wrap: 'truncate-end', children: [safeText(lines[0] ?? 'Error', 400)] })])]
1084  if (lines.length > 1) rows.push(trunked(t, p, 1, [t.Text({ color: p.faint, children: [G.ellipsis + ` +${plural(lines.length - 1, 'line')}`] })]))
1085  return t.Box({ flexDirection: 'column', children: rows })
1086}
1087
1088// ---- live clock ----------------------------------------------------------
1089
1090/** the hover group a call's dot and its tree row share */
1091export function callScope(id: string): string {
1092  return ('glass:' + id).slice(0, 64)
1093}
1094
1095/** cells the running row's clock takes: `12m 04s` at most */
1096export const CLOCK_CELLS = 7
1097// 99h 59m 59s, the longest time seven cells hold
1098const CLOCK_MAX_MS = ((99 * 60 + 59) * 60 + 59) * 1000
1099
1100const B64 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
1101function base64(bytes: Uint8Array): string {
1102  let out = ''
1103  for (let i = 0; i < bytes.length; i += 3) {
1104    const a = bytes[i]!
1105    const b = i + 1 < bytes.length ? bytes[i + 1]! : 0
1106    const c = i + 2 < bytes.length ? bytes[i + 2]! : 0
1107    const n = (a << 16) | (b << 8) | c
1108    out += B64[(n >> 18) & 63]! + B64[(n >> 12) & 63]!
1109    out += i + 1 < bytes.length ? B64[(n >> 6) & 63]! : '='
1110    out += i + 2 < bytes.length ? B64[n & 63]! : '='
1111  }
1112  return out
1113}
1114
1115// A Raster's cells for the elapsed time, right-aligned in CLOCK_CELLS: each
1116// cell a [codePoint, fg, bg] triplet of little-endian u32, the background
1117// the terminal's own (bit 24 alone). ASCII digits and letters only.
1118export function clockCells(ms: number, fg: string): string {
1119  // past 99h 59m the clock holds there: `100h 00m` is a cell too wide
1120  const text = fmtDuration(Math.min(Math.max(0, ms), CLOCK_MAX_MS)).padStart(CLOCK_CELLS)
1121  const color = /^#[0-9a-f]{6}$/i.test(fg) ? parseInt(fg.slice(1), 16) : 0x01000000
1122  const words = new Uint32Array(CLOCK_CELLS * 3)
1123  for (let i = 0; i < CLOCK_CELLS; i++) {
1124    words[i * 3] = text.charCodeAt(i)
1125    words[i * 3 + 1] = color
1126    words[i * 3 + 2] = 0x01000000
1127  }
1128  return base64(new Uint8Array(words.buffer))
1129}
1130
1131// ---- the hint line under the prompt ----------------------------------------
1132
1133// The engine's hint, its key reminders dropped (owner's request, 2026-10-04:
1134// keep the line under the prompt clean): `(shift+tab to cycle)` and
1135// `<left arrow> for agents` go. The vim mode comes first, wherever the engine
1136// put it (live: `<mode> . -- INSERT --`), then the permission mode. Null when
1137// the hint has neither and nothing was dropped (`? for shortcuts`), so the
1138// engine keeps its own line.
1139export function cleanHint(hint: string): { vim: string; rest: string } | null {
1140  const dropped = hint
1141    .replace(/\s*\((?:shift|ctrl|alt|meta)\+[a-z]+ to cycle\)/gi, '')
1142    .replace(new RegExp('\\s*' + G.middot + '?\\s*' + G.arrowLeft + '\\s*for agents', 'g'), '')
1143  const vimMatch = /--\s*[A-Z]+\s*--/.exec(dropped)
1144  const vim = vimMatch ? vimMatch[0] : ''
1145  const sepRe = new RegExp('^[\\s' + G.middot + ']+|[\\s' + G.middot + ']+$', 'g')
1146  const rest = (vim ? dropped.replace(vim, ' ') : dropped).replace(new RegExp('\\s*' + G.middot + '\\s*' + G.middot + '\\s*', 'g'), ' ' + G.middot + ' ').replace(sepRe, '')
1147  const changed = dropped !== hint
1148  if (!changed && !vim && !MODE_RE.test(rest)) return null
1149  return { vim, rest }
1150}
1151
1152const MODE_RE = /mode on|accept edits on|plan mode/i
1153
1154// the vim mode in `accentUser` (the person's own color: typing is theirs),
1155// the permission mode in the active theme's own slot for it (0.5.0: the
1156// engine's panels and glass agree under any theme): plan `planMode`,
1157// accepting edits `autoAccept`, auto and bypass `warning`; anything else `meta`
1158export function renderHint(t: Table, p: Palette, h: { vim: string; rest: string }): RenderElement {
1159  const modeColor = /auto|bypass/i.test(h.rest) ? THEME.warning : /plan/i.test(h.rest) ? THEME.planMode : /accept/i.test(h.rest) ? THEME.autoAccept : p.meta
1160  return t.Text({
1161    wrap: 'truncate-end',
1162    children: [
1163      ...(h.vim ? [t.Text({ color: /INSERT/.test(h.vim) ? p.accentUser : p.meta, children: [h.vim] })] : []),
1164      ...(h.vim && h.rest ? ['  '] : []),
1165      ...(h.rest ? [t.Text({ color: modeColor, children: [h.rest] })] : []),
1166    ],
1167  })
1168}
1169
hooks/glyphs.ts 56 lines
1// Every non-ASCII glyph the mod draws, built from code points. The agent
2// tool path has dropped private-use literals on the way into a file before
3// (the pill caps once shipped as ''), so no glyph outside printable ASCII
4// is ever written as a literal in hooks/, comments included. Verify with:
5//   LC_ALL=C grep -rn '[^ -~]' hooks/   -> must print nothing
6const cp = (n: number) => String.fromCodePoint(n)
7
8export const G = {
9  /** gutter mark beside a paragraph that needs the reader: LEFT ONE QUARTER BLOCK, U+258E */
10  mark: cp(0x258e),
11  /** rules and table header line: BOX DRAWINGS LIGHT HORIZONTAL, U+2500 */
12  rule: cp(0x2500),
13  /** list markers: BULLET U+2022, WHITE BULLET U+25E6, BALLOT BOX U+2610, BALLOT BOX WITH CHECK U+2611 */
14  dot: cp(0x2022),
15  ring: cp(0x25e6),
16  box: cp(0x2610),
17  check: cp(0x2611),
18  /** separator: MIDDLE DOT, U+00B7 */
19  middot: cp(0x00b7),
20  /** HORIZONTAL ELLIPSIS, U+2026 */
21  ellipsis: cp(0x2026),
22  /** tree connectors: BOX DRAWINGS LIGHT VERTICAL AND RIGHT U+251C, VERTICAL U+2502 */
23  tee: cp(0x251c),
24  pipe: cp(0x2502),
25  /** status marks: CHECK MARK U+2713, BALLOT X U+2717, WHITE CIRCLE U+25CB */
26  tick: cp(0x2713),
27  cross: cp(0x2717),
28  hollow: cp(0x25cb),
29  /** FISHEYE U+25C9: the assistant header mark and a folded group */
30  fisheye: cp(0x25c9),
31  /** BLACK DIAMOND U+25C6: the user row and a band row */
32  diamond: cp(0x25c6),
33  /** DOTTED CIRCLE U+25CC: the band header */
34  dotted: cp(0x25cc),
35  /** BLACK RIGHT-POINTING SMALL TRIANGLE U+25B8, DOWN U+25BE: fold chevrons */
36  right: cp(0x25b8),
37  down: cp(0x25be),
38  /** the band's rounded frame: BOX DRAWINGS LIGHT ARC DOWN AND RIGHT U+256D, DOWN AND LEFT U+256E, UP AND RIGHT U+2570, UP AND LEFT U+256F */
39  arcTL: cp(0x256d),
40  arcTR: cp(0x256e),
41  arcBL: cp(0x2570),
42  arcBR: cp(0x256f),
43  /** the count sign in `Bash x3`: MULTIPLICATION SIGN U+00D7 */
44  times: cp(0xd7),
45  /** a status dot: BLACK CIRCLE U+25CF */
46  disc: cp(0x25cf),
47  /** the agent face's smile: UNDERTIE U+203F */
48  smile: cp(0x203f),
49  /** TWO JOINED SQUARES U+29C9: the dots line's Copy button (0.5.0) */
50  copy: cp(0x29c9),
51  /** DOWNWARDS ARROW U+2193: the engine's `down to manage` key */
52  arrowDown: cp(0x2193),
53  /** LEFTWARDS ARROW U+2190: the engine's `left for agents` key */
54  arrowLeft: cp(0x2190),
55}
56
hooks/markdown.ts 351 lines
1// A small markdown reader for assistant replies. It covers what the mod
2// draws itself: paragraphs, headings, lists, fences, rules, tables, quotes
3// and the Bottom line callout. Raw html is kept for the engine's own
4// Markdown element. Streaming-safe: unclosed markup stays literal, and a
5// callout, once its head line is seen, stays a callout as rows arrive.
6
7export type Inline =
8  | { kind: 'text'; text: string }
9  | { kind: 'code'; text: string }
10  | { kind: 'bold' | 'italic' | 'strike'; children: Inline[] }
11  | { kind: 'link'; text: string; href: string }
12
13// `blocks`: fences indented under the item, drawn under its text (0.4.22)
14export type ListItem = { depth: number; marker: string; task?: 'todo' | 'done'; inlines: Inline[]; blocks?: Block[] }
15export type CalloutRow = { label: string; inlines: Inline[] }
16export type Align = 'left' | 'center' | 'right'
17
18export type Block =
19  | { kind: 'paragraph'; inlines: Inline[] }
20  | { kind: 'heading'; level: number; inlines: Inline[] }
21  | { kind: 'code'; lang: string; source: string }
22  | { kind: 'list'; items: ListItem[] }
23  | { kind: 'rule' }
24  | { kind: 'raw'; text: string }
25  | { kind: 'quote'; blocks: Block[] }
26  // align: null where the separator names none (`---`), so a numeric column can right-align
27  | { kind: 'table'; header: Inline[][]; align: (Align | null)[]; rows: Inline[][][]; raw: string }
28  | { kind: 'callout'; title: string; rows: CalloutRow[] }
29
30const LIST_RE = /^(\s*)([-*+]|\d+[.)])\s+(.*)$/
31const TASK_RE = /^\[([ xX])\]\s+(.*)$/
32const HEADING_RE = /^(#{1,6})\s+(.*?)\s*#*\s*$/
33const RULE_RE = /^\s*([-*_])(\s*\1){2,}\s*$/
34const TABLE_SEP_RE = /^\s*\|?\s*:?-+:?\s*(\|\s*:?-+:?\s*)*\|?\s*$/
35// the info string may carry attributes after the language: ```ts title=x
36const FENCE_RE = /^(\s{0,3})(`{3,}|~{3,})\s*([\w+#.-]*)[^`]*$/
37// a fence indented under a list item, any depth
38const ITEM_FENCE_RE = /^(\s+)(`{3,}|~{3,})\s*([\w+#.-]*)[^`]*$/
39const QUOTE_RE = /^\s*>\s?(.*)$/
40const RAW_START_RE = /^\s*<[a-zA-Z!/]/
41// `**Bottom line**`, `**Bottom line**:` and `**Bottom line:**`
42const CALLOUT_HEAD_RE = /^\*\*(Bottom line):?\*\*:?\s*$/i
43const CALLOUT_ROW_RE = /^(?:[-*+]\s+)?\*{0,2}(Verified|Issue|Fix)\s*:?\*{0,2}\s*:?\s+(.*)$/
44
45// U+FE0F after a symbol that is not an emoji by default (U+26A0 and kin)
46const TEXT_SYMBOL_VS16 = new RegExp('(\\P{Emoji_Presentation})' + String.fromCodePoint(0xfe0f), 'gu')
47
48export function parseMarkdown(input: string): Block[] {
49  // the API allows only tab and newline as control characters in a Text;
50  // anything else would get the whole tree refused
51  const text = input
52    .replace(/\r\n?/g, '\n')
53    .replace(/[\x00-\x08\x0b-\x1f\x7f]/g, '')
54    // a variation selector that turns a text-default symbol into an emoji
55    // makes the terminal draw it 2 cells while the engine counts 1, and the
56    // next character is drawn over: keep the symbol, drop the selector
57    .replace(TEXT_SYMBOL_VS16, '$1')
58  const lines = text.split('\n')
59  const blocks: Block[] = []
60  let i = 0
61  // a header line followed by a separator with the same cell count
62  const isTableStart = (idx: number) => {
63    const l = lines[idx]
64    const sep = lines[idx + 1]
65    return l !== undefined && sep !== undefined && l.includes('|') && TABLE_SEP_RE.test(sep) && splitRow(sep).length === splitRow(l).length
66  }
67  const startsBlock = (idx: number) => {
68    const l = lines[idx]!
69    return (
70      FENCE_RE.test(l) || HEADING_RE.test(l) || LIST_RE.test(l) || RULE_RE.test(l) || QUOTE_RE.test(l) || RAW_START_RE.test(l) || isTableStart(idx)
71    )
72  }
73
74  while (i < lines.length) {
75    const line = lines[i]!
76    if (line.trim() === '') {
77      i++
78      continue
79    }
80    const fence = FENCE_RE.exec(line)
81    if (fence) {
82      const marks = fence[2]!
83      const close = new RegExp(`^\\s{0,3}\\${marks[0]}{${marks.length},}\\s*$`)
84      const body: string[] = []
85      i++
86      while (i < lines.length && !close.test(lines[i]!)) body.push(lines[i++]!)
87      i++
88      blocks.push({ kind: 'code', lang: fence[3] ?? '', source: body.join('\n') })
89      continue
90    }
91    const heading = HEADING_RE.exec(line)
92    if (heading) {
93      blocks.push({ kind: 'heading', level: heading[1]!.length, inlines: parseInline(heading[2]!) })
94      i++
95      continue
96    }
97    if (RULE_RE.test(line)) {
98      blocks.push({ kind: 'rule' })
99      i++
100      continue
101    }
102    if (isTableStart(i)) {
103      const start = i
104      const header = splitRow(line)
105      const align = splitRow(lines[i + 1]!).map(alignOf)
106      i += 2
107      const rows: Inline[][][] = []
108      while (i < lines.length && lines[i]!.trim() !== '' && lines[i]!.includes('|')) {
109        rows.push(splitRow(lines[i++]!).map(parseInline))
110      }
111      blocks.push({ kind: 'table', header: header.map(parseInline), align, rows, raw: lines.slice(start, i).join('\n') })
112      continue
113    }
114    if (QUOTE_RE.test(line)) {
115      const inner: string[] = []
116      while (i < lines.length && lines[i]!.trim() !== '') inner.push(lines[i++]!.replace(QUOTE_RE, '$1'))
117      blocks.push({ kind: 'quote', blocks: parseMarkdown(inner.join('\n')) })
118      continue
119    }
120    if (RAW_START_RE.test(line)) {
121      const raw: string[] = []
122      while (i < lines.length && lines[i]!.trim() !== '') raw.push(lines[i++]!)
123      blocks.push({ kind: 'raw', text: raw.join('\n') })
124      continue
125    }
126    if (LIST_RE.test(line)) {
127      const items: { depth: number; marker: string; text: string; blocks: Block[] }[] = []
128      // nesting is the rank of an item's indent among the indents seen so
129      // far, not floor(spaces / 2): `1. a` then `   - b` (three spaces, the
130      // width of `1. `) is one level down, as CommonMark reads it
131      const indents: number[] = []
132      while (i < lines.length) {
133        const l = lines[i]!
134        if (l.trim() === '') {
135          // a blank inside an item's fence is the fence's; otherwise the
136          // list goes on only into another item
137          if (i + 1 < lines.length && (LIST_RE.test(lines[i + 1]!) || ITEM_FENCE_RE.test(lines[i + 1]!)) && items.length > 0) {
138            i++
139            continue
140          }
141          break
142        }
143        const m = LIST_RE.exec(l)
144        const fence = items.length > 0 ? ITEM_FENCE_RE.exec(l) : null
145        if (m) {
146          const indent = m[1]!.replace(/\t/g, '    ').length
147          while (indents.length > 0 && indent < indents[indents.length - 1]!) indents.pop()
148          if (indents.length === 0 || indent > indents[indents.length - 1]!) indents.push(indent)
149          items.push({ depth: indents.length - 1, marker: m[2]!, text: m[3]!, blocks: [] })
150        } else if (fence) {
151          // a fence typed under the item (`1. Run:` then an indented block):
152          // its lines lose the item's indent and draw as a card under the
153          // text, not as inline code with newlines in it (0.4.22)
154          const indent = fence[1]!.length
155          const marks = fence[2]!
156          const close = new RegExp(`^\\s*\\${marks[0]}{${marks.length},}\\s*$`)
157          const body: string[] = []
158          i++
159          while (i < lines.length && !close.test(lines[i]!)) {
160            const row = lines[i++]!
161            body.push(row.slice(Math.min(indent, row.length - row.trimStart().length)))
162          }
163          items[items.length - 1]!.blocks.push({ kind: 'code', lang: fence[3] ?? '', source: body.join('\n') })
164        } else if (/^\s+\S/.test(l) && items.length > 0) {
165          items[items.length - 1]!.text += '\n' + l.trim()
166        } else {
167          break
168        }
169        i++
170      }
171      blocks.push({
172        kind: 'list',
173        items: items.map(it => {
174          const task = TASK_RE.exec(it.text)
175          const blocks = it.blocks.length ? { blocks: it.blocks } : {}
176          if (!task) return { depth: it.depth, marker: it.marker, inlines: parseInline(it.text), ...blocks }
177          return {
178            depth: it.depth,
179            marker: it.marker,
180            task: task[1] === ' ' ? 'todo' : 'done',
181            inlines: parseInline(task[2]!),
182            ...blocks,
183          }
184        }),
185      })
186      continue
187    }
188    const para: string[] = [line]
189    i++
190    while (i < lines.length && lines[i]!.trim() !== '' && !startsBlock(i)) para.push(lines[i++]!)
191    blocks.push(paragraphBlock(para))
192  }
193  return mergeCallouts(blocks)
194}
195
196// `| a | b |` -> ['a', 'b']; a `\|` inside a cell stays a pipe
197function splitRow(line: string): string[] {
198  const cells = line
199    .trim()
200    .replace(/^\|/, '')
201    .replace(/\|$/, '')
202    .split(/(?<!\\)\|/)
203    .map(c => c.trim().replace(/\\\|/g, '|'))
204  return cells
205}
206
207function alignOf(sep: string): Align | null {
208  const left = sep.startsWith(':')
209  const right = sep.endsWith(':')
210  if (left && right) return 'center'
211  if (right) return 'right'
212  return left ? 'left' : null
213}
214
215// a callout row: labelled once `Label:` has arrived, a blank label before
216function calloutRow(line: string): CalloutRow {
217  const m = CALLOUT_ROW_RE.exec(line)
218  return m ? { label: m[1]!, inlines: parseInline(m[2]!) } : { label: '', inlines: parseInline(line) }
219}
220
221// Monotonic: once the head line reads **Bottom line**, the block is a card
222// for the rest of the stream, whatever the rows look like so far
223function paragraphBlock(lines: string[]): Block {
224  const head = CALLOUT_HEAD_RE.exec(lines[0]!)
225  if (head) return { kind: 'callout', title: head[1]!, rows: lines.slice(1).map(calloutRow) }
226  return { kind: 'paragraph', inlines: parseInline(lines.join('\n')) }
227}
228
229// `**Bottom line**` as a title-only card followed by a list: the list items
230// are its rows
231function mergeCallouts(blocks: Block[]): Block[] {
232  const out: Block[] = []
233  for (let i = 0; i < blocks.length; i++) {
234    const b = blocks[i]!
235    const next = blocks[i + 1]
236    if (b.kind === 'callout' && b.rows.length === 0 && next?.kind === 'list') {
237      out.push({ kind: 'callout', title: b.title, rows: next.items.map(it => calloutRow(inlineText(it.inlines))) })
238      i++
239      continue
240    }
241    out.push(b)
242  }
243  return out
244}
245
246export function inlineText(inlines: Inline[]): string {
247  return inlines
248    .map(n => (n.kind === 'text' || n.kind === 'code' || n.kind === 'link' ? n.text : inlineText(n.children)))
249    .join('')
250}
251
252// sticky: matched at `lastIndex`, so a long run is never copied per bracket
253const URL_RE = /https?:\/\/[^\s<>)]+/y
254// `[label](href)` and `[label](href "title")`; the title is not drawn
255const MD_LINK_RE = /\[([^\]]+)\]\(([^)\s]+)(?:\s+"[^"]*")?\)/y
256
257export function parseInline(src: string): Inline[] {
258  const out: Inline[] = []
259  let buf = ''
260  const flush = () => {
261    if (buf) out.push({ kind: 'text', text: buf })
262    buf = ''
263  }
264  const n = src.length
265  let i = 0
266  while (i < n) {
267    const c = src[i]!
268    if (c === '\\' && i + 1 < n && '`*_~[]\\'.includes(src[i + 1]!)) {
269      buf += src[i + 1]
270      i += 2
271      continue
272    }
273    if (c === '`') {
274      let run = 1
275      while (src[i + run] === '`') run++
276      const ticks = '`'.repeat(run)
277      const close = src.indexOf(ticks, i + run)
278      if (close >= 0) {
279        flush()
280        let code = src.slice(i + run, close)
281        if (code.length > 2 && code.startsWith(' ') && code.endsWith(' ')) code = code.slice(1, -1)
282        out.push({ kind: 'code', text: code })
283        i = close + run
284        continue
285      }
286    }
287    if (src.startsWith('**', i) || src.startsWith('__', i) || src.startsWith('~~', i)) {
288      const d = src.slice(i, i + 2)
289      const close = findClose(src, i + 2, d)
290      if (close >= 0) {
291        flush()
292        out.push({ kind: d === '~~' ? 'strike' : 'bold', children: parseInline(src.slice(i + 2, close)) })
293        i = close + 2
294        continue
295      }
296    }
297    if ((c === '*' || c === '_') && i + 1 < n && !/\s/.test(src[i + 1]!) && (c === '*' || i === 0 || !/\w/.test(src[i - 1]!))) {
298      const close = findClose(src, i + 1, c)
299      if (close >= 0) {
300        flush()
301        out.push({ kind: 'italic', children: parseInline(src.slice(i + 1, close)) })
302        i = close + 1
303        continue
304      }
305    }
306    // a link, or an image `![alt](src)`, which a terminal shows as the link
307    // its alt text names (the bang drew as text before 0.4.22)
308    if (c === '[' || (c === '!' && src[i + 1] === '[')) {
309      const at = c === '!' ? i + 1 : i
310      MD_LINK_RE.lastIndex = at
311      const m = MD_LINK_RE.exec(src)
312      if (m) {
313        flush()
314        out.push({ kind: 'link', text: m[1]!, href: m[2]! })
315        i = at + m[0].length
316        continue
317      }
318    }
319    if (c === 'h') {
320      URL_RE.lastIndex = i
321      const m = URL_RE.exec(src)
322      if (m) {
323        // sentence punctuation after a bare URL belongs to the sentence
324        const url = m[0].replace(/[.,;:!?]+$/, '')
325        flush()
326        out.push({ kind: 'link', text: url, href: url })
327        i += url.length
328        continue
329      }
330    }
331    buf += c
332    i++
333  }
334  flush()
335  return out
336}
337
338// the closing delimiter: not preceded by a space, and for `_` not followed
339// by a word character
340function findClose(src: string, from: number, d: string): number {
341  let j = src.indexOf(d, from)
342  while (j >= 0) {
343    // `**bold *nested***`: the bold closes on the last two of the three stars
344    if (d === '**' && src[j + 2] === '*') j += 1
345    const after = src[j + d.length]
346    if (!/\s/.test(src[j - 1]!) && (d[0] !== '_' || after === undefined || !/\w/.test(after))) return j
347    j = src.indexOf(d, j + 1)
348  }
349  return -1
350}
351
hooks/palette.ts 797 lines
1// Colors are raw hex; `Text.color` takes a theme key or a raw color.
2export type Palette = {
3  /**
4   * the terminal ground the palette is drawn for; left out, a dark one.
5   * A light palette's theme takes the engine's light base and its diff
6   * word tints step darker, not lighter (0.16.0)
7   */
8  ground?: 'light'
9  cmd: string
10  sub: string
11  flag: string
12  str: string
13  path: string
14  op: string
15  num: string
16  var: string
17  url: string
18  comment: string
19  /** inline code that is not a shell command */
20  code: string
21  /** H1 and H2 */
22  heading: string
23  /** H3 and deeper */
24  heading3: string
25  /** the reply bullet */
26  accent: string
27  /** list markers: dot, ring and the open task box */
28  bullet: string
29  /** ordered list numbers */
30  orderedNum: string
31  /** heading rules, table borders, horizontal rules */
32  rule: string
33  /** the thin bar down a quote's left edge */
34  quoteBar: string
35  /** success: status dots, the done task mark, ok words in output */
36  ok: string
37  err: string
38  warn: string
39  /** bold prose, brighter than the dimmed terminal fg */
40  bold: string
41  /** tint for code cards and the Bottom line card: one visible step above the terminal bg */
42  blockBg: string
43  /** tool name in a tool row header */
44  tool: string
45  /** Bottom line callout: bar + title, then the three labels and row text */
46  calloutBar: string
47  verified: string
48  issue: string
49  fix: string
50  calloutText: string
51  /** Claude's own planning note (a paragraph opening with Private), drawn italic */
52  private: string
53  /**
54   * gutter mark beside a paragraph that asks something of the reader: the
55   * palette's warn, never ok (it is not "done") and never a bar's color
56   * (the quote and Bottom line bars are the same glyph)
57   */
58  mark: string
59  /** one step under prose: times, counts, durations, the subject of a done tool row */
60  meta: string
61  /** scaffolding: tree connectors, folds, hints */
62  faint: string
63  /** the tint a tree row takes under the pointer */
64  rowHover: string
65  /** the user row's diamond and name */
66  accentUser: string
67  /**
68   * the prompt box border in the palette's theme, where it should not be
69   * `accentUser`; left out, the box takes the person's color (0.14.0)
70   */
71  promptBorder?: string
72  /**
73   * a JSON key in the highlighter, where it should not be `codeStr`; left
74   * out, a key is a string like its value (0.15.2)
75   */
76  jsonKey?: string
77  /** glass's own code highlighter: keywords, calls, types, strings, numbers */
78  codeKw: string
79  codeFn: string
80  codeType: string
81  codeStr: string
82  codeNum: string
83  /** row tints in a diff: an added line, a removed line */
84  addBg: string
85  delBg: string
86}
87
88export type PaletteName = 'tidepool' | 'codex' | 'water' | 'crimson' | 'tarnish' | 'overprint' | 'ironbow' | 'lagoon' | 'iris' | 'tangerine' | 'prism' | 'prism-light' | 'tangerine-light'
89
90// The owner's own nvim theme, ~/Documents/codes/packages/tidepool.nvim,
91// hybrid variant: lifted content over muted scaffolding. Mapped by role:
92// strings -> olive, constants/raw -> pine, functions -> iris, builtins -> foam,
93// links/dirs -> mint, operators quiet, errors -> love, warn -> gold.
94const tidepool: Palette = {
95  cmd: '#d2bdff', // iris: the verb of the line, as functions are
96  sub: '#6cc0e5', // foam: builtins
97  flag: '#96bdff', // parameter blue
98  str: '#9cce8b', // olive
99  path: '#d6b477', // gold_soft: a warm, calm color of its own, so paths never read as links
100  op: '#56738a', // muted operator, by design quiet
101  num: '#7bc0ae', // lifted pine
102  var: '#6cc0e5', // foam: builtin variables
103  url: '#7aa2f7', // mint underline
104  comment: '#86a8a8',
105  code: '#7bc0ae', // @markup.raw = pine
106  heading: '#9cce8b', // olive: the owner's pick over the theme's iris for H2
107  heading3: '#e9b873', // @markup.heading.3 = gold
108  accent: '#6cc0e5', // foam
109  bullet: '#7aa2b5', // punctuation
110  orderedNum: '#7aa2b5',
111  rule: '#48708c', // muted: line numbers, folds
112  quoteBar: '#7bc0ae', // lifted pine: colored, but quieter than foam
113  ok: '#9cce8b', // olive
114  err: '#e67680', // love
115  warn: '#e9b873', // gold
116  bold: '#c5d8e6',
117  blockBg: '#0e2a3a', // one visible step above the bg (1.23:1)
118  tool: '#d083e8', // rose: tags
119  calloutBar: '#6cc0e5', // foam
120  verified: '#9cce8b', // olive
121  issue: '#e67680', // love
122  fix: '#d2bdff', // iris
123  calloutText: '#c5d8e6',
124  private: '#486e6e', // the teal the owner picked for private notes
125  mark: '#e9b873', // warn (gold): a gutter mark reads "read this", apart from ok and the bars
126  meta: '#7aa2b5', // punctuation
127  faint: '#48708c', // muted
128  rowHover: '#0e2a3a', // the block tint
129  accentUser: '#7bc0ae', // lifted pine
130  codeKw: '#7aa2f7', // mint blue: the owner's pick from the engine's reply fence
131  codeFn: '#d2bdff', // iris, the verb's color (0.5.3; olive was both `ok` and the new codeStr)
132  codeType: '#7bc0ae', // pine
133  codeStr: '#9cce8b', // olive, as a string in prose or a shell fence (0.5.3; love was `err`, so a TS string read as an error)
134  codeNum: '#7bc0ae', // pine
135  addBg: '#0e2a3a', // the band tint, not a green: the marker and its color say added (colorblind-safe, owner's pick 2026-10-03)
136  delBg: '#241c2a', // a dim plum, apart from the band on the blue-violet axis
137}
138
139// Empryo's `proxysoul-water` theme, exact: the tokens of PROXYSOUL_WATER
140// over PROXYSOUL_MAIN in Empryo's src/core/theme/tokens.ts (read
141// 2026-10-02). Empryo has no shell-token colors, so the kinds are mapped
142// by role onto its brand set: brand for the verb, brandAlt for builtins
143// and raw, brandSecondary for flags, warning for paths, amber for
144// strings. Text steps are its textPrimary, textSecondary and textMuted;
145// textDim is kept for rules only, since textFaint vanishes off Empryo's
146// own near-black ground.
147const water: Palette = {
148  cmd: '#00a2ce', // brand
149  sub: '#3bb8d8', // brandAlt
150  flag: '#009a8b', // brandSecondary
151  str: '#e65f2a', // amber
152  path: '#948ff0', // periwinkle: water's secondary-text hue with the saturation lifted, so paths sit apart from the cyan code, the mint ok and the grey body text (owner's pick 2026-10-03; #a4a1e8 sat too near the text, sea glass #6ec9ab blurred into code and ok)
153  op: '#8e8ca1', // textSecondary
154  num: '#3bb8d8', // info
155  var: '#009a8b',
156  url: '#6fb0ff', // sky, underlined: a link apart from the brand cyan that tool, cmd and accent share (0.5.3; five roles on one hex)
157  comment: '#8e8ca1',
158  code: '#3bb8d8',
159  heading: '#e7e7ee', // textPrimary
160  heading3: '#3bb8d8',
161  accent: '#00a2ce', // accentAssistant
162  bullet: '#8e8ca1',
163  orderedNum: '#8e8ca1',
164  rule: '#5a5870', // textDim lifted: #3d3b50 is 1.69:1 on night-owl's ground and the rules vanished
165  quoteBar: '#009a8b',
166  ok: '#4fd1a0', // lifted: Empryo's success #0b8b00 is mud on a dark ground
167  err: '#e85c6b', // the dusty rose of Empryo's desktop; its #ee0b2a glares
168  warn: '#de7c00', // warning
169  bold: '#e7e7ee',
170  blockBg: '#0e2a3a', // Empryo's bgElevated #0e1a22 is 1.04:1 on night-owl's ground; this is the 1.23:1 step the other palettes use
171  tool: '#00a2ce',
172  calloutBar: '#00a2ce',
173  verified: '#4fd1a0',
174  issue: '#e85c6b',
175  fix: '#3bb8d8',
176  calloutText: '#d4d4dc', // a step under textPrimary, so the labels lead
177  private: '#6e6c82', // as faint
178  mark: '#de7c00', // warn: the teal it had was the quote bar's, the same glyph
179  meta: '#8e8ca1', // textSecondary
180  faint: '#6e6c82', // textMuted lifted one step: #5c5a6e is 2.7:1 on night-owl's ground
181  rowHover: '#0e2a3a', // same step; Empryo's brandDim #0e2030 is 1.11:1 here
182  accentUser: '#009a8b',
183  codeKw: '#00a2ce',
184  codeFn: '#3bb8d8',
185  codeType: '#de7c00',
186  codeStr: '#e65f2a',
187  codeNum: '#3bb8d8',
188  addBg: '#0e2a3a',
189  delBg: '#33222e', // lifted from #241c2a (1.11:1) toward SPEC's 1.2:1 tint floor
190}
191
192// Empryo's crimson world ("the heart"), read off empryo.com's own CSS
193// (`:root[data-world=crimson][data-theme=dark]`, 2026-10-16). The desktop
194// theme `proxysoul-crimson` is not in Empryo's public tokens.ts yet, so
195// these are the site's tokens mapped by role as water's are: the pigment
196// for the verb, the violet alt for builtins and raw, the pink nucleus for
197// flags, amber for strings. Text steps are its ink, ink-soft and ink-faint.
198const crimson: Palette = {
199  cmd: '#f43a6b', // pigment: the crimson itself
200  sub: '#ab7bf0', // pigment-alt: violet
201  flag: '#ffb3c8', // nucleus: the pink
202  str: '#f2a94c', // the site's warn, as water's amber
203  path: '#8fb6e6', // soft sky: the one cool hue the world lacks, so paths sit apart from the crimson verb, the violet code, the pink flags and the amber strings
204  op: '#9a8499', // ink-faint
205  num: '#ab7bf0', // info
206  var: '#ffb3c8',
207  url: '#6fa8ff', // sky, underlined, a step brighter than path
208  comment: '#9a8499',
209  code: '#ab7bf0',
210  heading: '#f6eaf1', // ink
211  heading3: '#ab7bf0',
212  accent: '#f43a6b',
213  bullet: '#9a8499',
214  orderedNum: '#9a8499',
215  rule: '#664468', // the site's #3f2040 is 1.34:1 on the audit ground; lifted to 2.4:1
216  quoteBar: '#ffb3c8',
217  ok: '#45c98d',
218  err: '#ff6a52', // bad: the site's orange-red, apart from the crimson verb
219  warn: '#f2a94c',
220  bold: '#f6eaf1',
221  blockBg: '#301a34', // pigment-deep #2c1022 is 1.09:1 on the audit ground; this is the 1.2:1 step
222  tool: '#f43a6b',
223  calloutBar: '#f43a6b',
224  verified: '#45c98d',
225  issue: '#ff6a52',
226  fix: '#ab7bf0',
227  calloutText: '#dccbd8', // a step under ink
228  private: '#7a6679', // as faint
229  mark: '#f2a94c', // warn
230  meta: '#9a8499', // ink-faint
231  faint: '#7a6679', // 3.6:1, between rule and meta
232  rowHover: '#3a1f3e', // a step above blockBg
233  accentUser: '#ffb3c8',
234  codeKw: '#f43a6b',
235  codeFn: '#ab7bf0',
236  codeType: '#ffb3c8',
237  codeStr: '#f2a94c',
238  codeNum: '#ab7bf0',
239  addBg: '#301a34', // the plum tint, as the other palettes use their band tint
240  delBg: '#3a2420', // a dim ember toward `bad`, apart from the plum
241}
242
243// glass's own palette (0.11.0), not a port: metals aging. Fresh copper is
244// the verb, Claude's mark and the tool name (what is happening now); the
245// verdigris it weathers to is the settled things: builtins, raw code, the
246// done mark's green cousin, the user's row, the card tint; brass for
247// strings, the steel blue of old blades for paths and links, and the violet
248// sheen on tarnished silver for flags and variables. Every value was placed
249// in OKLCH (one lightness band for the shell kinds, L 0.74-0.83, and one
250// chroma step between a role and its quieter twin) and read against the
251// audit ground #0d1117 and night-owl #011627; text is bone, a warm
252// off-white, never pure.
253const tarnish: Palette = {
254  cmd: '#e9934c', // copper, L0.74 C0.135 h58
255  sub: '#6fcabf', // verdigris, L0.78 C0.09 h185
256  flag: '#bea3df', // tarnish, L0.76 C0.09 h305
257  str: '#e5c370', // brass, L0.83 C0.11 h88
258  path: '#82bad5', // steel, L0.76 C0.07 h230
259  op: '#90847a', // a warm grey, quiet by design
260  num: '#6fcabf', // verdigris, as raw code
261  var: '#bea3df', // tarnish, with the flags
262  url: '#7ac8f5', // steel lifted, underlined
263  comment: '#928b83',
264  code: '#6fcabf',
265  heading: '#e5ddd0', // bone
266  heading3: '#e5c370', // brass, under the bone H2
267  accent: '#e9934c', // copper: Claude's mark, the band
268  bullet: '#928b83',
269  orderedNum: '#928b83',
270  rule: '#405853', // 2.5:1
271  quoteBar: '#60afa5', // verdigris a step under sub
272  ok: '#67d283', // the green verdigris weathers toward; apart from sub by hue (150 vs 185)
273  err: '#f66c6d', // oxblood lifted
274  warn: '#f4a437', // amber: more chroma than the brass strings, apart by 18 degrees
275  bold: '#efe7d9', // bone, brighter
276  blockBg: '#1b2827', // 1.24:1, a dark verdigris
277  tool: '#e9934c',
278  calloutBar: '#e9934c',
279  verified: '#67d283',
280  issue: '#f66c6d',
281  fix: '#bea3df',
282  calloutText: '#d8d0c3', // bone soft
283  private: '#5d6d69', // as faint
284  mark: '#f4a437', // warn
285  meta: '#928b83', // warm grey, 5.6:1
286  faint: '#5d6d69', // 3.5:1
287  rowHover: '#223130', // a step above the card
288  accentUser: '#6fcabf', // the person is the settled one; Claude the copper
289  codeKw: '#e9934c',
290  codeFn: '#82bad5',
291  codeType: '#bea3df',
292  codeStr: '#e5c370',
293  codeNum: '#6fcabf',
294  addBg: '#1b2827', // the verdigris tint
295  delBg: '#34211e', // a dark copper, apart from it by hue
296}
297
298// glass's own (0.12.0): Risograph inks on black paper. The fluorescent
299// inks of a riso print, as the ink charts list them: fluorescent pink for
300// the verb, Claude's mark and the headings, aqua for builtins and the
301// person's row, fluorescent yellow for flags and numbers, orange strings,
302// violet paths, fluorescent green for done, scarlet for failed. The tints
303// are an ink overprinted on black: a deep violet card, a wine removed row,
304// a teal added row. Loud by design; the owner approved the pink headings.
305const overprint: Palette = {
306  cmd: '#ff48b0',  // fluorescent pink
307  sub: '#5ec8e5',  // aqua
308  flag: '#ffe800',  // fluorescent yellow
309  str: '#ff6c2f',  // orange
310  path: '#9d7ad2',  // violet
311  op: '#8f93a0',
312  num: '#ffe800',
313  var: '#ffe800',
314  url: '#62a8e5',
315  comment: '#8f93a0',
316  code: '#5ec8e5',
317  heading: '#ff48b0',
318  heading3: '#ffe800',
319  accent: '#ff48b0',
320  bullet: '#8f93a0',
321  orderedNum: '#8f93a0',
322  rule: '#4a4f7a',  // indigo, 2.4:1
323  quoteBar: '#5ec8e5',
324  ok: '#44d62c',  // fluorescent green
325  err: '#f65058',  // scarlet
326  warn: '#ffb511',  // sunflower
327  bold: '#f2f0e6',  // the paper
328  blockBg: '#241b45',  // violet ink on black, 1.2:1
329  tool: '#ff48b0',
330  calloutBar: '#ff48b0',
331  verified: '#44d62c',
332  issue: '#f65058',
333  fix: '#9d7ad2',
334  calloutText: '#f2f0e6',
335  private: '#5e6390',
336  mark: '#ffb511',
337  meta: '#8f93a0',
338  faint: '#5e6390',  // indigo lifted, 3.3:1
339  rowHover: '#2e2458',
340  accentUser: '#5ec8e5',
341  codeKw: '#ff48b0',
342  codeFn: '#5ec8e5',
343  codeType: '#ffe800',
344  codeStr: '#ff6c2f',
345  codeNum: '#9d7ad2',
346  addBg: '#0f2a33',  // teal ink on black
347  delBg: '#47163a',  // wine ink on black
348}
349
350// glass's own (0.12.0): the thermal camera's ironbow gradient, violet
351// through magenta, red, orange and yellow to white-hot, with heat standing
352// for activity. The verb, Claude's mark and the tool name are yellow, the
353// hottest text; builtins orange; flags magenta; strings violet; paths the
354// cold blue; headings white-hot. Done is cold, so the status dots and the
355// Verified label are blue, not green, and failure is the one red. Placed
356// in OKLCH along the gradient (L 0.66 to 0.88 for the shell kinds).
357const ironbow: Palette = {
358  cmd: '#f9d544',  // yellow, L0.88 h95
359  sub: '#fe8c2c',  // orange, h55
360  flag: '#e45cbe',  // magenta, h340
361  str: '#b093e5',  // violet, h300
362  path: '#6b8fe2',  // cold blue, h265
363  op: '#8b798f',
364  num: '#fe8c2c',
365  var: '#e45cbe',
366  url: '#77a4f6',
367  comment: '#9d8ba2',
368  code: '#fe8c2c',
369  heading: '#faf5e6',  // white-hot
370  heading3: '#f9d544',
371  accent: '#f9d544',
372  bullet: '#9d8ba2',
373  orderedNum: '#9d8ba2',
374  rule: '#584b6f',
375  quoteBar: '#9274c3',
376  ok: '#769cef',  // cold: settled, apart from sub by the whole gradient
377  err: '#fc4447',  // the one red
378  warn: '#fe8c2c',  // orange, as sub: the mark is never a bar color
379  bold: '#faf5e6',
380  blockBg: '#282136',  // the cold tint
381  tool: '#f9d544',
382  calloutBar: '#e45cbe',  // magenta, apart from the orange mark
383  verified: '#769cef',
384  issue: '#fc4447',
385  fix: '#b093e5',
386  calloutText: '#e3decf',
387  private: '#6d6382',
388  mark: '#fe8c2c',
389  meta: '#9d8ba2',
390  faint: '#6d6382',
391  rowHover: '#312941',
392  accentUser: '#b093e5',
393  codeKw: '#f9d544',
394  codeFn: '#fe8c2c',
395  codeType: '#e45cbe',
396  codeStr: '#b093e5',
397  codeNum: '#6b8fe2',
398  addBg: '#282136',
399  delBg: '#3b1c1c',  // red-black
400}
401
402// glass's own (0.13.0): daylight shallows, where water is the night sea.
403// Turquoise leads (the verb, Claude's mark, the band, the bar), sky is the
404// secondary for code and the person's row, flags are hibiscus, strings sun
405// yellow, paths sand, headings and bold white sand; done is palm green,
406// failed coral, the card tint deep water. Placed in OKLCH, L 0.76 to 0.88
407// for the shell kinds, the brightest band of any palette here.
408const lagoon: Palette = {
409  cmd: '#40e5e5',  // turquoise, L0.84 h195
410  sub: '#70d5ed',  // sky, h215
411  flag: '#f786be',  // hibiscus, h350
412  str: '#f2d76c',  // sun yellow, h95
413  path: '#e3cead',  // sand, h80
414  op: '#7e989c',
415  num: '#70d5ed',
416  var: '#f786be',
417  url: '#60ccfc',
418  comment: '#7e989c',
419  code: '#70d5ed',
420  heading: '#f2eee3',  // white sand
421  heading3: '#f2d76c',
422  accent: '#40e5e5',
423  bullet: '#7e989c',
424  orderedNum: '#7e989c',
425  rule: '#3a5c5e',  // 2.6:1
426  quoteBar: '#30b4ad',
427  ok: '#87d576',  // palm green
428  err: '#fd7562',  // coral
429  warn: '#ffa44e',  // mango
430  bold: '#f6f2e7',
431  blockBg: '#12292c',  // deep water, 1.24:1
432  tool: '#40e5e5',
433  calloutBar: '#40e5e5',
434  verified: '#87d576',
435  issue: '#fd7562',
436  fix: '#f786be',
437  calloutText: '#e2ded3',
438  private: '#547275',
439  mark: '#ffa44e',
440  meta: '#7e989c',
441  faint: '#547275',  // 3.6:1
442  rowHover: '#1b3235',
443  accentUser: '#70d5ed',
444  codeKw: '#40e5e5',
445  codeFn: '#70d5ed',
446  codeType: '#f786be',
447  codeStr: '#f2d76c',
448  codeNum: '#e3cead',
449  addBg: '#12292c',
450  delBg: '#36201c',
451}
452
453// glass's own (0.13.0): the flower. Indigo petals lead (the verb, Claude's
454// mark, the band, the bar), the teal of the leaf's underside is the
455// secondary for code and the person's row, the beard is honey so strings
456// are honey; flags and `fix` orchid, paths sky, done leaf green, failed a
457// rose red. The neutrals carry an indigo cast, so the card tint and the
458// rules go violet-grey, which is what moves the page away from the blues.
459// Placed in OKLCH, L 0.74 to 0.82 for the shell kinds.
460const iris: Palette = {
461  cmd: '#92a2ff',  // indigo petal, L0.74 C0.14 h275
462  sub: '#63ccc0',  // teal, h185
463  flag: '#d997d2',  // orchid, h330
464  str: '#e6bd77',  // honey, h80
465  path: '#7dc3de',  // sky, h225
466  op: '#888b99',
467  num: '#63ccc0',
468  var: '#d997d2',
469  url: '#98bcff',
470  comment: '#888b99',
471  code: '#63ccc0',
472  heading: '#e2e4ef',  // lavender white
473  heading3: '#e6bd77',
474  accent: '#92a2ff',
475  bullet: '#888b99',
476  orderedNum: '#888b99',
477  rule: '#4c5169',  // 2.4:1
478  quoteBar: '#44a49e',
479  ok: '#75d78d',  // leaf green
480  err: '#f56b7c',  // rose red
481  warn: '#f0a646',  // amber
482  bold: '#e9eaf5',
483  blockBg: '#202436',  // indigo tint, 1.2:1
484  tool: '#92a2ff',
485  calloutBar: '#92a2ff',
486  verified: '#75d78d',
487  issue: '#f56b7c',
488  fix: '#d997d2',
489  calloutText: '#d5d7e2',
490  private: '#64687b',
491  mark: '#f0a646',
492  meta: '#888b99',
493  faint: '#64687b',  // 3.4:1
494  rowHover: '#292c40',
495  accentUser: '#63ccc0',
496  codeKw: '#92a2ff',
497  codeFn: '#63ccc0',
498  codeType: '#d997d2',
499  codeStr: '#e6bd77',
500  codeNum: '#7dc3de',
501  addBg: '#202436',
502  delBg: '#351f22',
503}
504
505// glass's own (0.14.0): a warm lead on water's cool set, from a brief of
506// "crimson's vibrance, water's cyan, tarnish's warmth". Tangerine is the
507// verb, the tool name, keywords and the Bottom line bar; orange is cyan's
508// complement, so it pops without the edge-vibration a saturated red has on
509// a navy ground (crimson in this seat bled; rose pink and violet were
510// drawn too and turned down). Water's cyan keeps Claude's mark, the band
511// and its tint, and the builtins; the person's row, flags and quote bars
512// are crimson's pink, paths water's periwinkle, strings lemon so they sit
513// apart from the lead, failed a rose red.
514const tangerine: Palette = {
515  cmd: '#ff9248',  // tangerine
516  sub: '#3bb8d8',  // water's brandAlt
517  flag: '#ffb3c8',  // crimson's nucleus pink
518  str: '#ecd06f',  // lemon
519  path: '#948ff0',  // water's periwinkle
520  op: '#8e8ca1',
521  num: '#3bb8d8',
522  var: '#ffb3c8',
523  url: '#6fb0ff',
524  comment: '#8e8ca1',
525  code: '#3bb8d8',
526  heading: '#e7e7ee',
527  heading3: '#ffb3c8',
528  accent: '#00a2ce',  // water's brand: Claude's mark, the band
529  bullet: '#8e8ca1',
530  orderedNum: '#8e8ca1',
531  rule: '#5a5870',
532  quoteBar: '#ffb3c8',
533  ok: '#4fd1a0',
534  err: '#ff5c7a',  // rose red, apart from the orange lead
535  warn: '#ecd06f',
536  bold: '#e7e7ee',
537  blockBg: '#0e2a3a',  // water's card tint, 1.23:1
538  tool: '#ff9248',
539  calloutBar: '#ff9248',
540  verified: '#4fd1a0',
541  issue: '#ff5c7a',
542  fix: '#3bb8d8',
543  calloutText: '#d4d4dc',
544  private: '#6e6c82',
545  mark: '#ecd06f',  // warn
546  meta: '#8e8ca1',
547  faint: '#6e6c82',
548  rowHover: '#143444',  // a step above the card
549  accentUser: '#ffb3c8',
550  codeKw: '#ff9248',
551  codeFn: '#3bb8d8',
552  codeType: '#ffb3c8',
553  codeStr: '#ecd06f',
554  codeNum: '#948ff0',
555  addBg: '#0e2a3a',
556  delBg: '#33222e',
557}
558
559// glass's own (0.14.0), from the owner's starship prompt: the
560// `gradient_modern` palette of ~/.config/starship.toml, each color in the
561// role its prompt segment plays. Coral (color_1, the username segment) is
562// the person's row, flags and types; deep orange (color_2, the directory)
563// paths; steel-cyan strings (0.15.2: Flat UI's Mediterranean Sea lifted
564// in OKLCH, since golden yellow, color_3, glared at 10.6:1 on a JSON-heavy
565// diff) with coral JSON keys; emerald teal (color_4, the
566// toolchains) builtins and raw code; vibrant blue (color_5) the verb, tool
567// and keywords; soft purple (color_6, the clock) Claude's mark, the band,
568// the Bottom line bar and the prompt box. The bright four are the prompt
569// character's states: success neon green for done, error red for failed,
570// vim-command yellow for warn and the mark; the last orange is H3; white
571// (color_fg0) headings and bold. The two dark greys are left out: bg1 is
572// 1.09:1 on night-owl's ground, and the owner chose water's tints over bg3
573// for the cards and diff rows. The neutral steps are greys, as the prompt
574// has none.
575const prism: Palette = {
576  cmd: '#4d96ff',  // color_5 vibrant blue
577  sub: '#43b581',  // color_4 emerald teal
578  flag: '#ff6b6b',  // color_1 coral
579  str: '#4eb4d3',  // Mediterranean Sea #1289a7 lifted: 7.0:1 on the owner's 0.96-opacity ground #0a1f30, 7.7:1 on night-owl's (0.15.2)
580  path: '#e28f2a',  // color_2 deep orange
581  op: '#8a8a8a',
582  num: '#43b581',
583  var: '#ff6b6b',
584  url: '#7fb3ff',  // the blue lifted, underlined
585  comment: '#8a8a8a',
586  code: '#43b581',
587  heading: '#ffffff',  // color_fg0
588  heading3: '#ff9f1a',  // color_10
589  accent: '#8c6ff0',  // color_6 soft purple
590  bullet: '#8a8a8a',
591  orderedNum: '#8a8a8a',
592  rule: '#565656',  // 2.5:1
593  quoteBar: '#43b581',
594  ok: '#32ff7e',  // color_8, the success symbol
595  err: '#e84118',  // color_7, the error symbol
596  warn: '#fff200',  // color_9, the vim command symbol
597  bold: '#ffffff',
598  blockBg: '#0e2a3a',  // water's card tint
599  tool: '#4d96ff',
600  calloutBar: '#8c6ff0',
601  verified: '#32ff7e',
602  issue: '#e84118',
603  fix: '#8c6ff0',
604  calloutText: '#dcdcdc',
605  private: '#6c6c6c',
606  mark: '#fff200',  // warn
607  meta: '#9a9a9a',
608  faint: '#6c6c6c',  // 3.5:1
609  rowHover: '#0e2a3a',  // as water
610  accentUser: '#ff6b6b',  // color_1, the username segment
611  promptBorder: '#8c6ff0',  // the band's purple, the owner's pick over the person's coral
612  codeKw: '#4d96ff',
613  codeFn: '#43b581',
614  codeType: '#ff6b6b',
615  codeStr: '#4eb4d3',
616  jsonKey: '#ff6b6b',  // coral, so a key reads apart from its value (0.15.2)
617  codeNum: '#8c6ff0',
618  addBg: '#0e2a3a',  // water's tints
619  delBg: '#33222e',
620}
621
622// The light pair (0.16.0): prism and tangerine by role, drawn for GitHub
623// Light (ground #ffffff, fg #1f2328), the default light ground of VS Code,
624// the macOS Terminal and GitHub itself. Every text role holds 4.5:1 on it
625// and on the darker light grounds devs run most: One Light #fafafa,
626// Solarized Light #fdf6e3 and Catppuccin Latte #eff1f5; scaffolding (rule,
627// faint, private) keeps the dark palettes' 2.4 to 3.5:1. The neon and
628// pastel steps cannot hold 4.5:1 on white, so each is taken down along its
629// own hue. The tints are a step under white; on Latte the card tint reads
630// as the ground itself.
631const prismLight: Palette = {
632  ground: 'light',
633  cmd: '#1f66d1',
634  sub: '#0f7b4f',
635  flag: '#c42f43',
636  str: '#0b7490',  // Mediterranean Sea #1289a7 taken down to 4.7:1 on Latte
637  path: '#a85000',
638  op: '#6b6b6b',
639  num: '#0f7b4f',
640  var: '#c42f43',
641  url: '#1a5fd0',
642  comment: '#6b6b6b',
643  code: '#0f7b4f',
644  heading: '#11151a',  // a step past the terminal fg, as white is on a dark ground
645  heading3: '#c2410c',
646  accent: '#6b4fd8',
647  bullet: '#6b6b6b',
648  orderedNum: '#6b6b6b',
649  rule: '#a8a8a8',  // 2.4:1, as the dark rule is 2.5:1
650  quoteBar: '#0f7b4f',
651  ok: '#0f7f36',  // the neon green, taken down to 4.5:1 on Latte
652  err: '#c4310f',
653  warn: '#7d6400',  // the vim yellow as a dark gold: yellow cannot reach 4.5:1 on white
654  bold: '#11151a',
655  blockBg: '#e9f3f7',  // water's card tint on white, 1.13:1
656  tool: '#1f66d1',
657  calloutBar: '#6b4fd8',
658  verified: '#0f7f36',
659  issue: '#c4310f',
660  fix: '#6b4fd8',
661  calloutText: '#2f343b',
662  private: '#858585',
663  mark: '#7d6400',
664  meta: '#5f6368',
665  faint: '#8a8a8a',  // 3.5:1, as the dark faint is
666  rowHover: '#dcebf2',
667  accentUser: '#c42f43',
668  promptBorder: '#6b4fd8',
669  codeKw: '#1f66d1',
670  codeFn: '#0f7b4f',
671  codeType: '#c42f43',
672  codeStr: '#0b7490',
673  jsonKey: '#c42f43',
674  codeNum: '#6b4fd8',
675  addBg: '#e9f3f7',
676  delBg: '#f8e8ee',  // a plum step, apart from it by hue
677}
678
679const tangerineLight: Palette = {
680  ground: 'light',
681  cmd: '#c2410c',  // tangerine as orange-700: 4.6:1 on Latte
682  sub: '#0e7490',
683  flag: '#be185d',
684  str: '#8a6400',  // lemon as a dark gold: yellow cannot reach 4.5:1 on white
685  path: '#5b55d6',
686  op: '#6b6b80',
687  num: '#0e7490',
688  var: '#be185d',
689  url: '#1a64cc',
690  comment: '#6b6b80',
691  code: '#0e7490',
692  heading: '#11151a',  // a step past the terminal fg
693  heading3: '#be185d',
694  accent: '#006f99',  // water's brand, taken down
695  bullet: '#6b6b80',
696  orderedNum: '#6b6b80',
697  rule: '#acacba',
698  quoteBar: '#be185d',
699  ok: '#17774a',
700  err: '#d1243f',
701  warn: '#8a6400',
702  bold: '#11151a',
703  blockBg: '#e9f3f7',  // water's card tint on white, 1.13:1
704  tool: '#c2410c',
705  calloutBar: '#c2410c',
706  verified: '#17774a',
707  issue: '#d1243f',
708  fix: '#0e7490',
709  calloutText: '#2f343b',
710  private: '#8a8a9a',
711  mark: '#8a6400',
712  meta: '#5c5c70',
713  faint: '#8a8a9a',  // 3.4:1
714  rowHover: '#dcebf2',
715  accentUser: '#be185d',
716  codeKw: '#c2410c',
717  codeFn: '#0e7490',
718  codeType: '#be185d',
719  codeStr: '#8a6400',
720  codeNum: '#5b55d6',
721  addBg: '#e9f3f7',
722  delBg: '#f8e8ee',  // a plum step, apart from it by hue
723}
724
725// Every palette spells out every required key: no shared block, so a theme reads whole.
726export const PALETTES: Record<PaletteName, Palette> = {
727  tidepool,
728  water,
729  crimson,
730  tarnish,
731  overprint,
732  ironbow,
733  lagoon,
734  iris,
735  tangerine,
736  prism,
737  'prism-light': prismLight,
738  'tangerine-light': tangerineLight,
739  // One Dark, filled out by role:
740  // cyan for the marks and bars, the gutter greys from the theme's own
741  // comment and line-number steps.
742  codex: {
743    cmd: '#6fb3ff',
744    sub: '#7fc8b8',
745    flag: '#e78fc7',
746    str: '#e5c07b',
747    path: '#56b6c2',
748    op: '#6fb3ff',
749    num: '#d19a66',
750    var: '#98c379',
751    url: '#6fb3ff',
752    comment: '#7a9a9a',
753    code: '#e5c07b',
754    heading: '#c678dd',
755    heading3: '#e5c07b', // the theme's yellow, under the purple H2
756    accent: '#c678dd',
757    bullet: '#7a9a9a',
758    orderedNum: '#7a9a9a',
759    rule: '#5f7a7a', // a step under meta (0.5.3; the comment grey outranked faint, so table rules beat tree connectors)
760    quoteBar: '#7fc8b8', // the sub teal, apart from the purple headings
761    ok: '#98c379',
762    err: '#e06c75',
763    warn: '#e5c07b',
764    bold: '#dcdfe4', // the theme's fg, lifted
765    blockBg: '#0e2a3a', // the one visible step above the night-owl ground
766    tool: '#c678dd',
767    calloutBar: '#56b6c2', // cyan
768    verified: '#98c379',
769    issue: '#e06c75',
770    fix: '#c678dd',
771    calloutText: '#dcdfe4',
772    private: '#4b6a6a', // a teal step under the comment grey
773    mark: '#e5c07b', // warn
774    meta: '#8a97a8', // the theme's line-number grey, lifted
775    faint: '#62707f', // its gutter grey lifted to 3.7:1 (0.5.3; #4f5b6b was 2.7:1)
776    rowHover: '#0e2a3a',
777    accentUser: '#98c379',
778    codeKw: '#c678dd',
779    codeFn: '#61afef',
780    codeType: '#e5c07b',
781    codeStr: '#98c379',
782    codeNum: '#d19a66',
783    addBg: '#0e2a3a',
784    delBg: '#241c2a',
785  },
786}
787
788/** the palette's name from the option's value: one of the thirteen, tidepool for anything else */
789export function paletteNameOf(name: unknown): PaletteName {
790  if (name === 'codex' || name === 'water' || name === 'crimson' || name === 'tarnish' || name === 'overprint' || name === 'ironbow' || name === 'lagoon' || name === 'iris' || name === 'tangerine' || name === 'prism' || name === 'prism-light' || name === 'tangerine-light') return name
791  return 'tidepool'
792}
793
794export function paletteNamed(name: unknown): Palette {
795  return PALETTES[paletteNameOf(name)]
796}
797
hooks/theme.ts 123 lines
1// The engine's theme and glass, both ways (0.5.0).
2//
3// Forward: where glass mirrors an engine panel it names the theme's own
4// slot, not a hex, so the drawing follows whatever theme is active: the
5// diff card's tints and marks, the hint line's mode word. THEME holds the
6// slot names a Text or Box color may carry.
7//
8// Reverse: every palette has a theme. `themeFor` maps a palette's roles onto
9// the engine's slots by one fixed table, and `/glass-theme` writes the result
10// to ~/.claude/themes/glass-<palette>.json. Under a glass theme the forward
11// slots resolve to the palette's own colors, so the two directions agree.
12import type { Palette, PaletteName } from './palette'
13
14/** the theme slots glass reads, by the names the engine resolves */
15export const THEME = {
16  success: 'success',
17  error: 'error',
18  planMode: 'planMode',
19  autoAccept: 'autoAccept',
20  warning: 'warning',
21  diffAdded: 'diffAdded',
22  diffRemoved: 'diffRemoved',
23  diffAddedWord: 'diffAddedWord',
24  diffRemovedWord: 'diffRemovedWord',
25} as const
26
27/** a custom theme as ~/.claude/themes/<name>.json holds it */
28export type ThemeFile = {
29  name: string
30  base: 'dark' | 'light'
31  overrides: Record<string, string>
32}
33
34// slot -> palette role; a role the palette leaves empty leaves the slot out
35const SLOTS: ReadonlyArray<[slot: string, role: keyof Palette]> = [
36  ['success', 'ok'],
37  ['error', 'err'],
38  ['warning', 'warn'],
39  ['claude', 'accent'],
40  ['permission', 'tool'],
41  ['planMode', 'cmd'],
42  ['autoAccept', 'ok'], // the engine's own autoAccept is a green (0.5.3; `warn` made it one color with `warning`)
43  // the prompt box is the person's: it takes their color, as the user row
44  // does (0.10.1; `rule` is a grey step in water, codex and rose, so the
45  // border looked uncolored); bash mode takes the verb's. A palette may set
46  // its own `promptBorder` (0.14.0: prism's box takes the band's purple)
47  ['promptBorder', 'promptBorder'],
48  ['bashBorder', 'cmd'],
49  ['secondaryBorder', 'rule'],
50  // no `text` row: prose is the terminal's own foreground in every palette
51  ['secondaryText', 'meta'],
52  ['inactive', 'faint'],
53  ['subtle', 'faint'],
54  ['suggestion', 'url'],
55  ['userMessageBackground', 'blockBg'],
56  ['bashMessageBackgroundColor', 'blockBg'],
57  ['userMessageBackgroundHover', 'rowHover'],
58  ['thinking', 'private'],
59  ['diffAdded', 'addBg'],
60  ['diffRemoved', 'delBg'],
61  ['diffAddedDimmed', 'addBg'],
62  ['diffRemovedDimmed', 'delBg'],
63]
64
65// the engine paints diff*Word as the background behind a changed word, a
66// step brighter than the row tint; a text color there was a bright block
67// behind the text (0.5.3). Lifted from the row tint toward white; on a
68// light palette, deepened toward black (0.16.0)
69const LIFT = 0.18
70const DEEPEN = 0.1
71const WORD_SLOTS: ReadonlyArray<[slot: string, role: keyof Palette]> = [
72  ['diffAddedWord', 'addBg'],
73  ['diffRemovedWord', 'delBg'],
74]
75export function lift(hex: string, k = LIFT): string {
76  const ch = (i: number) => parseInt(hex.slice(1 + 2 * i, 3 + 2 * i), 16)
77  return '#' + [0, 1, 2].map(i => Math.round(ch(i) + (255 - ch(i)) * k).toString(16).padStart(2, '0')).join('')
78}
79export function deepen(hex: string, k = DEEPEN): string {
80  const ch = (i: number) => parseInt(hex.slice(1 + 2 * i, 3 + 2 * i), 16)
81  return '#' + [0, 1, 2].map(i => Math.round(ch(i) * (1 - k)).toString(16).padStart(2, '0')).join('')
82}
83
84/** a palette's word tint: a step from its row tint, away from the ground */
85export function wordTint(p: Palette, hex: string): string {
86  return p.ground === 'light' ? deepen(hex) : lift(hex)
87}
88
89const HEX = /^#[0-9a-f]{6}$/i
90
91// an optional role and the role that stands in when a palette leaves it out
92const FALLBACK: Partial<Record<keyof Palette, keyof Palette>> = { promptBorder: 'accentUser' }
93
94/** the file name a palette's theme is written under, inside ~/.claude/themes */
95export function themeFileName(name: PaletteName): string {
96  return `glass-${name}.json`
97}
98
99/** the `theme` setting that selects a palette's theme */
100export function themeSetting(name: PaletteName): string {
101  return `custom:glass-${name}`
102}
103
104/** a palette's theme: every slot in the table whose role holds a hex color */
105export function themeFor(p: Palette, name: PaletteName): ThemeFile {
106  const overrides: Record<string, string> = {}
107  for (const [slot, role] of SLOTS) {
108    const stand = FALLBACK[role]
109    const v = p[role] ?? (stand ? p[stand] : undefined)
110    if (typeof v === 'string' && HEX.test(v)) overrides[slot] = v.toLowerCase()
111  }
112  for (const [slot, role] of WORD_SLOTS) {
113    const v = p[role]
114    if (typeof v === 'string' && HEX.test(v)) overrides[slot] = wordTint(p, v).toLowerCase()
115  }
116  return { name: `glass-${name}`, base: p.ground ?? 'dark', overrides }
117}
118
119/** the theme as the file holds it: serialised, never templated */
120export function themeJson(theme: ThemeFile): string {
121  return JSON.stringify(theme, null, 2) + '\n'
122}
123
hooks/prose.ts 82 lines
1// What a paragraph of Claude's prose asks of the reader: a question, an opening instruction, or an attention phrase
2// earns a gutter mark. Matters of wording, decided by small tables.
3
4const ATTENTION = [
5  // asks of the reader
6  'you need', "you'll need", 'you must', 'you should', 'you have to', 'you may want', 'you might want',
7  "you can't", 'you cannot', "don't forget", 'your call', 'up to you', 'let me know',
8  'do you want', 'should i', 'which one', 'manually', 'by hand', 'before you', 'if you want', 'on your machine',
9  'your machine', 'your terminal', 'yourself', 'restart', 'reboot', 'reinstall', 're-run', 'rerun', 'log in',
10  'sign in',
11  // what did not happen
12  'not verif*', "can't verify", 'cannot verify', 'could not verify', "couldn't verify", 'unverified',
13  'untested', 'not tested', 'no tests', 'i did not', "i didn't", "i haven't", 'i could not', "i couldn't",
14  'skipped', 'left out', 'blocked', 'not yet', "won't work", 'will not work', 'does not work', "doesn't work",
15  'still fail*', 'keeps fail*', 'regress*', 'assum*',
16  // risk
17  'warning', 'caution', 'careful', 'risk*', 'danger*', 'breaking', 'irreversib*', 'destructive', 'data loss',
18  'backup', 'security', 'vulnerab*', 'secret*', 'credential*', 'password*', 'deprecat*', 'caveat*', 'however',
19  'important', 'todo', 'fixme',
20]
21
22// openers that make the paragraph an instruction to the reader
23const IMPERATIVE = [
24  'run', 'set', 'add', 'install', 'restart', 'open', 'check', 'update', 'remove', 'delete', 'replace',
25  'rename', 'export', 'copy', 'paste', 'change', 'edit', 'enable', 'disable', 'confirm', 'review', 'decide',
26  'choose', 'pick', 'try', 'note', 'beware', 'remember', "don't", 'do not', 'never', 'always', 'please',
27  'make sure', 'be sure',
28]
29
30// verbs near the front of a prompt that ask Claude to write something rather
31// than do something: the reply is then the thing itself, and nothing in it
32// asks the reader for anything
33const WRITE_WORDS = new Set([
34  'write', 'draft', 'compose', 'reword', 'rewrite', 'rephrase', 'translate', 'proofread', 'polish',
35  'shorten', 'expand', 'summarize', 'summarise',
36])
37
38const RIGHT_QUOTE = String.fromCodePoint(0x2019)
39
40// ` word word ? word ` so phrases match on word boundaries
41function normalize(text: string): string {
42  let norm = ' '
43  let inWord = false
44  for (const c of text) {
45    const keep = /[\p{L}\p{N}]/u.test(c) || c === "'" || c === RIGHT_QUOTE || (c === '-' && inWord)
46    if (keep) {
47      norm += c === RIGHT_QUOTE ? "'" : c.toLowerCase()
48      inWord = true
49    } else {
50      if (inWord) norm += ' '
51      inWord = false
52      if (c === '?') norm += '? '
53    }
54  }
55  if (inWord) norm += ' '
56  return norm
57}
58
59/** does this paragraph need the reader? */
60export function needsAttention(text: string): boolean {
61  const norm = normalize(text)
62  if (norm.includes(' ? ')) return true
63  const body = norm.slice(1)
64  if (IMPERATIVE.some(w => body.startsWith(w + ' '))) return true
65  return ATTENTION.some(p => (p.endsWith('*') ? norm.includes(' ' + p.slice(0, -1)) : norm.includes(` ${p} `)))
66}
67
68/** does the prompt ask Claude to write something? one of WRITE_WORDS in its first six words */
69export function writeIntent(prompt: string): boolean {
70  return prompt
71    .toLowerCase()
72    .split(/[^\p{L}\p{N}]+/u)
73    .filter(w => w.length > 0)
74    .slice(0, 6)
75    .some(w => WRITE_WORDS.has(w))
76}
77
78/** Claude's own planning note: a paragraph opening with Private or Privately */
79export function isPrivateNote(text: string): boolean {
80  return /^Privately?\b/.test(text.trimStart())
81}
82
hooks/render.ts 731 lines
1// Draws a parsed reply as an element tree, following SPEC.md: full-width
2// prose, one rhythm rule, color-only inline code, two content-fit tinted
3// cards, one glyph family (see glyphs.ts), one width ruler (see width.ts).
4import type { Elements, RenderElement, RenderNode } from 'claude-code'
5
6import { G } from './glyphs'
7import { codeColor, highlight } from './highlight'
8import { inlineText } from './markdown'
9import type { Align, Block, CalloutRow, Inline, ListItem } from './markdown'
10import type { Palette } from './palette'
11import { bareWord, isUrl, pathLike } from './paths'
12import { isPrivateNote, needsAttention } from './prose'
13import { proseSpans, shellSpans } from './shell'
14import type { SpanKind } from './shell'
15import { cellWidth, clipMiddle } from './width'
16
17type Table = Elements['terminal']
18
19type Ctx = {
20  t: Table
21  p: Palette
22  /** the prose measure in cells */
23  m: number
24  /** a color for plain prose, when the block mutes it (a quote's `meta`) */
25  tone?: string
26}
27
28export type RenderOptions = {
29  /** the first text block of a reply: keeps a blank row above */
30  first?: boolean
31  columns: number
32  /** gutter marks beside paragraphs that need the reader; off when the prompt asked for writing */
33  marks: boolean
34  /** a compaction summary (0.5.0): one faint ` . summary` row closes the reply, as the engine's own mark reads */
35  summary?: boolean
36}
37
38const LABEL_WIDTH = 8
39const LABEL_COLOR: Record<string, keyof Palette> = {
40  Verified: 'verified',
41  Issue: 'issue',
42  Fix: 'fix',
43}
44
45// the API bounds a Text or Code string at this many characters
46const MAX_TEXT = 10000
47
48// A run as strings the API takes: past MAX_TEXT characters it goes as
49// several, side by side in the same Text, so it draws the same. A cut
50// never splits a surrogate pair.
51function cut(s: string): string[] {
52  if (s.length <= MAX_TEXT) return [s]
53  const out: string[] = []
54  for (let i = 0; i < s.length; ) {
55    let end = Math.min(s.length, i + MAX_TEXT)
56    const last = s.charCodeAt(end - 1)
57    if (end < s.length && last >= 0xd800 && last <= 0xdbff) end--
58    out.push(s.slice(i, end))
59    i = end
60  }
61  return out
62}
63// a tinted card never gets narrower than this
64const CARD_MIN = 60
65// how far H2 steps from the heading color toward `meta`
66const H2_STEP = 0.4
67// a table column squeezed to fit never gets narrower than this
68const COL_MIN = 4
69// a table cell that reads as a number: an optional approximation mark, sign
70// or currency mark, digits with separators, then a percent, a multiplier or
71// a short unit, with a per-unit tail (`1.5k`, `12ms`, `3GB`, `4.5MB/s`, `~2x`)
72const NUMERIC_RE = new RegExp(
73  '^[~<>' + String.fromCodePoint(0x2248) + ']?[-+]?[$' + String.fromCodePoint(0xa3, 0x20ac) + ']?\\d[\\d.,]*(?:%|' + String.fromCodePoint(0xd7) + '|[A-Za-z' + String.fromCodePoint(0xb5) + ']{1,4}(?:/[A-Za-z]{1,3})?)?$',
74)
75// a cell that stands for no value: it decides nothing, as an empty cell does
76// not (one dash in a column of numbers flipped the whole column left)
77const PLACEHOLDER_RE = new RegExp('^(?:-|' + String.fromCodePoint(0x2013) + '|' + String.fromCodePoint(0x2014) + '|n/a|N/A|\\?|' + String.fromCodePoint(0x2026) + ')$')
78
79// a color `k` of the way from `a` to `b`; a non-hex color stays `a`
80function blend(a: string, b: string, k: number): string {
81  const hex = /^#[0-9a-f]{6}$/i
82  if (!hex.test(a) || !hex.test(b)) return a
83  const ch = (s: string, i: number) => parseInt(s.slice(1 + 2 * i, 3 + 2 * i), 16)
84  return '#' + [0, 1, 2].map(i => Math.round(ch(a, i) + (ch(b, i) - ch(a, i)) * k).toString(16).padStart(2, '0')).join('')
85}
86
87// inside backticks a path needs a slash or a `:line` suffix:
88// `hooks/render.ts:88`, `src/main.rs`, `~/.zshrc`; not `shell.ts`
89const PATH_RE = /^(?:~|\.{1,2})?[\w.-]*(?:\/[\w.-]+)+\/?(?::\d+(?::\d+)?)?$|^[\w.-]+\.\w+:\d+(?::\d+)?$/
90
91export function measure(columns: number): number {
92  return Math.max(20, columns - 2)
93}
94
95// the words of a run of inlines: code spans and link targets left out, so a
96// `?` in `foo?.bar` or in a URL's query never marks the paragraph (0.4.22)
97function proseText(inlines: Inline[]): string {
98  return inlines
99    .map(n => (n.kind === 'text' ? n.text : n.kind === 'code' || n.kind === 'link' ? ' ' : proseText(n.children)))
100    .join('')
101}
102
103// cells a run of inlines takes once drawn
104function inlineWidth(inlines: Inline[]): number {
105  return inlines.reduce((n, node) => {
106    switch (node.kind) {
107      case 'text':
108      case 'link':
109      case 'code':
110        return n + cellWidth(node.text)
111      default:
112        return n + inlineWidth(node.children)
113    }
114  }, 0)
115}
116
117// a card hugs its content: the widest row plus padding, floored, capped
118function cardWidth(m: number, content: number): number {
119  return Math.min(m, Math.max(CARD_MIN, content))
120}
121
122export function renderReply(t: Table, blocks: Block[], p: Palette, o: RenderOptions): RenderElement {
123  const c: Ctx = { t, p, m: measure(o.columns) }
124  const rows: RenderElement[] = []
125  let prev: Block['kind'] | null = null
126  blocks.forEach((b, i) => {
127    const el = renderBlock(c, b)
128    // one rhythm rule: a blank above every block except the first and any
129    // text block right under a heading; the reply's first block keeps a
130    // blank, so it never sits glued to the tool rows above. No bullet: the
131    // assistant header under the user row carries it. A card, a table or a
132    // Bottom line keeps its blank under a heading: a tint or a second bold
133    // row glued to the heading read as one crowded block.
134    const tight = prev === 'heading' && b.kind !== 'code' && b.kind !== 'table' && b.kind !== 'callout'
135    const marginTop = i === 0 ? (o.first ? 1 : 0) : tight ? 0 : 1
136    // a paragraph that asks something of the reader gets a gutter mark in
137    // the two cells every other block leaves blank
138    const marked = o.marks && b.kind === 'paragraph' && !isPrivateNote(inlineText(b.inlines)) && needsAttention(proseText(b.inlines))
139    if (marked) {
140      rows.push(
141        t.Box({
142          flexDirection: 'row',
143          marginTop,
144          children: [t.Text({ color: p.mark, children: [G.mark + ' '] }), t.Box({ flexDirection: 'column', flexGrow: 1, flexShrink: 1, children: [el] })],
145        }),
146      )
147    } else {
148      rows.push(t.Box({ flexDirection: 'column', marginLeft: 2, marginTop, children: [el] }))
149    }
150    prev = b.kind
151  })
152  // a compaction summary ends on its own faint mark, as the engine's does
153  if (o.summary) rows.push(t.Box({ flexDirection: 'column', marginLeft: 2, children: [t.Text({ color: p.faint, children: [G.middot + ' summary'] })] }))
154  return t.Box({ flexDirection: 'column', children: rows })
155}
156
157function renderBlock(c: Ctx, b: Block): RenderElement {
158  const { t, p, m } = c
159  switch (b.kind) {
160    case 'paragraph': {
161      // Claude's own planning note, drawn italic in a quiet color so the
162      // real answer stands out
163      if (isPrivateNote(inlineText(b.inlines))) {
164        return t.Box({ width: m, children: [t.Text({ wrap: 'wrap', italic: true, color: p.private, children: cut(inlineText(b.inlines)) })] })
165      }
166      return t.Box({ width: m, children: [t.Text({ wrap: 'wrap', children: renderInlines(c, b.inlines) })] })
167    }
168    case 'heading':
169      return t.Text({
170        bold: true,
171        // H2 one step under H1, toward `meta`, so section levels survive a long reply
172        color: b.level >= 3 ? p.heading3 : b.level === 2 ? blend(p.heading, p.meta, H2_STEP) : p.heading,
173        children: renderInlines(c, b.inlines),
174      })
175    case 'code':
176      return renderFence(c, b.lang, b.source)
177    case 'list':
178      return renderList(c, b.items)
179    case 'rule':
180      return t.Text({ color: p.rule, children: [G.rule.repeat(Math.min(m, CARD_MIN))] })
181    case 'raw':
182      return t.Markdown({ text: b.text.slice(0, MAX_TEXT) })
183    case 'quote':
184      return renderQuote(c, b.blocks)
185    case 'table':
186      return renderTable(c, b.header, b.align, b.rows, b.raw)
187    case 'callout':
188      return renderCallout(c, b.title, b.rows)
189  }
190}
191
192// a fence with no language (or a plain-text one) whose rows are mostly
193// arrows, box-drawing, block or shape glyphs, or their ASCII stand-ins, is
194// a picture, not code
195const DIAGRAM_LANGS = new Set(['', 'text', 'txt', 'ascii', 'diagram'])
196
197function isDrawingGlyph(code: number): boolean {
198  return (code >= 0x2190 && code <= 0x21ff) || (code >= 0x2500 && code <= 0x25ff)
199}
200
201// the same pictures drawn in plain ASCII: a corner or tree branch (`+--`,
202// `|--`, `` `-- ``), a line into a corner (`--+`), a two-dash arrow (`-->`,
203// `<==`), a row boxed at both ends, or a connector row of `|`, `v`, `^`.
204// One dash is code's (`->`, `=>`), so it never counts, nor a corner after a
205// `+` (a diffstat's `+++---`)
206const ASCII_DRAWN = [
207  /(?<!\+)[+|`\\][-=]{2,}/,
208  /[-=]{2,}[+|]/,
209  /<[-=]{2,}|[-=]{2,}>/,
210  /^\s*\|.*\|\s*$/,
211  /^[\s|v^]*[|v^][\s|v^]*$/,
212]
213
214function isDrawnRow(row: string): boolean {
215  return [...row].some(ch => isDrawingGlyph(ch.codePointAt(0)!)) || ASCII_DRAWN.some(re => re.test(row))
216}
217
218function isDiagram(lang: string, source: string): boolean {
219  if (!DIAGRAM_LANGS.has(lang.toLowerCase())) return false
220  const rows = source.split('\n').filter(l => l.trim() !== '')
221  const drawn = rows.filter(isDrawnRow).length
222  return rows.length > 0 && drawn * 2 >= rows.length
223}
224
225// what a fence draws, worked out once for renderFence and blockRows so the
226// quote bar cannot drift from the card (0.4.0 dropped the short header in
227// renderFence alone, and the bar ran a row long until 0.4.9)
228interface FenceShape {
229  code: string
230  lines: string[]
231  diagram: boolean
232  gutter: boolean // the numbered gutter and the header row, past 8 lines
233  digits: number
234  width: number // the card, padding included
235}
236
237function fenceShape(lang: string, source: string, m: number): FenceShape {
238  // tabs expand here: the terminal jumps a tab without painting the card's
239  // tint, and the engine counts it as one cell (as renderDiff does)
240  const code = source.replace(/\n$/, '').replace(/\t/g, '    ')
241  const lines = code === '' ? [] : code.split('\n')
242  const diagram = isDiagram(lang, code)
243  const gutter = !diagram && lines.length > 8
244  const digits = String(lines.length).length
245  const widest = Math.max(0, ...lines.map(cellWidth))
246  const header = cellWidth(lang) + (gutter ? cellWidth(`${lines.length} lines`) + 2 : 0)
247  const width = cardWidth(m, Math.max(widest + (gutter ? digits + 2 : 0), header) + 2)
248  return { code, lines, diagram, gutter, digits, width }
249}
250
251// rows a fence draws: the header, then a row per line, more where a code
252// line wraps (its indent counts, the engine keeps leading spaces); a
253// diagram's rows are cut, never wrapped
254function fenceRows(s: FenceShape): number {
255  const text = s.width - 2 - (s.gutter ? s.digits + 2 : 0)
256  const wrapped = (l: string) => wrappedLines([{ kind: 'text', text: l.replace(/^ +/, i => 'x'.repeat(i.length)) }], text)
257  const body = s.diagram ? s.lines.length : s.lines.reduce((n, l) => n + wrapped(l), 0)
258  return (s.gutter ? 1 : 0) + Math.max(1, body)
259}
260
261// tinted card sized to its code: dim language left and line count right in
262// the header row, glass's own highlighter below, a gutter once long. A
263// diagram draws as typed: no header or gutter, rows cut at the card edge,
264// since a wrapped row breaks every box and arrow below it
265function renderFence(c: Ctx, lang: string, source: string): RenderElement {
266  const { t, p } = c
267  const { code, lines: codeLines, diagram, gutter, digits, width } = fenceShape(lang, source, c.m)
268  const lines = codeLines.length
269  const children: RenderElement[] = []
270  // a short fence has no header row: the highlighter colors by the
271  // language and the code says what it is (proposal 14, 2026-10-04)
272  if (gutter) {
273    children.push(
274      t.Box({
275        flexDirection: 'row',
276        children: [
277          t.Text({ color: p.faint, children: [lang ? lang.toUpperCase() : ''] }),
278          t.Box({ flexGrow: 1, children: [] }),
279          t.Text({ color: p.faint, children: [`${lines} lines`] }),
280        ],
281      }),
282    )
283  }
284  // the body is glass's own highlighter (hooks/highlight.ts), one row per
285  // line, the gutter in `faint` once over 8 lines: the engine's `Code`
286  // paints with a theme the owner rejected (2026-10-03)
287  highlight(code, lang.toLowerCase()).forEach((spans, i) => {
288    // a blank line is one space, so its row is drawn: a Text with no text
289    // may measure no rows at all, and the card would lose its blank lines
290    const body = t.Text({
291      wrap: diagram ? 'truncate-end' : 'wrap',
292      children: spans.length === 0 ? [' '] : spans.flatMap((s): RenderNode[] => (s.kind === 'plain' ? cut(s.text) : [t.Text({ color: codeColor(p, s.kind), children: cut(s.text) })])),
293    })
294    children.push(
295      gutter
296        ? t.Box({
297            flexDirection: 'row',
298            children: [
299              t.Text({ color: p.faint, children: [String(i + 1).padStart(digits) + '  '] }),
300              t.Box({ flexGrow: 1, flexShrink: 1, children: [body] }),
301            ],
302          })
303        : body,
304    )
305  })
306  return t.Box({
307    flexDirection: 'column',
308    width,
309    backgroundColor: p.blockBg,
310    paddingLeft: 1,
311    paddingRight: 1,
312    children,
313  })
314}
315
316
317// where each item sits: a child hangs off its parent's text column, so
318// under `1. Install` the ring lands under the `I`, as CommonMark renderers
319// and Claude Desktop draw it (`depth * 2` put it under the period); ordered
320// markers pad to the widest at their own depth
321type ListLayout = { indent: number[]; numWidth: number[] }
322function listLayout(items: ListItem[]): ListLayout {
323  const numWidth: number[] = []
324  for (const it of items) {
325    if (/^\d/.test(it.marker) && !it.task) numWidth[it.depth] = Math.max(numWidth[it.depth] ?? 0, cellWidth(it.marker))
326  }
327  const cols: number[] = []
328  const marks: number[] = []
329  const indent = items.map(it => {
330    const d = it.depth
331    const col = d === 0 ? 0 : (cols[d - 1] ?? 0) + (marks[d - 1] ?? 2)
332    cols[d] = col
333    marks[d] = itemMarker(it, numWidth[d] ?? 0)
334    return col
335  })
336  return { indent, numWidth: Array.from(numWidth, n => n ?? 0) }
337}
338
339function renderList(c: Ctx, items: ListItem[]): RenderElement {
340  const { t, p, m } = c
341  const { indent, numWidth } = listLayout(items)
342  const marker = (it: ListItem): RenderElement => {
343    // a done task is the one list mark that gets a color, as in tidepool
344    if (it.task === 'done') return t.Text({ color: p.ok, children: [G.check + ' '] })
345    if (it.task === 'todo') return t.Text({ color: p.bullet, children: [G.box + ' '] })
346    // numbers right-aligned, so `9.` and `10.` end on one column
347    if (/^\d/.test(it.marker)) return t.Text({ color: p.orderedNum, children: [it.marker.padStart(numWidth[it.depth] ?? 0) + ' '] })
348    return t.Text({ color: p.bullet, children: [(it.depth > 0 ? G.ring : G.dot) + ' '] })
349  }
350  const row = (it: ListItem, i: number, air: boolean) =>
351    t.Box({
352      flexDirection: 'row',
353      // nested items end at the measure like everything else
354      width: Math.max(10, m - indent[i]!),
355      marginLeft: indent[i],
356      ...(air ? { marginTop: 1 } : {}),
357      children: [
358        marker(it),
359        t.Box({
360          flexGrow: 1,
361          flexShrink: 1,
362          children: [t.Text({ wrap: 'wrap', children: renderInlines(c, it.inlines) })],
363        }),
364      ],
365    })
366  return t.Box({
367    flexDirection: 'column',
368    children: items.map((it, i) => {
369      // zero rows between items, except one each side of a card under an
370      // item: text touching a tint read as a glitch
371      const air = i > 0 && (items[i - 1]!.blocks?.length ?? 0) > 0
372      if (!it.blocks?.length) return row(it, i, air)
373      // a fence typed under the item sits under its text, at the text's
374      // left edge, as wide as the item's text at most (0.4.22)
375      const under = indent[i]! + itemMarker(it, numWidth[it.depth] ?? 0)
376      const inner = { ...c, m: Math.max(10, m - under) }
377      return t.Box({
378        flexDirection: 'column',
379        children: [row(it, i, air), ...it.blocks.map(b => t.Box({ marginLeft: under, marginTop: 1, children: [renderBlock(inner, b)] }))],
380      })
381    }),
382  })
383}
384
385// cells an item's marker takes before its text
386function itemMarker(it: ListItem, numWidth: number): number {
387  return /^\d/.test(it.marker) && !it.task ? numWidth + 1 : 2
388}
389
390// A quote: a thin continuous bar down the left edge, one quarter-block
391// glyph per row of the quote (the row count estimated from the same
392// wrapping the engine applies), a space, then the inner blocks at `M - 2`
393// with a blank row between them. No tint.
394function renderQuote(c: Ctx, blocks: Block[]): RenderElement {
395  const { t, p, m } = c
396  // quoted prose keeps the prose color: a `meta` step was tried and the
397  // owner wanted the color back (2026-10-11); `tone` stays for a block
398  // that may want it later
399  const inner = { ...c, m: m - 2 }
400  const height = quoteRows(blocks, m)
401  return t.Box({
402    flexDirection: 'row',
403    children: [
404      t.Box({ width: 2, flexShrink: 0, children: [t.Text({ color: p.quoteBar, children: [Array(height).fill(G.mark).join('\n')] })] }),
405      t.Box({
406        flexDirection: 'column',
407        flexGrow: 1,
408        flexShrink: 1,
409        width: m - 2,
410        rowGap: 1,
411        children: blocks.map(b => renderBlock(inner, b)),
412      }),
413    ],
414  })
415}
416
417// rows a quote takes at measure `m`: its blocks at `m - 2`, a blank between
418export function quoteRows(blocks: Block[], m: number): number {
419  const w = m - 2
420  const rows = blocks.reduce((n, b) => n + blockRows(b, w), 0) + Math.max(0, blocks.length - 1)
421  return Math.max(1, rows)
422}
423
424// rows a block takes at measure `m`, mirroring what renderBlock draws
425function blockRows(b: Block, m: number): number {
426  switch (b.kind) {
427    case 'paragraph':
428    case 'heading':
429      return wrappedLines(b.inlines, m)
430    case 'code':
431      return fenceRows(fenceShape(b.lang, b.source, m))
432    case 'list': {
433      const { indent, numWidth } = listLayout(b.items)
434      return b.items.reduce((n, it, i) => {
435        const marker = itemMarker(it, numWidth[it.depth] ?? 0)
436        const width = Math.max(10, m - indent[i]!) - marker
437        const air = i > 0 && (b.items[i - 1]!.blocks?.length ?? 0) > 0 ? 1 : 0
438        const under = (it.blocks ?? []).reduce((k, inner) => k + 1 + blockRows(inner, Math.max(10, m - indent[i]! - marker)), 0)
439        return n + air + wrappedLines(it.inlines, width) + under
440      }, 0)
441    }
442    case 'rule':
443      return 1
444    case 'raw':
445      return wrappedLines([{ kind: 'text', text: b.text }], m)
446    case 'quote':
447      return quoteRows(b.blocks, m)
448    case 'table':
449      // a table too wide even squeezed is the engine's Markdown, estimated as raw is
450      return tableColumns(b.header, b.rows, m) ? b.rows.length + 2 : wrappedLines([{ kind: 'text', text: b.raw }], m)
451    case 'callout': {
452      const rowWidth = (r: CalloutRow) => 2 + LABEL_WIDTH + 2 + inlineWidth(r.inlines) + 1
453      const width = cardWidth(m, Math.max(0, ...b.rows.map(rowWidth)))
454      const textWidth = width - 2 - LABEL_WIDTH - 2 - 1
455      return 1 + Math.max(1, b.rows.reduce((n, r) => n + wrappedLines(r.inlines, textWidth), 0))
456    }
457  }
458}
459
460// each column's width: its widest cell, header included
461function tableWidths(header: Inline[][], rows: Inline[][][]): number[] {
462  return Array.from({ length: header.length }, (_, col) =>
463    Math.max(1, inlineWidth(header[col] ?? []), ...rows.map(r => inlineWidth(r[col] ?? []))),
464  )
465}
466
467// the column widths glass draws the table with at measure `m`, two cells
468// kept free: too wide, the widest column gives up a cell at a time down to
469// COL_MIN; null when even that does not fit. The quote bar asks the same
470// question renderTable does.
471function tableColumns(header: Inline[][], rows: Inline[][][], m: number): number[] | null {
472  const widths = tableWidths(header, rows)
473  const room = m - 2 - 2 * (header.length - 1)
474  let over = widths.reduce((a, w) => a + w, 0) - room
475  while (over > 0) {
476    const widest = widths.indexOf(Math.max(...widths))
477    if ((widths[widest] ?? 0) <= COL_MIN) return null
478    widths[widest]!--
479    over--
480  }
481  return widths
482}
483
484// a cell past its column's width: its text cut in the middle (styling goes,
485// the cell being plain text from there)
486function squeeze(inlines: Inline[], w: number): Inline[] {
487  return inlineWidth(inlines) <= w ? inlines : [{ kind: 'text', text: clipMiddle(inlineText(inlines), w) }]
488}
489
490// row-separator table: bold header, one rule, two-cell gaps, no verticals;
491// numeric columns right-align unless the markdown says otherwise; a table
492// wider than the measure squeezes its widest columns, cells cut in the
493// middle, and falls back to the engine's renderer only when that is not
494// enough (a table three cells too wide jumped to the engine's boxes)
495function renderTable(c: Ctx, header: Inline[][], align: (Align | null)[], rows: Inline[][][], raw: string): RenderElement {
496  const { t, p } = c
497  const cols = header.length
498  const widths = tableColumns(header, rows, c.m)
499  if (!widths) return t.Markdown({ text: raw.slice(0, MAX_TEXT) })
500  header = header.map((h, i) => squeeze(h, widths[i] ?? COL_MIN))
501  rows = rows.map(r => r.map((cell, i) => squeeze(cell, widths[i] ?? COL_MIN)))
502  // `42`, `-3`, `1.5k`, `$12`, `80%`, `12ms`; an empty or placeholder cell does not decide
503  const numeric = (col: number) => {
504    const cells = rows.map(r => inlineText(r[col] ?? []).trim()).filter(x => x !== '' && !PLACEHOLDER_RE.test(x))
505    return cells.length > 0 && cells.every(x => NUMERIC_RE.test(x))
506  }
507  const cell = (inlines: Inline[], col: number, isHeader: boolean): RenderElement => {
508    const pad = Math.max(0, (widths[col] ?? 0) - inlineWidth(inlines))
509    const a: Align = align[col] ?? (numeric(col) ? 'right' : 'left')
510    // the header sits where its column's cells do, so `Count` ends over its numbers
511    const last = col === cols - 1
512    // the last column never pads to its right, nor to its left when empty
513    const left = last && inlineWidth(inlines) === 0 ? 0 : a === 'right' ? pad : a === 'center' ? Math.floor(pad / 2) : 0
514    const right = last ? 0 : pad - left
515    return t.Text({
516      ...(isHeader ? { bold: true, color: p.bold } : {}),
517      children: [' '.repeat(left), ...renderInlines(c, inlines), ' '.repeat(right) + (last ? '' : '  ')],
518    })
519  }
520  const line = (cells: Inline[][], isHeader: boolean) =>
521    t.Box({
522      flexDirection: 'row',
523      children: Array.from({ length: cols }, (_, col) => cell(cells[col] ?? [], col, isHeader)),
524    })
525  return t.Box({
526    flexDirection: 'column',
527    children: [
528      line(header, true),
529      t.Text({ color: p.rule, children: [widths.map(w => G.rule.repeat(w)).join('  ')] }),
530      ...rows.map(r => line(r, false)),
531    ],
532  })
533}
534
535// lines a run of inlines takes when wrapped at `width`, the way the engine
536// wraps: at spaces, a word wider than the line broken across lines
537function wrappedLines(inlines: Inline[], width: number): number {
538  if (width < 1) return 1
539  let lines = 0
540  for (const raw of inlineText(inlines).split('\n')) {
541    lines++
542    let col = 0
543    for (const word of raw.split(' ')) {
544      const w = cellWidth(word)
545      if (w === 0 && col === 0) continue
546      const need = col === 0 ? w : col + 1 + w
547      if (need <= width) {
548        col = need
549      } else if (w > width) {
550        // a word wider than the line starts on a fresh line and is chopped
551        if (col > 0) lines++
552        lines += Math.ceil(w / width) - 1
553        col = w % width || width
554      } else {
555        lines++
556        col = w
557      }
558    }
559  }
560  return lines
561}
562
563// The Bottom line card. The title sits above the card as a plain bold line;
564// only the labelled rows live inside, sized to the longest row. A thin
565// continuous bar down the left edge: a quarter-block glyph on every row of
566// the card, the row count computed from the same wrapping the engine
567// applies. Compact: no padding and no blank rows; the colored label column
568// keeps the rows apart.
569function renderCallout(c: Ctx, title: string, rows: CalloutRow[]): RenderElement {
570  const { t, p } = c
571  const rowWidth = (r: CalloutRow) => 2 + LABEL_WIDTH + 2 + inlineWidth(r.inlines) + 1
572  const width = cardWidth(c.m, Math.max(0, ...rows.map(rowWidth)))
573  const textWidth = width - 2 - LABEL_WIDTH - 2 - 1
574  const lines = rows.map(r => wrappedLines(r.inlines, textWidth))
575  // each row's wrapped lines; the title is outside the card
576  const height = Math.max(1, lines.reduce((n, l) => n + l, 0))
577  const card = t.Box({
578    flexDirection: 'row',
579    width,
580    backgroundColor: p.blockBg,
581    children: [
582      t.Box({ width: 1, children: [t.Text({ color: p.calloutBar, children: [Array(height).fill(G.mark).join('\n')] })] }),
583      t.Box({
584        flexDirection: 'column',
585        flexGrow: 1,
586        flexShrink: 1,
587        paddingLeft: 1,
588        children: rows.map(r =>
589          t.Box({
590            flexDirection: 'row',
591            children: [
592              // a fixed-width box, so a long row never squeezes the label column
593              t.Box({
594                width: LABEL_WIDTH + 2,
595                flexShrink: 0,
596                children: [t.Text({ bold: true, color: p[LABEL_COLOR[r.label] ?? 'calloutText'], children: [r.label.padEnd(LABEL_WIDTH) + '  '] })],
597              }),
598              t.Box({
599                flexGrow: 1,
600                flexShrink: 1,
601                paddingRight: 1,
602                children: [t.Text({ color: p.calloutText, wrap: 'wrap', children: renderInlines(c, r.inlines) })],
603              }),
604            ],
605          }),
606        ),
607      }),
608    ],
609  })
610  return t.Box({
611    flexDirection: 'column',
612    children: [t.Text({ bold: true, color: p.calloutBar, children: [title] }), card],
613  })
614}
615
616function renderInlines(c: Ctx, inlines: Inline[]): RenderNode[] {
617  const { t, p } = c
618  return inlines.flatMap((n): RenderNode[] => {
619    switch (n.kind) {
620      case 'text':
621        return c.tone ? [t.Text({ color: c.tone, children: renderProse(c, n.text) })] : renderProse(c, n.text)
622      case 'bold':
623        // bold keeps its own color inside a muted block
624        return [t.Text({ bold: true, color: p.bold, children: renderInlines({ ...c, tone: undefined }, n.children) })]
625      case 'italic':
626        return [t.Text({ italic: true, children: renderInlines(c, n.children) })]
627      case 'strike':
628        return [t.Text({ strikethrough: true, children: renderInlines(c, n.children) })]
629      case 'link':
630        return [renderLink(c, n.text, n.href)]
631      case 'code':
632        return [renderCode(c, n.text)]
633    }
634  })
635}
636
637// Prose outside backticks, painted: command
638// spans once there is evidence (`git push --follow-tags`, never `make
639// sure`), then paths and URLs anywhere (`README.md`, `~/.zshrc`,
640// `src/main.rs:42` with its line number in the number color).
641function renderProse(c: Ctx, text: string): RenderNode[] {
642  const { t, p } = c
643  const out: RenderNode[] = []
644  const spans = proseSpans(text)
645  let pos = 0
646  const colored = (s: string, kind: SpanKind): RenderNode[] => (kind === 'plain' ? cut(s) : [t.Text({ color: p[kind], children: cut(s) })])
647  for (const s of spans) {
648    if (s.start > pos) out.push(...renderWords(c, text.slice(pos, s.start)))
649    out.push(...colored(text.slice(s.start, s.end), s.kind))
650    pos = s.end
651  }
652  if (pos < text.length) out.push(...renderWords(c, text.slice(pos)))
653  return out
654}
655
656// paths and URLs in a run of plain prose
657function renderWords(c: Ctx, text: string): RenderNode[] {
658  if (!/[/.@]/.test(text)) return cut(text)
659  const { t, p } = c
660  const out: RenderNode[] = []
661  let buf = ''
662  const flush = () => {
663    if (buf) out.push(...cut(buf))
664    buf = ''
665  }
666  for (const part of text.split(/(\s+)/)) {
667    const { lead, word, tail } = bareWord(part)
668    if (!word) {
669      buf += part
670      continue
671    }
672    if (isUrl(word)) {
673      buf += lead
674      flush()
675      out.push(t.Text({ color: p.url, underline: true, children: cut(word) }))
676      buf += tail
677      continue
678    }
679    const path = pathLike(word)
680    if (path) {
681      buf += lead
682      flush()
683      out.push(t.Text({ color: p.path, children: cut(path.path) }))
684      if (path.lineno) out.push(t.Text({ color: p.num, children: [path.lineno] }))
685      buf += tail
686      continue
687    }
688    buf += part
689  }
690  flush()
691  return out
692}
693
694function renderLink(c: Ctx, label: string, href: string): RenderElement {
695  const { t, p } = c
696  const styled = t.Text({ color: p.url, underline: true, children: cut(label) })
697  const safe = safeHref(href)
698  return safe ? t.Link({ href: safe, children: [styled] }) : styled
699}
700
701// the Link element refuses the whole tree on a bad href, so be strict
702function safeHref(href: string): string | null {
703  try {
704    const u = new URL(href)
705    const ok = u.protocol === 'https:' || (u.protocol === 'http:' && u.hostname === 'localhost')
706    if (!ok || u.username || u.password || u.href.length > 2048) return null
707    if (!/^[\x21-\x7e]+$/.test(u.href)) return null
708    return u.href
709  } catch {
710    return null
711  }
712}
713
714// Inline code is color only, as Claude Desktop and the Codex TUI draw it:
715// shell tokens in their kind colors, paths in the path color underlined,
716// anything else in the code color. No tint, no padding. A span that is a
717// URL whole is a link like any other, so a wrapped one stays one click
718// (0.15.3: the engine's own renderer does this since 2.1.302).
719function renderCode(c: Ctx, code: string): RenderElement {
720  const { t, p } = c
721  if (!/\s/.test(code) && safeHref(code)) return renderLink(c, code, code)
722  const spans = shellSpans(code)
723  if (spans) {
724    return t.Text({
725      children: spans.flatMap((s): RenderNode[] => (s.kind === 'plain' ? cut(s.text) : [t.Text({ color: p[s.kind], children: cut(s.text) })])),
726    })
727  }
728  if (PATH_RE.test(code)) return t.Text({ color: p.path, children: cut(code) })
729  return t.Text({ color: p.code, children: cut(code) })
730}
731
hooks/highlight.ts 229 lines
1// glass's own code highlighter: one small tokenizer for the C-like family
2// and the script languages, painting with the palette's code keys. The
3// engine's `Code` element paints with its own theme, which the owner
4// rejected (2026-10-03); this keeps fences and diffs in the mod's colors.
5// Shell fences go through `shellSpans` and paint with the prose keys, so a
6// command reads in a fence exactly as it does in prose: the same command,
7// flag, string and operator colors (they took the code keys until 0.4.20,
8// so `--force` and `|` drew differently in the two places). Line by line: a block comment opened on one line carries to the
9// next through `State`.
10import type { Palette } from './palette'
11import { shellSpans } from './shell'
12import type { SpanKind } from './shell'
13
14// `sh.*`: a shell token in a fence, painted with the prose key of its kind
15export type CodeKind = 'key' | 'kw' | 'fn' | 'type' | 'str' | 'num' | 'comment' | 'plain' | `sh.${Exclude<SpanKind, 'plain' | 'comment'>}`
16export type CodeSpan = { text: string; kind: CodeKind }
17
18/** the palette key a code kind paints with */
19export const CODE_COLOR: Record<Exclude<CodeKind, 'plain'>, keyof Palette> = {
20  key: 'codeStr',
21  kw: 'codeKw',
22  fn: 'codeFn',
23  type: 'codeType',
24  str: 'codeStr',
25  num: 'codeNum',
26  comment: 'comment',
27  'sh.cmd': 'cmd',
28  'sh.sub': 'sub',
29  'sh.flag': 'flag',
30  'sh.str': 'str',
31  'sh.path': 'path',
32  'sh.op': 'op',
33  'sh.num': 'num',
34  'sh.var': 'var',
35  'sh.url': 'url',
36}
37
38/** the color a code kind paints in: a JSON key takes the palette's `jsonKey` where it sets one */
39export function codeColor(p: Palette, kind: Exclude<CodeKind, 'plain'>): string {
40  return (kind === 'key' ? p.jsonKey : undefined) ?? (p[CODE_COLOR[kind]] as string)
41}
42
43const SHELL_LANGS = new Set(['sh', 'bash', 'zsh', 'shell', 'console', 'fish'])
44// prose files: a diff of README.md is English, not code, so nothing paints
45const PROSE_LANGS = new Set(['md', 'markdown', 'mdx', 'txt', 'text', 'rst', 'adoc', 'asciidoc', 'org', 'tex', ''])
46// `#` opens a comment here; everywhere else `//` does
47const HASH_LANGS = new Set(['py', 'python', 'rb', 'ruby', 'yaml', 'yml', 'toml', 'ini', 'conf', 'perl', 'pl', 'r', 'make', 'makefile', 'dockerfile', 'nix', 'elixir', 'ex', 'exs', 'cmake'])
48const DASH_LANGS = new Set(['sql', 'lua', 'hs', 'haskell', 'ada'])
49
50// keywords by language family (0.5.3): one shared set painted `range(10)`
51// in Python and `values(x)` in TypeScript as keywords, since Go and SQL
52// own those words. The C-like set is the fallback for any unknown language.
53const words = (s: string) => new Set(s.split(/\s+/).filter(Boolean))
54const KW_CLIKE = words(
55  `abstract as async await break case catch class const continue debugger default delete do else enum export extends
56   finally for from function if implements import in instanceof interface let new of package private protected public
57   return static super switch this throw try typeof var void while with yield readonly declare namespace module type
58   keyof infer satisfies override get set
59   int float double char long short unsigned signed bool boolean byte string auto struct union typedef sizeof
60   static_assert constexpr template typename virtual inline explicit friend operator
61   final native synchronized transient volatile throws`,
62)
63const KW_PY = words(`and as assert async await break class continue def del elif else except finally for from global if import in is lambda nonlocal not or pass raise return try while with yield match case`)
64const KW_RB = words(`alias and begin break case class def defined? do else elsif end ensure false for if in module next nil not or redo rescue retry return self super then true undef unless until when while yield require include attr_accessor attr_reader attr_writer private public protected`)
65const KW_GO = words(`break case chan const continue default defer else fallthrough for func go goto if import interface map package range return select struct switch type var`)
66const KW_RUST = words(`as async await break const continue crate dyn else enum extern false fn for if impl in let loop match mod move mut pub ref return self Self static struct super trait true type unsafe use where while`)
67const KW_SQL = words(`select insert update delete into values create table drop alter where join on group by order having limit from as and or not null is in exists between like inner left right outer full union all distinct set index view primary key foreign references default constraint if begin end case when then else`)
68const KW_LUA = words(`and break do else elseif end false for function goto if in local nil not or repeat return then true until while`)
69const KW_BY_LANG: Record<string, Set<string>> = {
70  py: KW_PY, python: KW_PY,
71  rb: KW_RB, ruby: KW_RB,
72  go: KW_GO,
73  rs: KW_RUST, rust: KW_RUST,
74  sql: KW_SQL,
75  lua: KW_LUA,
76}
77const RUST_LANGS = new Set(['rs', 'rust'])
78// a YAML word before a colon is a key, painted as a call. A JSON key is
79// its own kind: the string color unless the palette sets `jsonKey` (water's
80// orange keys stay, the owner liked them 2026-10-11; prism's are coral)
81const JSON_LANGS = new Set(['json', 'jsonc', 'json5'])
82const YAML_LANGS = new Set(['yaml', 'yml'])
83const YAML_KEY = /^(\s*(?:-\s+)?)([\w.\/-]+)(\s*)(?=:(?:\s|$))/
84const CONSTANTS = new Set(['true', 'false', 'null', 'undefined', 'None', 'True', 'False', 'nil', 'NaN', 'Infinity'])
85
86export type State = { inBlock: boolean }
87
88const IDENT = /[A-Za-z_$][\w$]*/y
89const NUMBER = /0[xX][\da-fA-F_]+|0[bB][01_]+|\d[\d_]*(?:\.\d[\d_]*)?(?:[eE][+-]?\d+)?[a-zA-Z]*/y
90
91/** the language id a fence or a file path resolves to, lowercased */
92export function langOf(hint: string): string {
93  const h = hint.toLowerCase()
94  const dot = h.lastIndexOf('.')
95  const ext = dot >= 0 && !/[\/\\]/.test(h.slice(dot)) ? h.slice(dot + 1) : h
96  const base = h.split(/[\/\\]/).pop() ?? h
97  if (base === 'makefile' || base === 'dockerfile') return base
98  return ext
99}
100
101/** one line as colored spans; `state` carries a block comment across lines */
102export function highlightLine(line: string, lang: string, state: State = { inBlock: false }): CodeSpan[] {
103  if (PROSE_LANGS.has(lang)) return line === '' ? [] : [{ text: line, kind: 'plain' }]
104  if (SHELL_LANGS.has(lang)) {
105    // a comment-only line: shellSpans wants a command first, and the
106    // fallback below opens comments with `//`
107    const note = /^(\s*)(#.*)$/.exec(line)
108    if (note) return [...(note[1] ? [{ text: note[1], kind: 'plain' as const }] : []), { text: note[2]!, kind: 'comment' }]
109    const spans = shellSpans(line, true)
110    if (spans) return spans.map(s => ({ text: s.text, kind: s.kind === 'plain' || s.kind === 'comment' ? s.kind : (`sh.${s.kind}` as const) }))
111  }
112  const hash = HASH_LANGS.has(lang)
113  const dash = DASH_LANGS.has(lang)
114  const keywords = KW_BY_LANG[lang] ?? KW_CLIKE
115  const rust = RUST_LANGS.has(lang)
116  const out: CodeSpan[] = []
117  const push = (text: string, kind: CodeKind) => {
118    if (text === '') return
119    const last = out[out.length - 1]
120    if (last && last.kind === kind) last.text += text
121    else out.push({ text, kind })
122  }
123  let i = 0
124  const n = line.length
125  // a YAML key: the word before the colon, at the line's start or after `- `
126  if (YAML_LANGS.has(lang) && !state.inBlock) {
127    const key = YAML_KEY.exec(line)
128    if (key) {
129      push(key[1]!, 'plain')
130      push(key[2]!, 'fn')
131      push(key[3]!, 'plain')
132      i = key[0].length
133    }
134  }
135  if (state.inBlock) {
136    const end = line.indexOf('*/')
137    if (end < 0) {
138      push(line, 'comment')
139      return out
140    }
141    push(line.slice(0, end + 2), 'comment')
142    i = end + 2
143    state.inBlock = false
144  }
145  while (i < n) {
146    const ch = line[i]!
147    const two = line.slice(i, i + 2)
148    // comments
149    if ((!hash && !dash && two === '//') || (hash && ch === '#') || (dash && two === '--')) {
150      push(line.slice(i), 'comment')
151      break
152    }
153    if (!hash && two === '/*') {
154      const end = line.indexOf('*/', i + 2)
155      if (end < 0) {
156        push(line.slice(i), 'comment')
157        state.inBlock = true
158        break
159      }
160      push(line.slice(i, end + 2), 'comment')
161      i = end + 2
162      continue
163    }
164    // a Rust lifetime (`'a`, `'static`) is a quote with no closing quote
165    // after its word: it keeps the string color (the owner likes the
166    // orange on it) but ends at its word, so it never swallows the line
167    if (rust && ch === "'" && /[A-Za-z_]/.test(line[i + 1] ?? '')) {
168      IDENT.lastIndex = i + 1
169      const m = IDENT.exec(line)
170      if (m && line[i + 1 + m[0].length] !== "'") {
171        push("'" + m[0], 'str')
172        i += 1 + m[0].length
173        continue
174      }
175    }
176    // strings: one line, escapes honored
177    if (ch === '"' || ch === "'" || ch === '`') {
178      let j = i + 1
179      while (j < n && line[j] !== ch) j += line[j] === '\\' ? 2 : 1
180      const key = JSON_LANGS.has(lang) && /^\s*:/.test(line.slice(j + 1))
181      push(line.slice(i, Math.min(n, j + 1)), key ? 'key' : 'str')
182      i = Math.min(n, j + 1)
183      continue
184    }
185    // numbers
186    if (/\d/.test(ch) && !(i > 0 && /[\w$]/.test(line[i - 1]!))) {
187      NUMBER.lastIndex = i
188      const m = NUMBER.exec(line)
189      if (m) {
190        push(m[0], 'num')
191        i += m[0].length
192        continue
193      }
194    }
195    // words
196    if (/[A-Za-z_$]/.test(ch)) {
197      IDENT.lastIndex = i
198      const m = IDENT.exec(line)!
199      const word = m[0]
200      // the nearest non-space character after the word and before it,
201      // found in place: copying the line per word was quadratic
202      let a = i + word.length
203      while (a < n && /\s/.test(line[a]!)) a++
204      const after = line[a]
205      let b = i - 1
206      while (b >= 0 && /\s/.test(line[b]!)) b--
207      const before = b >= 0 ? line[b]! : ''
208      let kind: CodeKind = 'plain'
209      if (keywords.has(word) && before !== '.') kind = 'kw'
210      else if (CONSTANTS.has(word)) kind = 'num'
211      else if (after === '(') kind = 'fn'
212      else if (/^[A-Z]/.test(word) && /[a-z]/.test(word)) kind = 'type'
213      else if (before === ':' && !hash) kind = 'type'
214      push(word, kind)
215      i += word.length
216      continue
217    }
218    push(ch, 'plain')
219    i++
220  }
221  return out
222}
223
224/** every line of a source as spans, block comments carried across */
225export function highlight(source: string, lang: string): CodeSpan[][] {
226  const state: State = { inBlock: false }
227  return source.split('\n').map(line => highlightLine(line, lang, state))
228}
229
hooks/output.ts 82 lines
1// Paints a tool's text output over Claude Code's gray: commands with evidence, paths and URLs, error, warning and success
2// words, numbers and durations, check and cross marks, and git status codes
3// at the start of a line. Returns colored segments; render.ts draws them as
4// Text, since the engine strips escape codes from a rewritten result.
5import type { Palette } from './palette'
6import { bareWord, isUrl, pathLike } from './paths'
7import { proseSpans } from './shell'
8
9const ERR_WORDS = new Set('error errors Error ERROR FAILED FAIL failed fail failure panicked panic fatal Fatal FATAL'.split(' '))
10const WARN_WORDS = new Set('warning warnings Warning WARNING warn WARN deprecated Deprecated'.split(' '))
11const OK_WORDS = new Set('ok OK passed pass PASS PASSED success Success succeeded done Done'.split(' '))
12
13const cp = (n: number) => String.fromCodePoint(n)
14const CHECKS = new Set([cp(0x2713), cp(0x2714)])
15const CROSSES = new Set([cp(0x2717), cp(0x2718), cp(0xd7)])
16
17// `12`, `0.42s`, `1.2k`, `80%`: a number with at most two letters or a percent
18const NUMBER_RE = /^\d+(?:\.\d+)*(?:[A-Za-z]{1,2}|%)?$/
19
20/** a run of output text; `color` absent means the output's own gray */
21export type Segment = { text: string; color?: keyof Palette }
22
23function wordSegments(raw: string): Segment[] {
24  const { lead, word, tail } = bareWord(raw)
25  if (!word) return [{ text: raw }]
26  const wrap = (color: keyof Palette, body = word): Segment[] => [
27    ...(lead ? [{ text: lead }] : []),
28    { text: body, color },
29    ...(tail ? [{ text: tail }] : []),
30  ]
31  if (ERR_WORDS.has(word) || CROSSES.has(word)) return wrap('err')
32  if (WARN_WORDS.has(word)) return wrap('warn')
33  if (OK_WORDS.has(word) || CHECKS.has(word)) return wrap('ok')
34  if (NUMBER_RE.test(word)) return wrap('num')
35  if (isUrl(word)) return wrap('url')
36  const path = pathLike(word)
37  if (path) {
38    return [
39      ...(lead ? [{ text: lead }] : []),
40      { text: path.path, color: 'path' },
41      ...(path.lineno ? [{ text: path.lineno, color: 'num' as const }] : []),
42      ...(tail ? [{ text: tail }] : []),
43    ]
44  }
45  return [{ text: raw }]
46}
47
48// plain text: words and the whitespace between them
49function textSegments(text: string): Segment[] {
50  return text.split(/(\s+)/).flatMap(part => (part === '' ? [] : /^\s+$/.test(part) ? [{ text: part }] : wordSegments(part)))
51}
52
53// git status codes at the start of a line: `M src/x.rs`, `?? new/`
54function gitStatus(line: string): { head: Segment[]; rest: string } | null {
55  const m = /^(\s*)([MADRCU?!]{1,2})(\s{1,2})(\S+)/.exec(line)
56  if (!m) return null
57  const codes = m[2]!
58  const word = m[4]!
59  if (!(word.includes('/') || word.includes('.') || codes.length === 2)) return null
60  const color = (c: string): keyof Palette =>
61    c === 'A' ? 'ok' : c === 'D' || c === 'U' ? 'err' : c === '?' || c === '!' ? 'comment' : 'warn'
62  const head: Segment[] = [...(m[1] ? [{ text: m[1] }] : []), ...[...codes].map(c => ({ text: c, color: color(c) }))]
63  return { head, rest: line.slice(m[1]!.length + codes.length) }
64}
65
66/** one output line as colored segments */
67export function paintLine(line: string): Segment[] {
68  const git = gitStatus(line)
69  const head = git ? git.head : []
70  const body = git ? git.rest : line
71  const out: Segment[] = [...head]
72  let pos = 0
73  for (const s of proseSpans(body)) {
74    if (s.start > pos) out.push(...textSegments(body.slice(pos, s.start)))
75    const kind = s.kind === 'plain' ? undefined : (s.kind as keyof Palette)
76    out.push(kind ? { text: body.slice(s.start, s.end), color: kind } : { text: body.slice(s.start, s.end) })
77    pos = s.end
78  }
79  if (pos < body.length) out.push(...textSegments(body.slice(pos)))
80  return out
81}
82
hooks/shell.ts 484 lines
1// Shell tokenizer for inline code.
2// Inline code is a known code context, so every token gets a color; the
3// prose guards (stop words, bare-word budget) are not needed here.
4
5const COMMANDS = new Set(
6  `git gh npm npx pnpm yarn bun bunx node deno python python3 pip pip3 uv go cargo
7rustc make cmake brew apt apt-get dnf pacman docker docker-compose kubectl helm
8terraform aws gcloud az ssh scp rsync curl wget tar zip unzip cd ls cat head
9tail less grep rg fd find xargs sed awk sort uniq wc tr cut tee echo printf
10export source chmod chown mkdir rmdir rm cp mv ln touch pwd which env nvim vim
11tmux ghostty claude codex gemini open kill pkill ps lsof jq yq tsc tsx vitest
12jest eslint prettier next vite
13sudo doas nohup just pytest ruff mypy poetry pipx uvx conda mvn gradle dotnet
14swift ruby gem bundle rake rspec php composer psql mysql sqlite3 redis-cli
15mongosh systemctl journalctl launchctl xcodebuild xcrun flutter dart adb
16ffmpeg pandoc openssl gpg shellcheck protoc ansible vagrant nix zig perl lua
17gcc clang ninja bazel
18bash sh zsh fish exec exit man diff patch du df sleep time watch bat eza tree stat
19rustup nvm fnm pm2 podman k9s minikube kind htop nc dig ping ssh-keygen base64
20shasum sha256sum xxd hyperfine tokei cloc fzf zoxide code cursor pbcopy pbpaste
21xdg-open turbo nx lerna webpack esbuild biome prisma wrangler vercel netlify
22flyctl heroku supabase firebase ngrok mise asdf direnv gdb lldb valgrind strace
23mkcert caddy certbot crontab screen zellij`.split(/\s+/),
24)
25
26// tools whose bare-word args are subcommands; for others only flags, paths
27// and strings count
28const SUBCMD_TOOLS = new Set(
29  `git gh npm npx pnpm yarn bun bunx deno uv pip pip3 go cargo brew apt apt-get
30dnf pacman docker docker-compose kubectl helm terraform aws gcloud az claude
31codex gemini tmux make jq tsc next vite
32sudo doas nohup poetry pipx conda mvn gradle dotnet swift gem bundle rake
33composer systemctl journalctl launchctl flutter dart adb nix vagrant bazel openssl
34man rustup nvm fnm pm2 podman minikube kind turbo nx lerna prisma wrangler vercel
35netlify flyctl heroku supabase firebase mise asdf direnv crontab`.split(/\s+/),
36)
37
38// prefix runners: a known command right after them re-anchors the highlight
39const CHAIN_TOOLS = new Set('sudo doas env xargs nohup time watch exec'.split(' '))
40
41const MAX_SUB = 3
42
43export type SpanKind =
44  | 'cmd'
45  | 'sub'
46  | 'flag'
47  | 'str'
48  | 'path'
49  | 'op'
50  | 'num'
51  | 'var'
52  | 'url'
53  | 'comment'
54  | 'plain'
55
56export type Span = { text: string; kind: SpanKind }
57
58type TokKind =
59  | 'ws'
60  | 'str'
61  | 'chain'
62  | 'redirect'
63  | 'flag'
64  | 'path'
65  | 'sub'
66  | 'word'
67  | 'num'
68  | 'var'
69  | 'url'
70  | 'comment'
71
72type Tok = { kind: TokKind; start: number; end: number }
73
74const isSpace = (c: string) => /\s/.test(c)
75// newlines are whitespace too: multi-line commands keep their colors
76const isWs = (c: string) => c === ' ' || c === '\t' || c === '\n' || c === '\r'
77const isWord = (c: string) => /[A-Za-z0-9_]/.test(c)
78const isPathMark = (c: string) => '/.~=:@*'.includes(c)
79const isSentencePunct = (c: string) => '.,;:)'.includes(c)
80
81function wordEnd(t: string, j: number): number {
82  while (j < t.length && !isSpace(t[j]!)) j++
83  return j
84}
85
86function nextArg(t: string, i: number): Tok | null {
87  const n = t.length
88  if (i >= n) return null
89  const b = t[i]!
90  const atBoundary = (j: number) => j >= n || isSpace(t[j]!)
91  const opEnd = (j: number) => atBoundary(j) || !'><&|;'.includes(t[j]!)
92
93  if (isWs(b)) {
94    let j = i
95    while (j < n && isWs(t[j]!)) j++
96    return { kind: 'ws', start: i, end: j }
97  }
98  if (b === '"') {
99    let j = i + 1
100    while (j < n) {
101      if (t[j] === '\\' && j + 1 < n) j += 2
102      else if (t[j] === '"') return { kind: 'str', start: i, end: j + 1 }
103      else j++
104    }
105  } else if (b === "'" && !(i > 0 && /[A-Za-z0-9]/.test(t[i - 1]!))) {
106    // a quote opens only at a word's start, and closes on a quote that is
107    // not followed by a letter: the apostrophes in "the card's frame ...
108    // the card's room" are English, not a string (live, 2026-10-03)
109    let k = t.indexOf("'", i + 1)
110    while (k >= 0 && k + 1 < n && /[A-Za-z]/.test(t[k + 1]!) && /[A-Za-z]/.test(t[k - 1] ?? '')) k = t.indexOf("'", k + 1)
111    if (k >= 0) return { kind: 'str', start: i, end: k + 1 }
112  }
113  for (const op of ['&&', '||', '|', ';']) {
114    const j = i + op.length
115    if (t.startsWith(op, i) && (op === ';' ? atBoundary(j) : opEnd(j))) {
116      return { kind: 'chain', start: i, end: j }
117    }
118  }
119  for (const op of ['2>&1', '&>', '2>', '>>', '>', '<<', '<']) {
120    const j = i + op.length
121    if (t.startsWith(op, i) && opEnd(j)) return { kind: 'redirect', start: i, end: j }
122  }
123  if (b === '#' && (i + 1 >= n || isSpace(t[i + 1]!))) return { kind: 'comment', start: i, end: n }
124  if (b === '$') return { kind: 'var', start: i, end: wordEnd(t, i + 1) }
125  for (const scheme of ['http://', 'https://', 'ssh://', 'git@', 'file://', 'www.']) {
126    if (t.startsWith(scheme, i)) return { kind: 'url', start: i, end: wordEnd(t, i) }
127  }
128  if (b === '-') {
129    let j = i + 1
130    if (t[j] === '-') j++
131    if (j < n && /[A-Za-z]/.test(t[j]!)) {
132      j++
133      while (j < n && (isWord(t[j]!) || t[j] === '-')) j++
134      // `--flag=value`: the flag ends after `=`, the value is its own token
135      if (t[j] === '=') j++
136      return { kind: 'flag', start: i, end: j }
137    }
138    // numeric args: `tail -20`, `head -5` read as counts, not flags
139    if (j < n && /[0-9]/.test(t[j]!)) {
140      let k = j + 1
141      while (k < n && /[0-9]/.test(t[k]!)) k++
142      if (atBoundary(k) || t[k] === ')') return { kind: 'num', start: i, end: k }
143    }
144    // `--` and `-` on their own
145    if (atBoundary(j)) return { kind: 'flag', start: i, end: j }
146  }
147  // `chmod +x`, `date +%s`
148  if (b === '+' && i + 1 < n && !isSpace(t[i + 1]!)) return { kind: 'flag', start: i, end: wordEnd(t, i + 1) }
149  // numbers, versions, sizes, durations: 5  1.2.0  v1.2.0  10s  3.5GB  80%
150  if (/[0-9]/.test(b) || (b === 'v' && /[0-9]/.test(t[i + 1] ?? ''))) {
151    const j = wordEnd(t, i)
152    const bodyEnd = j - i > 1 && isSentencePunct(t[j - 1]!) ? j - 1 : j
153    const body = t.slice(i + (b === 'v' ? 1 : 0), bodyEnd)
154    if (body.length > 0 && /^[0-9.%kKmMgGBshd]+$/.test(body)) return { kind: 'num', start: i, end: j }
155  }
156  {
157    const j = wordEnd(t, i)
158    // `PORT=3000`: an environment assignment
159    if (/[A-Za-z_]/.test(b)) {
160      let k = i
161      while (k < j && isWord(t[k]!)) k++
162      if (k < j && t[k] === '=') return { kind: 'var', start: i, end: j }
163    }
164    const bodyEnd = j - i > 1 && isSentencePunct(t[j - 1]!) ? j - 1 : j
165    if ([...t.slice(i, bodyEnd)].some(isPathMark)) return { kind: 'path', start: i, end: j }
166  }
167  if (/[a-z]/.test(b)) {
168    let j = i + 1
169    while (j < n && /[a-z0-9-]/.test(t[j]!)) j++
170    // `size.` at the end of a sentence: keep the punctuation in the token so
171    // the span logic sees it and ends the span there
172    if (j < n && isSentencePunct(t[j]!) && atBoundary(j + 1)) j++
173    return { kind: 'sub', start: i, end: j }
174  }
175  if (isWord(b)) return { kind: 'word', start: i, end: wordEnd(t, i) }
176  return { kind: 'word', start: i, end: i + 1 }
177}
178
179/**
180 * Color spans for one inline-code string, or null when it is not a shell
181 * command line (its first real word is not a known command). With `trusted`
182 * the head is a command whatever it is: for a Bash tool row, where the text
183 * is known to be a command line.
184 */
185export function shellSpans(code: string, trusted = false): Span[] | null {
186  const t = code
187  const out: Span[] = []
188  const push = (start: number, end: number, kind: SpanKind) => {
189    if (end > start) out.push({ text: t.slice(start, end), kind })
190  }
191  let i = 0
192  // `$ ` prompt and leading env assignments precede the command
193  if (t.startsWith('$ ')) {
194    push(0, 2, 'comment')
195    i = 2
196  }
197  let cmd = ''
198  for (;;) {
199    const tok = nextArg(t, i)
200    if (!tok) return null
201    if (tok.kind === 'ws') {
202      push(tok.start, tok.end, 'plain')
203    } else if (tok.kind === 'var' && t[tok.start] !== '$') {
204      push(tok.start, tok.end, 'var')
205    } else {
206      const word = t.slice(tok.start, tok.end)
207      const isHead = tok.kind === 'sub' || tok.kind === 'word' || tok.kind === 'path'
208      if (isHead && (trusted || COMMANDS.has(word))) {
209        push(tok.start, tok.end, 'cmd')
210        cmd = word
211        i = tok.end
212        break
213      }
214      return null
215    }
216    i = tok.end
217  }
218
219  let subs = 0
220  let afterEq = false
221  let after: 'chain' | 'redirect' | null = null
222  let tok: Tok | null
223  while ((tok = nextArg(t, i))) {
224    const { kind, start, end } = tok
225    i = end
226    if (kind === 'ws') {
227      push(start, end, 'plain')
228      continue
229    }
230    const word = t.slice(start, end)
231    // a lone full stop or comma stays plain
232    if (word.length === 1 && isSentencePunct(word)) {
233      push(start, end, 'plain')
234      continue
235    }
236    // `--out=dist`: the word glued to a flag is its value
237    if (afterEq && (kind === 'sub' || kind === 'word')) {
238      afterEq = false
239      push(start, end, 'path')
240      continue
241    }
242    afterEq = kind === 'flag' && word.endsWith('=')
243
244    if (after === 'chain' && kind !== 'chain' && kind !== 'redirect') {
245      after = null
246      if ((kind === 'sub' || kind === 'word') && COMMANDS.has(word)) {
247        push(start, end, 'cmd')
248        cmd = word
249        subs = 0
250        continue
251      }
252      if (kind === 'path' || kind === 'var') {
253        push(start, end, kind)
254        cmd = ''
255        subs = 0
256        continue
257      }
258    }
259    if (after === 'redirect' && kind !== 'chain' && kind !== 'redirect') {
260      after = null
261      push(start, end, kind === 'str' || kind === 'var' || kind === 'num' ? kind : 'path')
262      continue
263    }
264
265    // a token carrying sentence punctuation: the body takes the color, the
266    // punctuation stays plain
267    const trimmed = TRIMMABLE.has(kind) && word.length > 1 && isSentencePunct(word[word.length - 1]!)
268    const bodyEnd = trimmed ? end - 1 : end
269    switch (kind) {
270      case 'sub':
271      case 'word': {
272        if (CHAIN_TOOLS.has(cmd) && COMMANDS.has(word)) {
273          push(start, bodyEnd, 'cmd')
274          cmd = word
275          subs = 0
276        } else if (kind === 'sub' && SUBCMD_TOOLS.has(cmd) && subs < MAX_SUB) {
277          subs++
278          push(start, bodyEnd, 'sub')
279        } else {
280          push(start, bodyEnd, 'path')
281        }
282        break
283      }
284      case 'chain':
285      case 'redirect':
286        after = kind
287        push(start, end, 'op')
288        break
289      default:
290        push(start, bodyEnd, kind)
291    }
292    if (trimmed) push(bodyEnd, end, 'plain')
293  }
294  return out
295}
296
297const TRIMMABLE = new Set<TokKind>(['sub', 'word', 'path', 'num', 'var'])
298
299// words that end a command span in prose: the sentence is resuming
300const STOP_WORDS = new Set(
301  'and or then to the a an in on for with is it that this if of at by from so but you we i will can should after before when do not into was are has have your our'.split(' '),
302)
303// in prose, bare non-subcommand words tolerated before giving up
304const MAX_BARE = 3
305// command words that are also plain English: a number after one (`sleep 5
306// seconds`, `code across 13 files`) is the sentence, not an argument, so it
307// does not count as evidence on its own; a flag, a path or an operator still does
308const ENGLISH = new Set(
309  'code sleep time watch open sort find cut tree kill touch make head tail less man diff patch which env source echo tee go kind dig ping stat zip tar cat'.split(' '),
310)
311// text right before a command that marks it as a command line rather than prose
312const RUNNER_PREFIXES = ['Ran', 'Run', 'Running', 'Bash(', '$']
313// chars that may not precede a command word
314const isCmdGlue = (c: string) => isWord(c) || '/.@~-'.includes(c)
315
316export type ProseSpan = { start: number; end: number; kind: SpanKind }
317
318// the next known command word at or after `from`, at a word boundary
319function findCmd(t: string, from: number): [number, number] | null {
320  let i = from
321  while (i < t.length) {
322    if (isSpace(t[i]!)) {
323      i++
324      continue
325    }
326    const start = i
327    while (i < t.length && !isSpace(t[i]!)) i++
328    for (let p = start; p < i; p++) {
329      if (p === 0 || !isCmdGlue(t[p - 1]!)) {
330        if (COMMANDS.has(t.slice(p, i))) return [p, i]
331      }
332    }
333  }
334  return null
335}
336
337/**
338 * Command spans inside prose, the hard case. `make sure`, `go ahead`
339 * and `next step` are valid command shapes, so a command in a sentence only
340 * paints once a flag, path, string, number or operator turns up, or when a
341 * runner prefix (`Ran`, `$`) precedes it. `git push --follow-tags` paints,
342 * `git status` in a sentence does not, nor does `make sure the build passes`.
343 */
344export function proseSpans(text: string): ProseSpan[] {
345  const t = text
346  const out: ProseSpan[] = []
347  let pos = 0
348  let found: [number, number] | null
349  while ((found = findCmd(t, pos))) {
350    const [cs, ce] = found
351    let cmd = t.slice(cs, ce)
352    const mark = out.length
353    out.push({ start: cs, end: ce, kind: 'cmd' })
354    const before = t.slice(0, cs).trimEnd()
355    const strong = RUNNER_PREFIXES.some(p => before.endsWith(p))
356    let i = ce
357    let subs = 0
358    let nargs = 0
359    let bare = 0
360    let afterEq = false
361    let evidence = false
362    let after: 'chain' | 'redirect' | null = null
363    let tok: Tok | null
364    scan: while ((tok = nextArg(t, i))) {
365      const { kind, start, end } = tok
366      if (kind === 'ws') {
367        i = end
368        continue
369      }
370      const word = t.slice(start, end)
371      // a lone full stop or comma is the sentence, not an argument
372      if (word.length === 1 && isSentencePunct(word)) break
373      if (afterEq && (kind === 'sub' || kind === 'word')) {
374        afterEq = false
375        out.push({ start, end, kind: 'path' })
376        nargs++
377        i = end
378        continue
379      }
380      afterEq = kind === 'flag' && word.endsWith('=')
381      if (after === 'chain' && kind !== 'chain' && kind !== 'redirect') {
382        if ((kind === 'sub' || kind === 'word') && COMMANDS.has(word)) {
383          out.push({ start, end, kind: 'cmd' })
384          cmd = word
385          subs = 0
386          after = null
387          evidence = true
388          i = end
389          continue
390        }
391        if ((kind === 'path' && /^(\.\/|\/|~)/.test(word)) || kind === 'var') {
392          out.push({ start, end, kind: kind === 'var' ? 'var' : 'path' })
393          cmd = ''
394          subs = 0
395          after = null
396          evidence = true
397          nargs++
398          i = end
399          continue
400        }
401        break
402      }
403      if (after === 'redirect' && kind !== 'chain' && kind !== 'redirect') {
404        if (kind === 'comment' || kind === 'flag') break
405        out.push({ start, end, kind: kind === 'str' || kind === 'var' || kind === 'num' ? kind : 'path' })
406        after = null
407        nargs++
408        evidence = true
409        i = end
410        continue
411      }
412      let color: SpanKind
413      switch (kind) {
414        case 'sub':
415        case 'word': {
416          if (CHAIN_TOOLS.has(cmd) && COMMANDS.has(word)) {
417            out.push({ start, end, kind: 'cmd' })
418            cmd = word
419            subs = 0
420            nargs++
421            evidence = true
422            i = end
423            continue
424          }
425          if (STOP_WORDS.has(word)) break scan
426          if (kind === 'sub' && SUBCMD_TOOLS.has(cmd) && subs < MAX_SUB) {
427            subs++
428            color = 'sub'
429          } else if (strong) {
430            color = 'path'
431          } else {
432            // prose: take a few bare words on trust while waiting for
433            // evidence; once there is some, a bare word is more likely the
434            // sentence resuming than an argument
435            bare++
436            if (evidence || bare > MAX_BARE) break scan
437            color = 'path'
438          }
439          break
440        }
441        case 'chain':
442        case 'redirect':
443          after = kind
444          color = 'op'
445          break
446        default:
447          color = kind
448      }
449      // operators only count once something real follows them; a bare
450      // number after an English-word command is not evidence
451      if (kind !== 'sub' && kind !== 'word' && kind !== 'chain' && kind !== 'redirect') {
452        if (!(kind === 'num' && ENGLISH.has(cmd))) evidence = true
453      }
454      // a bare word followed by sentence punctuation ends the span
455      if (TRIMMABLE.has(kind) && word.length > 1 && isSentencePunct(word[word.length - 1]!)) {
456        out.push({ start, end: end - 1, kind: color })
457        nargs++
458        i = end - 1
459        break
460      }
461      out.push({ start, end, kind: color })
462      nargs++
463      i = end
464    }
465    // a trailing chain operator paints nothing on its own
466    if (after) {
467      const last = out[out.length - 1]
468      if (last && last.kind === 'op') {
469        i = last.start
470        out.pop()
471        nargs--
472      }
473    }
474    if (nargs === 0 || (!strong && !evidence)) {
475      // bare command word in prose, or `make sure`: leave it alone
476      out.length = mark
477      pos = ce
478      continue
479    }
480    pos = i
481  }
482  return out
483}
484
hooks/width.ts 161 lines
1// Terminal cell widths, mirroring the engine's ruler: Claude Code lays out
2// with Bun.stringWidth(s, { ambiguousIsNarrow: true }). Every width in the
3// mod (table columns, heading rules, ordered gutters) goes through this so
4// the tree and the layout engine agree per glyph. Standalone: the hook
5// environment has no Bun. ASCII-only source; glyphs come from code points.
6//
7// The rules below were read off Bun 1.3 (2026-10-07, /tmp probe against
8// Bun.stringWidth): a grapheme is summed per code point, marks (Mn, Me, Mc)
9// and the invisible formats (ZWJ, ZWNJ, bidi marks, BOM, tags) count 0, a
10// VS16 lifts a one-cell Emoji-property base (digits, #, *, (c), the
11// text-default symbols) to 2, a keycap is 1, a flag pair is 1, a ZWJ
12// sequence counts its head, and a jamo vowel or tail after a head counts 0.
13const cp = (n: number) => String.fromCodePoint(n)
14const VS16 = 0xfe0f
15const ZWJ = 0x200d
16const KEYCAP = 0x20e3
17const SGR = new RegExp(cp(0x1b) + '\\[[0-9;]*m', 'g')
18const MARK = /^[\p{Mn}\p{Me}\p{Mc}]$/u
19const EMOJI = /^\p{Emoji}$/u
20const EMOJI_PRESENTATION = /^\p{Emoji_Presentation}$/u
21
22const segmenter =
23  typeof Intl !== 'undefined' && 'Segmenter' in Intl
24    ? new Intl.Segmenter(undefined, { granularity: 'grapheme' })
25    : null
26
27// East Asian Wide and Fullwidth ranges the Emoji_Presentation property does
28// not already cover (assigned code points; Bun follows EastAsianWidth.txt)
29const WIDE: ReadonlyArray<readonly [number, number]> = [
30  [0x1100, 0x115f],
31  [0x2329, 0x232a],
32  [0x2e80, 0x303e],
33  [0x3041, 0x3247],
34  [0x3250, 0x33ff],
35  [0x3400, 0x4dbf],
36  [0x4e00, 0x9fff],
37  [0xa000, 0xa4c6],
38  [0xa960, 0xa97c],
39  [0xac00, 0xd7a3],
40  [0xf900, 0xfaff],
41  [0xfe10, 0xfe19],
42  [0xfe30, 0xfe6b],
43  [0xff01, 0xff60],
44  [0xffe0, 0xffe6],
45  [0x16fe0, 0x16fe4],
46  [0x17000, 0x187f7],
47  [0x18800, 0x18cd5],
48  [0x18d00, 0x18d08],
49  [0x1aff0, 0x1affe],
50  [0x1b000, 0x1b122],
51  [0x1b132, 0x1b132],
52  [0x1b150, 0x1b152],
53  [0x1b155, 0x1b155],
54  [0x1b164, 0x1b167],
55  [0x1b170, 0x1b2fb],
56  [0x1f200, 0x1f202],
57  [0x1f210, 0x1f23b],
58  [0x1f240, 0x1f248],
59  [0x1f250, 0x1f251],
60  [0x1f260, 0x1f265],
61  [0x20000, 0x2fffd],
62  [0x30000, 0x3fffd],
63]
64
65function isWide(c: number): boolean {
66  return WIDE.some(([lo, hi]) => c >= lo && c <= hi)
67}
68
69// the format characters Bun counts as nothing; the other Cf (a soft hyphen,
70// a word joiner, the bidi controls) take a cell there. The Thai and Lao
71// SARA AM and the halfwidth voiced marks sit in Bun's zero table too.
72function isInvisible(c: number): boolean {
73  return (c >= 0x200b && c <= 0x200f) || c === 0xfeff || (c >= 0xe0000 && c <= 0xe007f) || c === 0xe33 || c === 0xeb3 || c === 0xff9e || c === 0xff9f
74}
75
76const isRegional = (c: number) => c >= 0x1f1e6 && c <= 0x1f1ff
77const isModifier = (c: number) => c >= 0x1f3fb && c <= 0x1f3ff
78// a jamo vowel or tail: one cell alone, none after a head or a syllable
79const isJamoTail = (c: number) => (c >= 0x1160 && c <= 0x11ff) || (c >= 0xd7b0 && c <= 0xd7ff)
80
81function codePointWidth(c: number): number {
82  if (c < 0x20 || (c >= 0x7f && c < 0xa0)) return 0
83  if (isInvisible(c) || isModifier(c)) return 0
84  const s = cp(c)
85  if (MARK.test(s)) return 0
86  if (EMOJI_PRESENTATION.test(s) || isWide(c)) return 2
87  return 1
88}
89
90function graphemeWidth(g: string): number {
91  const points = [...g].map(ch => ch.codePointAt(0)!)
92  const head = points[0]
93  if (head === undefined) return 0
94  if (points.includes(KEYCAP)) return 1
95  if (isRegional(head)) return 1
96  let n = 0
97  for (let i = 0; i < points.length; i++) {
98    const c = points[i]!
99    if (c === ZWJ) break
100    let w = codePointWidth(c)
101    // a selector lifts a one-cell Emoji-property base to the emoji form
102    if (w === 1 && points[i + 1] === VS16 && EMOJI.test(cp(c))) w = 2
103    if (i > 0 && isJamoTail(c)) w = 0
104    n += w
105  }
106  return n
107}
108
109/** cells `s` takes on the terminal, SGR escapes ignored */
110export function cellWidth(s: string): number {
111  const clean = s.replace(SGR, '')
112  if (segmenter) {
113    let n = 0
114    for (const { segment } of segmenter.segment(clean)) n += graphemeWidth(segment)
115    return n
116  }
117  let n = 0
118  for (const ch of clean) n += graphemeWidth(ch)
119  return n
120}
121
122// HORIZONTAL ELLIPSIS, U+2026, as glyphs.ts has it (width.ts stays standalone)
123const ELLIPSIS = cp(0x2026)
124
125/** the longest head of `s` within `n` cells */
126function headCells(s: string, n: number): string {
127  let out = ''
128  for (const ch of s) {
129    if (cellWidth(out + ch) > n) break
130    out += ch
131  }
132  return out
133}
134
135/** the longest tail of `s` within `n` cells */
136function tailCells(s: string, n: number): string {
137  const chars = [...s]
138  let out = ''
139  for (let i = chars.length - 1; i >= 0; i--) {
140    if (cellWidth(chars[i] + out) > n) break
141    out = chars[i] + out
142  }
143  return out
144}
145
146/** cut to `n` cells in the middle: the head and the tail stay, an ellipsis between */
147export function clipMiddle(s: string, n: number): string {
148  if (cellWidth(s) <= n) return s
149  if (n <= 0) return ''
150  const head = Math.ceil((n - 1) / 2)
151  return headCells(s, head) + ELLIPSIS + tailCells(s, n - 1 - head)
152}
153
154/** a path cut to `n` cells, its file name kept whole when it fits: `hooks/...render.ts` */
155export function clipPath(s: string, n: number): string {
156  if (cellWidth(s) <= n) return s
157  const base = s.slice(s.lastIndexOf('/') + 1)
158  if (base === s || cellWidth(base) + 2 > n) return clipMiddle(s, n)
159  return headCells(s, n - cellWidth(base) - 2) + ELLIPSIS + '/' + base
160}
161