Shows the LaTeX math in Claude's replies as real equations: images in kitty and Ghostty, text elsewhere

kittex typesets the LaTeX in Claude's replies right in your terminal. In kitty and Ghostty, display and inline math become real TeX images that follow your font and theme. While Claude writes, they show as readable Unicode, and nothing jumps when they land. Other terminals get clean Unicode math. With a local LaTeX install, TikZ, pgfplots, tikz-cd, circuitikz and chemfig diagrams are drawn as pictures too, compiled in a sandbox. Hover an equation to copy its LaTeX, and run /kittex-doctor to check your setup.
kittex runs entirely on your machine: it makes no network requests and sends nothing anywhere. It keeps rendered images in ~/.cache/kittex (the Cache option turns this off).
Options, setup for diagrams and the FAQ: https://github.com/brenocq/kittex
License: MIT.
Network. None. kittex never opens a connection, and nothing it reads leaves your machine: what it learns about your terminal stays in Claude Code's plugin storage and in the cache below.
Programs it runs, each with a time limit, only in a terminal session (not under claude -p or the SDK):
uname -s, once per session: macOS and Linux draw the reply bullet differently.perl -e …, or python3 -I -c … where perl is missing: asks the terminal Claude Code runs in for its cell size in pixels (the TIOCGWINSZ ioctl on that terminal, opened read-only), so images fit the text rows. On macOS the python probe runs ps to find that terminal. The scripts are fixed text in core/src/terminal/cell.ts.kitty +runpy …; in Ghostty, ghostty +show-config --changes-only=false: each prints the terminal's own colours and font from its config, so formulas take your text colour and weight. Without them kittex reads kitty.conf or Ghostty's config file itself.fc-match finds your terminal font's file (on macOS, osascript -l JavaScript -e … asks CoreText for it first, as Ghostty finds its fonts there; the script is fixed text in core/src/terminal/fontfile.ts, with the font's family and style as its arguments), and od reads byte ranges of it where Claude Code can't read the file whole: the font's metrics set the size of the math.rm -f on old entries of kittex's own cache, when it passes its size limit (the mod's file API has no delete).auto and TeX installed: latex and dvisvgm (version checks, then the compile of each diagram, with shell escape off), kpsewhich, realpath and ldd (to find what TeX needs, so the sandbox can show it), prlimit (CPU time and file size limits; where it is missing, as on macOS, /bin/sh -c sets the same limits with ulimit before running the TeX command) and on Linux bwrap (bubblewrap: TeX runs without your home folder or the temporary folders, only its own job folder), mktemp -d, mkdir -p, cp, mv, find … -delete and rm -rf on that job folder and on kittex's TeX cache. On macOS, TeX is also looked for in /Library/TeX/texbin, where MacTeX puts it, when that folder isn't on your PATH. The commands are built in core/src/diagram/tex.ts and hooks/tex.ts./kittex-doctor runs the same checks again, plus du and find on kittex's cache folder to report its size.Files it writes, none of them read or run by any other tool:
~/.cache/kittex/v<n>/ (or under $XDG_CACHE_HOME): rendered equations, so a resumed session draws them at once. The Cache option turns it off.~/.cache/kittex/tex/: drawn diagrams, and in tex/fmt/ the LaTeX format kittex precompiles for them.$TMPDIR/kittex-tex.XXXXXXXXXX/: one job folder per compile, removed after it.What it reads. Environment variables, by name and never written: TERM, TERM_PROGRAM, TERM_PROGRAM_VERSION, LC_TERMINAL, VTE_VERSION, TERMINAL_EMULATOR, KITTY_WINDOW_ID, KITTY_PID, KITTY_INSTALLATION_DIR, KITTY_CONFIG_DIRECTORY, GHOSTTY_RESOURCES_DIR, GHOSTTY_BIN_DIR, WEZTERM_PANE, WEZTERM_EXECUTABLE, ITERM_SESSION_ID, WT_SESSION, TMUX, STY, ZELLIJ, ZELLIJ_SESSION_NAME (which terminal draws, and whether a multiplexer sits in between); SSH_CONNECTION, SSH_CLIENT, SSH_TTY (only whether they are set: over SSH the terminal's files are on another machine); HOME, XDG_CONFIG_HOME, XDG_CONFIG_DIRS, XDG_CACHE_HOME, TMPDIR, PATH, CLAUDE_CONFIG_DIR (where configs, the cache and TeX are); CLAUDE_CODE_FORCE_TERMINAL_IMAGES, CLAUDE_CODE_SESSION_KIND, FORCE_HYPERLINK, CI, TEAMCITY_VERSION, NETLIFY (what Claude Code itself decides by). Files: the terminal's config, your terminal font, a custom Claude theme's file (<config dir>/themes/<name>.json), and for the doctor /etc/os-release and kittex's own plugin.json. Settings: the theme and maxProseWidth values, kittex's own options, and (for the doctor) only whether managed settings exist. kittex reads no credentials, tokens or keys, and has none to ask for.
Settings and storage it sets. Once, if you set the Cache option to false in kittex 0.1.0 (when it was a switch), kittex writes it again as off, the value /config now offers, through Claude Code's own /config path. Nothing else in your settings, and no environment variable. In Claude Code's plugin storage it keeps the terminal facts it measured (for the next session's first drawing), where TeX was found, and which conversations already have its current instructions.
What it adds to the conversation. In a terminal where it draws math, a system prompt section (kittex:math) tells Claude to write math as LaTeX ($…$ inline, $$ on lines of their own) and, with TeX, diagrams as TikZ in a latex code block; the text is MATH_INSTRUCTIONS and DIAGRAM_INSTRUCTIONS in hooks/math.ts. Where that section can't be added (a policy plugin drops it) or a conversation holds an older version, the same text rides once as context with the next prompt you send. $.prompt.compose, which kittex calls once at start, is Claude Code's own call: it checks whether the section reached the system prompt.
Hooks. /kittex-doctor is kittex's own command, answered by its command.run hook; no other command is hooked, and kittex never decides a permission. The config.set hooks on theme and maxProseWidth pass each change on unchanged and only redraw the math to match. The reply hooks change what you see, not what Claude wrote: while a reply streams, its formulas show as Unicode, and once it lands they are drawn as images in the same place. The session hooks (start, end, compaction, appended replies) only note when a conversation starts over.
The bundled code. hooks/core.js and hooks/core-parts/ are built from the TypeScript in core/src by npm run build (core/scripts/build.mjs): esbuild, not minified, each statement under a comment naming its source file, cut into parts that each import the one before (so Claude Code reads the mod without holding up the prompt). It bundles MathJax 4 with its New Computer Modern font (Apache-2.0), marked and fflate (MIT), as THIRD-PARTY-NOTICES lists. The long JSON texts at the start of the parts (__kittexJson…) are that font's tables, glyph metrics and SVG outlines, parsed only when the first formula is drawn. The getters and the Object.getOwnPropertyNames and Object.getOwnPropertyDescriptor calls (__export, __copyProps) are esbuild's module helpers, which give import * as its live bindings; the setTimeout in MathJax's maction tooltips never runs in the mod.
hooks/register.tsx 1958 lines1// kittex's Claude Code mod: typesets the LaTeX math in Claude's replies, as TeX
2// images where the terminal draws them (kitty, Ghostty) and as Unicode
3// elsewhere. Every function that takes `$` lives here; the pure side (the
4// rewrite of streamed text, the plan of a landed reply, the constants that
5// encode guesses about the engine) is in math.ts.
6//
7// The flow (design notes, "Streaming"): classic.MessageDisplay rewrites the
8// reply while it streams, display formulas becoming Unicode previews padded to
9// the rows their images will take, and records each preview with its TeX; when
10// the block lands, ui.render on AssistantMessage draws the prose through the
11// engine and puts an Image where each preview was. Anything that fails falls
12// back to what the engine would have drawn.
13
14import type { EngineInterface, EventResult, FsEntry, MatchedHook, Register, RenderElement, Timer } from 'claude-code'
15
16import {
17 cellProbeRan,
18 cellProbes,
19 chooseInk,
20 createLineScanner,
21 claudeCustomThemePath,
22 claudeThemeScheme,
23 colorProbes,
24 detectTerminal,
25 drawsEmojiSequences,
26 coreTextFontArgv,
27 faceIndexOf,
28 fontFileArgv,
29 GHOSTTY_BUILTIN_FONT,
30 imageInkBackground,
31 imageInkCurve,
32 matchesFamily,
33 odArgv,
34 parseCoreTextFont,
35 parseFontFile,
36 parseOd,
37 readFontMetrics,
38 measureDisplay,
39 measureDisplayResult,
40 previewDisplay,
41 readTerminalColors,
42 renderDisplay,
43 renderDisplayResult,
44 renderInline,
45 renderInlineResult,
46 renderImage,
47 renderPicture,
48 TexError,
49 strokeWeight,
50 toBase64,
51 BUILD_ID,
52} from './core.js'
53import type { ByteReader, CellSize, FontMetrics, ImageSpec, InkPlace, InlineEnv, PictureEnv, RenderedImage, RenderEnv, TerminalColors, TerminalInfo, TexDocument } from './core.js'
54import { imageBlockOf, imageBook, NO_PDF } from './image.ts'
55import type { ImageHost } from './image.ts'
56import {
57 BLANK_ALT,
58 BLOCK_LIMIT,
59 blockMatches,
60 BULLET,
61 bulletFor,
62 CELL_IDLE_MS,
63 CELL_REFRESH_MS,
64 cellOrFallback,
65 COPY_LABEL,
66 copiedFormula,
67 DIAGRAM_INSTRUCTIONS,
68 imageInstructions,
69 FALLBACK_COLUMNS,
70 graphicsFromBlit,
71 inlineAlt,
72 INK_PREFER,
73 IMAGE_LIMIT,
74 inlineEnvFor,
75 mathEmPxFor,
76 INSTRUCT_WITHOUT_IMAGES,
77 instructionsKey,
78 instructionsNeeded,
79 inlineFlow,
80 joinProse,
81 ON_SCREEN_REPORTED,
82 STREAMED_PATTERN,
83 linkEnv,
84 locatePreviews,
85 MessageStream,
86 MATH_INSTRUCTIONS,
87 mathOptions,
88 pictureEnvFor,
89 planLanded,
90 recordInstructed,
91 PROBE_TIMEOUT_MS,
92 proseWidthFor,
93 displayColumns,
94 PENDING_ROWS,
95 RECENT_BLOCKS,
96 renderEnvFor,
97 REPLY_INDENT,
98 RESIZE_SETTLE_MS,
99 SECTION_ID,
100 sourcePattern,
101 STREAM_LIMIT,
102 streamEnvFor,
103 UPDATED_INSTRUCTIONS,
104 withoutTextOverride,
105} from './math.ts'
106import { altText, fallbackLines, fitPictures, overBudget } from './budget.ts'
107import { base64Cache, base64Of, diagramImage, displayImage, displayRows, inlineImage, pictureRedraws, reservedOptions, signatureOf } from './drawing.ts'
108import { CACHE_LIMIT_BYTES, CACHE_READ_MS, cacheDir, cacheFacts, decodeEntry, encodeEntry, entryKey, entryPath, ENTRY_NAME, pruneList, TEX_CACHE_LIMIT_BYTES, TEX_ENTRY_NAME } from './cache.ts'
109import { newestFirst } from './schedule.ts'
110import type { EngineGraphics, InlineSlot, InstructedSessions, KittexEnv, LandedPlan, MathOptions, Piece, PlanOptions, PreviewRecord, StreamedBlock, StreamEnv, StreamRewrite, TexUse } from './math.ts'
111import { diagramJob, hiddenDirs, mathJob, onPath, pdfPicture, prepareFormat, probeTex, rememberedTex, TEX_BACKGROUND_MS, TEX_STREAM_BUDGET_MS, texBook, texCacheDir, texPath, texResult } from './tex.ts'
112import type { DiagramKind, TexHost } from './tex.ts'
113import { DOCTOR_DESCRIPTION, DOCTOR_PROBE_MS, formatDoctor, osFacts, plain, probeCache, probeDiagrams } from './doctor.ts'
114import type { DoctorFacts, DoctorHost, TerminalFacts } from './doctor.ts'
115
116type Engine = EngineInterface
117/** What a classic.MessageDisplay hook resolves to (rewriteFlush). */
118type FlushResult = EventResult<'classic.MessageDisplay'>
119
120const ENV = { plugin: 'kittex', key: 'env' } as const
121const BLOCKS = { plugin: 'kittex', key: 'blocks' } as const
122const REQUESTS = { plugin: 'kittex', key: 'requests' } as const
123const RECENT = { plugin: 'kittex', key: 'recent' } as const
124/** How long a render waits for session.start's kittex.env before it draws without kittex. */
125const ENV_WAIT_MS = 1500
126
127// Module state that drawing never reads (a hot reload resets it, and
128// session.start runs again then).
129
130/** A message streaming through MessageDisplay (one text block), as kittex follows it. */
131interface Streaming {
132 /** Its stream; null once kittex gave up on it (the rest passes as written). */
133 stream: MessageStream | null
134 /** The model's text so far, every delta as it came: what the block's transcript row holds. */
135 source: string
136 /** How much of it the engine shows (every flush's text joined): where the next flush's previews start. */
137 shown: number
138 /** Its block is in kittex.blocks. */
139 stored: boolean
140 /** A row's uuid links it (kittex.requests). */
141 linked: boolean
142 /** Its final flush came. */
143 done: boolean
144 /** The working directory its image blocks' relative paths resolve against (kept in its block). */
145 cwd?: string
146}
147
148/** Per message, a gate per flush index that opens once that flush's rewrite is done (see the MessageDisplay hook). */
149const flushGates = new Map<string, Map<number, { promise: Promise<void>; resolve: () => void }>>()
150
151/** The gate of a message's flush `index` (open at once below 0: there is no flush before the first). */
152function flushGate(id: string, index: number): { promise: Promise<void>; resolve: () => void } {
153 if (index < 0) return { promise: Promise.resolve(), resolve: () => undefined }
154 let gates = flushGates.get(id)
155 if (!gates) {
156 gates = new Map()
157 flushGates.set(id, gates)
158 for (const key of flushGates.keys()) if (flushGates.size > STREAM_LIMIT) flushGates.delete(key)
159 }
160 let gate = gates.get(index)
161 if (!gate) {
162 let resolve!: () => void
163 const promise = new Promise<void>(r => (resolve = r))
164 gate = { promise, resolve }
165 gates.set(index, gate)
166 // Only the last few are ever waited on.
167 gates.delete(index - 8)
168 }
169 return gate
170}
171
172/** Messages streaming through MessageDisplay, and the last ones that did (their rows may be appended after their final flush). */
173const streams = new Map<string, Streaming>()
174/** The message_ids of the blocks stored, oldest first: past BLOCK_LIMIT the oldest is dropped. */
175const storedBlocks: string[] = []
176/** Response rows appended before any flush of their block (a one-line reply): linked once its stream shows up. */
177const pendingRows: { uuid: string; text: string }[] = []
178/** Claude Code's environment as the terminal helpers read it. */
179let processEnv: Record<string, string | undefined> = {}
180let terminal: TerminalInfo | undefined
181let terminalColors: TerminalColors | undefined
182/** The light/dark scheme terminalColors were read for (kitty's auto themes, Ghostty's pairs follow it). */
183let colorScheme: 'dark' | 'light' | undefined
184let theme: string | undefined
185/** A custom theme's file contents, when `theme` is `custom:<slug>`. */
186let customTheme: string | undefined
187/** prompt.compose's section did not reach the prompt: instructions ride prompt.submit's context. */
188let instructByContext = false
189/** setUp found the model is instructed here (a terminal kittex draws math on). */
190let instructWanted = false
191/** The next request composes its conversation's system prompt anew (/clear, compaction): the current instructions are in it. */
192let composesFresh = false
193/** InstructedSessions in $.store, and as this process last wrote it (where the store can't be read). */
194const INSTRUCTED = 'instructed'
195let instructedHere: InstructedSessions = {}
196/** The session's key in InstructedSessions where the host can't name it. */
197const THIS_SESSION = 'this'
198/** The cell probes, bound to the `$` session.start received. */
199let cells: Cells | undefined
200/** Runs a function on session.start's clock once the current dispatch resolves, or `ms` later (a hook's `$` belongs to its one dispatch). */
201let later: ((fn: () => void, ms?: number) => void) | undefined
202/** Writes a file with session.start's `$`: the cache's entries a render could not write itself. */
203let writeFile: ((path: string, text: string) => Promise<void>) | undefined
204/** Where the cache's entries go (cache.ts), from XDG_CACHE_HOME or HOME; undefined without either. */
205let cacheFolder: string | undefined
206/**
207 * Settles once session.start has stored kittex.env (or given up). After
208 * --resume the engine asks for the transcript's drawings before it raises
209 * session.start: a render that comes first waits for it.
210 */
211let envSettled: (() => void) | undefined
212/** session.start has run setUp this process (kittex.env is then the truth, null included). */
213let envKnown = false
214let envReady: Promise<void> = new Promise(resolve => {
215 envSettled = resolve
216})
217/** kittex.env as this process last stored it (writeEnv): what a new session in the process starts with (readEnv). */
218let lastEnv: KittexEnv | null | undefined
219/** kittex.env as the last session stored it, for renders before session.start (read once). */
220let rememberedEnv: Promise<KittexEnv | undefined> | undefined
221const REMEMBERED = 'env'
222/** The `cache` option: drawings of resumed blocks kept on disk (cache.ts). */
223let cacheOn = true
224/** session.start's dispatches in this process (a hot reload makes a second). */
225let sessions = 0
226/** The local TeX may draw here (the `latex` option on, block math not Unicode): an earlier session's TeX cache is read. */
227let texAllowed = false
228/** Where the setup TeX was found with is remembered for the next session ($.store): its cache's key. */
229const REMEMBERED_TEX = 'tex'
230/** `darwin`, `linux`... from `uname -s`, when it ran. */
231let platform: string | undefined
232/** The probe for the local TeX (the `latex` option), started after session.start; settles once texBook knows. */
233let texProbe: Promise<void> | undefined
234/** Redraws the landed blocks once a compile they asked for ends (session.start's `$`). */
235let redraw: (() => void) | undefined
236
237export const register: Register = (on, options) => {
238 /** The `block` and `inline` options: how each kind of math is shown (image, unicode or raw). */
239 const math = mathOptions(options)
240 // Both left as Claude wrote them: kittex does nothing (no rewrite, no instructions to the model) but its doctor.
241 const off = math.block === 'raw' && math.inline === 'raw'
242 cacheOn = options.cache !== 'off' && options.cache !== false
243 /** The `latex` option: `auto` draws diagrams and the math MathJax refuses with the local LaTeX where it is found; `off` never runs it. */
244 const latex = options.latex === 'off' ? 'off' : 'auto'
245 texAllowed = !off && latex === 'auto' && math.block !== 'unicode'
246
247 // /kittex-doctor (doctor.ts), whatever the options: kittex's own command,
248 // answered here (a registered command has no core); no other command is hooked.
249 on('command.run', { command: 'kittex-doctor' }, $ => runDoctor($, options))
250
251 // ─── Setup ─────────────────────────────────────────────────────────────────
252
253 on('session.start', async ($, e, next) => {
254 const started = await next(e)
255 await startDoctor($, e.surface)
256 await migrateCacheOption($)
257 if (off) return started
258 if (e.surface !== 'terminal') {
259 // A -p run or the SDK (Claude Code for VS Code, the desktop app): no
260 // terminal draws here, and MessageDisplay's rewrite would become the
261 // reply's text in the SDK's output. Nothing is probed or rewritten.
262 cells?.stop()
263 cells = undefined
264 await writeEnv($, null).catch(() => undefined)
265 envKnown = true
266 envSettled?.()
267 return started
268 }
269 cells?.stop()
270 cells = cellsFor($)
271 later = laterFor($)
272 graphicsSoon = ms => void $.clock.after(ms, () => void checkGraphics($).catch(() => undefined))
273 // A drawing before session.start (a resume's) put Images on screen: asked now.
274 askSoon(GRAPHICS_ASK_MS)
275 writeFile = (path, text) => $.fs.write(path, text)
276 sessions += 1
277 let settled = false
278 void envReady.then(() => (settled = true))
279 await Promise.resolve()
280 if (settled) {
281 // A second session in this process (a hot reload): its own wait.
282 envReady = new Promise(resolve => {
283 envSettled = resolve
284 })
285 }
286 try {
287 await setUp($, e.surface)
288 } catch {
289 await writeEnv($, null).catch(() => undefined)
290 } finally {
291 envKnown = true
292 envSettled?.()
293 }
294 if (cacheOn) soon(() => void pruneCache($).catch(() => undefined))
295 if (unwritten.size > 0) soon(flushEntries)
296 // The local TeX, found after setup without holding it up (process.run: the terminal only).
297 // The first session keeps what renders before it read from TeX's cache (a resume's diagrams).
298 if (sessions > 1) texBook.reset()
299 texProbe = undefined
300 // Only where kittex draws images: elsewhere (Terminal.app, iTerm2) diagrams stay code, so TeX would never be shown.
301 const drawsImages = (await readEnv($).catch(() => null))?.images === true
302 // Image blocks are drawn from their files with session.start's `$` (a read may outlive the dispatch that asked for it).
303 imageBook.reset()
304 if (drawsImages) {
305 redraw = () => $.ui.invalidate('ui.render')
306 imageBook.reset(imageHost($), { cwd: await $.session.cwd().catch(() => undefined), home: processEnv.HOME })
307 // Blocks drawn before files could be read (a resumed conversation's) are drawn again with them.
308 $.ui.invalidate('ui.render')
309 }
310 if (latex === 'auto' && math.block !== 'unicode' && drawsImages) {
311 // Not awaited: a few short commands (each with its time limit) that settle meanwhile.
312 texProbe = setUpTex($)
313 }
314 return started
315 })
316 if (off) return
317
318 on('config.set', { key: 'theme' }, async ($, e, next) => {
319 const result = await next(e)
320 if (result.deny === undefined && typeof result.value === 'string') await refreshInk($, result.value).catch(() => undefined)
321 return result
322 })
323
324 // Prose wraps at maxProseWidth: inline images are placed by it.
325 on('config.set', { key: 'maxProseWidth' }, async ($, e, next) => {
326 const result = await next(e)
327 if (result.deny === undefined) await refreshProseWidth($).catch(() => undefined)
328 return result
329 })
330
331 // ─── Instructions to the model ─────────────────────────────────────────────
332
333 on('prompt.compose', async ($, e, next) => {
334 const composed = await next(e)
335 try {
336 const env = await readEnv($, true)
337 if (!e.surfaces.includes('terminal') || !instructs(env)) return composed
338 if (composed.sections.some(section => section.id === SECTION_ID)) return composed
339 return { sections: [...composed.sections, { id: SECTION_ID, text: await instructions(env, math), scope: 'session' as const }] }
340 } catch {
341 return composed
342 }
343 })
344
345 // The instructions as context, once, where the conversation lacks the
346 // current ones: the section was dropped (policy), or the system prompt the
347 // conversation was composed with holds older ones or none (a resume, a
348 // kittex reloaded or upgraded since, TeX found since).
349 on('prompt.submit', async ($, e, next) => {
350 let update: { record: InstructedSessions; session: string; key: string } | undefined
351 let note: string | undefined
352 try {
353 const env = await readEnv($, true)
354 if (instructWanted && instructs(env)) {
355 const text = await instructions(env, math)
356 const key = instructionsKey(text)
357 const session = await $.session.id().catch(() => THIS_SESSION)
358 const record = await readInstructed($)
359 // A conversation with nothing in it yet is composed with this text too (a new session, a hot reload before its first prompt).
360 const fresh = composesFresh || (record[session] !== key && (await $.session.messages().catch(() => [])).length === 0)
361 if (instructionsNeeded({ fresh, byContext: instructByContext, held: record[session], key })) note = fresh ? text : `${UPDATED_INSTRUCTIONS} ${text}`
362 update = { record, session, key }
363 }
364 } catch {
365 update = undefined
366 note = undefined
367 }
368 const entered = await next(note === undefined ? e : { ...e, context: [...(e.context ?? []), note] })
369 if (update && entered.drop === undefined) {
370 composesFresh = false
371 if (update.record[update.session] !== update.key) {
372 instructedHere = recordInstructed(update.record, update.session, update.key)
373 await $.store.set(INSTRUCTED, instructedHere).catch(() => undefined)
374 }
375 }
376 return entered
377 })
378
379 // A new conversation in the same process: /clear, and a compaction (which
380 // drops the turn that carried the instructions). The hooks only observe: a
381 // failure (here and at the other gating sites) lets the event go on as is.
382 on('session.end', ($, e, next) => {
383 if (e.reason === 'clear') composesFresh = true
384 return next(e)
385 })
386
387 on('classic.SessionStart', async ($, e, next) => {
388 const result = await next(e)
389 // A new session's state starts empty: kittex.env is stored again for it (readEnv).
390 await readEnv($, true).catch(() => null)
391 if (e.source === 'clear' || e.source === 'compact') composesFresh = true
392 // Another conversation resumed: it holds what it was composed with (recorded, or not).
393 if (e.source === 'resume') composesFresh = false
394 return result
395 })
396
397 on('session.compact', async ($, e, next) => {
398 const result = await next(e)
399 if (e.agentId === undefined && e.trigger !== 'precompute' && result.skip === undefined) composesFresh = true
400 return result
401 })
402
403 // ─── Streaming ─────────────────────────────────────────────────────────────
404
405 on('classic.MessageDisplay', async ($, e, next) => {
406 // The engine dispatches a message's flushes without waiting for the hook on the one before (measured live:
407 // while a flush waited for TeX, the next two ran first). A stream reads them in order: each waits for the
408 // flush before it (its index - 1) to be done, then is done itself however it ends.
409 const done = flushGate(e.message_id, e.index)
410 try {
411 const below = await next(e)
412 await flushGate(e.message_id, e.index - 1).promise
413 return await rewriteFlush($, e, below, math)
414 } finally {
415 done.resolve()
416 if (e.final) flushGates.delete(e.message_id)
417 }
418 })
419
420 // A landed block is told from the others by its transcript row: the row a
421 // text block is appended as holds the model's text, which the block's
422 // stream started (MessageDisplay's message_id and AssistantMessage's
423 // requestId, the row's uuid, are unrelated ids). The link is what a landed
424 // block's drawing reads its previews by (fuzz FUZZ-7, FUZZ-14).
425 on('session.append', { door: 'response' }, async ($, e, next) => {
426 try {
427 const text = e.message.content.flatMap(block => (block.type === 'text' ? [block.text] : [])).join('')
428 if (text.trim() !== '') {
429 const id = streamOf(text)
430 if (id !== undefined) {
431 await linkRow($, e.uuid, id)
432 } else {
433 pendingRows.push({ uuid: e.uuid, text })
434 pendingRows.splice(0, Math.max(0, pendingRows.length - PENDING_ROWS))
435 }
436 }
437 } catch {
438 // drawn by its text
439 }
440 return next(e)
441 })
442
443 // ─── Landed replies ────────────────────────────────────────────────────────
444
445 // Registered with matchers on the text, so a block that holds no math and
446 // no kittex preview is drawn by the engine alone (no round trip here).
447 //
448 // The engine draws a hooked block as nothing until the hook's answer
449 // arrives (a hop to the worker and back, 15 to 50 ms), unless the block was
450 // drawn unhooked before: then its own drawing stays up meanwhile. So in the
451 // fullscreen layout a block kittex streamed is hooked only once its
452 // `onScreen` is reported, which it never is on a block's first render: the
453 // engine draws that one itself, and its drawing of a streamed text is the
454 // streaming preview row for row, so the landing shows no blank, only the
455 // images arriving over their previews. A block holding a preview mark is a
456 // streamed one whatever else it holds (a reply's `$100` stays as written in
457 // it). LaTeX as written (after --resume) is hooked from the first render (its
458 // own drawing would show the source), as is every block on the main screen,
459 // which reports no `onScreen`. The three matchers never select the same
460 // render, so kittex runs once per render. A remote surface (desktop, vscode,
461 // mobile) is not hooked: it has no kitty graphics and draws the text it
462 // holds as markdown (and math) its own way, where a formula's Unicode laid
463 // out in rows would run together on one line.
464 on('ui.render', { component: 'AssistantMessage', surface: 'terminal', viewport: { isFullscreen: true }, props: { text: STREAMED_PATTERN, onScreen: ON_SCREEN_REPORTED } }, ($, e, next) => drawLanded($, e, next, math))
465 on('ui.render', { component: 'AssistantMessage', surface: 'terminal', viewport: { isFullscreen: false }, props: { text: STREAMED_PATTERN } }, ($, e, next) => drawLanded($, e, next, math))
466 on('ui.render', { component: 'AssistantMessage', surface: 'terminal', props: { text: sourcePattern(math, true) } }, ($, e, next) => drawLanded($, e, next, math))
467}
468
469/** One flush's rewrite (the MessageDisplay hook's work, its flushes taken in order). */
470async function rewriteFlush($: Engine, e: { message_id: string; delta: string; final: boolean }, below: FlushResult, math: MathOptions): Promise<FlushResult> {
471 const delta = below.displayContent ?? e.delta
472 let entry: Streaming | undefined
473 let before = 0
474 try {
475 const env = await readEnv($, true)
476 if (!env) return below
477 entry = streams.get(e.message_id)
478 if (entry?.done) entry = undefined
479 if (entry?.stream === null) {
480 entry.source += e.delta
481 entry.shown += delta.length
482 if (e.final) entry.done = true
483 return below
484 }
485 const streamEnv: StreamEnv = { ...streamEnvFor(env, math), ...texUse(env, math), ...imageUse(env, math) }
486 if (!entry) {
487 if (delta === '' && e.final) return below
488 // Relative paths in this reply's image blocks are the session's working directory's as it is now (a /cd since).
489 if (streamEnv.imageFiles) imageBook.cwd = await $.session.cwd().catch(() => imageBook.cwd)
490 // Diagrams are held for TeX where it draws them (a block streaming when TeX is found keeps its code), image blocks for their files.
491 const cwd = streamEnv.imageFiles ? imageBook.cwd : undefined
492 entry = { stream: new MessageStream(createLineScanner({ diagrams: streamEnv.tex?.block === true || streamEnv.imageFiles === true })), source: '', shown: 0, stored: false, linked: false, done: false, ...(cwd !== undefined ? { cwd } : {}) }
493 streams.delete(e.message_id)
494 streams.set(e.message_id, entry)
495 for (const id of streams.keys()) if (streams.size > STREAM_LIMIT) streams.delete(id)
496 }
497 before = entry.shown
498 entry.source += e.delta
499 const rewrite = await withTex(entry.stream!, entry.stream!.push(delta, e.final, streamEnv), streamEnv)
500 // Each preview where the engine will show it: a landed block maps its previews back by place, not by content.
501 const records = locatePreviews(rewrite.text, rewrite.records, before)
502 entry.shown = before + rewrite.text.length
503 if (e.final) entry.done = true
504 if (records.length > 0 || (!entry.stored && rewrite.text !== delta)) await storeBlock($, e.message_id, entry, records)
505 if (!entry.linked) await linkPending($, e.message_id, entry)
506 if (records.length > 0 && env.images) drawSoon(records, env)
507 return rewrite.text === delta ? below : { ...below, displayContent: rewrite.text }
508 } catch {
509 // Show whatever was held back, as written, and leave the rest of the message alone.
510 const unshown = entry?.stream?.unshown() ?? delta
511 if (entry) {
512 entry.stream = null
513 entry.shown = before + unshown.length
514 if (e.final) entry.done = true
515 // From here on the text is the model's as written: the landing may read its LaTeX.
516 await storeBlock($, e.message_id, entry, [], before).catch(() => undefined)
517 }
518 return unshown === delta ? below : { ...below, displayContent: unshown }
519 }
520}
521
522/**
523 * Draws a landed block (see the AssistantMessage registrations): its prose
524 * through the engine, an Image where each preview was; anything that fails
525 * falls back to the engine's drawing. `math`: the options (a kind set to
526 * `unicode` gets no image, one set to `raw` is left as written).
527 */
528async function drawLanded($: Engine, e: TerminalLanded, below: (e: TerminalLanded) => Promise<RenderElement>, math: MathOptions): Promise<RenderElement> {
529 if (e.props.isSummary || e.surface !== 'terminal') return below(e)
530 try {
531 let env = await readEnv($)
532 if (!env) {
533 // A resumed session asks for its blocks before session.start has
534 // measured the terminal: draw with what the last session measured in
535 // this terminal, else wait for session.start, rather than draw nothing
536 // of kittex's now and everything later (which moves rows twice).
537 env = (envKnown ? undefined : await (rememberedEnv ??= readRemembered($))) ?? (envKnown ? null : (await within(envReady, ENV_WAIT_MS, clockOf($)), await readEnv($)))
538 if (!env) return below(e)
539 }
540 const seen = e.surface === 'terminal' ? e.viewport?.columns : undefined
541 if (seen !== undefined && seen !== env.columns) {
542 // The window changed width since the cells were measured, and a font
543 // zoom changes the cells too: measure before drawing, so no image goes
544 // out for cells that are gone, and once more when the resize settles.
545 // A render may not write state, so the settle timer stores what it finds.
546 const cell = await cells?.probe()
547 if (cell) env = { ...env, ...cellEnv(cell, env), columns: seen }
548 cells?.settle(seen)
549 }
550 const columns = e.viewport?.columns ?? env.columns
551 const terminalImages = e.surface === 'terminal' && env.images
552 const blockImages = terminalImages && math.block === 'image'
553 const inlineImages = terminalImages && math.inline === 'image'
554 const images = blockImages || inlineImages
555 // The text may lack the block's last flush (or be empty) on the first
556 // render: nothing here is final, and the render runs again when it lands
557 // (and when its block's previews or its row's link are stored: read here).
558 const found = e.surface === 'terminal' ? await landedBlock($, e) : { streamed: false }
559 const streamed = found.streamed || STREAMED_PATTERN.test(e.props.text)
560 const records = images ? (found.block?.records ?? []) : []
561 const renderEnv = renderEnvFor(env, columns)
562 const inlineEnv = inlineEnvFor(env, columns)
563 const planOptions: PlanOptions = {
564 ...(streamed ? { streamed: found.block?.raw === undefined ? {} : { raw: found.block.raw } } : {}),
565 mode: { hyperlinks: env.hyperlinks, emojiSequences: env.emojiSequences },
566 columns,
567 maxColumns: renderEnv.maxColumns,
568 draw: blockImages ? (tex, rows, maxColumns) => displayImage(tex, maxColumns === undefined ? renderEnv : { ...renderEnv, maxColumns }, rows) : undefined,
569 width: proseWidthFor(env, columns),
570 measure: (tex, maxColumns) => displayRows(tex, { ...renderEnv, maxColumns }),
571 math,
572 inline:
573 inlineImages
574 ? { env: inlineEnv, width: proseWidthFor(env, columns), columns, draw: (tex, cells, place) => inlineImage(tex, inlineEnv, cells, place), hyperlinks: env.hyperlinks, emojiSequences: env.emojiSequences }
575 : undefined,
576 }
577 // Diagrams where the local TeX draws (its pictures as wide as the prose).
578 const texOn = e.surface === 'terminal' && texUse(env, math).tex?.block === true
579 // Image blocks where kittex draws image files (TeX or not).
580 const filesOn = e.surface === 'terminal' && imageUse(env, math).imageFiles === true
581 // A plan holding an image file's drawing (or its note) is never kept on disk: nothing in its key follows the
582 // file, which a script may rewrite or delete before the next --resume; the book looks at the file each session.
583 let fileDrawn = false
584 if (texOn || filesOn) {
585 const pictureEnv = pictureEnvFor(env, columns)
586 planOptions.diagram = (source, kind, rows) => {
587 fileDrawn ||= filesOn && imageBlockOf(source, kind) !== undefined
588 return diagramImage(source, kind, pictureEnv, rows, texOn, found.block?.cwd)
589 }
590 }
591 // A block read back as LaTeX (a resumed session) may be on disk already
592 // (cache.ts); one off screen in the fullscreen layout (`onScreen` null:
593 // the engine lays out blocks around the view) gets its rows only, its
594 // images once it is on screen; every other is typeset in its turn, the
595 // newest first (schedule.ts).
596 const resumed = e.surface === 'terminal' && images && !streamed && records.length === 0
597 const key = resumed && cacheOn && cacheFolder ? entryKey(e.props.text, cacheFacts(env, columns, math, `${BUILD_ID}|tex:${texOn}|files:${filesOn}`)) : undefined
598 let plan: LandedPlan | undefined = key ? await readEntry($, key) : undefined
599 if (!plan) {
600 const offScreen = resumed && e.viewport?.isFullscreen === true && (e.props as { onScreen?: unknown }).onScreen === null
601 const options = offScreen ? reservedOptions(planOptions, renderEnv) : planOptions
602 let asked: ReturnType<typeof texBook.takeAsked> = []
603 let files: ImageSpec[] = []
604 const release = await turns.take(() => $.state.get(ENV))
605 try {
606 texBook.takeAsked()
607 imageBook.takeAsked()
608 plan = planLanded(e.props.text, records, options)
609 asked = texBook.takeAsked()
610 files = imageBook.takeAsked()
611 } finally {
612 release()
613 }
614 // What TeX drew in an earlier session is on disk: read, then planned again (no jump after --resume); the rest is compiled, then redrawn.
615 // Read with this render's own $ (a resume's first renders come before TeX is probed); a missing file asked first, so no failed read is logged.
616 // Image files are read now too (a PDF within the stream's time), so a resumed reply's images are there in its first frame.
617 const read = async (path: string) => ((await $.fs.exists(path).catch(() => false)) ? $.fs.read(path).then(text => (typeof text === 'string' ? text : undefined), () => undefined) : undefined)
618 const [texFound, filesFound] = await Promise.all([asked.length > 0 && loadAsked(asked, read), files.length > 0 && loadFiles(files)])
619 if (texFound || filesFound) {
620 plan = planLanded(e.props.text, records, options)
621 asked = [...asked, ...texBook.takeAsked()]
622 files = [...files, ...imageBook.takeAsked()]
623 }
624 compileAsked(asked)
625 loadFilesLater(files)
626 // Kept only once final: no TeX document or image file it waits for.
627 const final =
628 asked.every(document => {
629 const known = texBook.known(document)
630 return known !== undefined && (known.ok || known.lasting)
631 }) &&
632 files.every(spec => {
633 const known = imageBook.known(spec)
634 return known !== undefined && (known.ok || known.lasting)
635 })
636 if (key && !offScreen && final && !fileDrawn) keepEntry(key, plan, (path, text) => $.fs.write(path, text))
637 }
638 if (!plan.changed) return below(e)
639 if (e.surface !== 'terminal' || plan.pieces.every(piece => piece.kind === 'prose' && !piece.inline?.length)) {
640 return below({ ...e, props: { ...e.props, text: joinProse(plan.pieces) } })
641 }
642 // Drawn as the engine drew the preview, row for row (measured live): the
643 // first prose piece is the engine's own drawing with the block's bullet;
644 // later pieces are drawn without a bullet (each brings a one-row top
645 // margin) and indented to the reply column; images and notes sit in that
646 // column, a blank row above them where a blank line was. A block that
647 // opens with a formula gets the bullet beside the image's first row,
648 // where the preview's first line had it.
649 // One answer holds at most 2 MiB of Image source: past it, the rest keep their Unicode (budget.ts).
650 // Pictures drawn at fewer pixels first (same cells), so they fit rather than stay placeholders.
651 const pieces = fitPictures(plan.pieces, (image, density) => pictureRedraws.get(image)?.(density))
652 const over = overBudget(pieces)
653 /** An image not drawn: past the budget, or only its rows reserved (off screen). */
654 const left = { has: (image: RenderedImage) => image.png.length === 0 || over.has(image) }
655 if (images) cells?.watch()
656 // Each Image's alt: its formula for a screen reader where Claude Code draws the pictures (or hasn't
657 // said); where it doesn't, the text already under it, so the preview stays as it streamed (BLANK_ALT).
658 const shownAlt = graphics.state === 'yes' || graphics.state === 'unknown'
659 // The smallest Image drawn here, to ask Claude Code by whether it draws pictures (checkGraphics).
660 let smallest: { key: string; image: RenderedImage } | undefined
661 const drawnImage = (key: string, image: RenderedImage) => {
662 if (!smallest || image.png.length < smallest.image.png.length) smallest = { key, image }
663 return key
664 }
665 const { Box, Button, Image, Text } = $.ui.resolve(e as Extract<LandedEvent, { surface: 'terminal' }>)
666 const indentOf = (isFirstOfReply: boolean) => (isFirstOfReply ? REPLY_INDENT : 0)
667 const first = e.props.isFirstOfReply
668 const indent = first ? REPLY_INDENT : 0
669 // A selection over an image copies the terminal's placeholder cells, not the
670 // formula (the engine copies screen cells and offers no hook), so each image
671 // carries a copy button, shown while the pointer is over it (fullscreen), in
672 // its top-right corner: absolute, so it moves no row.
673 const copy = (tex: string, source?: string) => async () => {
674 const copied = await $.ui.copy({ text: source ?? copiedFormula(tex), surface: e.surface })
675 $.ui.toast(copied.isCopied ? (source === undefined ? 'Copied the formula as LaTeX' : 'Copied the LaTeX source') : 'Could not copy the formula')
676 }
677 const own = (piece: Exclude<Piece, { kind: 'prose' }>, i: number) =>
678 piece.kind === 'image' && left.has(piece.image) ? (
679 <Box key={`kittex-formula-${i}-text`} width={piece.image.columns} height={piece.image.rows} flexDirection="column">
680 <Text>{fallbackLines(previewDisplay(piece.tex, { maxColumns: piece.image.columns }, piece.image.rows), piece.tex, piece.image.columns, piece.image.rows).join('\n')}</Text>
681 </Box>
682 ) : piece.kind === 'image' ? (
683 <Box key={`kittex-formula-${i}-${signatureOf(piece.image.png)}`}>
684 <Image key={drawnImage(`kittex-image-${i}`, piece.image)} source={{ png: base64Of(piece.image.png) }} columns={piece.image.columns} rows={piece.image.rows} alt={shownAlt ? altText(piece.tex) : BLANK_ALT} />
685 <Box position="absolute" top={0} right={0} display="none" hover={{ display: 'flex' }}>
686 <Button key={`kittex-copy-${i}`} label={COPY_LABEL} plain dimColor onPress={copy(piece.tex, piece.copy)} />
687 </Box>
688 </Box>
689 ) : (
690 <Text dimColor>{piece.text}</Text>
691 )
692 // A prose piece is the engine's own drawing; the images of its formulas
693 // lie over their previews, each at the cell its preview starts in: a row
694 // under the piece's top margin, the column after the bullet's where the
695 // piece draws one (a display formula's over its preview's rows, with its
696 // copy button). Not absolute: the engine puts an absolute box that falls
697 // above the screen on its first row (fullscreen, a reply scrolled past
698 // the top), so the images go in the flow of an overlay column, as wide as
699 // nothing and as tall as the piece, beside the drawing in a row-reverse
700 // Box: it starts at the piece's top-left cell, is painted after the
701 // drawing, and takes no room (nothing moves). The drawing's wrapper grows
702 // to the width instead of naming one: the engine refuses its own drawing
703 // under a Box with a size, a position or an overflow.
704 const prose = async (piece: Extract<Piece, { kind: 'prose' }>, isFirstOfReply: boolean, at: number) => {
705 const text = await below({ ...e, props: { ...e.props, text: piece.text, isFirstOfReply } })
706 const inline = piece.inline?.filter(one => !left.has(one.image))
707 if (!inline?.length) return text
708 return (
709 <Box flexDirection="row-reverse">
710 <Box flexDirection="column" flexGrow={1} flexShrink={1}>
711 {text}
712 </Box>
713 <Box flexDirection="column" width={0} flexShrink={0} alignItems="flex-start">
714 {inlineFlow(inline, indentOf(isFirstOfReply)).map(({ inline, marginTop, marginLeft }: InlineSlot, k: number) => (
715 <Box
716 key={`kittex-${inline.display ? 'formula' : 'inline'}-${k}-${signatureOf(inline.image.png)}`}
717 marginTop={marginTop}
718 marginLeft={marginLeft}
719 width={inline.image.columns}
720 height={inline.image.rows}
721 flexShrink={0}
722 >
723 <Image
724 key={drawnImage(`kittex-image-${at}-${k}`, inline.image)}
725 source={{ png: base64Of(inline.image.png) }}
726 columns={inline.image.columns}
727 rows={inline.image.rows}
728 alt={shownAlt ? altText(inline.tex) : inline.display ? BLANK_ALT : inlineAlt(inline.tex, inlineEnv, inline.image.columns)}
729 />
730 {inline.display ? (
731 <Box position="absolute" top={0} right={0} display="none" hover={{ display: 'flex' }}>
732 <Button key={`kittex-copy-${k}`} label={COPY_LABEL} plain dimColor onPress={copy(inline.tex, inline.copy)} />
733 </Box>
734 ) : null}
735 </Box>
736 ))}
737 </Box>
738 </Box>
739 )
740 }
741 // The prose pieces are drawn by the engine at once: each is a round trip, and a block may hold several.
742 const texts = await Promise.all(pieces.map((piece, i) => (piece.kind === 'prose' ? prose(piece, i === 0 ? first : false, i) : null)))
743 const drawn = []
744 for (const [i, piece] of pieces.entries()) {
745 if (i === 0) {
746 if (piece.kind === 'prose') {
747 drawn.push(texts[i])
748 } else {
749 drawn.push(
750 <Box flexDirection="row" marginTop={1}>
751 {first ? (
752 <Box minWidth={REPLY_INDENT}>
753 <Text color="text">{env.bullet ?? BULLET.other}</Text>
754 </Box>
755 ) : null}
756 {own(piece, i)}
757 </Box>,
758 )
759 }
760 } else if (piece.kind === 'prose') {
761 drawn.push(
762 <Box paddingLeft={indent} marginTop={piece.gap ? 0 : -1}>
763 {texts[i]}
764 </Box>,
765 )
766 } else if (piece.kind === 'image') {
767 drawn.push(
768 <Box marginLeft={indent} marginTop={piece.gap ? 1 : 0}>
769 {own(piece, i)}
770 </Box>,
771 )
772 } else {
773 drawn.push(
774 <Box paddingLeft={indent} marginTop={piece.gap ? 1 : 0}>
775 {own(piece, i)}
776 </Box>,
777 )
778 }
779 }
780 if (smallest) askGraphics({ requestId: e.requestId, key: smallest.key, source: { png: base64Of(smallest.image.png) }, columns: smallest.image.columns, rows: smallest.image.rows })
781 return <Box flexDirection="column">{drawn}</Box>
782 } catch {
783 return below(e)
784 }
785}
786
787/** A render of a landed block, as any of the AssistantMessage registrations receives it. */
788type LandedEvent = Parameters<MatchedHook<'ui.render', { component: 'AssistantMessage' }>>[1]
789/** A landed reply in the terminal, as each of drawLanded's hooks matches it. */
790type TerminalLanded = Parameters<MatchedHook<'ui.render', { component: 'AssistantMessage'; surface: 'terminal' }>>[1]
791
792// ─── Helpers that take $ ─────────────────────────────────────────────────────
793
794/**
795 * kittex.env as this conversation holds it. `$.state` is the session's, and a
796 * new session in this process (/clear, /resume of another conversation)
797 * starts without it while session.start does not run again: the env the
798 * setup stored last stands in, and with `reseed` (not from a render, which
799 * may not write) is stored again.
800 */
801async function readEnv($: Engine, reseed = false): Promise<KittexEnv | null> {
802 const held = (await $.state.get(ENV)).value
803 if (held !== undefined) return held
804 if (!envKnown || lastEnv === undefined) return null
805 if (reseed && lastEnv !== null) await $.state.set(ENV, lastEnv).catch(() => undefined)
806 return lastEnv
807}
808
809/** Stores kittex.env, and keeps it for a new session in this process (readEnv). */
810async function writeEnv($: Engine, env: KittexEnv | null): Promise<void> {
811 lastEnv = env
812 await $.state.set(ENV, env)
813}
814
815/** InstructedSessions as $.store holds it, else as this process last wrote it. */
816async function readInstructed($: Engine): Promise<InstructedSessions> {
817 const value = await $.store.get(INSTRUCTED).catch(() => undefined)
818 return value !== null && typeof value === 'object' && !Array.isArray(value) ? (value as InstructedSessions) : instructedHere
819}
820
821/** Whether the model is told to write LaTeX: kittex is set up and draws math on this terminal. */
822function instructs(env: KittexEnv | null): boolean {
823 return env !== null && (env.images || INSTRUCT_WITHOUT_IMAGES)
824}
825
826async function setUp($: Engine, surface: string | null): Promise<void> {
827 // MathJax is not loaded here: the first formula loads it (core's typeset is lazy).
828 processEnv = await readProcessEnv($)
829 cacheFolder = cacheDir(processEnv)
830 terminal = detectTerminal(processEnv)
831 const [cell, uname] = await Promise.all([probeCell($), probeSystem($), resolveTheme($)])
832 platform = uname?.trim().toLowerCase() || undefined
833 const cellAdjust = terminalColors?.cellAdjust
834 const kittyAdjust = terminalColors?.kittyAdjust
835 const env: KittexEnv = {
836 kind: terminal.kind,
837 // Off where Claude Code said it draws no pictures (checkGraphics), whatever the terminal is.
838 images: terminal.images && graphics.state !== 'no',
839 ...cellEnv(cell, { kind: terminal.kind, cellAdjust, kittyAdjust }),
840 ...(cellAdjust ? { cellAdjust } : {}),
841 ...(kittyAdjust ? { kittyAdjust } : {}),
842 columns: cell?.columns ?? FALLBACK_COLUMNS,
843 ink: inkNow(),
844 ...inkOverNow(),
845 ...backgroundNow(),
846 bullet: bulletFor(uname, processEnv.HOME),
847 maxProseWidth: await readProseWidth($),
848 ...linkEnv(processEnv),
849 emojiSequences: drawsEmojiSequences(terminal, terminalColors),
850 // Strokes as heavy as the terminal's text, when its font's weight is known.
851 ...(terminalColors?.fontWeight ? { weight: strokeWeight(terminalColors.fontWeight) } : {}),
852 }
853 // The text font's metrics as the last session read them in this terminal, at
854 // these cells: the first drawing has the size it keeps (loadFont reads them
855 // again and changes nothing when they match), as the renders before
856 // session.start had it from the remembered env.
857 const remembered = (await $.store.get(REMEMBERED).catch(() => undefined)) as { id?: unknown; env?: KittexEnv } | undefined
858 const known = remembered?.id === terminalId(processEnv) && remembered.env?.font && remembered.env.cellWidth === env.cellWidth && remembered.env.cellHeight === env.cellHeight ? remembered.env : undefined
859 const withFont = known ? { ...env, font: known.font, ...(env.weight === undefined && known.weight !== undefined ? { weight: known.weight } : {}) } : env
860 const start: KittexEnv = known ? { ...withFont, emPx: mathEmPxFor(withFont, withFont) } : env
861 await writeEnv($, start)
862 envSettled?.()
863 // For the next session's first renders, which come before its session.start.
864 await $.store.set(REMEMBERED, { id: terminalId(processEnv), env: start }).catch(() => undefined)
865 // The text font's metrics, read from its file after setup (the first drawing doesn't wait for them).
866 if (env.images) later?.(() => void loadFont($).catch(() => undefined))
867
868 // Self-check: a policy plugin (cc-plugin-sec-default on Team/Enterprise or
869 // managed machines) may skip installed plugins' prompt.compose hooks; then
870 // the instructions ride the first prompt's context instead.
871 const wanted = surface === 'terminal' && instructs(env)
872 let present = false
873 if (wanted) {
874 try {
875 const composed = await $.prompt.compose({ surfaces: ['terminal'] })
876 present = composed.sections.some(section => section.id === SECTION_ID)
877 } catch {
878 present = false
879 }
880 }
881 instructWanted = wanted
882 instructByContext = wanted && !present
883}
884
885/**
886 * The variables the terminal helpers read (detection, the colour probes'
887 * binaries, the config files' locations, Claude's config dir); names must be
888 * literals.
889 */
890async function readProcessEnv($: Engine): Promise<Record<string, string | undefined>> {
891 const values = await Promise.all([
892 $.env.get('TERM'),
893 $.env.get('TERM_PROGRAM'),
894 $.env.get('TERM_PROGRAM_VERSION'),
895 $.env.get('LC_TERMINAL'),
896 $.env.get('KITTY_WINDOW_ID'),
897 $.env.get('KITTY_PID'),
898 $.env.get('KITTY_INSTALLATION_DIR'),
899 $.env.get('KITTY_CONFIG_DIRECTORY'),
900 $.env.get('GHOSTTY_RESOURCES_DIR'),
901 $.env.get('GHOSTTY_BIN_DIR'),
902 $.env.get('WEZTERM_PANE'),
903 $.env.get('WEZTERM_EXECUTABLE'),
904 $.env.get('ITERM_SESSION_ID'),
905 $.env.get('TMUX'),
906 $.env.get('STY'),
907 $.env.get('ZELLIJ'),
908 $.env.get('ZELLIJ_SESSION_NAME'),
909 $.env.get('SSH_CONNECTION'),
910 $.env.get('SSH_CLIENT'),
911 $.env.get('SSH_TTY'),
912 $.env.get('CLAUDE_CODE_FORCE_TERMINAL_IMAGES'),
913 $.env.get('CLAUDE_CODE_SESSION_KIND'),
914 $.env.get('CLAUDE_CONFIG_DIR'),
915 $.env.get('HOME'),
916 $.env.get('XDG_CONFIG_HOME'),
917 $.env.get('XDG_CONFIG_DIRS'),
918 $.env.get('XDG_CACHE_HOME'),
919 $.env.get('FORCE_HYPERLINK'),
920 $.env.get('TERMINAL_EMULATOR'),
921 $.env.get('WT_SESSION'),
922 $.env.get('VTE_VERSION'),
923 $.env.get('CI'),
924 $.env.get('TEAMCITY_VERSION'),
925 $.env.get('NETLIFY'),
926 ])
927 const names = [
928 'TERM',
929 'TERM_PROGRAM',
930 'TERM_PROGRAM_VERSION',
931 'LC_TERMINAL',
932 'KITTY_WINDOW_ID',
933 'KITTY_PID',
934 'KITTY_INSTALLATION_DIR',
935 'KITTY_CONFIG_DIRECTORY',
936 'GHOSTTY_RESOURCES_DIR',
937 'GHOSTTY_BIN_DIR',
938 'WEZTERM_PANE',
939 'WEZTERM_EXECUTABLE',
940 'ITERM_SESSION_ID',
941 'TMUX',
942 'STY',
943 'ZELLIJ',
944 'ZELLIJ_SESSION_NAME',
945 'SSH_CONNECTION',
946 'SSH_CLIENT',
947 'SSH_TTY',
948 'CLAUDE_CODE_FORCE_TERMINAL_IMAGES',
949 'CLAUDE_CODE_SESSION_KIND',
950 'CLAUDE_CONFIG_DIR',
951 'HOME',
952 'XDG_CONFIG_HOME',
953 'XDG_CONFIG_DIRS',
954 'XDG_CACHE_HOME',
955 'FORCE_HYPERLINK',
956 'TERMINAL_EMULATOR',
957 'WT_SESSION',
958 'VTE_VERSION',
959 'CI',
960 'TEAMCITY_VERSION',
961 'NETLIFY',
962 ]
963 return Object.fromEntries(names.map((name, i) => [name, values[i]]))
964}
965
966/** `uname -s` (the engine's bullet differs on macOS), or undefined when it can't run. */
967async function probeSystem($: Engine): Promise<string | undefined> {
968 try {
969 const { exitCode, stdout } = await $.process.run(['uname', '-s'], { timeoutMs: PROBE_TIMEOUT_MS })
970 return exitCode === 0 ? stdout : undefined
971 } catch {
972 return undefined
973 }
974}
975
976/** The cell size from the first cell probe that runs (perl, then python3 where perl can't: cellProbeRan). */
977async function probeCell($: Engine): Promise<CellSize | undefined> {
978 for (const probe of cellProbes) {
979 try {
980 const { exitCode, stdout } = await $.process.run(probe.argv, { timeoutMs: PROBE_TIMEOUT_MS })
981 const cell = exitCode === 0 ? probe.parse(stdout) : undefined
982 if (cell || cellProbeRan(exitCode, stdout)) return cell
983 } catch {
984 // the next probe
985 }
986 }
987 return undefined
988}
989
990/** The terminal's configured colours: its probes, else its config files. */
991async function readColors($: Engine, info: TerminalInfo, scheme: 'dark' | 'light'): Promise<TerminalColors | undefined> {
992 for (const probe of colorProbes(info, { env: processEnv, scheme })) {
993 try {
994 const { exitCode, stdout } = await $.process.run(probe.argv, { timeoutMs: PROBE_TIMEOUT_MS })
995 const colors = exitCode === 0 ? probe.parse(stdout) : undefined
996 if (colors?.foreground) return colors
997 } catch {
998 // the next probe
999 }
1000 }
1001 try {
1002 return await readTerminalColors(info, path => readText($, path), { env: processEnv, scheme })
1003 } catch {
1004 return undefined
1005 }
1006}
1007
1008async function readText($: Engine, path: string): Promise<string | undefined> {
1009 try {
1010 return await $.fs.read(path)
1011 } catch {
1012 return undefined
1013 }
1014}
1015
1016async function readThemeSetting($: Engine): Promise<string | undefined> {
1017 try {
1018 const row = (await $.config.list()).find(one => one.key === 'theme')
1019 return typeof row?.value === 'string' ? row.value : undefined
1020 } catch {
1021 return undefined
1022 }
1023}
1024
1025/**
1026 * Reads what the ink depends on: the theme setting (unless given), a custom
1027 * theme's file, and the terminal's colours for the theme's light/dark scheme
1028 * (read again only when the scheme changes).
1029 */
1030async function resolveTheme($: Engine, setting?: string): Promise<void> {
1031 theme = setting ?? (await readThemeSetting($))
1032 const configDir = processEnv.CLAUDE_CONFIG_DIR ?? (processEnv.HOME ? `${processEnv.HOME}/.claude` : undefined)
1033 const path = configDir ? claudeCustomThemePath(theme, configDir) : undefined
1034 customTheme = path ? await readText($, path) : undefined
1035 // `auto` follows the terminal's background, so read the colours (dark first) before settling the scheme.
1036 for (let pass = 0; pass < 2 && terminal; pass += 1) {
1037 const scheme = claudeThemeScheme(theme, customTheme, terminalColors)
1038 if (scheme === colorScheme) break
1039 terminalColors = await readColors($, terminal, scheme)
1040 colorScheme = scheme
1041 }
1042}
1043
1044/** The formulas' ink: the terminal's foreground first; a custom theme's `text` colour (the bullet's) never. */
1045function inkNow() {
1046 return chooseInk({ theme, customTheme: withoutTextOverride(customTheme), terminal: terminalColors, prefer: INK_PREFER })
1047}
1048
1049/** The background the ink's alpha is corrected against (imageInkBackground), as kittex.env's `inkOver`: none where images blend as text does. */
1050function inkOverNow(): Pick<KittexEnv, 'inkOver' | 'inkCurve'> {
1051 const over = terminal ? imageInkBackground(terminal.kind, terminalColors, platform) : undefined
1052 const curve = terminal ? imageInkCurve(terminal.kind, terminalColors, platform) : undefined
1053 return over ? { inkOver: { r: over.r, g: over.g, b: over.b }, ...(curve ? { inkCurve: { gamma: curve.gamma, contrast: curve.contrast } } : {}) } : {}
1054}
1055
1056/** The terminal's background as kittex.env's `background`, when its colours were read (diagrams are drawn for it). */
1057function backgroundNow(): Pick<KittexEnv, 'background'> {
1058 const background = terminalColors?.background
1059 return background ? { background: { r: background.r, g: background.g, b: background.b } } : {}
1060}
1061
1062const sameColor = (a: KittexEnv['inkOver'], b: KittexEnv['inkOver']) => a === b || (!!a && !!b && a.r === b.r && a.g === b.g && a.b === b.b)
1063const sameCurve = (a: KittexEnv['inkCurve'], b: KittexEnv['inkCurve']) => a === b || (!!a && !!b && a.gamma === b.gamma && a.contrast === b.contrast)
1064
1065/** The `maxProseWidth` setting, when set: reply prose wraps at most this wide. */
1066async function readProseWidth($: Engine): Promise<number | undefined> {
1067 try {
1068 const value = (await $.settings.read()).maxProseWidth
1069 return typeof value === 'number' && Number.isFinite(value) && value >= 1 ? Math.floor(value) : undefined
1070 } catch {
1071 return undefined
1072 }
1073}
1074
1075/** maxProseWidth changed: inline images are placed at the new width. */
1076async function refreshProseWidth($: Engine): Promise<void> {
1077 const env = await readEnv($)
1078 if (!env) return
1079 const maxProseWidth = await readProseWidth($)
1080 if (maxProseWidth !== env.maxProseWidth) await writeEnv($, { ...env, maxProseWidth })
1081}
1082
1083/** The theme changed: the formulas' ink may follow it. */
1084async function refreshInk($: Engine, setting: string): Promise<void> {
1085 await resolveTheme($, setting)
1086 const env = await readEnv($)
1087 if (!env) return
1088 const ink = inkNow()
1089 const over = inkOverNow()
1090 const back = backgroundNow()
1091 if (sameColor(ink, env.ink) && sameColor(over.inkOver, env.inkOver) && sameCurve(over.inkCurve, env.inkCurve) && sameColor(back.background, env.background)) return
1092 const { inkOver: _, inkCurve: __, background: ___, ...rest } = env
1093 await writeEnv($, { ...rest, ink, ...over, ...back })
1094}
1095
1096/**
1097 * The cell probes after setup: for a render that sees a new width (a font
1098 * zoom changes the width in cells too), once a resize settles, for a drawing
1099 * with images when the last probe is a while old, and rarely while idle (a
1100 * move to a monitor of another scale may keep the width). Each measures the terminal's own
1101 * TIOCGWINSZ (its columns and pixels); the timers store what they find in
1102 * kittex.env when it changed, which redraws every block that read it.
1103 */
1104interface Cells {
1105 /** Probes now, for drawing: one probe at a time, shared by every render that asks meanwhile. Stores nothing (a render may not write state). */
1106 probe(): Promise<CellSize | undefined>
1107 /**
1108 * Probes and stores once the width has stopped changing: every call
1109 * restarts the wait, so a drag ends with the final size. `seen`: the width a
1110 * render saw, kept when the probe can't tell the columns.
1111 */
1112 settle(seen?: number): void
1113 /**
1114 * A drawing with images: probes (on the clock, not holding the drawing up)
1115 * when the last probe is older than CELL_REFRESH_MS, and starts the idle
1116 * probe every CELL_IDLE_MS (once): a change of the cells' pixels alone
1117 * draws nothing by itself.
1118 */
1119 watch(): void
1120 stop(): void
1121}
1122
1123/**
1124 * The probes on session.start's `$`: a render's `$` belongs to its one
1125 * dispatch, and the timers outlive it. A timer's callback is a dispatch of its
1126 * own, where a state write is allowed.
1127 */
1128function cellsFor($: Engine): Cells {
1129 let probing: Promise<CellSize | undefined> | undefined
1130 /** The stores, one after another (a settle never skipped for a periodic probe running). */
1131 let stores: Promise<void> = Promise.resolve()
1132 let settleTimer: Timer | undefined
1133 let pollTimer: Timer | undefined
1134 /** When the last probe that stores ran, on the clock ($.clock.now): setup's, made as these are (session.start). */
1135 let probed = -Infinity
1136 void $.clock.now().then(
1137 now => (probed = Math.max(probed, now)),
1138 () => undefined,
1139 )
1140 const store = (seen?: number) => {
1141 stores = stores
1142 .then(async () => {
1143 probed = await $.clock.now().catch(() => probed)
1144 await storeCells($, await probeCell($), seen)
1145 })
1146 .catch(() => undefined)
1147 }
1148 const refresh = async () => {
1149 const now = await $.clock.now()
1150 if (now - probed >= CELL_REFRESH_MS) store()
1151 }
1152 return {
1153 probe() {
1154 return (probing ??= probeCell($).finally(() => {
1155 probing = undefined
1156 }))
1157 },
1158 settle(seen) {
1159 settleTimer?.cancel()
1160 try {
1161 settleTimer = $.clock.after(RESIZE_SETTLE_MS, () => {
1162 settleTimer = undefined
1163 store(seen)
1164 })
1165 } catch {
1166 settleTimer = undefined
1167 }
1168 },
1169 watch() {
1170 try {
1171 $.clock.after(0, () => void refresh().catch(() => undefined))
1172 } catch {
1173 // no clock: the width change and the idle probe still measure
1174 }
1175 if (pollTimer) return
1176 try {
1177 pollTimer = $.clock.every(CELL_IDLE_MS, () => void refresh().catch(() => undefined))
1178 } catch {
1179 pollTimer = undefined
1180 }
1181 },
1182 stop() {
1183 settleTimer?.cancel()
1184 pollTimer?.cancel()
1185 },
1186 }
1187}
1188
1189/**
1190 * A measured cell as kittex.env holds it, with the math's em for it
1191 * (mathEmPxFor: from the text font's metrics once read, else the font's own
1192 * cell, the terminal's adjustments undone).
1193 */
1194function cellEnv(cell: CellSize | undefined, env: Pick<KittexEnv, 'kind' | 'cellAdjust' | 'kittyAdjust' | 'font'>): Pick<KittexEnv, 'cellWidth' | 'cellHeight' | 'measured' | 'emPx'> {
1195 const { cellWidth, cellHeight, measured } = cellOrFallback(cell)
1196 return { cellWidth, cellHeight, measured, emPx: mathEmPxFor({ cellWidth, cellHeight }, env) }
1197}
1198
1199/**
1200 * Reads the text font's metrics and stores them in kittex.env, with the emhooks/core.js 147 lines1import{BUILD_ID,DIAGRAM_ENVS,FORMAT_SOURCE,GHOSTTY_BUILTIN_FONT,GlyphError,IMAGE_FILE_BYTES,IMAGE_GAP,INLINE_OVERFLOW,ImageError,JOB_NAME,KEPT_IMAGE_PIXELS,LATEX_ARGV,LINE_WIDTH_PT,MAX_BLOCK_IMAGES,MAX_IMAGE_BYTES,MAX_IMAGE_FILE_BYTES,MAX_IMAGE_PIXELS,MAX_IMAGE_SIDE,MAX_PICTURE_ROWS,MAX_PIXELS,MAX_TEX_LENGTH,MAX_TEX_SOURCE,MIN_DISPLAY_SCALE,MIN_IMAGE_DENSITY,MIN_INLINE_SCALE,MIN_PICTURE_SCALE,PDF_NAME,PREAMBLE_VERSION,SvgError,TEXT_HEIGHT_PT,TRIAL_PDF,TexError,VECTOR_PX_PER_EM,XmlError,adaptColor,assumedBackground,blockImages,blockParts,bwrapProbe,cellProbe,cellProbeRan,cellProbes,charsOf,chooseInk,claudeCustomThemePath,claudeThemeInk,claudeThemeScheme,colorProbes,confined,coreTextFontArgv,createLineScanner,decodeImage,detectTerminal,diagramDocument,diagramFence,drawsEmojiSequences,drawsPicture,dvisvgmArgv,emPxForCell,encodePng,encodeRgbaPng,engineHyperlinks,faceIndexOf,fitImage,fitImageBlock,fontCell,fontFileArgv,formatArgv,formatName,imageBlock,imageColumns,imageHeader,imageInkBackground,imageInkCurve,init,initTypeset,inkAlpha,inlineTables,isJobDir,jobDirTemplate,latexArgv,layoutHeading,layoutList,layoutProse,layoutQuote,layoutTable,matchesFamily,mathDocument,mathEmPx,measure,measureDisplay,measureDisplayResult,measureImage,measureImageBlock,measureInline,measureInlineResult,measurePicture2,odArgv,parseCoreTextFont,parseFontFile,parseLength,parseOd,pdfArgv,pdfCopyArgv,pictureSource,previewDisplay,previewInline,previewWidth,proseBlocks,rasterize,readFontMetrics,readImageFile,readTerminalColors,recolorPng,renderDisplay,renderDisplayResult,renderImage,renderImageBlock,renderInline,renderInlineResult,renderPicture,resolveImagePath,scaleBitmap,scan,strokeWeight,texEnvironment,texError,texFormula,texPicture2,texToMathML2,textBaseline,textLayout,textWidth,toBase64,toHex,toUnicode,typeset,typesetLoaded,ulimitProbe,unsafeTex,visibleProse,wrapLine,wrapRows}from'./core-parts/p37.js';
2export {
3 BUILD_ID,
4 DIAGRAM_ENVS,
5 FORMAT_SOURCE,
6 GHOSTTY_BUILTIN_FONT,
7 GlyphError,
8 IMAGE_FILE_BYTES,
9 IMAGE_GAP,
10 INLINE_OVERFLOW,
11 ImageError,
12 JOB_NAME,
13 KEPT_IMAGE_PIXELS,
14 LATEX_ARGV,
15 LINE_WIDTH_PT,
16 MAX_BLOCK_IMAGES,
17 MAX_IMAGE_BYTES,
18 MAX_IMAGE_FILE_BYTES,
19 MAX_IMAGE_PIXELS,
20 MAX_IMAGE_SIDE,
21 MAX_PICTURE_ROWS,
22 MAX_PIXELS,
23 MAX_TEX_LENGTH,
24 MAX_TEX_SOURCE,
25 MIN_DISPLAY_SCALE,
26 MIN_IMAGE_DENSITY,
27 MIN_INLINE_SCALE,
28 MIN_PICTURE_SCALE,
29 PDF_NAME,
30 PREAMBLE_VERSION,
31 SvgError,
32 TEXT_HEIGHT_PT,
33 TRIAL_PDF,
34 TexError,
35 VECTOR_PX_PER_EM,
36 XmlError,
37 adaptColor,
38 assumedBackground,
39 blockImages,
40 blockParts,
41 bwrapProbe,
42 cellProbe,
43 cellProbeRan,
44 cellProbes,
45 charsOf,
46 chooseInk,
47 claudeCustomThemePath,
48 claudeThemeInk,
49 claudeThemeScheme,
50 colorProbes,
51 confined,
52 coreTextFontArgv,
53 createLineScanner,
54 decodeImage,
55 detectTerminal,
56 diagramDocument,
57 diagramFence,
58 drawsEmojiSequences,
59 drawsPicture,
60 dvisvgmArgv,
61 emPxForCell,
62 encodePng,
63 encodeRgbaPng,
64 engineHyperlinks,
65 faceIndexOf,
66 fitImage,
67 fitImageBlock,
68 fontCell,
69 fontFileArgv,
70 formatArgv,
71 formatName,
72 imageBlock,
73 imageColumns,
74 imageHeader,
75 imageInkBackground,
76 imageInkCurve,
77 init,
78 initTypeset,
79 inkAlpha,
80 inlineTables,
81 isJobDir,
82 jobDirTemplate,
83 latexArgv,
84 layoutHeading,
85 layoutList,
86 layoutProse,
87 layoutQuote,
88 layoutTable,
89 matchesFamily,
90 mathDocument,
91 mathEmPx,
92 measure,
93 measureDisplay,
94 measureDisplayResult,
95 measureImage,
96 measureImageBlock,
97 measureInline,
98 measureInlineResult,
99 measurePicture2 as measurePicture,
100 odArgv,
101 parseCoreTextFont,
102 parseFontFile,
103 parseLength,
104 parseOd,
105 pdfArgv,
106 pdfCopyArgv,
107 pictureSource,
108 previewDisplay,
109 previewInline,
110 previewWidth,
111 proseBlocks,
112 rasterize,
113 readFontMetrics,
114 readImageFile,
115 readTerminalColors,
116 recolorPng,
117 renderDisplay,
118 renderDisplayResult,
119 renderImage,
120 renderImageBlock,
121 renderInline,
122 renderInlineResult,
123 renderPicture,
124 resolveImagePath,
125 scaleBitmap,
126 scan,
127 strokeWeight,
128 texEnvironment,
129 texError,
130 texFormula,
131 texPicture2 as texPicture,
132 texToMathML2 as texToMathML,
133 textBaseline,
134 textLayout,
135 textWidth,
136 toBase64,
137 toHex,
138 toUnicode,
139 typeset,
140 typesetLoaded,
141 ulimitProbe,
142 unsafeTex,
143 visibleProse,
144 wrapLine,
145 wrapRows
146};
147hooks/image.ts 241 lines1// Image files shown in place of an image block (a ```latex block holding
2// \includegraphics commands: core's imageBlock). Nothing here takes `$`:
3// register.tsx hands an ImageHost of closures over session.start's `$`, as it
4// does TeX's. The book reads and decodes each file once per version of it
5// (its real path, size and modification time), and the stream and the
6// landing read what it holds synchronously, as they read TeX's outcomes
7// (tex.ts). A block of several images is drawn once all its files are read.
8
9import { blockImages, ImageError, imageBlock, KEPT_IMAGE_PIXELS, MAX_BLOCK_IMAGES, MAX_IMAGE_FILE_BYTES, pictureSource, readImageFile, resolveImagePath, SvgError, XmlError } from './core.js'
10import type { ImageBlock, ImageSource, ImageSpec } from './core.js'
11import type { DiagramKind, TexOutcome } from './tex.ts'
12
13/** What an image block's file gave: what to draw (`id`: the file's version), or why there is nothing. */
14export type ImageOutcome =
15 | { ok: true; source: ImageSource; id: string }
16 /** `lasting`: the file's own answer (missing, not an image), shown as a note; else (a PDF conversion that ran out of time) it may be tried again. */
17 | { ok: false; error: string; lasting: boolean }
18
19/** What reading image files needs from the host (register.tsx backs it with `$`). */
20export interface ImageHost {
21 /** A path's kind, size and modification time, and where it lands (links followed); undefined when it isn't there. */
22 stat(path: string): Promise<{ kind: 'file' | 'dir' | 'other'; size: number; mtimeMs: number; realPath?: string } | undefined>
23 readBytes(path: string): Promise<Uint8Array | undefined>
24 /** A PDF's first page as a picture, where the local TeX converts PDF (tex.ts pdfPicture); absent where nothing does. */
25 pdf?: (path: string, timeoutMs: number) => Promise<TexOutcome>
26}
27
28/** Why a PDF file stays code where nothing converts it. */
29export const NO_PDF = 'PDF files are drawn with the local TeX, which is not there or reads no PDF'
30
31/** The images a diagram segment shows: a ```latex block that is an image block (imageBlock); undefined for any other. */
32export function imageBlockOf(source: string, kind: DiagramKind): ImageBlock | undefined {
33 return kind === 'latex' ? imageBlock(source) : undefined
34}
35
36/** What an image block's files gave together: every file drawn (`sources` in reading order, `id` their versions), or why the block is not. */
37export type BlockOutcome = { ok: true; sources: ImageSource[]; id: string } | { ok: false; error: string }
38
39/**
40 * Files the book keeps decoded, at most, and their kept pixels in all
41 * (KEPT_IMAGE_PIXELS each at most): a block's MAX_BLOCK_IMAGES files stay
42 * together at their largest, so drawing one never evicts its own files.
43 */
44const BOOK_LIMIT = 8
45const BOOK_PIXELS = MAX_BLOCK_IMAGES * KEPT_IMAGE_PIXELS
46
47interface Entry {
48 outcome: ImageOutcome
49 /** The file's version it was read from: real path, size and modification time. */
50 stamp?: string
51 /** When the file was last looked at (Date.now()). */
52 checkedAt: number
53}
54
55/**
56 * Image files read and decoded, by the path they resolve to: the stream and
57 * the landing read outcomes here synchronously (`known`), and ask for the
58 * ones missing (`load`). Each load looks at the file again, and decodes it
59 * again only when it changed.
60 */
61export class ImageBook {
62 private readonly entries = new Map<string, Entry>()
63 private readonly running = new Map<string, Promise<ImageOutcome>>()
64 private readonly asked = new Map<string, ImageSpec>()
65 /** Blocks the stream showed as written (the file took too long): left so when their block lands. */
66 private readonly shownAsSource = new Set<string>()
67 host: ImageHost | undefined
68 /** The session's working directory and the home directory, which relative and `~/` paths resolve against. */
69 cwd: string | undefined
70 home: string | undefined
71
72 /** Forgets everything (a new session, tests). */
73 reset(host?: ImageHost, where: { cwd?: string; home?: string } = {}): void {
74 this.entries.clear()
75 this.running.clear()
76 this.asked.clear()
77 this.shownAsSource.clear()
78 this.host = host
79 this.cwd = where.cwd
80 this.home = where.home
81 }
82
83 /** Files can be read. */
84 get ready(): boolean {
85 return this.host !== undefined
86 }
87
88 /** The book's key for a block's file: the path it resolves to (or as written, where it resolves to none). */
89 key(spec: ImageSpec): string {
90 return resolveImagePath(spec.path, this.cwd, this.home) ?? `unplaced:${spec.path}`
91 }
92
93 /**
94 * A block with its paths resolved against `cwd`, the working directory its
95 * reply streamed in (kept with the reply), so redrawing that reply after a
96 * /cd still shows its own files. A path is as given where `cwd` is unknown
97 * or the path can't be placed: then it resolves against the book's.
98 */
99 place(block: ImageBlock, cwd: string | undefined): ImageBlock {
100 if (cwd === undefined) return block
101 return {
102 rows: block.rows.map(row =>
103 row.map(image => {
104 const path = resolveImagePath(image.path, cwd, this.home)
105 return path === undefined ? image : { ...image, path }
106 }),
107 ),
108 }
109 }
110
111 /**
112 * What a block's files gave, as far as this process read them: all drawn,
113 * or the first file (in reading order) that failed for good; undefined
114 * while any is unread or failed only for now.
115 */
116 knownBlock(block: ImageBlock): BlockOutcome | undefined {
117 const outcomes = blockImages(block).map(image => this.known(image))
118 const failed = outcomes.find(outcome => outcome !== undefined && !outcome.ok && outcome.lasting)
119 if (failed && !failed.ok) return { ok: false, error: failed.error }
120 const sources: ImageSource[] = []
121 const ids: string[] = []
122 for (const outcome of outcomes) {
123 if (!outcome?.ok) return undefined
124 sources.push(outcome.source)
125 ids.push(outcome.id)
126 }
127 return { ok: true, sources, id: ids.join('\n') }
128 }
129
130 /** What a file gave, when it was read in this process; a passing failure included. */
131 known(spec: ImageSpec): ImageOutcome | undefined {
132 const key = this.key(spec)
133 const entry = this.entries.get(key)
134 if (!entry) return undefined
135 this.entries.delete(key)
136 this.entries.set(key, entry)
137 return entry.outcome
138 }
139
140 /** Whether the file was looked at since `since` (Date.now()): a new reply's stream looks again, so a plot written since shows. */
141 checkedSince(spec: ImageSpec, since: number): boolean {
142 const entry = this.entries.get(this.key(spec))
143 return entry !== undefined && entry.checkedAt >= since
144 }
145
146 /** A landing wants this file drawn (a reply read back after --resume): kept until takeAsked. Not one shown as source. */
147 ask(spec: ImageSpec): void {
148 const key = this.key(spec)
149 if (this.host && !this.shownAsSource.has(key) && this.asked.size < 64) this.asked.set(key, spec)
150 }
151
152 takeAsked(): ImageSpec[] {
153 const specs = [...this.asked.values()]
154 this.asked.clear()
155 return specs
156 }
157
158 markShownAsSource(spec: ImageSpec): void {
159 this.shownAsSource.add(this.key(spec))
160 if (this.shownAsSource.size > 256) this.shownAsSource.delete(this.shownAsSource.values().next().value!)
161 }
162
163 wasShownAsSource(spec: ImageSpec): boolean {
164 return this.shownAsSource.has(this.key(spec))
165 }
166
167 /** Records an outcome (tests, and what load finds), keeping at most BOOK_LIMIT files and BOOK_PIXELS kept pixels. */
168 remember(spec: ImageSpec, outcome: ImageOutcome, stamp?: string): void {
169 const key = this.key(spec)
170 this.entries.delete(key)
171 this.entries.set(key, { outcome, ...(stamp !== undefined ? { stamp } : {}), checkedAt: Date.now() })
172 const pixels = () => [...this.entries.values()].reduce((sum, entry) => sum + (entry.outcome.ok && entry.outcome.source.kind === 'bitmap' ? entry.outcome.source.bitmap.width * entry.outcome.source.bitmap.height : 0), 0)
173 while (this.entries.size > BOOK_LIMIT || (this.entries.size > 1 && pixels() > BOOK_PIXELS)) this.entries.delete(this.entries.keys().next().value!)
174 }
175
176 /**
177 * The block's file, looked at now: its outcome, decoded again only where
178 * the file changed since it was last read. A PDF is converted within
179 * `timeoutMs`; running out of time is an outcome that isn't kept.
180 */
181 load(spec: ImageSpec, timeoutMs: number): Promise<ImageOutcome> {
182 const key = this.key(spec)
183 const running = this.running.get(key)
184 if (running) return running
185 // Every load is recorded, a passing failure too: the stream that waited for it then goes on (checkedSince).
186 const job = this.read(spec, timeoutMs).catch((error: unknown): ImageOutcome => {
187 const outcome: ImageOutcome = { ok: false, error: String(error), lasting: false }
188 this.remember(spec, outcome)
189 return outcome
190 })
191 this.running.set(key, job)
192 void job.finally(() => this.running.delete(key))
193 return job
194 }
195
196 private async read(spec: ImageSpec, timeoutMs: number): Promise<ImageOutcome> {
197 const failed = (error: string, lasting = true): ImageOutcome => {
198 const outcome: ImageOutcome = { ok: false, error, lasting }
199 this.remember(spec, outcome)
200 return outcome
201 }
202 const host = this.host
203 if (!host) return failed('no file access', false)
204 const path = resolveImagePath(spec.path, this.cwd, this.home)
205 if (path === undefined) return failed(`can't tell where ${spec.path} is`)
206 const stat = await host.stat(path).catch(() => undefined)
207 if (!stat) return failed(`no file at ${path}`)
208 if (stat.kind !== 'file') return failed(`${path} is not a file`)
209 if (stat.size === 0) return failed(`${path} is empty`)
210 if (stat.size > MAX_IMAGE_FILE_BYTES) return failed(`${path} is larger than ${MAX_IMAGE_FILE_BYTES / 1024 / 1024} MiB`)
211 const real = stat.realPath ?? path
212 const stamp = `${real}\n${stat.size}\n${stat.mtimeMs}`
213 const entry = this.entries.get(this.key(spec))
214 if (entry?.stamp === stamp && (entry.outcome.ok || entry.outcome.lasting)) {
215 entry.checkedAt = Date.now()
216 return entry.outcome
217 }
218 const bytes = await host.readBytes(path)
219 if (!bytes) return failed(`can't read ${path}`)
220 // What the file's contents gave is named by its path, as every answer above is: a block of several files says which one.
221 let outcome: ImageOutcome
222 try {
223 const read = readImageFile(bytes)
224 if (read !== 'pdf') outcome = { ok: true, source: read, id: stamp }
225 else if (!host.pdf) outcome = { ok: false, error: `${path}: ${NO_PDF}`, lasting: true }
226 else {
227 const converted = await host.pdf(real, timeoutMs)
228 outcome = converted.ok ? { ok: true, source: pictureSource(converted.picture), id: stamp } : { ok: false, error: `${path}: ${converted.error}`, lasting: converted.lasting }
229 }
230 } catch (error) {
231 if (!(error instanceof ImageError || error instanceof SvgError || error instanceof XmlError)) throw error
232 outcome = { ok: false, error: `${path}: ${error.message}`, lasting: true }
233 }
234 this.remember(spec, outcome, outcome.ok || outcome.lasting ? stamp : undefined)
235 return outcome
236 }
237}
238
239/** The process's book: register.tsx gives it its host, math.ts reads it. */
240export const imageBook = new ImageBook()
241hooks/math.ts 3079 lines1// kittex's pure side: the constants, the streaming rewrite and the plan of a
2// landed reply. Nothing here takes `$` (it cannot cross an import); register.tsx
3// does the I/O and hands these functions plain values.
4//
5// The layout rules below were measured on the live engine (Claude Code
6// 2.1.290 and 2.1.291); docs/engine-findings.md has the recordings.
7
8import {
9 createLineScanner,
10 blockParts,
11 engineHyperlinks,
12 layoutHeading,
13 layoutList,
14 layoutProse,
15 layoutQuote,
16 layoutTable,
17 blockImages,
18 measureDisplay,
19 measureDisplayResult,
20 measureInline,
21 measureInlineResult,
22 measureImageBlock,
23 measurePicture,
24 MAX_PICTURE_ROWS,
25 MAX_TEX_LENGTH,
26 previewDisplay,
27 GlyphError,
28 previewInline,
29 scan,
30 TexError,
31 textBaseline,
32 textLayout,
33 textWidth,
34 typeset,
35 emPxForCell,
36 fontCell,
37 mathEmPx,
38} from './core.js'
39import type { BlockPart, CellBox, CellSize, ImageBlock, ImageSpec, InkPlace, InlineEnv, LineScanner, LinkMode, PictureEnv, ProseBlock, ProseLayout, RenderedImage, RenderEnv, Segment, SourceSpan, SpanPlace, TexDocument } from './core.js'
40import type { KittexBlock, KittexEnv, KittexPreview } from '../types'
41import { imageBlockOf, imageBook } from './image.ts'
42import { diagramJob, diagramLabel, mathJob, texBook, texResult } from './tex.ts'
43import type { DiagramKind } from './tex.ts'
44
45// ─── The engine's layout (measured) ──────────────────────────────────────────
46
47/**
48 * Columns the engine draws reply text in from the left edge of a block that
49 * opens a reply: the bullet's box (`minWidth: 2`). A block drawn without the
50 * bullet (`isFirstOfReply: false`) starts at column 0.
51 */
52export const REPLY_INDENT = 2
53
54/**
55 * The bullet that opens a reply, as the engine draws it (in the theme's `text`
56 * colour): `⏺` on macOS, `●` elsewhere.
57 */
58export const BULLET = { macos: '⏺', other: '●' } as const
59
60/** The label of the copy button shown over a formula image while the pointer is on it. */
61export const COPY_LABEL = '⧉ copy LaTeX'
62
63/** What the copy button puts on the clipboard: the formula as a display block, ready to paste back into markdown. */
64export function copiedFormula(tex: string): string {
65 return `$$\n${tex.trim()}\n$$`
66}
67
68/**
69 * What stands for a space at the start of a preview line, and for a padding
70 * line: markdown would strip a leading space (or read four of them as code)
71 * and drop an empty line. The engine draws ` ` as one blank cell, and a
72 * text that holds it always goes through its markdown parser, so the escapes
73 * in a preview line are always read.
74 */
75export const PREVIEW_PAD = ' '
76
77/**
78 * What a padding line (a preview row with no text) ends with: U+2800, a blank
79 * cell that no trim takes for whitespace. The engine's streaming preview drops
80 * a line of pads alone at the end of a paragraph (its landed drawing keeps
81 * it), which would move everything below by a row at landing.
82 */
83export const BLANK_CELL = '\u2800'
84
85/** ASCII characters markdown may read as syntax inside a preview line; each is backslash-escaped. */
86export const MARKDOWN_SPECIALS = /[\\`*_[\]<>|~&!#]/g
87
88/** Whether the preview lines are centred in the reply column, as the image's formula is. */
89export const PREVIEW_CENTERED = true
90
91/**
92 * What a MessageDisplay flush shows while an open display block is held: the
93 * empty text, which the engine takes as "show nothing for this flush".
94 */
95export const HELD_DISPLAY = ''
96
97/**
98 * How a landed reply that MessageDisplay rewrote is mapped back to its TeX: by
99 * content. A preview is a pure function of the formula and the terminal, and
100 * each one kittex wrote is recorded with its TeX (in `$.state`, so the landed
101 * block redraws once the record arrives). MessageDisplay's `message_id` and
102 * AssistantMessage's `requestId` are unrelated ids, and after `--resume` the
103 * landed text is the original LaTeX again, typeset directly.
104 */
105export const MAP_BY = 'content' as const
106
107/**
108 * Which colour the formulas take: reply text is drawn in the terminal's
109 * default foreground under every theme (the theme's `text` colour paints only
110 * the bullet), so the terminal's configured foreground wins, and a custom
111 * theme's `text` override never applies.
112 */
113export const INK_PREFER: 'theme' | 'terminal' = 'terminal'
114
115/** The prefix of the line drawn under a formula MathJax refused. */
116export const NOT_RENDERED = 'not rendered: '
117
118/**
119 * Where inline images put the math baseline in a cell, from the top, as a
120 * fraction of the cell's height. The terminal font's own baseline is 21 px down
121 * a 13×26 px cell in kitty (DejaVu Sans Mono: glyphs reach 16 px above it and 4
122 * below); one pixel higher leaves room under it for brackets, bars and \ne at
123 * 0.91 of the display size, so every inline formula draws as an image at one
124 * size instead of bracketed ones staying Unicode. The pixel is not visible at
125 * normal size.
126 */
127export const TEXT_BASELINE = 20 / 26
128
129/**
130 * How far below its baseline an inline formula's ink reaches, in em of the
131 * math, as each terminal's text compares: the stroke weight's dilation and
132 * Computer Modern's overshoot, against the bottom edge of the terminal's own
133 * letters (kitty hints them onto the pixel row, Ghostty's linear-corrected
134 * blending draws their edge a little lower). Measured on kitty 0.49 and
135 * Ghostty 1.3 over eleven fonts at 9 to 18 pt (math `x` against text `x`):
136 * with the math on the text's own baseline its ink ended 0.55 to 0.9 px
137 * lower in kitty and 0.25 to 0.75 px lower in Ghostty, growing with the size.
138 * The math's baseline goes that much higher, to the nearest pixel.
139 */
140export const MATH_INK_DEPTH = { kitty: 0.04, ghostty: 0.026 } as const
141
142/**
143 * What joins the words of an inline preview: a no-break space, one cell that
144 * the engine's word wrap (Bun.wrapAnsi, which splits at U+0020 alone) never
145 * breaks at, and that marked and the engine draw as it is. Measured live.
146 */
147export const INLINE_JOIN = '\u00a0'
148
149/**
150 * What pads an inline preview to its image's width: U+2800, a blank cell that
151 * neither breaks a line nor counts as whitespace, so emphasis closing right
152 * after a formula (`*… $x$*`) still closes, and no trim takes it.
153 */
154export const INLINE_PAD = BLANK_CELL
155
156/**
157 * What marks an inline preview that holds neither a join nor a pad (its
158 * Unicode as wide as its image, one word): U+034F, a combining mark of no
159 * width that the engine, kitty and Ghostty draw as nothing, so the preview is
160 * found again by its content without a blank cell after the image.
161 */
162export const INLINE_MARK = '\u034f'
163
164/**
165 * The ASCII inline Unicode escapes, padded or not (markdown could read it as
166 * syntax: `_(…)` and `B*A*` as emphasis, a `|` as a table cell's end, `[a](b)`
167 * as a link). Each is one that makes the engine read the text as markdown at
168 * all, so the escape is always read as one, never drawn as a backslash; a `]`
169 * or a `<` is not (in a text the engine draws as written its escape would
170 * show), and needs none: `[` is escaped, so no link opens, and a `<` that
171 * could open a tag is kept apart from the letter after it (inlineUnicode).
172 */
173export const INLINE_SPECIALS = /[`*_[|~#>]/g
174
175/** A `<` the engine's markdown could read as the start of a tag. */
176const TAG_OPEN = /<[A-Za-z/!?]/
177
178/** Inline Unicode with its markdown syntax escaped (INLINE_SPECIALS). */
179export function escapeInline(text: string): string {
180 return text.replace(INLINE_SPECIALS, '\\$&')
181}
182
183/**
184 * An inline formula as the reader sees it where it stays text (no image: a
185 * terminal without images, a block the replay doesn't follow, math read back
186 * after `--resume`): one line of Unicode with TeX's spacing (a relation keeps
187 * its spaces, so a `<` never touches a letter), at any width (prose wraps),
188 * escaped; null where Unicode has no one-line form.
189 */
190export function inlineText(tex: string): string | null {
191 const unicode = previewInline(tex, undefined, { tight: false })
192 return unicode === null ? null : escapeInline(unicode)
193}
194
195/** The most cells of `not rendered: <reason>` a refused inline formula's note quotes. */
196const INLINE_NOTE_CELLS = 60
197
198/** An inline math segment: what the fallbacks below read. */
199type InlineMath = Pick<Extract<Segment, { kind: 'math' }>, 'tex' | 'raw' | 'delimiter'>
200
201/**
202 * An inline formula where it gets neither an image nor one line of Unicode
203 * (stress report F5): its source as a code span, where markdown reads none of
204 * it (no `\\` eaten, in a table cell neither), as the model wrote it (so a
205 * table cell's `\|` still reads as a pipe), and where MathJax refuses it an
206 * italic `not rendered: …` in parentheses after it, as a refused display formula has. Never
207 * the TeX as prose.
208 */
209export function inlineSource(math: InlineMath): string {
210 const open = math.delimiter === '$' ? 1 : 2
211 const source = math.raw.slice(open, math.raw.length - open).replace(/\s+/g, ' ').trim() || math.tex
212 const longest = Math.max(0, ...[...source.matchAll(/`+/g)].map(run => run[0].length))
213 const fence = '`'.repeat(longest + 1)
214 const code = fence + (/^`|`$/.test(source) ? ` ${source} ` : source) + fence
215 const reason = inlineTexError(math.tex)
216 return reason === undefined ? code : `${code} (*${escapeMarkdown(oneLine(NOT_RENDERED + reason, INLINE_NOTE_CELLS))}*)`
217}
218
219/** An inline formula as it is written where it gets no image: its one-line Unicode, or its source (inlineSource). */
220export function inlineFallback(math: InlineMath): string {
221 return inlineText(math.tex) ?? inlineSource(math)
222}
223
224/** Why MathJax refuses an inline formula, or undefined when it doesn't. */
225function inlineTexError(tex: string): string | undefined {
226 if (tex.length > MAX_TEX_LENGTH) return `formula longer than ${MAX_TEX_LENGTH} characters`
227 try {
228 typeset(tex, { display: false })
229 return undefined
230 } catch (error) {
231 if (error instanceof TexError) return reasonOf(error)
232 throw error
233 }
234}
235
236/**
237 * Rows from the top of a prose piece's drawing (a `next()` result) to its first
238 * row of text: the one-row top margin every AssistantMessage drawing brings.
239 */
240export const PIECE_TOP = 1
241
242// ─── Engine-independent settings ─────────────────────────────────────────────
243
244/** Cells assumed when the cell probe fails, at FALLBACK_PIXEL_SCALE resolution (the terminal scales the image to the cells). */
245export const FALLBACK_CELL = { cellWidth: 10, cellHeight: 20 } as const
246export const FALLBACK_PIXEL_SCALE = 2
247/** Terminal columns assumed until the probe or a render says. */
248export const FALLBACK_COLUMNS = 80
249/** How long a probe command may run. */
250export const PROBE_TIMEOUT_MS = 2000
251/**
252 * Wait after the last change of width before probing the cell size once more
253 * (a font zoom changes both); every change restarts it, so a drag ends with
254 * the final size.
255 */
256export const RESIZE_SETTLE_MS = 400
257/**
258 * A drawing with images probes the cell size when the last probe is older
259 * than this: a move to a monitor of another scale changes the cells' pixels
260 * and may keep the width, so no render says so, but the next reply does. (A
261 * font zoom changes the width in cells, which every render sees.)
262 */
263export const CELL_REFRESH_MS = 10_000
264/** How often the cell size is probed while images are on screen and nothing draws (one short process): a monitor move with no reply after it. */
265export const CELL_IDLE_MS = 60_000
266/** Formula images kept drawn, by formula and geometry (a long reply holds hundreds, inline ones included). */
267export const IMAGE_LIMIT = 1024
268/**
269 * Streamed blocks whose previews are kept for their landed drawings, each
270 * block its own (fuzz FUZZ-14: one store for the session, an early block
271 * redrawn after 512 later previews lost its images). A block past this is
272 * drawn as it streamed.
273 */
274export const BLOCK_LIMIT = 1024
275/** The newest blocks, looked through by their text for a landed block that no row id links to its stream (after a hot reload). */
276export const RECENT_BLOCKS = 8
277/** Appended rows remembered until a stream they start shows up (a reply whose only flush comes after its row). */
278export const PENDING_ROWS = 8
279/** Streaming messages tracked at once (a message that never sees `final` is dropped past this). */
280export const STREAM_LIMIT = 64
281/** Also instruct the model where the terminal shows no images (math then reads as Unicode). */
282export const INSTRUCT_WITHOUT_IMAGES = true
283
284export const SECTION_ID = 'kittex:math'
285
286/** The instructions to the model (design notes, "Instructions to the model"). */
287export const MATH_INSTRUCTIONS =
288 'Math in your replies is typeset in this terminal. Write every formula and mathematical symbol in LaTeX: ' +
289 'inline as `$...$` with no space just inside the dollars, and display math as `$$` on a line of its own, ' +
290 'the formula, then `$$` on a line of its own, with a blank line before and after. Inline math is shown as ' +
291 'Unicode text, so put tall formulas (stacked fractions, sums with limits, matrices) in display math. Use ' +
292 '`aligned`, `cases`, `pmatrix` and similar inside `$$`. Never put math in backticks or code blocks, and ' +
293 "don't write α, x² or ≤ in place of LaTeX. Put dollar amounts and shell variables in code spans, or write a " +
294 'literal dollar sign as `\\$`. In an answer to a side question (/btw), which is shown where math isn\'t ' +
295 'typeset, write math as Unicode text instead. This overrides the plain CommonMark note for math only.'
296
297/**
298 * The texts kittex may change once landed: math delimiters (a reply that never
299 * streamed through MessageDisplay, or one read back after `--resume`), a
300 * display preview's pad, an inline preview's join or pad, or a refused
301 * formula's source block. The AssistantMessage
302 * hook is registered with this as its `props.text` matcher (split as below on
303 * the terminal), so every other block is drawn by the engine without a round
304 * trip through kittex.
305 */
306export const LANDED_PATTERN = /\$|\\[([]|\\begin\{| |```latex|\u00a0|\u2800|\u034f|(?:^|\n)[ \t>]*(?:`{3,}|~{3,})[ \t]*[Mm][Aa][Tt][Hh](?![^\s])/
307
308/**
309 * What only kittex writes into a streamed block: a display preview's pad, an
310 * inline preview's join, pad or mark, a refused formula's note. A block
311 * holding one is one kittex streamed, whatever else it holds (a reply's
312 * currency, `$` in code, a `$` a preview shows).
313 */
314const PREVIEW_MARK = String.raw` |\u00a0|\u2800|\u034f|\*${NOT_RENDERED}`
315
316/**
317 * Inline math as written, by the scanner's dollar rules (scan/inline.ts): a
318 * single unescaped `$` not followed by whitespace, closed by the next `$` if
319 * that one is single, not after whitespace and not before a digit, within a
320 * paragraph and no code span. So a reply's currency (`$100`, `\$100`, `$25,000
321 * at 6.5% and $25,000`, `$5-$10`) is no math.
322 */
323const INLINE_DOLLARS = String.raw`(?<![\\$\`])\$(?![\s$])(?:[^$\`\\\n]|\\[^\n]|\n(?![ \t]*\n))*(?<![\s\\])\$(?![$\d])`
324
325/** Display math as written: `$$` (not escaped, not a longer run) up to the next `$$`. */
326const DISPLAY_DOLLARS = String.raw`(?<![\\$])\$\$(?!\$)[\s\S]*?\$\$`
327
328/**
329 * A ```math (or ~~~math) fence's opening line, as the scanner reads one
330 * (scan/blocks.ts: the info string's first word, any case): its body is
331 * display math (stress report F15, fuzz FUZZ-8).
332 */
333const MATH_FENCE = String.raw`(?:^|\n)[ \t>]*(?:\`{3,}|~{3,})[ \t]*[Mm][Aa][Tt][Hh](?![^\s])`
334
335/**
336 * What follows a backslash that the engine's markdown reads as an escape and
337 * drops (`\{` drawn `{`, `\,` drawn `,`): ASCII punctuation, and a line break
338 * (a hard break). `$` aside: an escaped dollar is kittex's scanner's too, and
339 * stays one.
340 */
341const ESCAPED = String.raw`(?:[!-#%-\/:-@\[-\`{-~]|\r?\n)`
342const ESCAPING = new RegExp(String.raw`\\(?=${ESCAPED})`, 'g')
343
344/**
345 * `$$…$$` with other text on its first or last line: inline math (a display
346 * formula has its lines to itself), within a paragraph (no blank line).
347 */
348const INLINE_DISPLAY_DOLLARS = (() => {
349 const one = String.raw`(?<![\\$])\$\$(?!\$)(?:(?!\$\$)(?!\n[ \t]*\n)[\s\S])*?\$\$`
350 return String.raw`[^\s>][^\n]*?${one}|${one}[ \t]*[^\s]`
351})()
352
353/**
354 * LaTeX as written: a reply that never streamed through MessageDisplay, or one
355 * read back after `--resume`. Never a block holding a preview mark (one kittex
356 * streamed: its `\[` is a bracket its previews escaped, `𝔼\[x\]`, and a `$`
357 * left in it is code or a preview's), and never for a currency dollar alone.
358 */
359export const SOURCE_PATTERN = sourcePattern({})
360
361/** A ```latex, ```tex or ```tikz fence's opening line. */
362const DIAGRAM_FENCE = String.raw`(?:^|\n)[ \t>]*(?:\`{3,}|~{3,})[ \t]*(?:latex|tex|tikz)\b`
363
364/**
365 * SOURCE_PATTERN for these options (and `diagrams`: where the local TeX may draw them): only the math of a kind kittex changes
366 * (a block whose math is all left raw stays the engine's, which would
367 * otherwise draw nothing until kittex answered). Math left raw counts where a
368 * backslash in it needs its mark (rawSource), as math read back after
369 * --resume does. With display math raw, `$$…$$` counts only where it is
370 * inline math.
371 */
372export function sourcePattern(math: Partial<MathOptions>, diagrams = false): RegExp {
373 const inline = math.inline !== 'raw'
374 const block = math.block !== 'raw'
375 const needs = String.raw`\\(?=${ESCAPED})`
376 const kinds = [
377 ...(inline ? [INLINE_DOLLARS] : [String.raw`(?<![\\$])\$(?![\s$])[^$\n]*?${needs}`]),
378 String.raw`\\\(`,
379 ...(block
380 ? [DISPLAY_DOLLARS, MATH_FENCE, String.raw`\\\[`, String.raw`\\begin\{`]
381 : [String.raw`(?<![\\$])\$\$(?:(?!\$\$)[\s\S])*?${needs}`, String.raw`\\\[`, String.raw`\\begin\{(?:(?!\\end\{)[\s\S])*?${needs}`, ...(inline ? [INLINE_DISPLAY_DOLLARS] : [])]),
382 // A diagram for the local TeX: a ```latex, ```tex or ```tikz block (`diagrams`, with display math drawn).
383 ...(diagrams && block ? [DIAGRAM_FENCE] : []),
384 ]
385 return new RegExp(String.raw`^(?![\s\S]*(?:${PREVIEW_MARK}))[\s\S]*?(?:${kinds.join('|')})`)
386}
387
388/**
389 * A block as kittex streamed it: one holding a preview mark. The engine's own
390 * drawing of such a text is the streaming preview row for row, so it may
391 * stand in while kittex's drawing is on its way (the AssistantMessage hook,
392 * in the fullscreen layout). Never matches a text SOURCE_PATTERN matches.
393 */
394export const STREAMED_PATTERN = new RegExp(PREVIEW_MARK)
395
396/**
397 * A matcher for a render's `onScreen` once the engine reports it: a range,
398 * or null for a block laid out off screen; not a render that has none. A
399 * RegExp tests the value as a string, so a range reads `[object Object]`;
400 * an object matcher (`[{}, null]`) did the same but made the engine warn,
401 * on every render it didn't select, that `{}` can never match a null.
402 * Built here like STREAMED_PATTERN: the plugin directory couldn't follow
403 * the hook whose matcher held it as a regular expression literal.
404 */
405export const ON_SCREEN_REPORTED = new RegExp('^(?:\\[object Object\\]|null)$')
406
407// ─── Shared state ────────────────────────────────────────────────────────────
408
409/** What drawing needs to know about the terminal (kittex.env in `$.state`). */
410export type { KittexEnv }
411/** One preview written while streaming, and the TeX it stands for. */
412export type PreviewRecord = KittexPreview
413/** What kittex keeps of one streamed block (kittex.blocks): its previews, each where it was written. */
414export type StreamedBlock = KittexBlock
415
416/** The environment for a cell size, falling back to FALLBACK_CELL. */
417export function cellOrFallback(cell: CellSize | undefined): { cellWidth: number; cellHeight: number; measured: boolean } {
418 if (cell && cell.cellWidth >= 1 && cell.cellHeight >= 1 && Number.isFinite(cell.cellWidth) && Number.isFinite(cell.cellHeight)) {
419 return { cellWidth: Math.round(cell.cellWidth), cellHeight: Math.round(cell.cellHeight), measured: true }
420 }
421 return {
422 cellWidth: FALLBACK_CELL.cellWidth * FALLBACK_PIXEL_SCALE,
423 cellHeight: FALLBACK_CELL.cellHeight * FALLBACK_PIXEL_SCALE,
424 measured: false,
425 }
426}
427
428/** Cells across the reply column for a viewport this wide (`columns - 2`), 1 to 255: what an image spans. */
429export function replyColumns(columns: number): number {
430 return Math.max(1, Math.min(255, Math.floor(columns) - REPLY_INDENT))
431}
432
433/** Cells a preview's own text may take: two fewer than the reply column, so a pad leads every line and none reaches the edge. */
434export function previewColumns(maxColumns: number): number {
435 return Math.max(1, maxColumns - 2)
436}
437
438/**
439 * Where formulas are drawn for a viewport this wide: a display formula's
440 * image (and its preview) spans the width prose wraps at, the reply column or
441 * `maxProseWidth` when that is narrower (fuzz FUZZ-2: centred in the whole
442 * column, a preview's lines wrapped at the prose width while streaming).
443 */
444export function renderEnvFor(env: KittexEnv, columns = env.columns): RenderEnv {
445 const renderEnv: RenderEnv = { cellWidth: env.cellWidth, cellHeight: env.cellHeight, maxColumns: proseWidthFor(env, columns), emPx: env.emPx, ink: env.ink }
446 if (env.inkOver) renderEnv.inkOver = env.inkOver
447 if (env.inkOver && env.inkCurve) renderEnv.inkCurve = env.inkCurve
448 if (env.weight !== undefined) renderEnv.weight = env.weight
449 return renderEnv
450}
451
452/** Where inline formulas are drawn: one text row, the math on the font's baseline. */
453export function inlineEnvFor(env: KittexEnv, columns = env.columns): InlineEnv {
454 return { ...renderEnvFor(env, columns), baselinePx: mathBaseline(env) }
455}
456
457/** The text font's layout in the env's cells (textLayout), when its metrics are known. */
458function fontLayout(env: Pick<KittexEnv, 'kind' | 'cellWidth' | 'cellHeight' | 'cellAdjust' | 'kittyAdjust' | 'font'>) {
459 const { font } = env
460 if (!font) return undefined
461 const { sizePt, platform, ...metrics } = font
462 return textLayout(env.kind, metrics, { cellWidth: env.cellWidth, cellHeight: env.cellHeight }, {
463 ...(sizePt ? { sizePt } : {}),
464 ...(platform ? { platform } : {}),
465 ...(env.cellAdjust ? { adjust: env.cellAdjust } : {}),
466 ...(env.kittyAdjust ? { kittyAdjust: env.kittyAdjust } : {}),
467 })
468}
469
470/**
471 * Where an inline formula's baseline goes, in pixels from the top of its
472 * cell: the text font's own baseline as the terminal sets it (from the font's
473 * metrics, adjustments included), raised by the math's ink depth
474 * (MATH_INK_DEPTH); before the font is read, TEXT_BASELINE of the cell.
475 */
476export function mathBaseline(env: Pick<KittexEnv, 'kind' | 'cellWidth' | 'cellHeight' | 'cellAdjust' | 'kittyAdjust' | 'font' | 'emPx'>): number {
477 const layout = fontLayout(env)
478 if (!layout) return textBaseline(env.cellHeight, TEXT_BASELINE, env.cellAdjust)
479 const depth = env.kind === 'kitty' || env.kind === 'ghostty' ? MATH_INK_DEPTH[env.kind] : MATH_INK_DEPTH.ghostty
480 return Math.max(1, layout.baselinePx - Math.round(depth * env.emPx))
481}
482
483/**
484 * Pixels per em of the math in these cells: its x-height against the text
485 * font's (mathEmPx) when the font's metrics are known, else from the cell's
486 * width (emPxForCell, the terminal's adjustments undone).
487 */
488export function mathEmPxFor(cell: Pick<CellSize, 'cellWidth' | 'cellHeight'>, env: Pick<KittexEnv, 'kind' | 'cellAdjust' | 'kittyAdjust' | 'font'>): number {
489 const own = fontCell(cell, env.cellAdjust)
490 const layout = fontLayout({ ...env, cellWidth: cell.cellWidth, cellHeight: cell.cellHeight })
491 return layout ? mathEmPx(layout, own) : emPxForCell(own)
492}
493
494/**
495 * The cells a display preview (and its image) takes in a blockquote `depth`
496 * deep: the engine draws a quote's text two cells in (a bar and a space),
497 * at most maxProseWidth wide.
498 */
499export function quoteColumns(env: KittexEnv, depth: number, columns = env.columns): number {
500 return Math.max(1, proseWidthFor(env, columns) - 2 * depth)
501}
502
503/**
504 * The cells a recorded display preview's image spans: the prose width (the
505 * reply column, or maxProseWidth), a quote's text, or a list item's text (see
506 * PreviewRecord's `quote`, `indent`).
507 */
508export function displayColumns(record: PreviewRecord, env: KittexEnv, columns = env.columns): number {
509 if (record.quote !== undefined) return quoteColumns(env, record.quote, columns)
510 if (record.indent !== undefined) return Math.max(1, proseWidthFor(env, columns) - record.indent)
511 return proseWidthFor(env, columns)
512}
513
514/**
515 * How the engine draws links in a terminal with these variables (as OSC 8
516 * hyperlinks, or as text with the url beside it), for KittexEnv; nothing when
517 * that isn't known, and links then keep their paragraph's math Unicode.
518 */
519export function linkEnv(variables: Readonly<Record<string, string | undefined>>): Pick<KittexEnv, 'hyperlinks'> {
520 const hyperlinks = engineHyperlinks(variables)
521 return hyperlinks === undefined ? {} : { hyperlinks }
522}
523
524/** The width reply prose wraps at: the reply column, or `maxProseWidth` when that is narrower. */
525export function proseWidthFor(env: KittexEnv, columns = env.columns): number {
526 const reply = replyColumns(columns)
527 return env.maxProseWidth !== undefined && env.maxProseWidth >= 1 ? Math.min(reply, Math.floor(env.maxProseWidth)) : reply
528}
529
530// ─── The options ─────────────────────────────────────────────────────────────
531
532/**
533 * How one kind of math is shown (the `block` and `inline` options): `image`,
534 * typeset images where the terminal draws them (Unicode elsewhere);
535 * `unicode`, Unicode text, never an image; `raw`, the LaTeX as Claude wrote it.
536 */
537export type MathMode = 'image' | 'unicode' | 'raw'
538
539export const MATH_MODES: readonly MathMode[] = ['image', 'unicode', 'raw']
540
541/** The two options: display math (`$$…$$`, `\[…\]`, bare environments, ```math fences) and inline math (`$…$`, `\(…\)`). */
542export interface MathOptions {
543 block: MathMode
544 inline: MathMode
545}
546
547/** The options as register receives them; a value that is no mode (unset, or stored by an older manifest) is `image`, the default. */
548export function mathOptions(options: Readonly<Record<string, unknown>>): MathOptions {
549 const mode = (value: unknown): MathMode => (MATH_MODES.includes(value as MathMode) ? (value as MathMode) : 'image')
550 return { block: mode(options.block), inline: mode(options.inline) }
551}
552
553/** What a streamed message is rewritten for, in this terminal with these options. */
554export function streamEnvFor(env: KittexEnv, math: MathOptions): StreamEnv {
555 return { ...env, inline: math.inline === 'image' && env.images, math }
556}
557
558/** What a streamed message is rewritten for: the terminal, whether inline math becomes images, and the options. */
559export type StreamEnv = KittexEnv & {
560 /** Inline math is drawn as images (the `inline` option, where the terminal draws images). */
561 inline?: boolean
562 /**
563 * The options (each kind `image` when absent): a kind set to `raw` is
564 * written as Claude wrote it, display math set to `unicode` as where the
565 * terminal draws no images.
566 */
567 math?: Partial<MathOptions>
568 /**
569 * Where the local LaTeX draws (the `latex` option, TeX found, images
570 * drawn): diagrams and display math MathJax refuses (`block`), inline math
571 * it refuses (`inline`). Absent: neither.
572 */
573 tex?: TexUse
574 /** Image blocks (a ```latex block holding one \includegraphics) are drawn as the file they name: images drawn, display math as images. */
575 imageFiles?: boolean
576}
577
578/** Whether a math segment is of a kind these options leave as written. */
579function leftRaw(segment: { display: boolean }, math: Partial<MathOptions> | undefined): boolean {
580 return (segment.display ? math?.block : math?.inline) === 'raw'
581}
582
583
584/**
585 * Math left raw as the engine draws it as written: INLINE_MARK (no width,
586 * drawn as nothing) after every backslash its markdown would read as an escape,
587 * so the backslash is no escape and stays, whether the engine reads the text
588 * as markdown or draws it plain (it does either, part by part, while a reply
589 * streams). A ```math fence is code, where markdown reads no escapes; in a
590 * GFM table row `\|` is the row's escape of a pipe and stays one. Idempotent:
591 * the landing reads the streamed text again.
592 */
593export function rawSource(math: Pick<MathSegment, 'raw' | 'tex' | 'display' | 'delimiter'>): string {
594 if (math.delimiter === 'fence') return math.raw
595 const tableRow = !math.display && math.raw.includes('\\|') && !math.tex.includes('\\|')
596 return math.raw.replace(ESCAPING, (backslash: string, at: number) => (tableRow && math.raw[at + 1] === '|' ? backslash : backslash + INLINE_MARK))
597}
598
599/**
600 * An inline formula as it is written while it streams, when it will be drawn
601 * as an image once landed: its one-line Unicode, words joined by INLINE_JOIN,
602 * padded with INLINE_PAD to exactly the image's columns (the image is widened
603 * instead when the Unicode is wider; one that holds neither a join nor a pad
604 * ends with INLINE_MARK: a preview is found again by its content), markdown
605 * syntax escaped.
606 */
607export interface InlinePreview {
608 markdown: string
609 tex: string
610 columns: number
611}
612
613/**
614 * The preview of an inline formula drawn as an image, or null when it stays
615 * plain Unicode: too tall for a row (see measureInline), refused by MathJax,
616 * wider than a row of prose (`rowWidth`), no one-line Unicode, a character whose
617 * width isn't certain, or a backslash.
618 */
619export function inlinePreview(tex: string, env: InlineEnv, rowWidth = env.maxColumns): InlinePreview | null {
620 // Tight, so the text is no wider than the image; spaced where tight would put a `<` against a letter.
621 let unicode = previewInline(tex, env.maxColumns)?.trim()
622 if (unicode && TAG_OPEN.test(unicode)) unicode = previewInline(tex, env.maxColumns, { tight: false })?.trim()
623 if (unicode && TAG_OPEN.test(unicode)) return null
624 if (unicode) unicode = ungroupScripts(unicode, tex)
625 if (!unicode || /[\\\s]/.test(unicode.replaceAll(' ', ''))) return null
626 const width = textWidth(unicode)
627 if (width < 1) return null
628 const box = measureInline(tex, env)
629 if (!box) return null
630 const columns = Math.max(box.columns, width)
631 // The image is drawn on one row: wider than prose wraps, it could never be placed.
632 if (columns > Math.min(255, env.maxColumns, rowWidth)) return null
633 const body = escapeInline(unicode.replaceAll(' ', INLINE_JOIN))
634 const mark = columns === width && !unicode.includes(' ') ? INLINE_MARK : ''
635 return { markdown: body + mark + INLINE_PAD.repeat(columns - width), tex, columns }
636}
637
638/**
639 * A script written as letters or digits with no Unicode script form, which
640 * the Unicode renderer groups as `_(…)` or `^(…)`, when nothing that could
641 * read as part of it (a letter, a digit, a mark, another script) follows.
642 * Script characters (`^(xˣ)`, a script of its own) are no such letters.
643 */
644const GROUPED_SCRIPT = /([_^])\(((?:(?![\u00b2\u00b3\u00b9\u02b0-\u02ff\u1d2c-\u1dbf\u2070-\u209f\u2c7c\u2c7d])[\p{L}\p{N}])+)\)(?![\p{L}\p{N}\p{M}_^])/gu
645
646/**
647 * An inline preview's scripts without the parentheses the Unicode renderer
648 * groups them in (`π_(ref)` as `π_ref`, `D_(KL)` as `D_KL`), where they
649 * only take cells: the preview sets its image's slot, and every cell it is
650 * wider than the image is blank around the formula once it lands. Kept where
651 * the formula has parentheses of its own (one could be the group's).
652 */
653export function ungroupScripts(unicode: string, tex: string): string {
654 return /\(|\\lparen/.test(tex) ? unicode : unicode.replace(GROUPED_SCRIPT, '$1$2')
655}
656
657/** What may open a phrase right before a formula: an opening bracket, a quote or a dash (`non-$x$`). */
658const OPENS = /^[\p{Ps}\p{Pi}\p{Pd}"'`]$/u
659/** What may close one right after it: a closing bracket or quote, punctuation (`,`, `:`, `.`) or a dash (`$x$-axis`). */
660const CLOSES = /^[\p{Pe}\p{Pf}\p{Po}\p{Pd}]$/u
661
662/**
663 * Where an inline formula's ink goes in a slot wider than it, from the
664 * characters drawn in the cells right before and after the slot (undefined at
665 * the start or end of the row's text): flush with the text column at its
666 * start (`start`) and against the slot's right edge at its end (`end`, unless
667 * a bracket opens right before it); against the right edge when a space is
668 * before it and punctuation, a dash or a closing bracket after it (`y_l,`,
669 * `x-axis`: the blank joins the space before), against its left edge in the
670 * mirror case (`(x_k `), centred otherwise (`(y_w)`, `a x b`).
671 */
672export function inkPlaceBeside(before: string | undefined, after: string | undefined): InkPlace {
673 if (before === undefined) return 'start'
674 if (after === undefined) return OPENS.test(before) ? 'start' : 'end'
675 const blankBefore = /^\s$/u.test(before)
676 const blankAfter = /^\s$/u.test(after)
677 if (blankBefore && !blankAfter && CLOSES.test(after)) return 'end'
678 if (blankAfter && !blankBefore && OPENS.test(before)) return 'start'
679 return 'center'
680}
681
682/**
683 * What a row may hold before its text: indentation, quote bars, and a list
684 * item's marker (`-`, `•`, `1.`, `a.`, `iv.`) with the space after it.
685 */
686const TEXT_START = /^[\s▎]*(?:(?:[-*+•◦▪‣]|\d{1,9}[.)]|[a-z]{1,6}[.)])\s+)?$/u
687
688/**
689 * The characters drawn in the cell before column `col` of a row and in the
690 * cell after the `columns` from it (zero-width marks skipped; undefined past
691 * the ends of the row's text: before its first character, a list marker or
692 * quote bar not counted, and after its last).
693 */
694export function cellsBeside(line: string, col: number, columns: number): [string | undefined, string | undefined] {
695 const chars = [...line]
696 let at = 0
697 let before: string | undefined
698 let prefix = ''
699 for (const [i, char] of chars.entries()) {
700 const cells = cellsOf(char)
701 if (cells === 0) continue
702 if (at + cells <= col) {
703 before = char
704 prefix += char
705 } else if (at >= col + columns) {
706 // Blanks to the row's end are past its text.
707 const after = /^\s*$/u.test(chars.slice(i).join('')) ? undefined : char
708 return [TEXT_START.test(prefix) ? undefined : before, after]
709 }
710 at += cells
711 }
712 return [TEXT_START.test(prefix) ? undefined : before, undefined]
713}
714
715// ─── Markdown forms ──────────────────────────────────────────────────────────
716
717/** Terminal cells a line takes, counting common wide characters as two. */
718export function cellsOf(line: string): number {
719 let cells = 0
720 for (const char of line) {
721 const code = char.codePointAt(0)!
722 if (code >= 0x300 && code <= 0x36f) continue
723 cells += isWide(code) ? 2 : 1
724 }
725 return cells
726}
727
728function isWide(code: number): boolean {
729 return (
730 (code >= 0x1100 && code <= 0x115f) ||
731 (code >= 0x2e80 && code <= 0xa4cf) ||
732 (code >= 0xac00 && code <= 0xd7a3) ||
733 (code >= 0xf900 && code <= 0xfaff) ||
734 (code >= 0xfe30 && code <= 0xfe4f) ||
735 (code >= 0xff00 && code <= 0xff60) ||
736 (code >= 0xffe0 && code <= 0xffe6) ||
737 (code >= 0x1f300 && code <= 0x1faff)
738 )
739}
740
741/** Text with every character markdown could read as syntax escaped. */
742export function escapeMarkdown(text: string): string {
743 return text.replace(MARKDOWN_SPECIALS, '\\$&')
744}
745
746/**
747 * Preview lines as markdown that the engine draws one row per line, each
748 * exactly as given: leading spaces become pads (at least one, so no line starts
749 * with markdown syntax), the lines are centred in `maxColumns`, trailing
750 * spaces are dropped, a blank line keeps its pads and ends in BLANK_CELL,
751 * and syntax is escaped.
752 */
753export function previewMarkdownLines(lines: readonly string[], maxColumns: number): string[] {
754 const width = Math.max(0, ...lines.map(line => cellsOf(line.replace(/\s+$/, ''))))
755 const centre = PREVIEW_CENTERED ? Math.floor((maxColumns - width) / 2) : 0
756 const lead = Math.max(1, centre)
757 return lines.map(line => {
758 const body = line.replace(/\s+$/, '')
759 const content = body.trimStart()
760 if (content === '') return PREVIEW_PAD.repeat(lead) + BLANK_CELL
761 return PREVIEW_PAD.repeat(lead + body.length - content.length) + escapeMarkdown(content)
762 })
763}
764
765/**
766 * A display preview's markdown lines: exactly `rows` lines when given (the
767 * rows its image takes). Where no Unicode form fits the width (stress report
768 * F4: a wide formula in a narrow window), its one-line form wrapped at the
769 * width, cut with `…` past the rows; the TeX source (cut likewise) only where
770 * Unicode has no form at all.
771 */
772export function displayPreviewLines(tex: string, maxColumns: number, rows?: number): string[] | null {
773 const lines = previewDisplay(tex, { maxColumns: previewColumns(maxColumns) }, rows)
774 if (lines && lines.length > 0) return previewMarkdownLines(spreadRows(lines, tex), maxColumns)
775 if (rows !== undefined && rows < 1) return null
776 const flat = previewInline(tex, undefined, { tight: false })
777 if (flat === null && rows === undefined) return null
778 const width = previewColumns(maxColumns)
779 let text = flat === null ? [oneLine(tex, width)] : wrapCells(flat, width)
780 if (rows === undefined) return previewMarkdownLines(text, maxColumns)
781 if (text.length > rows) text = [...text.slice(0, rows - 1), oneLine(text.slice(rows - 1).join(' '), width)]
782 const above = Math.floor((rows - text.length) / 2)
783 const padded = [...Array<string>(above).fill(''), ...text, ...Array<string>(rows - text.length - above).fill('')]
784 return previewMarkdownLines(padded, maxColumns)
785}
786
787/** Text broken into lines at most `width` cells wide: at spaces, and inside a word only where it is wider than a line. */
788export function wrapCells(text: string, width: number): string[] {
789 const lines: string[] = []
790 let line = ''
791 for (const word of text.split(' ').filter(word => word !== '')) {
792 const joined = line === '' ? word : `${line} ${word}`
793 if (cellsOf(joined) <= width) {
794 line = joined
795 continue
796 }
797 if (line !== '') lines.push(line)
798 line = ''
799 for (const char of word) {
800 if (line !== '' && cellsOf(line + char) > width) {
801 lines.push(line)
802 line = ''
803 }
804 line += char
805 }
806 }
807 if (line !== '' || lines.length === 0) lines.push(line)
808 return lines
809}
810
811/**
812 * A preview with a line per row of a tall environment (`aligned`, `gathered`,
813 * a derivation), padded to its image's rows with more blank rows than it has
814 * lines, spread over the image's height: each line about where its row of the
815 * image will be, instead of a block in the middle with blank slabs above and
816 * below (stress report F18). Anything else is returned as it is.
817 */
818export function spreadRows(lines: readonly string[], tex: string): readonly string[] {
819 const blank = (line: string) => line.trim() === ''
820 const first = lines.findIndex(line => !blank(line))
821 const last = lines.findLastIndex(line => !blank(line))
822 if (first < 0) return lines
823 const content = lines.slice(first, last + 1)
824 const rows = lines.length
825 if (content.length < 3 || content.some(blank) || rows - content.length < content.length) return lines
826 // One line per row of the environment: as many lines as the formula has rows (its `\\`s, none nested).
827 const body = /^\s*\\begin\{(aligned|align\*?|gathered|gather\*?|split|eqnarray\*?|multline\*?)\}([\s\S]*)\\end\{\1\}\s*$/.exec(tex)?.[2]
828 if (body === undefined || /\\begin\{/.test(body)) return lines
829 if (body.replace(/\\\\\s*$/, '').split('\\\\').length !== content.length) return lines
830 const width = Math.max(...content.map(line => line.length))
831 const out = Array.from({ length: rows }, () => ' '.repeat(width))
832 for (const [i, line] of content.entries()) out[Math.floor(((i + 0.5) * rows) / content.length)] = line
833 return out
834}
835
836/** Text on one line (whitespace runs collapsed), cut with `…` to `max` cells. */
837export function oneLine(text: string, max: number): string {
838 const flat = text.replace(/\s+/g, ' ').trim()
839 if (cellsOf(flat) <= max) return flat
840 let out = ''
841 for (const char of flat) {
842 if (cellsOf(out + char) > max - 1) break
843 out += char
844 }
845 return out + '…'
846}
847
848/** The line drawn under a refused formula, as plain text. */
849export function notRenderedText(reason: string, maxColumns: number): string {
850 return oneLine(NOT_RENDERED + reason, previewColumns(maxColumns))
851}
852
853/**
854 * A formula MathJax refused: its source in a `latex` block, a blank line, and
855 * `not rendered: <reason>` (italic while streaming, drawn dim once landed).
856 * The note is a paragraph of its own: a fence followed directly by text takes
857 * an extra row while streaming.
858 */
859export function refusedMarkdownLines(tex: string, reason: string, maxColumns: number): string[] {
860 return [...sourceMarkdownLines(tex), '', '*' + escapeMarkdown(notRenderedText(reason, maxColumns)) + '*']
861}
862
863/** A formula's source in a `latex` block: where Unicode can't write it and no image is drawn. */
864export function sourceMarkdownLines(tex: string): string[] {
865 const longest = Math.max(0, ...[...tex.matchAll(/`+/g)].map(run => run[0].length))
866 const fence = '`'.repeat(Math.max(3, longest + 1))
867 return [fence + 'latex', ...tex.split('\n'), fence]
868}
869
870function reasonOf(error: TexError): string {
871 return error.message || 'TeX error'
872}
873
874/** A line's start that only opens blockquotes (`> `, `>> `, `> > `). */
875const QUOTE_LEAD = /^[ \t]{0,3}(?:>[ \t]?)+$/
876
877/**
878 * Where MarkdownWriter.block puts a block written after `written`: what it
879 * writes before the block's first line (a blank line, or in a quote a `>`
880 * line, unless one is there; a paragraph break after text), and the
881 * indentation (or blockquote prefix, `quote`) of its other lines. `started`:
882 * something other than whitespace was written.
883 */
884export function blockOpening(written: string, started = /\S/.test(written)): { before: string; indent: string; quote: string } {
885 const start = written.lastIndexOf('\n') + 1
886 const lead = written.slice(start)
887 const above = written.slice(0, start)
888 if (/^[ \t]*$/.test(lead)) return { before: started && !/\n[ \t]*\n$/.test(above) ? '\n' + lead : '', indent: lead, quote: '' }
889 // A paragraph of its own inside the quote: a `>` line above it unless one is there.
890 if (QUOTE_LEAD.test(lead)) return { before: started && !/(?:^|\n)[ \t]*(?:>[ \t]*)+\n$/.test(above) ? '\n' + lead : '', indent: lead, quote: lead }
891 return { before: '\n\n', indent: '', quote: '' }
892}
893
894/**
895 * Builds markdown out of source text and blocks. A block is a paragraph of its
896 * own: a blank line before and after it, each line at the indentation of the
897 * line it starts on (so it stays in its list item). A block always ends with a
898 * newline, as a streamed flush does.
899 */
900export class MarkdownWriter {
901 out = ''
902 /**
903 * What earlier takes wrote, all of it: the part being written is read from
904 * where it starts (a long list's outer items included), as the landing reads it.
905 */
906 private tail = ''
907 /** Something other than whitespace was written. */
908 private started = false
909 /** A block was the last thing written: the next text must leave a blank line. */
910 private afterBlock = false
911 /** The blockquote prefix the last block was written under ('' outside a quote). */
912 private quote = ''
913
914 text(text: string): void {
915 if (text === '') return
916 const written = this.prepare(text)
917 this.afterBlock = false
918 if (/\S/.test(text)) this.started = true
919 this.out += written
920 }
921
922 /**
923 * What text() writes for `text`: the text, after the blank line (in a quote,
924 * the `>` line) a block right before it needs. Only its start may differ.
925 */
926 prepare(text: string): string {
927 if (text === '' || !this.afterBlock) return text
928 if (this.quote !== '') {
929 // In a quote the blank line after a block is a `>` line: a bare one would end the quote.
930 if (/^[ \t]*\r?\n[ \t]*(?:>[ \t]*)+\r?\n/.test(text)) return text.replace(/^[ \t]*\r?\n/, '')
931 // One that opens with such a line already has it (a flush starting right after the block's closing line).
932 if (/^[ \t]*(?:>[ \t]*)+\r?\n/.test(text)) return text
933 return this.quote.trimEnd() + (/^[ \t]*\r?\n/.test(text) ? '' : '\n') + text
934 }
935 return /^[ \t]*\r?\n/.test(text) ? text : '\n' + text
936 }
937
938 /**
939 * Writes a block and returns it as written (lines after the first indented,
940 * or under the blockquote prefix the line it starts on opens with).
941 */
942 block(lines: readonly string[]): string {
943 const opening = blockOpening(this.tail + this.out, this.started)
944 this.quote = opening.quote
945 const block = lines.join('\n' + opening.indent)
946 this.out += opening.before + block + '\n'
947 this.started = true
948 this.afterBlock = true
949 return block
950 }
951
952 /** How many blockquotes deep the line being written is (its `>` prefix so far; 0 outside a quote). */
953 quoteDepth(): number {
954 const written = this.tail + this.out
955 const lead = written.slice(written.lastIndexOf('\n') + 1)
956 return QUOTE_LEAD.test(lead) ? (lead.match(/>/g) ?? []).length : 0
957 }
958
959 /** Everything written so far, earlier takes included. */
960 recent(): string {
961 return this.tail + this.out
962 }
963
964 /** Takes the text written so far (one flush, or one prose piece). */
965 take(): string {
966 const out = this.out
967 this.tail += out
968 this.out = ''
969 return out
970 }
971}
972
973// ─── Streaming (MessageDisplay) ──────────────────────────────────────────────
974
975export interface StreamRewrite {
976 text: string
977 records: PreviewRecord[]
978 /**
979 * Documents the stream waits for TeX to compile (TexBook): everything from
980 * the first segment that needs one is held, and comes out of resume() once
981 * their outcomes are known.
982 */
983 pending?: TexDocument[]
984 /** Image blocks whose files the stream waits for (ImageBook), held the same way. */
985 images?: ImageSpec[]
986}
987
988/**
989 * Where the landing will cut what is being streamed (planLanded): it draws a
990 * display image, or a refused formula's note, as an item of its own, and lays
991 * the text after it out as a piece of its own, part by part (blockParts). So
992 * the stream reads the part a formula is in as the landing reads it: from
993 * where its piece starts, all of it however long (a long list's outer items
994 * included). Offsets index everything the writer wrote.
995 */
996export class StreamPlan {
997 /** Where the piece being written starts: right after the last image's or note's block. */
998 piece = 0
999 /**
1000 * Where the last block read in it so far starts (proseBlocks' block: what
1001 * comes before it can't join a later part). blockParts reads the piece again
1002 * from there, so a flush costs about as much as the block it ends in, not
1003 * the whole reply.
1004 */
1005 anchor = 0
1006
1007 /** A new piece starts at `at`. */
1008 cut(at: number): void {
1009 this.piece = at
1010 this.anchor = at
1011 }
1012}
1013
1014/**
1015 * Rewrites the segments one flush completed: inline math as one line of
1016 * Unicode (padded to its image's width, with a record, when inline images are
1017 * on and the landing will place its image: see writeProse), a display formula
1018 * as its preview (exactly the rows its image will take when the terminal draws
1019 * images), a formula MathJax refuses as its source and a `not rendered` line.
1020 * `writer` carries the line state across the message's flushes, `plan` where
1021 * the landing cuts it.
1022 */
1023export function rewriteSegments(segments: readonly Segment[], env: StreamEnv, writer: MarkdownWriter, plan = new StreamPlan()): StreamRewrite {
1024 const records: PreviewRecord[] = []
1025 // Math its option leaves raw is text from here on (as written, its backslashes kept), as the landing reads it.
1026 segments = asWritten(segments, env.math)
1027 for (let k = 0; k < segments.length; ) {
1028 const segment = segments[k]!
1029 if (segment.kind === 'math' && segment.display) {
1030 if (segment.diagram !== undefined) writeDiagram(segment, env, writer, plan, records)
1031 else writeDisplay(segment, env, writer, plan, records)
1032 k++
1033 continue
1034 }
1035 let end = k + 1
1036 while (end < segments.length && !isDisplayMath(segments[end]!)) end++
1037 writeProse(segments.slice(k, end), segments[end], env, writer, plan, records)
1038 k = end
1039 }
1040 return { text: writer.take(), records }
1041}
1042
1043type MathSegment = Extract<Segment, { kind: 'math' }>
1044
1045/** The segments with the math of each kind its option leaves raw turned into text, as written (adjacent text joined). */
1046function asWritten(segments: readonly Segment[], math: Partial<MathOptions> | undefined): Segment[] {
1047 if (math?.block !== 'raw' && math?.inline !== 'raw') return [...segments]
1048 return joinText(segments.map(segment => (segment.kind === 'math' && leftRaw(segment, math) ? { kind: 'text', text: rawSource(segment), start: segment.start, end: segment.end } : segment)))
1049}
1050
1051function isDisplayMath(segment: Segment): boolean {
1052 return segment.kind === 'math' && segment.display
1053}
1054
1055/** How the engine draws links and the terminal emoji sequences, as the replays take it. */
1056function linkModeOf(env: KittexEnv): LinkMode {
1057 return { hyperlinks: env.hyperlinks, emojiSequences: env.emojiSequences }
1058}
1059
1060/**
1061 * Writes a display formula's preview. In a blockquote it stays inside it, as
1062 * wide as the quote's text (one quote deep, its image lies over it once
1063 * landed); in a list item likewise, as wide as the item's text, its image over
1064 * it in the item; anywhere else it is as wide as the reply column and lands as
1065 * an image of its own, after which a new piece starts (as after a refused
1066 * formula's note).
1067 */
1068function writeDisplay(segment: MathSegment, env: StreamEnv, writer: MarkdownWriter, plan: StreamPlan, records: PreviewRecord[]): void {
1069 const renderEnv = renderEnvFor(env)
1070 const { maxColumns } = renderEnv
1071 const quote = writer.quoteDepth()
1072 // Display math gets images where the terminal draws them, unless the `block` option says Unicode.
1073 const images = env.images && env.math?.block !== 'unicode'
1074 // The item's text is laid out from where its list starts, however far back that is.
1075 const indent = quote === 0 && images ? itemIndent(writer.recent().slice(plan.anchor), proseWidthFor(env), linkModeOf(env)) : undefined
1076 const width = quote > 0 ? quoteColumns(env, quote) : indent !== undefined ? Math.max(1, proseWidthFor(env) - indent) : maxColumns
1077 // In a quote at any depth (fuzz FUZZ-9), where the quote so far is one the landing lays out (else its image could never be placed).
1078 const drawn = images && (quote === 0 || placeable(writer.recent().slice(plan.anchor), proseWidthFor(env), env.columns, linkModeOf(env)))
1079 // The landing cuts its text only at a refused formula's note in the reply column (in a list item or a quote the
1080 // note stays in it: planLanded's nestedAt); a display formula's image lies over its preview in the text.
1081 const head = writer.recent().slice(plan.anchor)
1082 const nested = quote > 0 || nestedAt(head, head.length)
1083 let rows: number | undefined
1084 try {
1085 rows = drawn ? measureDisplay(segment.tex, { ...renderEnv, maxColumns: width }).rows : undefined
1086 } catch (error) {
1087 if (!(error instanceof TexError)) throw error
1088 // What MathJax refuses, the local TeX may draw.
1089 const viaTex = drawn && env.tex?.block ? texDisplay(segment.tex, { ...renderEnv, maxColumns: width }) : undefined
1090 if (viaTex && 'rows' in viaTex) return writeDisplayPreview(segment, renderEnv, viaTex.rows, width, quote, indent, writer, plan, records)
1091 const reason = viaTex?.error ?? reasonOf(error)
1092 const preview = writer.block(refusedMarkdownLines(segment.tex, reason, maxColumns))
1093 if (images) {
1094 records.push({ preview, tex: segment.tex, rows: 0, error: reason })
1095 if (!nested) plan.cut(writer.recent().length)
1096 }
1097 return
1098 }
1099 writeDisplayPreview(segment, renderEnv, rows, width, quote, indent, writer, plan, records)
1100}
1101
1102/** Writes a display formula's preview `rows` tall (none: as Unicode alone) and records it; its source where Unicode has no form. */
1103function writeDisplayPreview(
1104 segment: MathSegment,
1105 renderEnv: RenderEnv,
1106 rows: number | undefined,
1107 width: number,
1108 quote: number,
1109 indent: number | undefined,
1110 writer: MarkdownWriter,
1111 plan: StreamPlan,
1112 records: PreviewRecord[],
1113): void {
1114 const lines = displayPreviewLines(segment.tex, width, rows)
1115 if (lines) {
1116 const preview = writer.block(lines)
1117 if (rows === undefined) return
1118 records.push({ preview, tex: segment.tex, rows, ...(quote > 0 ? { quote } : {}), ...(indent !== undefined ? { indent } : {}) })
1119 return
1120 }
1121 const refused = texErrorOf(segment.tex, renderEnv)
1122 writer.block(refused ? refusedMarkdownLines(segment.tex, refused, renderEnv.maxColumns) : sourceMarkdownLines(segment.tex))
1123}
1124
1125/** Layouts of one run of prose a flush may take beyond the first before what is still undecided in it is written plain. */
1126const MAX_RELAYOUTS = 32
1127
1128/** An inline formula of a run being written: the forms it may take, padded first, and the one it has (`options.length`: plain Unicode). */
1129interface InlineChoice {
1130 segment: MathSegment
1131 options: InlinePreview[]
1132 choice: number
1133 /** Placed for good: a part's drawing up to a formula never depends on what comes after it (a table's does). */
1134 done: boolean
1135 /** Where it is in the text being laid out, as the forms chosen so far put it. */
1136 start: number
1137 end: number
1138}
1139
1140/**
1141 * Writes a run of prose (its text and inline math, up to a display formula).
1142 * Inline math is written padded to its image's width only where the landing
1143 * will draw the image over it: where its part, read as the landing reads it
1144 * (blockParts from where its piece starts) with the whole run in it, is laid
1145 * out with the preview whole on one row (the rule placeInline places images
1146 * by); else unpadded, its image in those cells, where that is placed
1147 * (narrowPreview); else as plain Unicode. Each part is laid out with all its
1148 * formulas at once; where one isn't placed it takes its next form and the
1149 * part is laid out again (its drawing up to a formula doesn't depend on what
1150 * follows, so those before it stay placed); past where the replay follows the
1151 * part, every formula is plain at once. `next`: the segment after the run.
1152 */
1153function writeProse(run: readonly Segment[], next: Segment | undefined, env: StreamEnv, writer: MarkdownWriter, plan: StreamPlan, records: PreviewRecord[]): void {
1154 const choices = new Map<number, InlineChoice>()
1155 if (env.inline && env.images && run.some(segment => segment.kind === 'math')) decideInline(run, next !== undefined && isDisplayMath(next), env, writer, plan, choices)
1156 let before = lastChar(writer.recent())
1157 for (const [at, segment] of run.entries()) {
1158 const choice = choices.get(at)
1159 const inline = choice?.options[choice.choice]
1160 const text = segment.kind === 'text' ? segment.text : inline ? inline.markdown : inlineFallback(segment)
1161 if (text === '') continue
1162 const written = writer.prepare(text)
1163 if (inline && segment.kind === 'math') {
1164 // Where its ink will go, as the source around it says (the landed rows decide; this draws it ahead).
1165 const after = run[at + 1] ?? next
1166 const first = after === undefined ? undefined : after.kind === 'text' ? [...after.text][0] : after.raw[0]
1167 const place = inkPlaceBeside((written.length > text.length ? lastChar(written.slice(0, -text.length)) : before)?.replace('\n', ' '), first)
1168 records.push({ preview: inline.markdown, tex: segment.tex, rows: 1, inline: true, columns: inline.columns, ...(place === 'center' ? {} : { place }) })
1169 }
1170 writer.text(text)
1171 before = lastChar(written) ?? before
1172 }
1173}
1174
1175/** The last character of a text (a surrogate pair whole), or undefined. */
1176function lastChar(text: string): string | undefined {
1177 if (text === '') return undefined
1178 const code = text.charCodeAt(text.length - 1)
1179 return code >= 0xdc00 && code <= 0xdfff && text.length > 1 ? text.slice(-2) : text.slice(-1)
1180}
1181
1182/**
1183 * Chooses the form of each inline formula in a run (see writeProse), keyed by
1184 * its index in the run. `display`: a display formula follows the run (its
1185 * block is read as a line of text where MarkdownWriter.block will put it).
1186 */
1187function decideInline(run: readonly Segment[], display: boolean, env: StreamEnv, writer: MarkdownWriter, plan: StreamPlan, choices: Map<number, InlineChoice>): void {
1188 const inlineEnv = inlineEnvFor(env)
1189 const width = proseWidthFor(env)
1190 const mode = linkModeOf(env)
1191 const head = writer.recent().slice(plan.anchor)
1192 // The run as written with the forms chosen so far; each formula's place in it.
1193 const build = (): string => {
1194 let body = ''
1195 let first = true
1196 for (const [at, segment] of run.entries()) {
1197 const choice = choices.get(at)
1198 const text = segment.kind === 'text' ? segment.text : choice && choice.choice < choice.options.length ? choice.options[choice.choice]!.markdown : inlineFallback(segment)
1199 if (text === '') continue
1200 body += first ? writer.prepare(text) : texthooks/budget.ts 101 lines1// The images one landed block may draw. Claude Code takes at most 2 MiB of
2// Image source (decoded PNG bytes) in one ui.render answer, all its Images
3// together; past it, it throws the whole answer away and draws its own text
4// (measured live on 2.1.291: "more than 2097152 bytes of Image source in one
5// tree"). A long block of large formulas could get there, so its images are
6// counted in reading order and those that no longer fit are left out: each
7// keeps the Unicode its rows already hold, so nothing moves.
8import { MAX_IMAGE_BYTES } from './core.js'
9import type { RenderedImage } from './core.js'
10import type { Piece } from './math.ts'
11
12/** The PNG bytes one drawing may hold: the engine's limit for all its Images together. */
13export const TREE_IMAGE_BYTES = MAX_IMAGE_BYTES
14
15/**
16 * The images of `pieces` that do not fit in `limit` bytes, in reading order
17 * (a piece's display image, then a prose piece's inline images row by row):
18 * each one taken while it fits, the rest left out.
19 */
20export function overBudget(pieces: readonly Piece[], limit = TREE_IMAGE_BYTES): Set<RenderedImage> {
21 const left = new Set<RenderedImage>()
22 let used = 0
23 const take = (image: RenderedImage) => {
24 if (used + image.png.length <= limit) used += image.png.length
25 else left.add(image)
26 }
27 for (const piece of pieces) {
28 if (piece.kind === 'image') take(piece.image)
29 else if (piece.kind === 'prose' && piece.inline) for (const one of [...piece.inline].sort((a, b) => a.row - b.row || a.col - b.col)) take(one.image)
30 }
31 return left
32}
33
34/**
35 * A display formula left out of the budget, as text in its image's box:
36 * `lines` (its Unicode preview, from core's previewDisplay) centred across
37 * `columns`, padded with blank lines to `rows`; its source on one line when
38 * there is no preview.
39 */
40export function fallbackLines(lines: readonly string[] | null, tex: string, columns: number, rows: number): string[] {
41 const body = lines && lines.length <= rows ? [...lines] : [oneLine(tex, columns)]
42 const width = Math.max(...body.map(line => [...line].length))
43 const pad = ' '.repeat(Math.max(0, Math.floor((columns - width) / 2)))
44 const above = Math.floor((rows - body.length) / 2)
45 const out = [...Array<string>(Math.max(0, above)).fill(''), ...body.map(line => (pad + line).trimEnd())]
46 while (out.length < rows) out.push('')
47 return out.slice(0, rows)
48}
49
50function oneLine(text: string, max: number): string {
51 const flat = text.replace(/\s+/g, ' ').trim()
52 const chars = [...flat]
53 return chars.length <= max ? flat : `${chars.slice(0, Math.max(1, max - 1)).join('')}…`
54}
55
56/**
57 * An Image's alt as the engine takes it: a control character in it (a form
58 * feed, a newline in a formula's source) fails the whole drawing, so each
59 * becomes a space; never empty.
60 */
61export function altText(text: string): string {
62 // eslint-disable-next-line no-control-regex
63 const clean = text.replace(/[\u0000-\u001f\u007f-\u009f]/g, ' ')
64 return clean === '' ? ' ' : clean
65}
66
67/** The densities a picture is drawn again at, in turn, to fit a drawing's budget (its pixels each way: 1/2, then 1/3). */
68export const PICTURE_DENSITIES: readonly number[] = [0.5, 1 / 3]
69
70/**
71 * A drawing's pieces with its pictures (TeX diagrams) drawn at fewer pixels,
72 * largest first, while all its images together pass `limit`: a picture keeps
73 * its cells (the terminal scales an image to them), so nothing moves, and
74 * it is drawn after all instead of being left out. `redraw` gives a
75 * picture's image drawn again at a density (undefined for anything else: a
76 * formula is small and keeps its pixels).
77 */
78export function fitPictures(pieces: readonly Piece[], redraw: (image: RenderedImage, density: number) => RenderedImage | undefined, limit = TREE_IMAGE_BYTES): Piece[] {
79 const images = pieces.flatMap(piece => (piece.kind === 'image' ? [piece.image] : piece.kind === 'prose' ? (piece.inline ?? []).map(one => one.image) : []))
80 let total = images.reduce((sum, image) => sum + image.png.length, 0)
81 if (total <= limit) return [...pieces]
82 const swap = new Map<RenderedImage, RenderedImage>()
83 for (const density of PICTURE_DENSITIES) {
84 for (const image of [...images].sort((a, b) => b.png.length - a.png.length)) {
85 if (total <= limit) break
86 const now = swap.get(image) ?? image
87 const smaller = redraw(image, density)
88 if (!smaller || smaller.png.length >= now.png.length) continue
89 total += smaller.png.length - now.png.length
90 swap.set(image, smaller)
91 }
92 if (total <= limit) break
93 }
94 if (swap.size === 0) return [...pieces]
95 return pieces.map(piece => {
96 if (piece.kind === 'image') return swap.has(piece.image) ? { ...piece, image: swap.get(piece.image)! } : piece
97 if (piece.kind === 'prose' && piece.inline) return { ...piece, inline: piece.inline.map(one => (swap.has(one.image) ? { ...one, image: swap.get(one.image)! } : one)) }
98 return piece
99 })
100}
101hooks/drawing.ts 205 lines1// The images kittex draws, and the caches that keep them: formulas through
2// MathJax (or TeX's drawing where MathJax refused one), diagrams and image
3// files as TexBook and ImageBook have them, each PNG's base64 and signature,
4// and the reserved options of a block off screen. Nothing here takes `$`;
5// register.tsx composes these images into what Claude Code draws.
6
7import { blockImages, measureDisplay, measureDisplayResult, renderDisplay, renderDisplayResult, renderImageBlock, renderInline, renderInlineResult, renderPicture, TexError, toBase64 } from './core.js'
8import type { ImageBlock, InkPlace, InlineEnv, PictureEnv, RenderedImage, RenderEnv } from './core.js'
9import { imageBlockOf, imageBook } from './image.ts'
10import { IMAGE_LIMIT } from './math.ts'
11import type { PlanOptions } from './math.ts'
12import { diagramJob, mathJob, texBook, texResult } from './tex.ts'
13import type { DiagramKind } from './tex.ts'
14
15/**
16 * Images drawn, by formula and geometry (cells, column, ink, rows or columns),
17 * least recently used first. Each keeps one PNG object, so its base64 and its
18 * signature are computed once, and a re-render of a landed block sends the
19 * same source (no new transmission).
20 */
21const drawnImages = new Map<string, RenderedImage>()
22
23function cachedImage(key: string, draw: () => RenderedImage): RenderedImage {
24 let image = drawnImages.get(key)
25 if (image) {
26 drawnImages.delete(key)
27 } else {
28 image = draw()
29 while (drawnImages.size >= IMAGE_LIMIT) drawnImages.delete(drawnImages.keys().next().value!)
30 }
31 drawnImages.set(key, image)
32 return image
33}
34
35function geometryKey(env: RenderEnv): string {
36 const over = env.inkOver ? [env.inkOver.r, env.inkOver.g, env.inkOver.b, env.inkCurve?.gamma ?? '', env.inkCurve?.contrast ?? ''] : []
37 return [env.cellWidth, env.cellHeight, env.maxColumns, env.emPx, env.weight ?? '', env.ink.r, env.ink.g, env.ink.b, ...over].join(',')
38}
39
40/** A display formula's image, `rows` tall (measured when not given). Throws TexError. */
41export function displayImage(tex: string, env: RenderEnv, rows?: number): RenderedImage {
42 let height: number
43 try {
44 height = rows ?? measureDisplay(tex, env).rows
45 return cachedImage(`d\n${geometryKey(env)}\n${height}\n${tex}`, () => renderDisplay(tex, env, height))
46 } catch (error) {
47 // MathJax refused it: TeX's drawing where the local LaTeX made one.
48 const result = error instanceof TexError ? texDrawn(tex, true) : undefined
49 if (!result) throw texRefusal(tex, true) ?? error
50 height = rows ?? measureDisplayResult(result, env).rows
51 return cachedImage(`t\n${geometryKey(env)}\n${height}\n${tex}`, () => renderDisplayResult(result, env, height))
52 }
53}
54
55/** The rows a display formula's image takes: MathJax's, or TeX's where MathJax refused it. Throws TexError. */
56export function displayRows(tex: string, env: RenderEnv): number {
57 try {
58 return measureDisplay(tex, env).rows
59 } catch (error) {
60 const result = error instanceof TexError ? texDrawn(tex, true) : undefined
61 if (!result) throw texRefusal(tex, true) ?? error
62 return measureDisplayResult(result, env).rows
63 }
64}
65
66/** An inline formula's image, `columns` wide, its ink where `place` says. Throws TexError. */
67export function inlineImage(tex: string, env: InlineEnv, columns: number, place: InkPlace = 'center'): RenderedImage {
68 const key = `${geometryKey(env)},${env.baselinePx}\n${columns},${place}\n${tex}`
69 try {
70 return cachedImage(`i\n${key}`, () => renderInline(tex, env, columns, place))
71 } catch (error) {
72 // MathJax refused it: TeX's drawing where the local LaTeX made one.
73 const result = error instanceof TexError ? texDrawn(tex, false) : undefined
74 if (!result) throw error
75 return cachedImage(`ti\n${key}`, () => renderInlineResult(result, env, columns, place))
76 }
77}
78
79export const base64Cache = new WeakMap<Uint8Array, string>()
80const signatureCache = new WeakMap<Uint8Array, string>()
81
82/**
83 * A PNG's FNV-1a hash, for the key of the Box that holds its Image: an image
84 * whose pixels change (new cells, width or ink) is a new element, which the
85 * engine sends under a new image id, deleting the old one. Sent again under
86 * the same id, Ghostty keeps drawing an earlier transmission.
87 */
88export function signatureOf(png: Uint8Array): string {
89 let signature = signatureCache.get(png)
90 if (signature === undefined) {
91 let hash = 0x811c9dc5
92 for (const byte of png) hash = Math.imul(hash ^ byte, 0x01000193)
93 signature = (hash >>> 0).toString(36)
94 signatureCache.set(png, signature)
95 }
96 return signature
97}
98
99export function base64Of(png: Uint8Array): string {
100 let base64 = base64Cache.get(png)
101 if (base64 === undefined) {
102 base64 = toBase64(png)
103 base64Cache.set(png, base64)
104 }
105 return base64
106}
107
108const NO_PNG = new Uint8Array(0)
109
110/**
111 * A plan's options for a block off screen: every formula measured (its rows
112 * and its slot reserved, as the full drawing has them) and none drawn; an
113 * image with no PNG is drawn as its Unicode (budget.ts's fallback), and an
114 * inline one leaves its preview, until the block comes on screen.
115 */
116export function reservedOptions(options: PlanOptions, renderEnv: RenderEnv): PlanOptions {
117 return {
118 ...options,
119 ...(options.draw
120 ? {
121 draw: (tex: string, rows?: number, maxColumns?: number) => {
122 const box = measureDisplay(tex, maxColumns === undefined ? renderEnv : { ...renderEnv, maxColumns })
123 return { columns: box.columns, rows: rows ?? box.rows, scale: box.scale, png: NO_PNG }
124 },
125 }
126 : {}),
127 ...(options.inline ? { inline: { ...options.inline, draw: (_tex: string, columns: number) => ({ columns, rows: 1, scale: 1, png: NO_PNG }) } } : {}),
128 }
129}
130
131/** How each picture's image is drawn again at fewer pixels (fitPictures). */
132export const pictureRedraws = new WeakMap<RenderedImage, (density: number) => RenderedImage>()
133
134/**
135 * A diagram's image `rows` tall (its own when not given), for the landing: as
136 * TexBook has it, or null / { error } (see PlanOptions.diagram). An image
137 * block's relative path resolves against `cwd`, its reply's own working
138 * directory where kept (ImageBook.place).
139 */
140export function diagramImage(source: string, kind: DiagramKind, env: PictureEnv, rows?: number, tex = true, cwd?: string): RenderedImage | { error: string } | null {
141 const files = imageBlockOf(source, kind)
142 if (files) return filesImage(imageBook.place(files, cwd), env, rows)
143 if (!tex) return null
144 const job = diagramJob(source, kind)
145 if (!job) return null
146 if ('refused' in job) return { error: job.refused }
147 const outcome = texBook.known(job.document)
148 if (!outcome || (!outcome.ok && !outcome.lasting)) {
149 texBook.ask(job.document)
150 return null
151 }
152 if (!outcome.ok) return { error: outcome.error }
153 try {
154 const key = `p\n${geometryKey(env)},${env.background ? [env.background.r, env.background.g, env.background.b].join(',') : ''}\n${rows ?? ''}\n${job.document.text}`
155 const image = cachedImage(key, () => renderPicture(outcome.picture, env, rows))
156 if (!pictureRedraws.has(image)) pictureRedraws.set(image, density => cachedImage(`${key}\n${density}`, () => renderPicture(outcome.picture, env, image.rows, density)))
157 return image
158 } catch (error) {
159 if (error instanceof TexError) return { error: error.message }
160 throw error
161 }
162}
163
164/** An image block's files drawn `rows` tall (their own when not given): as ImageBook has them, or null (those unread asked for, drawn once read) or { error }. */
165function filesImage(block: ImageBlock, env: PictureEnv, rows?: number): RenderedImage | { error: string } | null {
166 const outcome = imageBook.knownBlock(block)
167 if (!outcome) {
168 for (const image of blockImages(block)) {
169 const known = imageBook.known(image)
170 if (!known || (!known.ok && !known.lasting)) imageBook.ask(image)
171 }
172 return null
173 }
174 if (!outcome.ok) return { error: outcome.error }
175 try {
176 const background = env.background ? [env.background.r, env.background.g, env.background.b].join(',') : ''
177 const key = `f\n${geometryKey(env)},${background},${env.maxRows ?? ''}\n${rows ?? ''}\n${outcome.id}\n${JSON.stringify(block)}`
178 const image = cachedImage(key, () => renderImageBlock(outcome.sources, block, env, rows))
179 // Drawn again at fewer pixels (fitPictures) relative to the density it was drawn at: a photo is already below 1.
180 const drawnAt = 'density' in image && typeof image.density === 'number' ? image.density : 1
181 if (!pictureRedraws.has(image)) pictureRedraws.set(image, density => cachedImage(`${key}\n${density}`, () => renderImageBlock(outcome.sources, block, env, image.rows, density * drawnAt)))
182 return image
183 } catch (error) {
184 if (error instanceof TexError) return { error: error.message }
185 throw error
186 }
187}
188
189/** A formula MathJax refused, as TeX drew it (TexBook), or undefined: then wanted for the next draw. */
190function texDrawn(tex: string, display: boolean): ReturnType<typeof texResult> | undefined {
191 const document = mathJob(tex, display)
192 if (!document) return undefined
193 const outcome = texBook.known(document)
194 if (outcome?.ok) return texResult(outcome.picture)
195 if (!outcome || !outcome.lasting) texBook.ask(document)
196 return undefined
197}
198
199/** TeX's own error for a formula MathJax refused and TeX failed on for good (the note shows it, as the stream did). */
200function texRefusal(tex: string, display: boolean): TexError | undefined {
201 const document = mathJob(tex, display)
202 const outcome = document ? texBook.known(document) : undefined
203 return outcome && !outcome.ok && outcome.lasting ? new TexError(outcome.error) : undefined
204}
205hooks/cache.ts 200 lines1// kittex's image cache (the `cache` option): the drawing of a landed block
2// read back as LaTeX (a resumed session) kept on disk, so the next resume
3// draws it without typesetting: no MathJax at all when every block hits.
4//
5// Claude Code's $.store holds 4 MiB of JSON in all, too little, so the
6// entries are files: `<dir>/<key>.json` under
7// `${XDG_CACHE_HOME:-~/.cache}/kittex/v<CACHE_VERSION>/`, written with
8// $.fs.write (text: the PNGs go in base64) and read with $.fs.read. An entry's
9// key is a hash of everything that changes its pixels or its layout: the
10// block's text, the options, the cells and the reply's width, the ink and its
11// blending, the stroke weight, the baseline, how the engine draws links and
12// emoji, and kittex's build. Its text carries its own key and length, so a
13// file cut short by a concurrent write or a crash reads as a miss (and every
14// writer of one key writes the same bytes). This module is pure: register.tsx
15// does the I/O.
16import type { RenderedImage } from './core.js'
17import type { InlineImage, KittexEnv, MathOptions, Piece } from './math.ts'
18
19/** Bumped when an entry's layout changes: older entries live in another folder and are never read. */
20export const CACHE_VERSION = 1
21
22/** The cache's size cap, in bytes: past it, session.start removes the oldest entries. */
23export const CACHE_LIMIT_BYTES = 50 * 1024 * 1024
24
25/** What pruning keeps of the cap, so a session does not prune again at once. */
26export const CACHE_PRUNE_TO = 0.8
27
28/** How long a render waits for a cache read before it draws without it. */
29export const CACHE_READ_MS = 150
30
31/** An entry's file name: its key and `.json`; nothing else in the folder is ever read or removed. */
32export const ENTRY_NAME = /^[0-9a-z]{26}\.json$/
33/**
34 * What TeX drew (tex.ts): `<cache>/kittex/tex/<sha-256>.json`, pruned on its
35 * own past TEX_CACHE_LIMIT_BYTES. Its `fmt/` folder (the TeX format, about
36 * 11 MB) is neither counted nor removed here: prepareFormat replaces it when
37 * TeX's version changes.
38 */
39export const TEX_ENTRY_NAME = /^[0-9a-f]{64}\.json$/
40export const TEX_CACHE_LIMIT_BYTES = 20 * 1024 * 1024
41
42/** The folder entries go in: XDG_CACHE_HOME (absolute), else ~/.cache; undefined without either. */
43export function cacheDir(env: { XDG_CACHE_HOME?: string | undefined; HOME?: string | undefined }): string | undefined {
44 const xdg = env.XDG_CACHE_HOME
45 const base = xdg && xdg.startsWith('/') ? xdg : env.HOME && env.HOME.startsWith('/') ? `${env.HOME}/.cache` : undefined
46 return base ? `${base.replace(/\/+$/, '')}/kittex/v${CACHE_VERSION}` : undefined
47}
48
49/**
50 * The key of a block's drawing: a 128-bit hash (26 base-36 digits) of its
51 * text and of `facts`, everything else its drawing depends on (any JSON).
52 */
53export function entryKey(text: string, facts: unknown): string {
54 return hash128(`${CACHE_VERSION}\n${JSON.stringify(facts)}\n${text}`)
55}
56
57/** What a resumed block's drawing depends on besides its text (the key's facts): the build, the options, the reply's width, the cells and the text font, the ink and its blending, the weight, the prose width, links and emoji. */
58export function cacheFacts(env: KittexEnv, columns: number, math: MathOptions, build: string): unknown {
59 return {
60 build,
61 math,
62 columns,
63 cell: [env.cellWidth, env.cellHeight, env.emPx],
64 adjust: env.cellAdjust ?? null,
65 kitty: env.kittyAdjust ?? null,
66 font: env.font ?? null,
67 curve: env.inkCurve ?? null,
68 ink: [env.ink.r, env.ink.g, env.ink.b],
69 over: env.inkOver ? [env.inkOver.r, env.inkOver.g, env.inkOver.b] : null,
70 weight: env.weight ?? null,
71 prose: env.maxProseWidth ?? null,
72 links: env.hyperlinks ?? null,
73 emoji: env.emojiSequences ?? null,
74 }
75}
76
77/** An entry's file path. */
78export function entryPath(dir: string, key: string): string {
79 return `${dir}/${key}.json`
80}
81
82type StoredImage = { columns: number; rows: number; scale: number; png: string }
83type StoredPiece =
84 | { kind: 'prose'; text: string; gap: boolean; inline?: { tex: string; row: number; col: number; display?: true; image: StoredImage }[] }
85 | { kind: 'image'; tex: string; gap: boolean; image: StoredImage }
86 | { kind: 'note'; text: string; gap: boolean }
87
88/** A drawing as an entry's text. `base64` gives a PNG's base64 (the one the Image is sent with). */
89export function encodeEntry(key: string, pieces: readonly Piece[], base64: (png: Uint8Array) => string): string {
90 const image = (one: RenderedImage): StoredImage => ({ columns: one.columns, rows: one.rows, scale: one.scale, png: base64(one.png) })
91 const stored: StoredPiece[] = pieces.map(piece =>
92 piece.kind === 'image'
93 ? { kind: 'image', tex: piece.tex, gap: piece.gap, image: image(piece.image) }
94 : piece.kind === 'note'
95 ? { kind: 'note', text: piece.text, gap: piece.gap }
96 : { kind: 'prose', text: piece.text, gap: piece.gap, ...(piece.inline ? { inline: piece.inline.map(one => ({ tex: one.tex, row: one.row, col: one.col, ...(one.display ? { display: true as const } : {}), image: image(one.image) })) } : {}) },
97 )
98 const body = JSON.stringify(stored)
99 return `${JSON.stringify({ kittex: CACHE_VERSION, key, length: body.length })}\n${body}`
100}
101
102/**
103 * The drawing an entry's text holds, or null when the text is not a whole
104 * entry for `key` (another version, cut short, garbled). `remember` is told
105 * each PNG with its base64, so the Image is sent without encoding it again.
106 */
107export function decodeEntry(text: string, key: string, remember?: (png: Uint8Array, base64: string) => void): Piece[] | null {
108 try {
109 const cut = text.indexOf('\n')
110 if (cut < 0) return null
111 const head = JSON.parse(text.slice(0, cut)) as { kittex?: unknown; key?: unknown; length?: unknown }
112 const body = text.slice(cut + 1)
113 if (head.kittex !== CACHE_VERSION || head.key !== key || head.length !== body.length) return null
114 const stored = JSON.parse(body) as StoredPiece[]
115 if (!Array.isArray(stored)) return null
116 const image = (one: StoredImage): RenderedImage => {
117 if (!isCells(one.columns) || !isCells(one.rows) || typeof one.scale !== 'number' || typeof one.png !== 'string') throw new Error('bad image')
118 const png = fromBase64(one.png)
119 // The engine refuses a whole drawing over one PNG without its signature and IHDR.
120 if (!isPng(png)) throw new Error('not a PNG')
121 remember?.(png, one.png)
122 return { columns: one.columns, rows: one.rows, scale: one.scale, png }
123 }
124 return stored.map((piece): Piece => {
125 if (typeof piece?.gap !== 'boolean') throw new Error('bad piece')
126 if (piece.kind === 'image') {
127 if (typeof piece.tex !== 'string') throw new Error('bad piece')
128 return { kind: 'image', tex: piece.tex, gap: piece.gap, image: image(piece.image) }
129 }
130 if (typeof piece.text !== 'string') throw new Error('bad piece')
131 if (piece.kind === 'note') return { kind: 'note', text: piece.text, gap: piece.gap }
132 if (piece.kind !== 'prose') throw new Error('bad piece')
133 if (piece.inline === undefined) return { kind: 'prose', text: piece.text, gap: piece.gap }
134 if (!Array.isArray(piece.inline)) throw new Error('bad piece')
135 const inline: InlineImage[] = piece.inline.map(one => {
136 if (typeof one?.tex !== 'string' || !Number.isInteger(one.row) || !Number.isInteger(one.col)) throw new Error('bad inline')
137 return { tex: one.tex, row: one.row, col: one.col, ...(one.display === true ? { display: true as const } : {}), image: image(one.image) }
138 })
139 return { kind: 'prose', text: piece.text, gap: piece.gap, inline }
140 })
141 } catch {
142 return null
143 }
144}
145
146const SIGNATURE = [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]
147const isPng = (png: Uint8Array) => png.length >= 33 && SIGNATURE.every((byte, i) => png[i] === byte) && String.fromCharCode(...png.subarray(12, 16)) === 'IHDR'
148
149const isCells = (n: unknown): n is number => Number.isInteger(n) && (n as number) >= 1 && (n as number) <= 255
150
151/** One file of the cache folder, as $.fs.list gives it. */
152export interface CacheFile {
153 name: string
154 kind: string
155 size: number
156 mtimeMs: number
157}
158
159/**
160 * The entries to remove so the folder holds at most `limit` bytes: none
161 * while it fits, else the oldest (by mtime) until it holds CACHE_PRUNE_TO of
162 * it. Only entry files (`name`: ENTRY_NAME, or TEX_ENTRY_NAME in TeX's
163 * folder) count and are ever named: never a folder, never the TeX format.
164 */
165export function pruneList(files: readonly CacheFile[], limit = CACHE_LIMIT_BYTES, name: RegExp = ENTRY_NAME): string[] {
166 const entries = files.filter(file => file.kind === 'file' && name.test(file.name))
167 let total = entries.reduce((sum, file) => sum + file.size, 0)
168 if (total <= limit) return []
169 const out: string[] = []
170 for (const file of [...entries].sort((a, b) => a.mtimeMs - b.mtimeMs || (a.name < b.name ? -1 : 1))) {
171 if (total <= limit * CACHE_PRUNE_TO) break
172 out.push(file.name)
173 total -= file.size
174 }
175 return out
176}
177
178/** A 128-bit hash of `text` as 26 base-36 digits: four 32-bit FNV-1a lanes, each seeded apart and mixed. */
179export function hash128(text: string): string {
180 const bytes = new TextEncoder().encode(text)
181 const seeds = [0x811c9dc5, 0x01000193 ^ 0x9e3779b9, 0x85ebca6b, 0xc2b2ae35]
182 const lanes = seeds.map(seed => {
183 let h = seed >>> 0
184 for (let i = 0; i < bytes.length; i++) h = Math.imul(h ^ bytes[i]!, 0x01000193)
185 // A final mix, so the lanes differ in every bit.
186 h ^= h >>> 16
187 h = Math.imul(h, 0x85ebca6b)
188 h ^= h >>> 13
189 h = Math.imul(h, seed | 1)
190 h ^= h >>> 16
191 return BigInt(h >>> 0)
192 })
193 const value = (lanes[0]! << 96n) | (lanes[1]! << 64n) | (lanes[2]! << 32n) | lanes[3]!
194 return value.toString(36).padStart(26, '0')
195}
196
197function fromBase64(text: string): Uint8Array {
198 return (Uint8Array as unknown as { fromBase64(text: string): Uint8Array }).fromBase64(text)
199}
200hooks/schedule.ts 63 lines1// The order landed blocks are typeset in. After --resume the engine asks for
2// a drawing of every block it lays out at once (the last 18 of a 100-reply
3// session in the fullscreen layout, the last 67 on the main screen), oldest
4// first, and the worker typesets one at a time: the newest blocks, the ones
5// on screen, came last. Here a block that has to be typeset waits its turn,
6// newest first, so the bottom of the screen is final first.
7//
8// Pure. A turn taken while the queue is idle first lets the rest of a wave
9// arrive: `gather` is a round trip the caller makes for that (register.tsx:
10// a state read, a hop to the engine and back), done GATHER_HOPS times, so no
11// clock is needed (a mocked or missing one would stall the queue).
12
13/** Round trips a turn taken on an idle queue waits for the rest of its wave. */
14export const GATHER_HOPS = 2
15
16export interface Turns {
17 /** Resolves when it is this caller's turn; call the release it gives once its work is done (a second call does nothing). */
18 take(gather?: () => Promise<unknown>): Promise<() => void>
19 /** Callers waiting (not counting the one at work). */
20 readonly waiting: number
21}
22
23export function newestFirst(): Turns {
24 const stack: (() => void)[] = []
25 let busy = false
26 let gathering = false
27 const pump = () => {
28 if (busy || gathering) return
29 const next = stack.pop()
30 if (!next) return
31 busy = true
32 next()
33 }
34 return {
35 async take(gather) {
36 const turn = new Promise<() => void>(resolve => {
37 let released = false
38 stack.push(() =>
39 resolve(() => {
40 if (released) return
41 released = true
42 busy = false
43 pump()
44 }),
45 )
46 })
47 if (!busy && !gathering && gather) {
48 gathering = true
49 try {
50 for (let hop = 0; hop < GATHER_HOPS; hop++) await gather().catch(() => undefined)
51 } finally {
52 gathering = false
53 }
54 }
55 pump()
56 return turn
57 },
58 get waiting() {
59 return stack.length
60 },
61 }
62}
63hooks/tex.ts 803 lines1// The local LaTeX, for what MathJax can't draw: diagrams (TikZ, pgfplots,
2// chemfig, circuitikz, tikz-cd) and math MathJax refuses (siunitx's \unit,
3// \qty...). Nothing here takes `$`: register.tsx hands a TexHost of closures
4// over session.start's `$` (a compile may outlive the dispatch that asked for
5// it). core/src/diagram/tex.ts has the documents, the commands and the threat
6// model; this file runs them, remembers what they gave, and caches it on disk.
7//
8// The order is the approved one: MathJax first for everything it draws (it
9// takes milliseconds and lets the stream reserve exact rows), the local TeX
10// only for what it refuses, and the source (or Unicode) when TeX fails too.
11
12import {
13 confined,
14 diagramDocument,
15 drawsPicture,
16 dvisvgmArgv,
17 FORMAT_SOURCE,
18 formatArgv,
19 formatName,
20 inlineTables,
21 isJobDir,
22 latexArgv,
23 JOB_NAME,
24 jobDirTemplate,
25 LATEX_ARGV,
26 mathDocument,
27 PDF_NAME,
28 pdfArgv,
29 pdfCopyArgv,
30 PREAMBLE_VERSION,
31 SvgError,
32 TRIAL_PDF,
33 texEnvironment,
34 texError,
35 texFormula,
36 texPicture,
37 ulimitProbe,
38 unsafeTex,
39 XmlError,
40} from './core.js'
41import type { Confinement, PdfConverter, Picture, TexDocument, TypesetResult } from './core.js'
42
43/** What a compile gave: the picture, or why there is none. */
44export type TexOutcome =
45 | { ok: true; picture: Picture }
46 /** `lasting`: TeX's own answer (an error in the source), kept on disk; else (a timeout, a missing command) it may be tried again. */
47 | { ok: false; error: string; lasting: boolean }
48
49/** What a TeX run needs from the host: commands, and text files (register.tsx backs these with `$`). */
50export interface TexHost {
51 run(argv: readonly string[], init: { cwd?: string; env?: Record<string, string>; timeoutMs: number }): Promise<{ exitCode: number; stdout: string; stderr: string; isStdoutTruncated: boolean }>
52 write(path: string, text: string): Promise<void>
53 read(path: string): Promise<string | undefined>
54 /** A file's bytes (the DVI, for its specials), or undefined when it can't be read; absent: never read. */
55 readBytes?(path: string): Promise<Uint8Array | undefined>
56}
57
58/** The host as found at session start: TeX's commands are there, and how jobs are confined. */
59export interface TexSetup {
60 /** `latex --version`'s and `dvisvgm --version`'s first lines: they key the disk cache with the preamble version. */
61 versions: string
62 confinement: Confinement
63 /** The host's temporary directory (TMPDIR), where each job gets a directory of its own. */
64 tmpdir: string | undefined
65 /** Where outcomes are cached across sessions; absent: not cached on disk. */
66 cacheDir?: string
67 /** The dumped fragment format (prepareFormat), once it is there: its name and the directory holding `<name>.fmt`. */
68 format?: { name: string; dir: string }
69 /**
70 * False where dvisvgm has no `--libgs` (built with Ghostscript linked in or
71 * left out, as Arch's, Debian's and Fedora's are): it refuses the option,
72 * so jobs run without it. Absent: dvisvgm takes it (TeX Live's own build).
73 */
74 libgs?: false
75 /**
76 * True where dvisvgm has Ghostscript linked in and can't be told to ignore
77 * PostScript (3.5 to 3.6.1 read `--no-specials=<list>` wrongly and ignore
78 * nothing): it runs every PostScript special through Ghostscript, which it
79 * starts with -dDELAYSAFER and never makes safe. kittex's own documents
80 * carry none; a document that does is refused unless bubblewrap confines
81 * the job.
82 */
83 postscript?: true
84 /**
85 * The converter whose trial conversion of a tiny PDF (TRIAL_PDF) drew it,
86 * the first of pdfConverters: mutool, else dvisvgm with Ghostscript inside
87 * bubblewrap. Absent: PDFs are not drawn here.
88 */
89 pdf?: PdfConverter
90 /** With bubblewrap: what its namespace must still show (the TeX trees and programs it hides) and the PATH jobs run with. */
91 sandbox?: Sandbox
92}
93
94/** What a job's namespace binds back read-only, and the PATH TeX is found by inside it. */
95export interface Sandbox {
96 /** Directories and files TeX needs that lie in a hidden directory (TeX Live installed into the home folder): bound read-only, nothing more. */
97 binds: string[]
98 /** PATH with latex's and dvisvgm's own directories first, so the namespace finds them where a hidden link would have; absent: the host's. */
99 path?: string
100}
101
102/** Whether a job's sandbox runs TeX here, and if not, why (the first line its trial printed). */
103export type SandboxProbe = { ok: true; sandbox: Sandbox } | { ok: false; error: string }
104
105/** Where MacTeX and BasicTeX link TeX's programs (/etc/paths.d/TeX puts it on a login shell's PATH). */
106export const MACTEX_BIN = '/Library/TeX/texbin'
107
108/**
109 * The PATH TeX's commands run with on macOS: the host's with MacTeX's
110 * folder after its own, where it lacks it (a terminal started from the Dock
111 * or Spotlight, a shell config that sets PATH outright, TeX installed after
112 * the shell started), so a MacTeX that is there is found. Undefined where
113 * the host's PATH is used as it is (it has the folder, or not macOS).
114 */
115export function texPath(path: string | undefined, platform: string | undefined): string | undefined {
116 if (platform !== 'darwin') return undefined
117 const dirs = (path ?? '').split(':').filter(Boolean)
118 if (dirs.some(dir => dir.replace(/\/+$/, '') === MACTEX_BIN)) return undefined
119 return [...(dirs.length > 0 ? dirs : ['/usr/bin', '/bin', '/usr/sbin', '/sbin']), MACTEX_BIN].join(':')
120}
121
122/** The host with its commands run on `path` (texPath), unless a command sets its own PATH (bubblewrap's). */
123export function onPath<H extends TexHost>(host: H, path: string | undefined): H {
124 if (path === undefined) return host
125 return { ...host, run: (argv, init) => host.run(argv, { ...init, env: { PATH: path, ...init.env } }) }
126}
127
128/** How long a probe command may run. */
129const PROBE_MS = 3000
130/** How long a stream holds a diagram (or a formula MathJax refused) for TeX before it shows the source. */
131export const TEX_STREAM_BUDGET_MS = 3000
132/** How long a compile in the background (a landed block's, after --resume) may run. */
133export const TEX_BACKGROUND_MS = 20_000
134/** Compiles that run at once (each is one TeX process, then one dvisvgm). */
135const MAX_COMPILES = 3
136/** Outcomes kept in memory. */
137const BOOK_LIMIT = 256
138
139/**
140 * Finds TeX: `latex` and `dvisvgm` answering `--version`, and what jobs can
141 * be confined with: prlimit, and bubblewrap where TeX runs inside its
142 * namespace (probeSandbox: a real trial, not a bare `true`), else none.
143 * Undefined when either command is missing.
144 */
145export async function probeTex(host: TexHost, options: { tmpdir: string | undefined; hide: readonly string[]; cacheDir?: string; path?: string }): Promise<TexSetup | undefined> {
146 const ok = (argv: readonly string[]) =>
147 host.run(argv, { timeoutMs: PROBE_MS }).then(
148 result => (result.exitCode === 0 ? result.stdout : undefined),
149 () => undefined,
150 )
151 const [latex, dvisvgm, help, extended, prlimit] = await Promise.all([
152 ok(['latex', '--version']),
153 ok(['dvisvgm', '--version']),
154 ok(['dvisvgm', '--help']),
155 ok(['dvisvgm', '-V1']),
156 ok(['prlimit', '--version']),
157 ])
158 if (latex === undefined || dvisvgm === undefined) return undefined
159 // No prlimit (macOS has none): the same limits through sh's ulimit.
160 const ulimit = prlimit === undefined && (await ok(ulimitProbe())) !== undefined
161 const sandbox = options.hide.length > 0 ? await probeSandbox(host, { hide: options.hide, tmpdir: options.tmpdir, path: options.path, prlimit: prlimit !== undefined }) : undefined
162 const first = (text: string) => text.split('\n', 1)[0]!.trim()
163 const setup: TexSetup = {
164 versions: `${first(latex)}\n${first(dvisvgm)}`,
165 confinement: { prlimit: prlimit !== undefined, ...(ulimit ? { ulimit: true as const } : {}), ...(sandbox?.ok ? { bwrap: { hide: options.hide } } : {}) },
166 tmpdir: options.tmpdir,
167 ...(options.cacheDir !== undefined ? { cacheDir: options.cacheDir } : {}),
168 ...(help !== undefined && !takesLibgs(help) ? { libgs: false as const } : {}),
169 ...(help !== undefined && !takesLibgs(help) && runsPostScript(first(dvisvgm), extended) ? { postscript: true as const } : {}),
170 ...(sandbox?.ok ? { sandbox: sandbox.sandbox } : {}),
171 }
172 const pdf = await probePdf(host, setup)
173 if (pdf.ok) setup.pdf = pdf.converter
174 return setup
175}
176
177// ─── PDF images ──────────────────────────────────────────────────────────────
178
179/**
180 * The converters this host may try, in order: mutool everywhere, then
181 * dvisvgm with Ghostscript only inside bubblewrap, since dvisvgm runs
182 * Ghostscript without -dSAFER (see core/src/diagram/tex.ts).
183 */
184export function pdfConverters(setup: Pick<TexSetup, 'confinement'>): PdfConverter[] {
185 return setup.confinement.bwrap ? ['mutool', 'ghostscript'] : ['mutool']
186}
187
188/** `converter` on the PDF already in the job directory `dir`, confined as TeX's jobs are, read into a Picture. */
189async function convertPdf(host: TexHost, setup: TexSetup, converter: PdfConverter, dir: string, timeoutMs: number): Promise<TexOutcome> {
190 const jail = sandboxed(setup)
191 let svg
192 try {
193 svg = await host.run(confined(pdfArgv(converter, dir), dir, setup.confinement, jail.binds), { cwd: dir, env: { ...texEnvironment(dir), ...jail.env }, timeoutMs: Math.max(1, timeoutMs) })
194 } catch {
195 return { ok: false, error: `the PDF took longer than ${(timeoutMs / 1000).toFixed(0)} s`, lasting: false }
196 }
197 if (svg.exitCode !== 0 || svg.isStdoutTruncated || !svg.stdout.includes('<svg')) {
198 return { ok: false, error: svg.isStdoutTruncated ? 'the picture is too large' : firstLine(svg.stderr) || `${converter === 'mutool' ? 'mutool' : 'dvisvgm'} failed`, lasting: true }
199 }
200 try {
201 return { ok: true, picture: texPicture(svg.stdout, { baseline: 'bottom', fontSize: 10 }) }
202 } catch (error) {
203 if (error instanceof SvgError || error instanceof XmlError) return { ok: false, error: error.message, lasting: true }
204 throw error
205 }
206}
207
208/** A fresh job directory for `body`, removed after it. */
209async function inJob(host: TexHost, setup: Pick<TexSetup, 'tmpdir'>, body: (dir: string) => Promise<TexOutcome>): Promise<TexOutcome> {
210 const made = await host.run(['mktemp', '-d', jobDirTemplate(setup.tmpdir)], { timeoutMs: PROBE_MS }).catch(() => undefined)
211 const dir = made?.stdout.trim() ?? ''
212 if (made?.exitCode !== 0 || !isJobDir(dir)) return { ok: false, error: 'no temporary directory for the PDF', lasting: false }
213 try {
214 return await body(dir)
215 } finally {
216 await host.run(['rm', '-rf', '--', dir], { timeoutMs: PROBE_MS }).catch(() => undefined)
217 }
218}
219
220/**
221 * The first page of the PDF at `path` (absolute) as a Picture, in em at 10 pt
222 * (its natural size), within `timeoutMs`: copied into a job directory under
223 * the job's limits, checked to be a PDF, converted by setup.pdf (convertPdf).
224 * Refused where the trial set no converter.
225 */
226export async function pdfPicture(host: TexHost, setup: TexSetup, path: string, timeoutMs: number): Promise<TexOutcome> {
227 const converter = setup.pdf
228 if (converter === undefined) return { ok: false, error: 'PDF not drawn: nothing converts PDF here (it needs mutool, or Ghostscript 9.50 to 10.0 inside bubblewrap)', lasting: true }
229 if (!path.startsWith('/') || path.includes('\n')) return { ok: false, error: 'PDF not drawn: its path is not absolute', lasting: true }
230 const deadline = Date.now() + timeoutMs
231 const late: TexOutcome = { ok: false, error: `the PDF took longer than ${(timeoutMs / 1000).toFixed(0)} s`, lasting: false }
232 return inJob(host, setup, async dir => {
233 const left = () => deadline - Date.now()
234 if (left() < 50) return late
235 const copied = await host.run(pdfCopyArgv(path, dir, setup.confinement), { cwd: dir, timeoutMs: Math.max(1, Math.min(left(), PDF_COPY_MS)) }).catch(() => undefined)
236 if (!copied) return late
237 if (copied.exitCode !== 0) return { ok: false, error: `PDF not drawn: ${firstLine(copied.stderr) || 'it could not be read'}`, lasting: false }
238 // Only a PDF goes to the converter (Ghostscript would run a PostScript file as a program, and mutool opens other formats too).
239 const head = await host.run(['head', '-c', '1024', '--', `${dir}/${PDF_NAME}`], { timeoutMs: PROBE_MS }).catch(() => undefined)
240 if (!head?.stdout.includes('%PDF-')) return { ok: false, error: 'PDF not drawn: the file is not a PDF', lasting: true }
241 if (left() < 50) return late
242 return convertPdf(host, setup, converter, dir, left())
243 })
244}
245
246/** How long copying a PDF into its job may take (it stops at MAX_OUTPUT_BYTES anyway). */
247const PDF_COPY_MS = 10_000
248
249/**
250 * The trial conversion (TRIAL_PDF, as pdfPicture converts) with each of
251 * pdfConverters in turn: the first that draws it, else why each did not.
252 */
253export async function probePdf(host: TexHost, setup: TexSetup): Promise<{ ok: true; converter: PdfConverter } | { ok: false; error: string }> {
254 const errors: string[] = []
255 for (const converter of pdfConverters(setup)) {
256 const outcome = await inJob(host, setup, async dir => {
257 await host.write(`${dir}/${PDF_NAME}`, TRIAL_PDF)
258 return convertPdf(host, setup, converter, dir, PROBE_MS)
259 }).catch((error: unknown): TexOutcome => ({ ok: false, error: String(error), lasting: false }))
260 const error = !outcome.ok ? outcome.error : outcome.picture.ops.some(op => op.type === 'fill' && op.paint.color.b === 255) ? undefined : 'the trial PDF drew nothing'
261 if (error === undefined) return { ok: true, converter }
262 errors.push(error)
263 }
264 if (errors.length === 1) return { ok: false, error: errors[0]! }
265 return { ok: false, error: pdfConverters(setup).map((converter, i) => `${PDF_CONVERTER_NAMES[converter]}: ${errors[i]}`).join('; ') }
266}
267
268/** How the doctor and the trial's errors name each converter. */
269export const PDF_CONVERTER_NAMES: Record<PdfConverter, string> = { mutool: 'mutool', ghostscript: 'dvisvgm with Ghostscript' }
270
271/**
272 * Whether a dvisvgm without --libgs hands PostScript specials to Ghostscript
273 * whatever --no-specials says: Ghostscript linked in (`-V1` names it) and a
274 * version whose list parsing ignores nothing (3.5 to 3.6.1, fixed after).
275 */
276export function runsPostScript(version: string, extended: string | undefined): boolean {
277 const m = /(\d+)\.(\d+)(?:\.(\d+))?/.exec(version)
278 if (!m || !/^Ghostscript:/m.test(extended ?? '')) return false
279 const v = Number(m[1]) * 10_000 + Number(m[2]) * 100 + Number(m[3] ?? 0)
280 return v >= 30_500 && v <= 30_601
281}
282
283/** The special prefixes dvisvgm's PostScript handler takes (PsSpecialHandler::prefixes). */
284const POSTSCRIPT_PREFIXES = new Set(['header=', 'pdffile=', 'psfile=', 'PSfile=', 'ps:', 'ps::', '!', '"', 'pst:', 'PST:'])
285
286/** A special's prefix as dvisvgm reads it: letters and digits, then one punctuation character (`ps::` whole). */
287function specialPrefix(text: string): string {
288 const m = /^[A-Za-z0-9]*/.exec(text)!
289 let prefix = m[0]
290 const next = text[prefix.length]
291 if (next !== undefined && /[!-/:-@[-`{-~]/.test(next)) prefix += next
292 if (prefix === 'ps:' && text[3] === ':') prefix += ':'
293 return prefix
294}
295
296/**
297 * The specials a DVI file holds, in order (a walk over its commands from the
298 * preamble to the postamble); undefined when the bytes aren't a DVI file.
299 */
300export function dviSpecials(bytes: Uint8Array): string[] | undefined {
301 const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength)
302 const n = (at: number, size: number) => (size === 1 ? view.getUint8(at) : size === 2 ? view.getUint16(at) : size === 3 ? (view.getUint16(at) << 8) | view.getUint8(at + 2) : view.getUint32(at))
303 const out: string[] = []
304 let at = 0
305 try {
306 if (view.getUint8(0) !== 247) return undefined
307 at = 15 + view.getUint8(14)
308 while (at < bytes.length) {
309 const op = view.getUint8(at++)
310 if (op <= 127 || (op >= 171 && op <= 234) || op === 138 || op === 140 || op === 141 || op === 142 || op === 147 || op === 152 || op === 161 || op === 166) continue
311 if (op >= 128 && op <= 131) at += op - 127
312 else if (op === 132 || op === 137) at += 8
313 else if (op >= 133 && op <= 136) at += op - 132
314 else if (op === 139) at += 44
315 else if (op >= 143 && op <= 146) at += op - 142
316 else if (op >= 148 && op <= 151) at += op - 147
317 else if (op >= 153 && op <= 156) at += op - 152
318 else if (op >= 157 && op <= 160) at += op - 156
319 else if (op >= 162 && op <= 165) at += op - 161
320 else if (op >= 167 && op <= 170) at += op - 166
321 else if (op >= 235 && op <= 238) at += op - 234
322 else if (op >= 239 && op <= 242) {
323 const size = op - 238
324 const length = n(at, size)
325 at += size
326 let text = ''
327 for (const byte of bytes.subarray(at, at + length)) text += String.fromCharCode(byte)
328 out.push(text)
329 at += length
330 } else if (op >= 243 && op <= 246) {
331 at += op - 242 + 12
332 const a = view.getUint8(at)
333 const l = view.getUint8(at + 1)
334 at += 2 + a + l
335 } else if (op === 248) return out
336 else return undefined
337 }
338 } catch {
339 return undefined
340 }
341 return undefined
342}
343
344/** Whether any of these specials is PostScript (dvisvgm would hand it to Ghostscript). */
345export function hasPostScript(specials: readonly string[]): boolean {
346 return specials.some(special => POSTSCRIPT_PREFIXES.has(specialPrefix(special.trimStart())))
347}
348
349/** The kpathsea variables naming every tree TeX reads: its root (programs, texmf.cnf), the search path, the config path. */
350const TEX_TREES = '-expand-braces=$TEXMFROOT:$TEXMF:$TEXMFCNF'
351
352/**
353 * Whether TeX runs inside bubblewrap's namespace here, and what that needs:
354 * the TeX trees (kpsewhich, as a job's environment sees them), latex's and
355 * dvisvgm's real files and the libraries they load, each bound read-only
356 * where it lies in a hidden directory (never a hidden directory itself), and
357 * latex's and dvisvgm's directories first on PATH. The trial runs latex
358 * (its format loaded) and dvisvgm in that namespace, as a job does.
359 */
360export async function probeSandbox(host: TexHost, options: { hide: readonly string[]; tmpdir: string | undefined; path?: string; prlimit: boolean }): Promise<SandboxProbe> {
361 const run = (argv: readonly string[], init: { cwd?: string; env?: Record<string, string> } = {}) =>
362 host.run(argv, { ...init, timeoutMs: PROBE_MS }).catch(() => undefined)
363 const lines = (text: string | undefined) => (text ?? '').split('\n').map(line => line.trim()).filter(Boolean)
364 const dirs = (options.path ?? '').split(':').filter(dir => dir.startsWith('/')).map(dir => dir.replace(/\/+$/, '') || '/')
365 // The first latex and dvisvgm on PATH, links resolved (realpath prints only the ones there, in order).
366 const find = async (name: string) => (dirs.length > 0 ? lines((await run(['realpath', '-e', '--', ...dirs.map(dir => `${dir}/${name}`)]))?.stdout)[0] : undefined)
367 const placeholder = `${jobDirTemplate(options.tmpdir).replace(/\.X+$/, '')}.probe`
368 const [latex, dvisvgm, trees, hidden] = await Promise.all([
369 find('latex'),
370 find('dvisvgm'),
371 run(['kpsewhich', TEX_TREES], { env: texEnvironment(placeholder) }),
372 run(['realpath', '-m', '--', ...options.hide]),
373 ])
374 const programs = [latex, dvisvgm].filter((one): one is string => one !== undefined)
375 const libraries = await Promise.all(programs.map(program => run(['ldd', program])))
376 const candidates = [
377 ...programs.map(program => program.replace(/\/[^/]+$/, '')),
378 ...(trees?.exitCode === 0 ? trees.stdout.trim().split(':') : []).map(tree => tree.replace(/^!!/, '').replace(/\/+$/, '')),
379 ...libraries.flatMap(result => lines(result?.stdout).flatMap(line => /(?:=>\s*)?(\/[^\s()]+)\s*\(0x/.exec(line)?.[1] ?? [])),
380 ].filter(path => path.startsWith('/'))
381 const real = candidates.length > 0 ? lines((await run(['realpath', '-e', '--', ...new Set(candidates)]))?.stdout) : []
382 const hide = [...new Set([...options.hide, ...lines(hidden?.stdout)])]
383 const binds = sandboxBinds(real, hide)
384 const bin = [...new Set(programs.map(program => program.replace(/\/[^/]+$/, '')))]
385 const sandbox: Sandbox = { binds, ...(options.path !== undefined ? { path: [...new Set([...bin, ...dirs])].join(':') } : {}) }
386 // The trial: latex with its format and dvisvgm, in the namespace a job gets.
387 const made = await run(['mktemp', '-d', jobDirTemplate(options.tmpdir)])
388 const job = made?.stdout.trim() ?? ''
389 if (made?.exitCode !== 0 || !isJobDir(job)) return { ok: false, error: 'no temporary directory for the trial' }
390 try {
391 const confinement: Confinement = { prlimit: options.prlimit, bwrap: { hide: options.hide } }
392 const env = { ...texEnvironment(job), ...(sandbox.path ? { PATH: sandbox.path } : {}) }
393 for (const argv of [['latex', '-no-shell-escape', '-interaction=nonstopmode', '-halt-on-error', '\\stop'], ['dvisvgm', '--version']]) {
394 const result = await run(confined(argv, job, confinement, binds), { cwd: job, env })
395 if (result?.exitCode !== 0) {
396 const said = lines(result?.stderr)[0] ?? lines(result?.stdout).find(line => line.startsWith('!'))
397 return { ok: false, error: `${argv[0]} in the sandbox: ${said ?? (result ? `exit ${result.exitCode}` : 'did not run')}`.slice(0, 200) }
398 }
399 }
400 return { ok: true, sandbox }
401 } finally {
402 await run(['rm', '-rf', '--', job])
403 }
404}
405
406/**
407 * The paths a job's namespace binds back: those of `paths` that lie inside a
408 * hidden directory (never one of them, nor anything holding one), each once
409 * (none inside another).
410 */
411export function sandboxBinds(paths: readonly string[], hide: readonly string[]): string[] {
412 const inside = (path: string, dir: string) => path.startsWith(`${dir.replace(/\/+$/, '')}/`)
413 const under = [...new Set(paths)].filter(path => hide.some(dir => inside(path, dir)) && !hide.some(dir => dir === path || inside(dir, path)))
414 return under.filter(path => !under.some(other => other !== path && inside(path, other))).sort()
415}
416
417/** The extra paths every confined command of a job binds back, and the variables it runs with (a sandbox's PATH). */
418function sandboxed(setup: Pick<TexSetup, 'confinement' | 'sandbox'>): { binds: string[]; env: Record<string, string> } {
419 const jailed = setup.confinement.bwrap !== undefined
420 return { binds: jailed ? (setup.sandbox?.binds ?? []) : [], env: jailed && setup.sandbox?.path ? { PATH: setup.sandbox.path } : {} }
421}
422
423/** Whether `dvisvgm --help` lists `--libgs`; a help that isn't dvisvgm's (no `--no-specials`) counts as yes. */
424export function takesLibgs(help: string): boolean {
425 return !/--no-specials\b/.test(help) || /--libgs\b/.test(help)
426}
427
428/** dvisvgm on a job in `dir`, as this host's dvisvgm takes it (without `--libgs` where it has none). */
429export function dvisvgmCommand(dir: string, setup: Pick<TexSetup, 'libgs'>): string[] {
430 const argv = dvisvgmArgv(dir)
431 return setup.libgs === false ? argv.filter(arg => !arg.startsWith('--libgs=')) : argv
432}
433
434/**
435 * The directories a confined job can't see: the home directory and the
436 * temporary ones (a job's own directory is bound back inside). Only absolute
437 * paths that are no system root.
438 */
439export function hiddenDirs(home: string | undefined, tmpdir: string | undefined): string[] {
440 const dirs = [home, '/tmp', '/var/tmp', '/run', tmpdir]
441 return [...new Set(dirs.filter((dir): dir is string => dir !== undefined && /^\/[^\s]+$/.test(dir) && !['/', '/usr', '/etc', '/opt', '/bin', '/lib', '/nix'].includes(dir.replace(/\/+$/, ''))).map(dir => dir.replace(/\/+$/, '')))]
442}
443
444/** The disk cache's directory: XDG_CACHE_HOME's (or ~/.cache's) kittex/tex. */
445export function texCacheDir(env: { XDG_CACHE_HOME?: string | undefined; HOME?: string | undefined }): string | undefined {
446 const base = env.XDG_CACHE_HOME?.startsWith('/') ? env.XDG_CACHE_HOME : env.HOME?.startsWith('/') ? `${env.HOME}/.cache` : undefined
447 return base === undefined ? undefined : `${base.replace(/\/+$/, '')}/kittex/tex`
448}
449
450/**
451 * Compiles documents and remembers what they gave, by document: the stream
452 * and the landing read outcomes from here synchronously (`known`), and ask
453 * for the ones missing (`compile`), MAX_COMPILES at a time, each document
454 * compiled once however many ask.
455 */
456export class TexBook {
457 private readonly outcomes = new Map<string, TexOutcome>()
458 private readonly running = new Map<string, Promise<TexOutcome>>()
459 /** Compiles running now, and those waiting for one of them to end (at most MAX_COMPILES at once). */
460 private active = 0
461 private readonly waiting: (() => void)[] = []
462 /** Documents the stream showed as source (TeX too slow): left as source when their block lands, though TeX finished later. */
463 private readonly shownAsSource = new Set<string>()
464 /** Documents a landing asked for that TeX hasn't drawn yet (drawn later, then the blocks redraw). */
465 private readonly asked = new Map<string, TexDocument>()
466 host: TexHost | undefined
467 setup: TexSetup | undefined
468 /**
469 * The setup an earlier session found (rememberedTex): its versions key the
470 * disk cache, so the pictures it compiled are read with it before TeX is
471 * probed (a resume draws them from its first render), and once TeX is gone.
472 */
473 cached: TexSetup | undefined
474
475 /** A landing wants this document drawn (a reply read back after --resume): kept until takeAsked. Not one shown as source. */
476 ask(document: TexDocument): void {
477 if (this.drawable && !this.shownAsSource.has(document.text) && this.asked.size < BOOK_LIMIT) this.asked.set(document.text, document)
478 }
479
480 /** The documents asked for since the last take. */
481 takeAsked(): TexDocument[] {
482 const documents = [...this.asked.values()]
483 this.asked.clear()
484 return documents
485 }
486
487 /** Forgets everything (a new host, tests). */
488 reset(host?: TexHost, setup?: TexSetup): void {
489 this.outcomes.clear()
490 this.running.clear()
491 this.shownAsSource.clear()
492 this.asked.clear()
493 this.active = 0
494 this.waiting.length = 0
495 this.host = host
496 this.setup = setup
497 this.cached = undefined
498 }
499
500 /** TeX is there to ask. */
501 get ready(): boolean {
502 return this.host !== undefined && this.setup !== undefined
503 }
504
505 /** Pictures can be shown: TeX is there, or the disk cache of an earlier session's TeX can be read. */
506 get drawable(): boolean {
507 return this.ready || this.cached?.cacheDir !== undefined
508 }
509
510 /** What a document gave, if it was compiled (or read from the disk cache) in this process; a passing failure (a timeout) included. */
511 known(document: TexDocument): TexOutcome | undefined {
512 const outcome = this.outcomes.get(document.text)
513 if (outcome) {
514 this.outcomes.delete(document.text)
515 this.outcomes.set(document.text, outcome)
516 }
517 return outcome
518 }
519
520 /** Records an outcome (tests, and what compile and load find). */
521 remember(document: TexDocument, outcome: TexOutcome): void {
522 this.outcomes.delete(document.text)
523 this.outcomes.set(document.text, outcome)
524 while (this.outcomes.size > BOOK_LIMIT) this.outcomes.delete(this.outcomes.keys().next().value!)
525 }
526
527 markShownAsSource(document: TexDocument): void {
528 this.shownAsSource.add(document.text)
529 if (this.shownAsSource.size > BOOK_LIMIT) this.shownAsSource.delete(this.shownAsSource.values().next().value!)
530 }
531
532 wasShownAsSource(document: TexDocument): boolean {
533 return this.shownAsSource.has(document.text)
534 }
535
536 /**
537 * Reads a document's outcome from the disk cache into the book, when it is
538 * there: with TeX's host, else with `read` (a render's own file reads) and
539 * the cached setup, before TeX is found or once it is gone.
540 */
541 async load(document: TexDocument, read?: (path: string) => Promise<string | undefined>): Promise<TexOutcome | undefined> {
542 const known = this.known(document)
543 if (known && (known.ok || known.lasting)) return known
544 const reader = this.host ? (path: string) => this.host!.read(path) : read
545 const setup = this.setup ?? this.cached
546 if (!reader || !setup?.cacheDir) return undefined
547 try {
548 const text = await reader(`${setup.cacheDir}/${await cacheKey(document, setup)}.json`)
549 if (text === undefined) return undefined
550 const stored = JSON.parse(text) as { ok?: unknown; svg?: unknown; error?: unknown }
551 const outcome: TexOutcome | undefined =
552 stored.ok === true && typeof stored.svg === 'string'
553 ? { ok: true, picture: texPicture(stored.svg, document) }
554 : stored.ok === false && typeof stored.error === 'string'
555 ? { ok: false, error: stored.error, lasting: true }
556 : undefined
557 if (outcome) this.remember(document, outcome)
558 return outcome
559 } catch {
560 return undefined
561 }
562 }
563
564 /**
565 * The document's outcome: known, cached on disk, or compiled now (after the
566 * compiles before it), within `timeoutMs` of TeX's own time. A timeout is
567 * an outcome that isn't kept (the next ask compiles again).
568 */
569 compile(document: TexDocument, timeoutMs: number): Promise<TexOutcome> {
570 const known = this.known(document)
571 if (known && (known.ok || known.lasting)) return Promise.resolve(known)
572 const running = this.running.get(document.text)
573 if (running) return running
574 const job = (async (): Promise<TexOutcome> => {
575 const cached = await this.load(document)
576 if (cached) return cached
577 const host = this.host
578 const setup = this.setup
579 if (!host || !setup) return { ok: false, error: 'no TeX', lasting: false }
580 const deadline = Date.now() + timeoutMs
581 if (this.active >= MAX_COMPILES) await new Promise<void>(resolve => this.waiting.push(resolve))
582 this.active++
583 const outcome = await compileOnce(host, setup, document, deadline, timeoutMs).catch((error: unknown): TexOutcome => ({ ok: false, error: String(error), lasting: false }))
584 this.active--
585 this.waiting.shift()?.()
586 // A passing failure is remembered too (the stream reads it and shows the source), but compiled again when asked.
587 this.remember(document, outcome)
588 if ((outcome.ok || outcome.lasting) && setup.cacheDir) await store(host, setup, document, outcome)
589 return outcome
590 })()
591 this.running.set(document.text, job)
592 void job.finally(() => this.running.delete(document.text))
593 return job
594 }
595}
596
597/** How long dumping the format may take. */
598const FORMAT_MS = 60_000
599
600/**
601 * Makes the fragment format available (setup.format): the one dumped
602 * earlier into the cache directory, else dumped now from FORMAT_SOURCE (no
603 * source of the model's in it), confined as every job is, and copied there.
604 * Without a cache directory, or where mylatexformat is missing, there is no
605 * format and fragments load their packages each time.
606 */
607export async function prepareFormat(host: TexHost, setup: TexSetup): Promise<void> {
608 if (!setup.cacheDir) return
609 const name = formatName(setup.versions)
610 const dir = `${setup.cacheDir}/fmt`
611 const path = `${dir}/${name}.fmt`
612 const run = (argv: readonly string[], init: { cwd?: string; env?: Record<string, string>; timeoutMs: number }) => host.run(argv, init).catch(() => ({ exitCode: 1, stdout: '', stderr: '', isStdoutTruncated: false }))
613 if ((await run(['test', '-s', path], { timeoutMs: PROBE_MS })).exitCode === 0) {
614 setup.format = { name, dir }
615 return
616 }
617 const made = await run(['mktemp', '-d', jobDirTemplate(setup.tmpdir)], { timeoutMs: PROBE_MS })
618 const job = made.stdout.trim()
619 if (made.exitCode !== 0 || !isJobDir(job)) return
620 try {
621 await host.write(`${job}/${name}.tex`, FORMAT_SOURCE)
622 const jail = sandboxed(setup)
623 const dumped = await run(confined(formatArgv(name), job, setup.confinement, jail.binds), { cwd: job, env: { ...texEnvironment(job), ...jail.env }, timeoutMs: FORMAT_MS })
624 if (dumped.exitCode !== 0) return
625 if ((await run(['mkdir', '-p', '--', dir], { timeoutMs: PROBE_MS })).exitCode !== 0) return
626 // Copied under a name of its own, then renamed: a session starting meanwhile never reads half a format.
627 const part = `${path}.${job.slice(-10)}`
628 if ((await run(['cp', '--', `${job}/${name}.fmt`, part], { timeoutMs: PROBE_MS })).exitCode !== 0) return
629 if ((await run(['mv', '-f', '--', part, path], { timeoutMs: PROBE_MS })).exitCode !== 0) return
630 setup.format = { name, dir }
631 // The formats of an earlier TeX (or kittex preamble) are superseded: removed, about 11 MB each.
632 await run(['find', dir, '-maxdepth', '1', '-type', 'f', '-name', 'kittex-*.fmt', '!', '-name', `${name}.fmt`, '-delete'], { timeoutMs: PROBE_MS })
633 } finally {
634 await run(['rm', '-rf', '--', job], { timeoutMs: PROBE_MS })
635 }
636}
637
638/** The process's book: register.tsx gives it its host and setup, math.ts reads it. */
639export const texBook = new TexBook()
640
641async function cacheKey(document: TexDocument, setup: TexSetup): Promise<string> {
642 const bytes = new TextEncoder().encode(`kittex-tex ${PREAMBLE_VERSION}\n${setup.versions}\n${document.baseline} ${document.fontSize}\n${document.text}`)
643 const digest = new Uint8Array(await crypto.subtle.digest('SHA-256', bytes))
644 return [...digest].map(byte => byte.toString(16).padStart(2, '0')).join('')
645}
646
647async function store(host: TexHost, setup: TexSetup, document: TexDocument, outcome: TexOutcome): Promise<void> {
648 try {
649 const svg = outcomeSvgs.get(outcome)
650 const body = outcome.ok ? (svg === undefined ? undefined : { ok: true, svg }) : { ok: false, error: outcome.error }
651 if (body) await host.write(`${setup.cacheDir}/${await cacheKey(document, setup)}.json`, JSON.stringify(body))
652 } catch {
653 // not cached
654 }
655}
656
657/** The SVG each compiled outcome was read from, for the disk cache. */
658const outcomeSvgs = new WeakMap<TexOutcome, string>()
659
660/**
661 * One job: a fresh directory (mktemp), the document written into it, latex,
662 * dvisvgm (SVG on stdout), the SVG read into a Picture, the directory removed.
663 * latex and dvisvgm run with what is left until `deadline` (the time asked
664 * for, `timeoutMs`, counts from the ask: a job waiting behind another uses it).
665 */
666async function compileOnce(host: TexHost, setup: TexSetup, document: TexDocument, deadline: number, timeoutMs: number): Promise<TexOutcome> {
667 const left = () => deadline - Date.now()
668 const late: TexOutcome = { ok: false, error: `TeX took longer than ${(timeoutMs / 1000).toFixed(0)} s`, lasting: false }
669 if (left() < 50) return late
670 const made = await host.run(['mktemp', '-d', jobDirTemplate(setup.tmpdir)], { timeoutMs: PROBE_MS })
671 const dir = made.stdout.trim()
672 if (made.exitCode !== 0 || !isJobDir(dir)) return { ok: false, error: 'no temporary directory for TeX', lasting: false }
673 try {
674 await host.write(`${dir}/${JOB_NAME}.tex`, document.text)
675 const jail = sandboxed(setup)
676 const env = { ...texEnvironment(dir), ...jail.env }
677 let latex
678 // A fragment starts from the dumped format, read where the namespace hides the cache directory.
679 const format = document.format ? setup.format : undefined
680 try {
681 latex = format
682 ? await host.run(confined(latexArgv(format.name), dir, setup.confinement, [...jail.binds, format.dir]), { cwd: dir, env: { ...env, TEXFORMATS: `${format.dir}:` }, timeoutMs: Math.max(1, left()) })
683 : await host.run(confined(LATEX_ARGV, dir, setup.confinement, jail.binds), { cwd: dir, env, timeoutMs: Math.max(1, left()) })
684 // A format TeX can't read (a stale or broken file): the same job without it.
685 if (format && latex.exitCode !== 0 && /format file|\.fmt\b/i.test(latex.stdout)) {
686 latex = await host.run(confined(LATEX_ARGV, dir, setup.confinement, jail.binds), { cwd: dir, env, timeoutMs: Math.max(1, left()) })
687 }
688 } catch {
689 return late
690 }
691 if (latex.exitCode !== 0) {
692 const log = `${latex.stdout}\n${(await host.read(`${dir}/${JOB_NAME}.log`)) ?? ''}`
693 return { ok: false, error: texError(log, document.offset), lasting: true }
694 }
695 // A dvisvgm that would run PostScript through Ghostscript unconfined (setup.postscript): only a DVI without any.
696 if (setup.postscript && !setup.confinement.bwrap) {
697 const bytes = await host.readBytes?.(`${dir}/${JOB_NAME}.dvi`).catch(() => undefined)
698 const specials = bytes ? dviSpecials(bytes) : undefined
699 if (!specials || hasPostScript(specials)) return { ok: false, error: 'uses PostScript (a rotation or scaling, say), which this dvisvgm runs through Ghostscript outside any sandbox', lasting: true }
700 }
701 let svg
702 try {
703 if (left() < 1) return late
704 svg = await host.run(confined(dvisvgmCommand(dir, setup), dir, setup.confinement, jail.binds), { cwd: dir, env, timeoutMs: Math.max(1, left()) })
705 } catch {
706 return late
707 }
708 if (svg.exitCode !== 0 || svg.isStdoutTruncated || !svg.stdout.includes('<svg')) {
709 return { ok: false, error: svg.isStdoutTruncated ? 'the picture is too large' : firstLine(svg.stderr) || 'dvisvgm failed', lasting: true }
710 }
711 try {
712 const outcome: TexOutcome = { ok: true, picture: texPicture(svg.stdout, document) }
713 outcomeSvgs.set(outcome, svg.stdout)
714 return outcome
715 } catch (error) {
716 if (error instanceof SvgError || error instanceof XmlError) return { ok: false, error: error.message, lasting: true }
717 throw error
718 }
719 } finally {
720 await host.run(['rm', '-rf', '--', dir], { timeoutMs: PROBE_MS }).catch(() => undefined)
721 }
722}
723
724/**
725 * One compile of `document` outside the book: nothing remembered, nothing
726 * cached (/kittex-doctor's trial picture), within `timeoutMs`.
727 */
728export function compileTrial(host: TexHost, setup: TexSetup, document: TexDocument, timeoutMs: number): Promise<TexOutcome> {
729 return compileOnce(host, setup, document, Date.now() + timeoutMs, timeoutMs).catch((error: unknown): TexOutcome => ({ ok: false, error: String(error), lasting: false }))
730}
731
732function firstLine(text: string): string {
733 return (text.split('\n').find(line => line.trim() !== '') ?? '').replace(/^\s*(?:ERROR|WARNING):?\s*/i, '').trim().slice(0, 200)
734}
735
736// ─── Which segments go to TeX, as which document ─────────────────────────────
737
738/** A diagram segment's kind (the scanner's `diagram` mark). */
739export type DiagramKind = 'latex' | 'tikz' | 'env'
740
741/** What becomes of a diagram: compiled as `document`, refused (`refused`: why), or no drawing at all (left as code). */
742export type DiagramJob = { document: TexDocument; label: string } | { refused: string } | undefined
743
744/**
745 * The job of a diagram (a ```latex, ```tex or ```tikz fence's content, or a
746 * bare environment): undefined for LaTeX that draws nothing (a formula or a
747 * preamble shown as code stays code), refused for a source unsafeTex refuses.
748 */
749export function diagramJob(source: string, kind: DiagramKind): DiagramJob {
750 const lang = kind === 'env' ? 'env' : kind
751 if (!drawsPicture(source, lang)) return undefined
752 const inlined = inlineTables(source)
753 const refused = unsafeTex(inlined)
754 if (refused !== undefined) return { refused }
755 return { document: diagramDocument(inlined, lang), label: diagramLabel(source) }
756}
757
758/** The document a formula MathJax refused compiles as, or undefined when its source is refused. */
759export function mathJob(tex: string, display: boolean): TexDocument | undefined {
760 return unsafeTex(tex) === undefined ? mathDocument(tex, display) : undefined
761}
762
763/** A word for what a diagram draws, shown in its placeholder while it waits to land. */
764export function diagramLabel(source: string): string {
765 if (/\\begin\{(?:axis|semilogxaxis|semilogyaxis|loglogaxis|polaraxis)\}/.test(source)) return 'plot'
766 if (/\\begin\{circuitikz\}|\\ctikzset/.test(source)) return 'circuit'
767 if (/\\begin\{tikzcd\}/.test(source)) return 'commutative diagram'
768 if (/\\chemfig|\\schemestart/.test(source)) return 'molecule'
769 if (/\\documentclass/.test(source)) return 'LaTeX document'
770 return 'diagram'
771}
772
773const results = new WeakMap<Picture, TypesetResult>()
774
775/** A formula TeX drew, as one ink's draw ops (texFormula), worked out once per picture. */
776export function texResult(picture: Picture): TypesetResult {
777 let result = results.get(picture)
778 if (!result) {
779 result = texFormula(picture)
780 results.set(picture, result)
781 }
782 return result
783}
784
785/** A setup as it is remembered for the next session ($.store): plain data, or undefined when it isn't one. */
786export function rememberedTex(value: unknown): TexSetup | undefined {
787 if (typeof value !== 'object' || value === null) return undefined
788 const setup = value as Partial<TexSetup>
789 if (typeof setup.versions !== 'string' || typeof setup.cacheDir !== 'string' || typeof setup.confinement !== 'object' || setup.confinement === null) return undefined
790 return {
791 versions: setup.versions,
792 confinement: setup.confinement,
793 tmpdir: typeof setup.tmpdir === 'string' ? setup.tmpdir : undefined,
794 cacheDir: setup.cacheDir,
795 ...(setup.format && typeof setup.format.name === 'string' && typeof setup.format.dir === 'string' ? { format: setup.format } : {}),
796 ...(setup.libgs === false ? { libgs: false as const } : {}),
797 ...(setup.postscript === true ? { postscript: true as const } : {}),
798 ...(setup.sandbox && Array.isArray(setup.sandbox.binds) && setup.sandbox.binds.every(bind => typeof bind === 'string')
799 ? { sandbox: { binds: setup.sandbox.binds, ...(typeof setup.sandbox.path === 'string' ? { path: setup.sandbox.path } : {}) } }
800 : {}),
801 }
802}
803hooks/doctor.ts 806 lines1// /kittex-doctor: what kittex depends on, checked, and for what is missing,
2// what to install. Nothing here takes `$`: register.tsx gathers the facts it
3// holds (the terminal, the options, the streaming hooks seen) and hands a
4// DoctorHost of closures over `$` for the probes; this file runs the probes,
5// maps a missing piece to the package that ships it on the host's OS, and
6// writes the report.
7//
8// The report is a CommandOutput row, drawn as markdown (the engine's own
9// drawing: kittex hooks AssistantMessage only, so none of it is read as
10// math). It holds no `$`, and every name from the host (a path, a TeX error)
11// goes in code spans or through `plain`, so no markdown in it changes the row.
12
13import { diagramDocument, formatName, ulimitProbe } from './core.js'
14import type { PdfConverter } from './core.js'
15import { compileTrial, onPath, PDF_CONVERTER_NAMES, probePdf, probeSandbox, runsPostScript, takesLibgs, texCacheDir, texPath } from './tex.ts'
16import { CACHE_LIMIT_BYTES, TEX_CACHE_LIMIT_BYTES } from './cache.ts'
17import type { Sandbox, SandboxProbe, TexHost, TexSetup } from './tex.ts'
18
19/** The command's name: typed as `/kittex-doctor`. */
20export const DOCTOR_COMMAND = 'kittex-doctor'
21export const DOCTOR_DESCRIPTION = "Check kittex's terminal, streaming and local TeX setup, and what to install for diagrams"
22
23/** How long one probe command may run. */
24export const DOCTOR_PROBE_MS = 2000
25/** How long the trial picture may take (TeX loading every picture package without the format takes about a second). */
26export const DOCTOR_TRIAL_MS = 8000
27
28/** The fixed picture the doctor compiles: the only source it ever gives TeX. */
29export const TRIAL_PICTURE = '\\draw[->] (0,0) -- (1,0.6) node[right] {$x$};\n\\draw (0,0) circle (0.3);'
30
31// ─── What TeX needs ──────────────────────────────────────────────────────────
32
33/** A command or a TeX file kittex's documents need, and what it costs when missing. */
34export interface Requirement {
35 name: string
36 kind: 'command' | 'file'
37 /**
38 * `pictures`: every diagram (one preamble loads every picture package);
39 * `math`: the formulas MathJax refuses; `speed`: the dumped format;
40 * `check`: this doctor's package check; `confine`: confinement (Linux).
41 */
42 need: 'pictures' | 'math' | 'speed' | 'check' | 'confine' | 'postscript'
43}
44
45/** The commands, in the order the report lists them. */
46export const TEX_COMMANDS: readonly Requirement[] = [
47 { name: 'latex', kind: 'command', need: 'pictures' },
48 { name: 'dvisvgm', kind: 'command', need: 'pictures' },
49 { name: 'kpsewhich', kind: 'command', need: 'check' },
50]
51
52/** What confines TeX on Linux. */
53export const CONFINE_COMMANDS: readonly Requirement[] = [
54 { name: 'bwrap', kind: 'command', need: 'confine' },
55 { name: 'prlimit', kind: 'command', need: 'confine' },
56]
57
58/**
59 * The files the documents load (core/src/diagram/tex.ts: the fragment
60 * preamble, the format's mylatexformat, the math preamble), and three a
61 * distribution may split off: chemfig's simplekv, the Computer Modern
62 * outlines dvisvgm draws the glyphs from, and dvips's PostScript header
63 * (tex.pro), which a dvisvgm that runs PostScript through Ghostscript reads
64 * first (kittex's own documents carry no PostScript; a whole document that
65 * rotates or scales with graphicx does).
66 */
67export const TEX_FILES: readonly Requirement[] = [
68 { name: 'standalone.cls', kind: 'file', need: 'pictures' },
69 { name: 'amsmath.sty', kind: 'file', need: 'pictures' },
70 { name: 'amssymb.sty', kind: 'file', need: 'pictures' },
71 { name: 'tikz.sty', kind: 'file', need: 'pictures' },
72 { name: 'pgfplots.sty', kind: 'file', need: 'pictures' },
73 { name: 'tikz-cd.sty', kind: 'file', need: 'pictures' },
74 { name: 'circuitikz.sty', kind: 'file', need: 'pictures' },
75 { name: 'chemfig.sty', kind: 'file', need: 'pictures' },
76 { name: 'simplekv.tex', kind: 'file', need: 'pictures' },
77 { name: 'siunitx.sty', kind: 'file', need: 'pictures' },
78 { name: 'cmr10.pfb', kind: 'file', need: 'pictures' },
79 { name: 'tex.pro', kind: 'file', need: 'postscript' },
80 { name: 'mathtools.sty', kind: 'file', need: 'math' },
81 { name: 'preview.sty', kind: 'file', need: 'math' },
82 { name: 'mylatexformat.ltx', kind: 'file', need: 'speed' },
83]
84
85// ─── Which OS, which packages ────────────────────────────────────────────────
86
87/** How the host installs TeX: its distribution's packages, TeX Live's own tlmgr (macOS, an installer's TeX Live), or unknown. */
88export type InstallFamily = 'arch' | 'debian' | 'fedora' | 'macos' | 'texlive'
89
90/** The OS as read from `uname -s` and /etc/os-release. */
91export interface OsFacts {
92 /** `linux`, `darwin`... (uname -s, lowercased). */
93 platform?: string
94 /** /etc/os-release's ID, ID_LIKE and PRETTY_NAME. */
95 id?: string
96 idLike?: readonly string[]
97 name?: string
98}
99
100/** /etc/os-release's variables (quotes removed). */
101export function parseOsRelease(text: string): Record<string, string> {
102 const out: Record<string, string> = {}
103 for (const line of text.split('\n')) {
104 const m = /^([A-Z0-9_]+)=(.*)$/.exec(line.trim())
105 if (m) out[m[1]!] = m[2]!.replace(/^(["'])(.*)\1$/, '$2')
106 }
107 return out
108}
109
110/** The OS facts from uname's output and /etc/os-release's text (either may be missing). */
111export function osFacts(uname: string | undefined, osRelease: string | undefined): OsFacts {
112 const platform = uname?.trim().toLowerCase() || undefined
113 const vars = osRelease ? parseOsRelease(osRelease) : {}
114 const idLike = (vars.ID_LIKE ?? '').split(/\s+/).filter(Boolean)
115 return {
116 ...(platform ? { platform } : {}),
117 ...(vars.ID ? { id: vars.ID.toLowerCase() } : {}),
118 ...(idLike.length > 0 ? { idLike: idLike.map(one => one.toLowerCase()) } : {}),
119 ...(vars.PRETTY_NAME || vars.NAME ? { name: vars.PRETTY_NAME || vars.NAME } : {}),
120 }
121}
122
123/**
124 * How TeX is installed here: by the distribution's packages (Arch and its
125 * derivatives, Debian and Ubuntu and theirs, Fedora), by tlmgr on macOS and
126 * where `latex` comes from TeX Live's own installer (a `texlive/<year>/bin`
127 * or `/Library/TeX` path), else TeX Live's way. RHEL and its rebuilds lack
128 * several of the packages, so they get TeX Live's way too.
129 */
130export function installFamily(os: OsFacts, latexPath?: string): InstallFamily {
131 if (os.platform === 'darwin') return 'macos'
132 if (latexPath && (/\/texlive\/\d{4}\/bin\//.test(latexPath) || latexPath.startsWith('/Library/TeX/'))) return 'texlive'
133 const ids = [os.id ?? '', ...(os.idLike ?? [])]
134 if (ids.includes('arch')) return 'arch'
135 if (ids.includes('debian') || ids.includes('ubuntu')) return 'debian'
136 if (os.id === 'fedora' || (ids.includes('fedora') && !ids.includes('rhel'))) return 'fedora'
137 return 'texlive'
138}
139
140/**
141 * The package that ships each requirement, per family. Checked against each
142 * distribution's own index (Arch: pacman -F; Debian 13 and Ubuntu 24.04:
143 * apt-file; Fedora 44: dnf repoquery --whatprovides 'tex(<file>)'; TeX Live:
144 * tlmgr search --file) and installed end to end in a container of each, where
145 * kittex's format, pictures and math compiled.
146 */
147export const PACKAGES: Readonly<Record<InstallFamily, Readonly<Record<string, string>>>> = {
148 arch: {
149 latex: 'texlive-latex',
150 dvisvgm: 'dvisvgm',
151 kpsewhich: 'texlive-bin',
152 bwrap: 'bubblewrap',
153 prlimit: 'util-linux',
154 'standalone.cls': 'texlive-latexextra',
155 'amsmath.sty': 'texlive-latex',
156 'amssymb.sty': 'texlive-basic',
157 'tikz.sty': 'texlive-pictures',
158 'pgfplots.sty': 'texlive-pictures',
159 'tikz-cd.sty': 'texlive-pictures',
160 'circuitikz.sty': 'texlive-pictures',
161 'chemfig.sty': 'texlive-pictures',
162 'simplekv.tex': 'texlive-plaingeneric',
163 'siunitx.sty': 'texlive-mathscience',
164 'cmr10.pfb': 'texlive-basic',
165 'tex.pro': 'texlive-basic',
166 'mathtools.sty': 'texlive-latexrecommended',
167 'preview.sty': 'texlive-latexextra',
168 'mylatexformat.ltx': 'texlive-latexextra',
169 },
170 debian: {
171 latex: 'texlive-latex-base',
172 dvisvgm: 'dvisvgm',
173 kpsewhich: 'texlive-binaries',
174 bwrap: 'bubblewrap',
175 prlimit: 'util-linux',
176 'standalone.cls': 'texlive-latex-extra',
177 'amsmath.sty': 'texlive-latex-base',
178 'amssymb.sty': 'texlive-base',
179 'tikz.sty': 'texlive-pictures',
180 'pgfplots.sty': 'texlive-pictures',
181 'tikz-cd.sty': 'texlive-pictures',
182 'circuitikz.sty': 'texlive-pictures',
183 'chemfig.sty': 'texlive-pictures',
184 'simplekv.tex': 'texlive-plain-generic',
185 'siunitx.sty': 'texlive-science',
186 'cmr10.pfb': 'texlive-base',
187 'tex.pro': 'texlive-base',
188 'mathtools.sty': 'texlive-latex-recommended',
189 'preview.sty': 'preview-latex-style',
190 'mylatexformat.ltx': 'texlive-latex-extra',
191 },
192 fedora: {
193 latex: 'texlive-latex',
194 dvisvgm: 'texlive-dvisvgm',
195 kpsewhich: 'texlive-kpathsea',
196 bwrap: 'bubblewrap',
197 prlimit: 'util-linux',
198 'standalone.cls': 'texlive-standalone',
199 'amsmath.sty': 'texlive-amsmath',
200 'amssymb.sty': 'texlive-amsfonts',
201 'tikz.sty': 'texlive-pgf',
202 'pgfplots.sty': 'texlive-pgfplots',
203 'tikz-cd.sty': 'texlive-tikz-cd',
204 'circuitikz.sty': 'texlive-circuitikz',
205 'chemfig.sty': 'texlive-chemfig',
206 'simplekv.tex': 'texlive-simplekv',
207 'siunitx.sty': 'texlive-siunitx',
208 'cmr10.pfb': 'texlive-amsfonts',
209 'tex.pro': 'texlive-dvips',
210 'mathtools.sty': 'texlive-mathtools',
211 'preview.sty': 'texlive-preview',
212 'mylatexformat.ltx': 'texlive-mylatexformat',
213 },
214 macos: TEXLIVE(),
215 texlive: TEXLIVE(),
216}
217
218/** TeX Live's package names (tlmgr), from scheme-basic up (BasicTeX holds more). */
219function TEXLIVE(): Record<string, string> {
220 return {
221 dvisvgm: 'dvisvgm',
222 'standalone.cls': 'standalone',
223 'amsmath.sty': 'amsmath',
224 'amssymb.sty': 'amsfonts',
225 'tikz.sty': 'pgf',
226 'pgfplots.sty': 'pgfplots',
227 'tikz-cd.sty': 'tikz-cd',
228 'circuitikz.sty': 'circuitikz',
229 'chemfig.sty': 'chemfig',
230 'simplekv.tex': 'simplekv',
231 'siunitx.sty': 'siunitx',
232 'cmr10.pfb': 'amsfonts',
233 'tex.pro': 'dvips',
234 'mathtools.sty': 'mathtools',
235 'preview.sty': 'preview',
236 'mylatexformat.ltx': 'mylatexformat',
237 }
238}
239
240/** Every requirement a family installs, in order (the whole set: what a host with no TeX at all needs). */
241const ALL = [...TEX_COMMANDS, ...TEX_FILES].map(one => one.name)
242
243/**
244 * The whole set as a host with no TeX installs it, where a shorter list
245 * brings the rest as dependencies (each installed as is in a fresh container:
246 * Arch, Debian 13 and Ubuntu 24.04 without recommends; the README gives the
247 * same lines).
248 */
249const FULL: Partial<Record<InstallFamily, readonly string[]>> = {
250 arch: ['texlive-basic', 'texlive-latex', 'texlive-latexrecommended', 'texlive-latexextra', 'texlive-pictures', 'texlive-mathscience', 'texlive-plaingeneric', 'dvisvgm', 'bubblewrap'],
251 debian: ['texlive-latex-extra', 'texlive-pictures', 'texlive-science', 'texlive-plain-generic', 'preview-latex-style', 'dvisvgm', 'bubblewrap'],
252}
253
254/** The install advice: a heading and the commands, or nothing when nothing is missing. */
255export interface InstallAdvice {
256 family: InstallFamily
257 /** The OS as the heading names it. */
258 label: string
259 /** Only confinement is missing (diagrams already draw). */
260 confineOnly: boolean
261 /** Shell commands, one per line, in order. */
262 commands: string[]
263 /** A line after them (another way, a caveat), as markdown, when there is one. */
264 note?: string
265}
266
267/**
268 * What to install for the requirements `missing` (names from TEX_COMMANDS,
269 * CONFINE_COMMANDS, TEX_FILES): everything when `latex` is missing, else the
270 * packages that ship what is missing. Undefined when nothing is.
271 */
272export function installAdvice(os: OsFacts, missing: readonly string[], latexPath?: string): InstallAdvice | undefined {
273 if (missing.length === 0) return undefined
274 const family = installFamily(os, latexPath)
275 const linux = os.platform !== 'darwin'
276 const noTex = missing.includes('latex')
277 // With latex, everything (its own package brings kpsewhich); bubblewrap with it on Linux.
278 const names = noTex ? [...new Set([...ALL.filter(name => name !== 'kpsewhich'), ...missing, ...(linux ? ['bwrap'] : [])])] : [...missing]
279 const confineOnly = names.every(name => name === 'bwrap' || name === 'prlimit')
280 const map = PACKAGES[family]
281 const full = noTex ? FULL[family] : undefined
282 const packages = full ? [...full] : [...new Set(names.map(name => map[name]).filter((one): one is string => one !== undefined))]
283 const label = family === 'macos' ? 'macOS' : family === 'texlive' && !os.name ? 'TeX Live' : (os.name ?? family)
284 const base = { family, label, confineOnly }
285 switch (family) {
286 case 'arch':
287 return { ...base, commands: [`sudo pacman -S --needed ${packages.join(' ')}`] }
288 case 'debian':
289 return { ...base, commands: [`sudo apt install ${packages.join(' ')}`] }
290 case 'fedora':
291 return { ...base, commands: [`sudo dnf install ${packages.join(' ')}`] }
292 case 'macos': {
293 if (!noTex) return { ...base, commands: [`sudo tlmgr install ${packages.join(' ')}`] }
294 return {
295 ...base,
296 commands: ['brew install --cask basictex', 'sudo /Library/TeX/texbin/tlmgr update --self', `sudo /Library/TeX/texbin/tlmgr install ${packages.join(' ')}`],
297 note: 'Or the full MacTeX, everything included (about 6 GB): `brew install --cask mactex-no-gui`.',
298 }
299 }
300 case 'texlive': {
301 const confine = linux ? [...new Set(names.filter(name => name === 'bwrap' || name === 'prlimit').map(name => (name === 'bwrap' ? 'bubblewrap' : 'util-linux')))] : []
302 const notes = [
303 noTex ? 'Install TeX Live first (https://tug.org/texlive, its basic scheme is enough), then run the line above.' : packages.length > 0 ? 'With sudo where TeX Live is installed system-wide.' : '',
304 confine.length > 0 ? `Also install ${confine.map(code).join(' and ')} from your distribution, so TeX runs confined.` : '',
305 ].filter(Boolean)
306 return { ...base, commands: packages.length > 0 ? [`tlmgr install ${packages.join(' ')}`] : [], ...(notes.length > 0 ? { note: notes.join(' ') } : {}) }
307 }
308 }
309}
310
311// ─── The probes ──────────────────────────────────────────────────────────────
312
313/** What the probes need from the host: TexHost's commands and files, and a path's existence and size. */
314export interface DoctorHost extends TexHost {
315 exists(path: string): Promise<boolean>
316 /** A file's size in bytes, or undefined when it isn't there. */
317 size(path: string): Promise<number | undefined>
318}
319
320/** A command as found: where on PATH, and its `--version` line. */
321export interface ToolFacts {
322 path?: string
323 version?: string
324}
325
326/** The trial picture's compile. */
327export type TrialFacts = { ok: true; ms: number; format: boolean } | { ok: false; ms: number; error: string } | { skipped: string }
328
329export interface DiagramFacts {
330 /** The `latex` option. */
331 option: 'auto' | 'off'
332 /** Whether kittex draws diagrams here at all: images on this terminal, block math as images. */
333 drawn: boolean
334 /** Whether this session's kittex found TeX when it started (it looks once, at session start). */
335 found: boolean
336 latex: ToolFacts
337 dvisvgm: ToolFacts
338 kpsewhich: ToolFacts
339 tlmgr: ToolFacts
340 /** Each TEX_FILES name with the path kpsewhich gave; undefined when kpsewhich couldn't run. */
341 files?: { name: string; path?: string }[]
342 /** Linux only: bubblewrap found and whether its trial namespace runs (else its first error line). */
343 /** Linux only: bubblewrap found, whether TeX runs in its namespace (else why not), and what it binds back. */
344 bwrap?: ToolFacts & { usable: boolean; error?: string; sandbox?: Sandbox }
345 prlimit?: ToolFacts
346 /** Without prlimit (macOS): whether sh's ulimit sets the CPU-time and file-size limits. */
347 ulimit?: boolean
348 /** The dumped format for this TeX (prepareFormat), when latex and dvisvgm answered. */
349 format?: { path: string; bytes?: number }
350 /** Whether dvisvgm takes --libgs (false: kittex leaves it out). */
351 libgs?: boolean
352 /** dvisvgm runs PostScript specials through a Ghostscript it links, whatever kittex asks (3.5 to 3.6.1). */
353 postscript?: boolean
354 trial: TrialFacts
355 /** The trial PDF conversion (tex.ts probePdf), where the trial picture ran. */
356 pdf?: { ok: true; converter: PdfConverter } | { ok: false; error: string }
357}
358
359export interface CacheFacts {
360 /** ~/.cache/kittex (XDG_CACHE_HOME's kittex). */
361 dir?: string
362 bytes?: number
363 files?: number
364 /** Its parts: the images of resumed replies (`v<n>/`), what TeX drew (`tex/`), the TeX format (`tex/fmt/`). */
365 images?: CachePart
366 tex?: CachePart
367 format?: CachePart
368}
369
370export interface CachePart {
371 bytes?: number
372 files: number
373}
374
375/** What the probes start from. */
376export interface ProbeInput {
377 option: 'auto' | 'off'
378 drawn: boolean
379 found: boolean
380 os: OsFacts
381 env: { PATH?: string; HOME?: string; TMPDIR?: string; XDG_CACHE_HOME?: string }
382 /** The directories a confined job can't see (tex.ts hiddenDirs). */
383 hide: readonly string[]
384}
385
386/** The first non-empty line of a command's output. */
387function firstLine(text: string | undefined): string | undefined {
388 return text?.split('\n').map(line => line.trim()).find(line => line !== '') || undefined
389}
390
391/** The first directory on PATH holding `name`. */
392export async function which(host: Pick<DoctorHost, 'exists'>, name: string, path: string | undefined): Promise<string | undefined> {
393 const dirs = (path ?? '').split(':').filter(dir => dir.startsWith('/'))
394 const found = await Promise.all(dirs.map(dir => host.exists(`${dir.replace(/\/+$/, '')}/${name}`).catch(() => false)))
395 const at = found.indexOf(true)
396 return at < 0 ? undefined : `${dirs[at]!.replace(/\/+$/, '')}/${name}`
397}
398
399/**
400 * Probes the local TeX: the commands (PATH and `--version`), the files
401 * (kpsewhich), the confinement (Linux), the format, and once latex and
402 * dvisvgm answer, the trial picture. The commands run at once; only the
403 * trial waits for them. TeX never sees anything but TRIAL_PICTURE.
404 */
405export async function probeDiagrams(given: DoctorHost, input: ProbeInput): Promise<DiagramFacts> {
406 // On macOS, MacTeX's folder too (as the session's TeX finds it: texPath).
407 const texPATH = texPath(input.env.PATH, input.os.platform)
408 const host = onPath(given, texPATH)
409 const run = (argv: readonly string[], timeoutMs = DOCTOR_PROBE_MS) =>
410 host.run(argv, { timeoutMs }).then(
411 result => result,
412 () => undefined,
413 )
414 const version = async (name: string, path: string | undefined): Promise<ToolFacts> => {
415 if (!path) return {}
416 const out = await run([name, '--version'])
417 const line = out?.exitCode === 0 ? firstLine(out.stdout) : undefined
418 return { path, ...(line ? { version: line } : {}) }
419 }
420 const linux = input.os.platform !== 'darwin'
421 const PATH = texPATH ?? input.env.PATH
422 const [latexAt, dvisvgmAt, kpsewhichAt, tlmgrAt, bwrapAt, prlimitAt] = await Promise.all(
423 ['latex', 'dvisvgm', 'kpsewhich', 'tlmgr', 'bwrap', 'prlimit'].map(name => (linux || (name !== 'bwrap' && name !== 'prlimit') ? which(host, name, PATH) : Promise.resolve(undefined))),
424 )
425 const [latex, dvisvgm, kpsewhich, prlimit, help, extended, kpse, bwrapRun] = await Promise.all([
426 version('latex', latexAt),
427 version('dvisvgm', dvisvgmAt),
428 version('kpsewhich', kpsewhichAt),
429 linux ? version('prlimit', prlimitAt) : Promise.resolve(undefined),
430 dvisvgmAt ? run(['dvisvgm', '--help']) : Promise.resolve(undefined),
431 dvisvgmAt ? run(['dvisvgm', '-V1']) : Promise.resolve(undefined),
432 kpsewhichAt ? run(['kpsewhich', ...TEX_FILES.map(file => file.name)]) : Promise.resolve(undefined),
433 // The sandbox's own trial (latex and dvisvgm inside it), not run where Local LaTeX is off.
434 linux && bwrapAt && latexAt && dvisvgmAt && input.hide.length > 0 && input.option === 'auto'
435 ? probeSandbox(host, { hide: input.hide, tmpdir: input.env.TMPDIR, path: PATH, prlimit: prlimitAt !== undefined })
436 : Promise.resolve(undefined as SandboxProbe | undefined),
437 ])
438 // No prlimit (always on macOS): sh's ulimit sets the same limits, where it runs.
439 const ulimit = prlimitAt === undefined ? (await run(ulimitProbe()))?.exitCode === 0 : undefined
440 const tlmgr: ToolFacts = tlmgrAt ? { path: tlmgrAt } : {}
441 // kpsewhich prints the path of each file it finds (exit 1 when any is missing).
442 const found = kpse?.stdout.split('\n').map(line => line.trim()).filter(Boolean) ?? []
443 const files = kpse ? TEX_FILES.map(({ name }) => ({ name, path: found.find(path => path === name || path.endsWith(`/${name}`)) })).map(({ name, path }) => (path ? { name, path } : { name })) : undefined
444 const bwrap: DiagramFacts['bwrap'] = linux
445 ? {
446 ...(bwrapAt ? { path: bwrapAt } : {}),
447 usable: bwrapRun?.ok === true,
448 ...(bwrapRun?.ok ? { sandbox: bwrapRun.sandbox } : bwrapRun ? { error: bwrapRun.error } : bwrapAt && input.option === 'auto' && latexAt && dvisvgmAt ? { error: 'not tried' } : {}),
449 }
450 : undefined
451 const libgs = help?.exitCode === 0 ? takesLibgs(help.stdout) : undefined
452 const postscript = libgs === false && dvisvgm.version !== undefined && runsPostScript(dvisvgm.version, extended?.exitCode === 0 ? extended.stdout : undefined)
453 const facts: DiagramFacts = {
454 option: input.option,
455 drawn: input.drawn,
456 found: input.found,
457 latex,
458 dvisvgm,
459 kpsewhich,
460 tlmgr,
461 ...(files ? { files } : {}),
462 ...(bwrap ? { bwrap } : {}),
463 ...(prlimit ? { prlimit } : {}),
464 ...(ulimit !== undefined ? { ulimit } : {}),
465 ...(libgs !== undefined ? { libgs } : {}),
466 ...(postscript ? { postscript } : {}),
467 trial: { skipped: '' },
468 }
469 // The format kittex dumps for this TeX (named by the versions, as tex.ts's probeTex reads them).
470 const cacheDir = texCacheDir(input.env)
471 let format: TexSetup['format']
472 if (latex.version && dvisvgm.version && cacheDir) {
473 const name = formatName(`${latex.version}\n${dvisvgm.version}`)
474 const path = `${cacheDir}/fmt/${name}.fmt`
475 const bytes = await host.size(path).catch(() => undefined)
476 facts.format = { path, ...(bytes !== undefined ? { bytes } : {}) }
477 if (bytes !== undefined && bytes > 0) format = { name, dir: `${cacheDir}/fmt` }
478 }
479 if (!latex.version || !dvisvgm.version) {
480 facts.trial = { skipped: !latex.path ? 'no latex' : !dvisvgm.path ? 'no dvisvgm' : `${latex.version ? 'dvisvgm' : 'latex'} does not answer` }
481 } else if (input.option === 'off') {
482 facts.trial = { skipped: 'Local LaTeX is off' }
483 } else {
484 const setup: TexSetup = {
485 versions: `${latex.version}\n${dvisvgm.version}`,
486 confinement: { prlimit: !linux ? false : prlimit?.path !== undefined, ...(ulimit ? { ulimit: true as const } : {}), ...(bwrap?.usable ? { bwrap: { hide: input.hide } } : {}) },
487 tmpdir: input.env.TMPDIR,
488 ...(format ? { format } : {}),
489 ...(libgs === false ? { libgs: false as const } : {}),
490 ...(postscript ? { postscript: true as const } : {}),
491 ...(bwrap?.sandbox ? { sandbox: bwrap.sandbox } : {}),
492 }
493 const started = Date.now()
494 const outcome = await compileTrial(host, setup, diagramDocument(TRIAL_PICTURE, 'tikz'), DOCTOR_TRIAL_MS)
495 const ms = Date.now() - started
496 facts.trial = outcome.ok ? { ok: true, ms, format: format !== undefined } : { ok: false, ms, error: outcome.error }
497 facts.pdf = await probePdf(host, setup)
498 }
499 return facts
500}
501
502/**
503 * The cache directory's size and file count (du, find), or just its path
504 * when it isn't there, with its parts apart: the images (pruned past 50 MB),
505 * what TeX drew (past 20 MB) and the TeX format (never pruned, replaced for
506 * a new TeX).
507 */
508export async function probeCache(host: DoctorHost, env: ProbeInput['env']): Promise<CacheFacts> {
509 const tex = texCacheDir(env)
510 if (!tex) return {}
511 const dir = tex.replace(/\/tex$/, '')
512 if (!(await host.exists(dir).catch(() => false))) return { dir }
513 const [du, find] = await Promise.all([
514 host.run(['du', '-sk', dir, `${dir}/tex`, `${dir}/tex/fmt`], { timeoutMs: DOCTOR_PROBE_MS }).catch(() => undefined),
515 host.run(['find', dir, '-type', 'f'], { timeoutMs: DOCTOR_PROBE_MS }).catch(() => undefined),
516 ])
517 // du prints a line per path it could read (a missing one only on stderr): kB, a tab, the path.
518 const kb = new Map<string, number>()
519 for (const line of du?.stdout.split('\n') ?? []) {
520 const match = /^(\d+)\s+(.+)$/.exec(line.trim())
521 if (match) kb.set(match[2]!.replace(/\/+$/, ''), Number(match[1]) * 1024)
522 }
523 const files = find?.exitCode === 0 || (find && find.stdout.trim() !== '') ? find.stdout.split('\n').filter(line => line.trim() !== '') : undefined
524 const all = kb.get(dir)
525 const texAll = kb.get(`${dir}/tex`)
526 const fmt = kb.get(`${dir}/tex/fmt`)
527 const facts: CacheFacts = { dir, ...(all !== undefined ? { bytes: all } : {}), ...(files ? { files: files.length } : {}) }
528 if (files) {
529 const formats = files.filter(path => path.startsWith(`${dir}/tex/fmt/`)).length
530 const drawn = files.filter(path => path.startsWith(`${dir}/tex/`)).length - formats
531 const images = files.length - formats - drawn
532 const texOnly = texAll !== undefined ? texAll - (fmt ?? 0) : undefined
533 facts.images = { files: images, ...(all !== undefined && texAll !== undefined ? { bytes: all - texAll } : {}) }
534 facts.tex = { files: drawn, ...(texOnly !== undefined ? { bytes: texOnly } : {}) }
535 facts.format = { files: formats, ...(fmt !== undefined ? { bytes: fmt } : {}) }
536 }
537 return facts
538}
539
540// ─── The report ──────────────────────────────────────────────────────────────
541
542export interface TerminalFacts {
543 kind: 'kitty' | 'ghostty' | 'wezterm' | 'iterm2' | 'other'
544 images: boolean
545 multiplexer?: string
546 ssh?: boolean
547 /** TERM, and TERM_PROGRAM with its version, as the environment says. */
548 term?: string
549 program?: string
550 /** The cell in pixels, and whether it was measured (else the fallback). */
551 cell?: { width: number; height: number; measured: boolean }
552 /** The text font as the terminal's config names it, and its metrics as kittex read them. */
553 font?: { family?: string; style?: string; sizePt?: number; file?: string; source?: 'kitty' | 'fontconfig' | 'coretext' | 'ghostty'; metrics: boolean }
554 /** The formulas' ink and the background, as #rrggbb, and where they came from. */
555 ink?: string
556 background?: string
557 colors: 'terminal' | 'theme'
558 /**
559 * Claude Code's own decision on drawing pictures (its probe of the
560 * terminal), as a blit to one of kittex's Images read it: `unknown` before
561 * kittex drew one, `pending` while Claude Code hasn't asked the terminal.
562 */
563 claude?: { state: 'unknown' | 'pending' | 'yes' | 'no'; source?: string }
564}
565
566export interface StreamingFacts {
567 /** kittex is off (block and inline both raw): no hook rewrites anything. */
568 off: boolean
569 /** Text blocks that streamed through kittex's MessageDisplay hook this session (the last few). */
570 streamed: number
571 /** Replies that landed with no stream through that hook (the last few). */
572 unstreamed: number
573 /** Whether kittex's system-prompt section was in the composed prompt; undefined when not asked (kittex off, not a terminal). */
574 section?: boolean
575 /** Whether managed settings (policy) are present. */
576 managed: boolean
577}
578
579export interface DoctorFacts {
580 kittex: { version?: string; build?: string }
581 claudeCode?: string
582 /** Where the session draws: `terminal`, a remote surface, or `none` (a -p run or the SDK with no client attached). */
583 surface?: string
584 /** The remote surfaces drawing beside the terminal (a phone attached), when there are any. */
585 clients?: readonly string[]
586 terminal?: TerminalFacts
587 streaming: StreamingFacts
588 /** The options as set, by name, shown as given. */
589 options: Readonly<Record<string, string>>
590 diagrams: DiagramFacts
591 cache: CacheFacts
592 os: OsFacts
593 /** The home directory, written as ~ in paths. */
594 home?: string
595}
596
597const OK = '✓'
598const NO = '✗'
599const INFO = '–'
600
601/** Free text from the host (a font's name, a TeX error) as markdown that draws as written. */
602export function plain(text: string): string {
603 return text.replace(/`/g, "'").replace(/([\\*_[\]<>#|~])/g, '\\$1').replace(/\s+/g, ' ').trim()
604}
605
606/** A path or command as a code span (backticks in it, none expected, become quotes). */
607function code(text: string): string {
608 return `\`${text.replace(/`/g, "'")}\``
609}
610
611function bytes(n: number): string {
612 if (n < 1000) return `${n} B`
613 if (n < 1_000_000) return `${(n / 1000).toFixed(0)} kB`
614 return `${(n / 1_000_000).toFixed(1)} MB`
615}
616
617function seconds(ms: number): string {
618 return `${(ms / 1000).toFixed(2)} s`
619}
620
621const TERMINAL_NAMES: Record<TerminalFacts['kind'], string> = { kitty: 'kitty', ghostty: 'Ghostty', wezterm: 'WezTerm', iterm2: 'iTerm2', other: 'an unknown terminal' }
622
623/** The report, as the command's markdown text. */
624export function formatDoctor(facts: DoctorFacts): string {
625 const home = facts.home && facts.home !== '/' ? facts.home.replace(/\/+$/, '') : undefined
626 const path = (p: string) => code(home && (p === home || p.startsWith(`${home}/`)) ? `~${p.slice(home.length)}` : p)
627 const out: string[] = []
628 const line = (mark: string, text: string) => out.push(`${mark} ${text}`)
629 const section = (title: string) => {
630 if (out.length > 0) out.push('')
631 out.push(`**${title}**`)
632 }
633
634 // The row reads `kittex: ` first (the engine names the plugin that answered).
635 const head = [`${facts.kittex.version ?? 'version unknown'}${facts.kittex.build ? ` (build ${facts.kittex.build})` : ''}`]
636 if (facts.claudeCode) head.push(`Claude Code ${plain(facts.claudeCode)}`)
637 if (facts.surface) head.push(facts.surface === 'none' ? 'no surface' : `${facts.surface} surface`)
638 out.push(head.join(' · '))
639
640 // Terminal
641 section('Terminal')
642 const t = facts.terminal
643 const elsewhere = facts.surface !== undefined && facts.surface !== 'terminal'
644 if (facts.surface === 'none') {
645 line(INFO, 'no terminal (a -p run or the SDK): kittex leaves replies as Claude wrote them (images need kitty or Ghostty, in a terminal).')
646 } else if (elsewhere) {
647 line(INFO, `the ${facts.surface} surface: kittex leaves replies to its own drawing here (images need kitty or Ghostty, in a terminal).`)
648 } else if (t) {
649 // Terminal.app names itself only in TERM_PROGRAM.
650 const name = t.kind === 'other' && /^Apple_Terminal(?:\s|$)/.test(t.program ?? '') ? 'Terminal.app' : TERMINAL_NAMES[t.kind]
651 const program = t.program?.replace(/^Apple_Terminal(?=\s|$)/, 'Terminal.app')
652 const shown = program && program.toLowerCase() !== name.toLowerCase() ? (program.toLowerCase().startsWith(`${name.toLowerCase()} `) ? program.slice(name.length + 1) : program) : undefined
653 const where = [shown ? plain(shown) : t.kind === 'other' && t.term ? `TERM=${plain(t.term)}` : undefined, t.multiplexer ? `inside ${t.multiplexer}` : undefined, t.ssh ? 'over ssh' : undefined].filter(Boolean).join(', ')
654 if (t.images) {
655 line(OK, `${name}${where ? ` (${where})` : ''}: kitty graphics with Unicode placeholders`)
656 const c = t.claude
657 const said = c?.source ? ` (${plain(c.source)})` : ''
658 if (c?.state === 'yes') line(OK, 'Claude Code draws the pictures: kitty answered its graphics query')
659 else if (c?.state === 'no') {
660 line(NO, `Claude Code draws no pictures here${said}, so kittex shows math as Unicode text. Where this terminal does show kitty graphics and only answered late (ssh, a busy machine), start Claude Code with ${code('CLAUDE_CODE_FORCE_TERMINAL_IMAGES=1')} to skip its check.`)
661 } else if (c?.state === 'pending') line(INFO, `Claude Code hasn't asked the terminal about pictures yet${said}: run this again in a moment`)
662 else if (c) line(INFO, "Claude Code's own check on pictures: known once kittex has drawn an image (run this again after a reply with math)")
663 } else {
664 const why = t.multiplexer ? `${t.multiplexer} doesn't pass kitty graphics through` : name === 'Terminal.app' ? 'Terminal.app has no kitty graphics' : t.kind === 'other' ? 'no kitty graphics detected' : `${name} has no kitty Unicode placeholders`
665 line(NO, `${name}${where ? ` (${where})` : ''}: ${why}. kittex shows math as Unicode text instead; images work in kitty (0.28 or newer) and Ghostty${t.multiplexer ? `, outside ${t.multiplexer}` : ''}.`)
666 }
667 if (t.cell) line(t.cell.measured ? OK : NO, t.cell.measured ? `cell ${t.cell.width}×${t.cell.height} px, measured` : `cell not measured: drawing for ${t.cell.width}×${t.cell.height} px (perl or python3 reads the size from the terminal)`)
668 if (t.images || t.font) {
669 const f = t.font
670 const base = f?.file?.split('/').pop()
671 const named = [f?.family ? plain(f.family) : base ? plain(base) : undefined, f?.style ? plain(f.style) : undefined, f?.sizePt ? `${f.sizePt} pt` : undefined].filter(Boolean).join(' ')
672 const source = f?.source === 'kitty' ? 'kitty names it' : f?.source === 'fontconfig' ? 'fontconfig matched it' : f?.source === 'coretext' ? 'CoreText matched it' : undefined
673 const size = f?.sizePt ? ` ${f.sizePt} pt` : ''
674 if (f?.metrics && f.source === 'ghostty' && !f.file) {
675 if (f.family) line(INFO, `font ${plain(f.family)}${size}: ${facts.os.platform === 'darwin' ? 'CoreText' : 'fontconfig'} doesn't know it, so the math follows Ghostty's built-in JetBrains Mono`)
676 else line(OK, `font Ghostty's built-in JetBrains Mono${size}: metrics built in`)
677 }
678 else if (f?.metrics) line(OK, `font ${named || 'as configured'}: metrics read from ${f.file ? path(f.file) : 'its file'}${source ? ` (${source})` : ''}`)
679 else line(INFO, `font ${named || 'not named by the terminal'}: metrics not read${t.ssh ? ' (over ssh the font is on the other machine)' : ''}; math is sized from the cell`)
680 }
681 const colors = [t.ink ? `text ${t.ink}` : undefined, t.background ? `on ${t.background}` : undefined].filter(Boolean).join(' ')
682 if (colors) line(t.colors === 'terminal' ? OK : INFO, `colours: ${colors} (${t.colors === 'terminal' ? "the terminal's" : "the Claude theme's default: the terminal's colours couldn't be read"})`)
683 } else {
684 line(INFO, 'not set up (kittex is off)')
685 }
686 if (!elsewhere && facts.clients?.length) line(INFO, `also drawn on ${facts.clients.join(', ')}: kittex leaves replies to that surface's own drawing there`)
687
688 // Streaming
689 section('Drawing while streaming')
690 const s = facts.streaming
691 const fix = "Fix: ask an admin to deploy kittex through Claude Code's managed settings."
692 if (s.off) {
693 line(INFO, 'kittex is off: Block math and Inline math are both raw')
694 } else if (elsewhere) {
695 line(INFO, 'not a terminal: replies pass as Claude wrote them, and Claude gets no instructions about math')
696 } else if (s.streamed > 0) {
697 line(OK, 'live: replies reach kittex as they stream')
698 } else if (s.unstreamed > 0) {
699 line(NO, `bypassed: ${s.unstreamed === 1 ? 'a reply' : `${s.unstreamed} replies`} streamed without reaching kittex (cc-plugin-sec-default${s.managed ? ', seated by managed settings,' : ' on Team and Enterprise plans'} skips plugins' streaming hooks): equations stay LaTeX until each part lands. ${fix}`)
700 } else if (s.section === false) {
701 line(NO, `likely bypassed: kittex's system-prompt section is skipped here (cc-plugin-sec-default on Team and Enterprise plans${s.managed ? ', or managed settings' : ''}), which skips the streaming hook too. ${fix}`)
702 } else {
703 line(INFO, 'no reply has streamed yet this session: run this again after one to confirm')
704 }
705 if (!s.off && s.section === false && (s.streamed > 0 || s.unstreamed > 0)) line(INFO, "instructions to Claude ride your first message (the system-prompt hook is skipped here)")
706 else if (!s.off && s.section === true) line(OK, "instructions to Claude: in the system prompt")
707
708 // Options
709 section('Options')
710 out.push(Object.entries(facts.options).map(([key, value]) => `${key} ${code(value)}`).join(' · '))
711
712 // Diagrams
713 section('Diagrams (local TeX)')
714 const d = facts.diagrams
715 const os = facts.os
716 const linux = os.platform !== 'darwin'
717 if (d.option === 'off') line(INFO, 'Local LaTeX is off: TeX never runs, diagrams stay code blocks (set it to auto in /config)')
718 else if (!d.drawn) line(INFO, 'diagrams are drawn only where equations are images (kitty or Ghostty, Block math image)')
719 const tool = (name: string, facts: ToolFacts, missing: string) => {
720 if (facts.path) line(facts.version ? OK : NO, `${name}: ${path(facts.path)}${facts.version ? `, ${plain(facts.version)}` : ' does not answer --version'}`)
721 else line(name === 'kpsewhich' ? INFO : NO, `${name}: not found on PATH${missing}`)
722 }
723 tool('latex', d.latex, '')
724 tool('dvisvgm', d.dvisvgm, '')
725 tool('kpsewhich', d.kpsewhich, ": the packages can't be checked")
726 if (d.files) {
727 const missing = d.files.filter(file => !file.path).map(file => file.name)
728 if (missing.length === 0) {
729 line(OK, `packages: all ${d.files.length} found (TikZ, pgfplots, tikz-cd, circuitikz, chemfig, siunitx...)`)
730 } else {
731 const need = (name: string) => TEX_FILES.find(file => file.name === name)?.need
732 const pictures = missing.filter(name => need(name) === 'pictures')
733 const math = missing.filter(name => need(name) === 'math')
734 const speed = missing.filter(name => need(name) === 'speed')
735 if (pictures.length > 0) line(NO, `missing ${pictures.map(code).join(', ')}: no diagram compiles without ${pictures.length === 1 ? 'it' : 'them'} (one preamble loads every picture package)`)
736 if (math.length > 0) line(NO, `missing ${math.map(code).join(', ')}: math MathJax refuses can't be drawn by TeX`)
737 if (speed.length > 0) line(NO, `missing ${speed.map(code).join(', ')}: no format, so each picture loads its packages (about twice as slow)`)
738 const ps = missing.filter(name => need(name) === 'postscript')
739 if (ps.length > 0) line(INFO, `missing ${ps.map(code).join(', ')}: a whole document that rotates or scales (graphicx) can't be drawn where dvisvgm runs Ghostscript`)
740 const present = d.files.length - missing.length
741 if (present > 0) line(OK, `${present} of ${d.files.length} packages found`)
742 }
743 }
744 if (linux) {
745 const b = d.bwrap
746 const p = d.prlimit
747 const bound = b?.sandbox?.binds ?? []
748 if (b?.usable) line(OK, `bubblewrap: TeX runs with your home, /tmp and /run hidden${bound.length > 0 ? ` (but for ${bound.map(path).join(', ')}, bound read-only)` : ''}, and no network`)
749 else if (b?.path && d.option === 'auto' && b.error !== undefined) line(NO, `bubblewrap can't run TeX here (${plain(b.error)}): kittex runs TeX without it, so TeX can read any file you can (kittex still refuses diagrams that read a file by its path)`)
750 else if (b?.path) line(INFO, 'bubblewrap: found (not tried: Local LaTeX is off or TeX is missing)')
751 else line(NO, 'bubblewrap: not found: TeX can read any file you can (kittex still refuses diagrams that read a file by its path)')
752 if (p?.path) line(OK, 'prlimit: TeX runs under a CPU-time and a file-size limit')
753 else if (d.ulimit) line(OK, "prlimit: not found: sh's ulimit sets the CPU-time and file-size limits instead")
754 else line(NO, 'prlimit: not found: no CPU or file-size limit, only the time limit')
755 } else {
756 const limits = d.ulimit ? "a CPU-time and a file-size limit (sh's ulimit)" : 'no CPU-time or file-size limit'
757 line(INFO, `confinement: no bubblewrap on macOS. TeX runs as you, with its shell escape off, writes kept to its job folder, a time limit, and ${limits}; kittex refuses diagrams that read a file by its path, but nothing hides your files from TeX.`)
758 }
759 if (d.libgs === false) line(INFO, 'dvisvgm has no --libgs option here: kittex leaves it out')
760 if (d.postscript) line(INFO, `this dvisvgm runs PostScript through its own Ghostscript, without -dSAFER, whatever it is told (3.5 to 3.6.1): kittex's pictures hold none; a document that rotates or scales ${d.bwrap?.usable ? 'runs inside bubblewrap' : 'is refused, as there is no sandbox'}`)
761 if (d.format) {
762 if (d.format.bytes !== undefined && d.format.bytes > 0) line(OK, `format: built, ${path(d.format.path)} (${bytes(d.format.bytes)})`)
763 else if (!d.drawn) line(INFO, 'format: not built (kittex dumps it only where it draws diagrams)')
764 else line(INFO, `format: not built yet${d.files?.some(file => file.name === 'mylatexformat.ltx' && !file.path) ? ' (needs mylatexformat)' : ': kittex dumps it in the background once a session finds TeX'}`)
765 }
766 const trial = d.trial
767 if ('skipped' in trial) line(INFO, `trial picture: skipped${trial.skipped ? ` (${plain(trial.skipped)})` : ''}`)
768 else if (trial.ok) line(OK, `trial picture: drawn in ${seconds(trial.ms)}${trial.format ? '' : ' (without the format)'}`)
769 else line(NO, `trial picture: failed after ${seconds(trial.ms)}: ${plain(trial.error)}`)
770 if (d.pdf?.ok) line(OK, `PDF images: drawn from their first page by ${PDF_CONVERTER_NAMES[d.pdf.converter]}${d.bwrap?.usable ? ', inside bubblewrap' : ', with Ghostscript kept off (no sandbox to confine it)'}`)
771 else if (d.pdf) line(INFO, `PDF images: not drawn (${plain(d.pdf.error)})${d.bwrap?.usable ? '' : ': without bubblewrap kittex converts them only with mutool (MuPDF), never Ghostscript'}`)
772 const ready = d.latex.version !== undefined && d.dvisvgm.version !== undefined
773 if (ready && !d.found && d.option === 'auto' && d.drawn) line(INFO, 'this session started before TeX was there: restart Claude Code to draw diagrams')
774
775 // Cache
776 section('Cache')
777 const c = facts.cache
778 if (!c.dir) line(INFO, 'no cache directory (neither XDG_CACHE_HOME nor HOME is set)')
779 else if (c.bytes === undefined && c.files === undefined) line(INFO, `${path(c.dir)}: empty`)
780 else {
781 line(INFO, `${path(c.dir)}: ${c.bytes !== undefined ? bytes(c.bytes) : 'size unknown'}${c.files !== undefined ? ` in ${c.files} ${c.files === 1 ? 'file' : 'files'}` : ''}`)
782 const part = (p: CachePart) => `${p.bytes !== undefined ? bytes(p.bytes) : 'size unknown'} in ${p.files} ${p.files === 1 ? 'file' : 'files'}`
783 if (c.images) line(INFO, `images of resumed replies: ${c.images.files === 0 ? 'none' : part(c.images)} (the oldest go past ${CACHE_LIMIT_BYTES / 2 ** 20} MiB)`)
784 if (c.tex) line(INFO, `pictures TeX drew: ${c.tex.files === 0 ? 'none' : part(c.tex)} (the oldest go past ${TEX_CACHE_LIMIT_BYTES / 2 ** 20} MiB)`)
785 if (c.format) line(INFO, `TeX format: ${c.format.files === 0 ? 'none' : part(c.format)} (kept; replaced when TeX changes)`)
786 }
787
788 // What to install
789 const missing = [
790 ...(d.latex.path ? [] : ['latex']),
791 ...(d.dvisvgm.path ? [] : ['dvisvgm']),
792 ...(d.kpsewhich.path || !d.latex.path ? [] : ['kpsewhich']),
793 ...(d.files ?? []).filter(file => !file.path).map(file => file.name),
794 ...(linux && !d.bwrap?.path ? ['bwrap'] : []),
795 ...(linux && !d.prlimit?.path && !d.ulimit ? ['prlimit'] : []),
796 ]
797 const advice = d.option === 'off' ? undefined : installAdvice(os, missing, d.latex.path)
798 if (advice && advice.commands.length + (advice.note ? 1 : 0) > 0) {
799 section(`${advice.confineOnly ? 'To confine TeX' : 'To enable diagrams'} (${plain(advice.label)})`)
800 if (advice.commands.length > 0) out.push('```sh', ...advice.commands, '```')
801 if (advice.note) out.push(advice.note)
802 out.push('Then restart Claude Code and run /kittex-doctor again.')
803 }
804 return out.join('\n')
805}
806types/index.d.ts 127 lines1// kittex's contract: the values it keeps in `$.state` (PluginState), named in
2// plugin.json as "types". Self-contained (no import), types only.
3
4/** What drawing needs to know about the terminal (kittex.env). */
5export type KittexEnv = {
6 kind: 'kitty' | 'ghostty' | 'wezterm' | 'iterm2' | 'other'
7 /** Whether Image draws pictures here. */
8 images: boolean
9 /** One cell, in pixels. */
10 cellWidth: number
11 cellHeight: number
12 /** Terminal (viewport) columns as last known. */
13 columns: number
14 /** Pixels per em of the math font. */
15 emPx: number
16 /** The formulas' colour. */
17 ink: { r: number; g: number; b: number }
18 /** The background the ink's alpha is corrected against, as the terminal corrects its text (Ghostty's linear-corrected blending); absent where images and text blend alike. */
19 inkOver?: { r: number; g: number; b: number }
20 /** How the terminal set its cells off its font's (Ghostty's adjust-cell-width, adjust-cell-height, adjust-font-baseline); absent when none is set. */
21 cellAdjust?: {
22 width?: { factor: number } | { px: number }
23 height?: { factor: number } | { px: number }
24 baseline?: { factor: number } | { px: number }
25 }
26 /** Whether the cell size was measured (false: the fallback cell). */
27 measured: boolean
28 /** The glyph the engine opens a reply with (`⏺` on macOS, `●` elsewhere); `●` when absent. */
29 bullet?: string
30 /** The `maxProseWidth` setting: reply prose wraps at most this wide; absent when unset. */
31 maxProseWidth?: number
32 /** Whether the engine draws links as OSC 8 hyperlinks (their text alone) or as text with the url beside it; absent when unknown (links aren't followed). */
33 hyperlinks?: boolean
34 /** Whether the terminal draws emoji sequences (an emoji with U+FE0F or a skin tone, joiner chains, flags, keycaps) two cells wide, as the engine counts them; absent: they keep their paragraph's math Unicode. */
35 emojiSequences?: boolean
36 /** The stroke weight the math is drawn with, matched to the terminal font's weight (strokeWeight); absent when that weight isn't known (the default weight). */
37 weight?: number
38 /** The terminal's background, when its colours were read: TeX's white becomes it, and diagrams' colours are kept legible on it. */
39 background?: { r: number; g: number; b: number }
40 /** With `inkOver`: kitty's text curve (text_composition_strategy) the ink's alpha follows instead of the gamma-blend correction. */
41 inkCurve?: { gamma: number; contrast: number }
42 /** kitty's modify_font changes to its cells; absent when none is set. */
43 kittyAdjust?: {
44 cellWidth?: { value: number; unit: 'pt' | 'px' | '%' }
45 cellHeight?: { value: number; unit: 'pt' | 'px' | '%' }
46 baseline?: { value: number; unit: 'pt' | 'px' | '%' }
47 }
48 /**
49 * The text font's metrics (read from its file once kittex is set up), its
50 * configured size and the platform: the math's em and baseline follow the
51 * text's (textLayout); absent until read, or when they can't be.
52 */
53 font?: {
54 unitsPerEm: number
55 ascender: number
56 descender: number
57 lineGap: number
58 xHeight?: number
59 advance?: number
60 sizePt?: number
61 platform?: string
62 }
63}
64
65/** One preview written while a reply streamed (display, or inline when `inline`), and the TeX it stands for (kittex.records). */
66export type KittexPreview = {
67 /** The markdown exactly as written into the reply (lines after the first carry its indentation). */
68 preview: string
69 tex: string
70 /** Rows reserved on screen; the image is drawn at least this tall (0 for a refused formula). */
71 rows: number
72 /** MathJax refused the formula: why. The preview is its source and a `not rendered` line. */
73 error?: string
74 /** An inline formula's preview (one row, `columns` cells, drawn over by its image once landed). */
75 inline?: true
76 /** Inline: the cells the preview and its image take. */
77 columns?: number
78 /**
79 * Inline: where its ink goes in those cells, as the characters around it in
80 * the source suggest (an image drawn ahead of landing; the landed layout's
81 * rows decide).
82 */
83 place?: 'center' | 'start' | 'end'
84 /** Where the preview starts in the block's text as the engine shows it (every flush's displayContent joined): how a landed block finds it. */
85 at?: number
86 /** Display: written in a blockquote this deep (its lines carry the quote's `>`, its width the quote's text width). */
87 quote?: number
88 /**
89 * Display: written in a list item whose text is this many cells in from the
90 * reply column (its lines carry the item's indentation, its width the item's
91 * text width); its image lies over it in the item once landed.
92 */
93 indent?: number
94 /**
95 * A diagram for the local TeX (a ```latex, ```tex or ```tikz block, or a
96 * bare picture environment), `tex` its source: the preview is its
97 * placeholder, `rows` tall, drawn over by its picture once landed (with
98 * `error`: the block as written and its `not rendered` line).
99 */
100 diagram?: 'latex' | 'tikz' | 'env'
101}
102
103/** One text block kittex streamed (kittex.blocks, by MessageDisplay's message_id). */
104export type KittexBlock = {
105 /** Its previews, in the order written, each with `at`. */
106 records: KittexPreview[]
107 /** Where the stream gave up: from this offset of the shown text on, the model's text passed as written. */
108 raw?: number
109 /** The session's working directory when it streamed: its image blocks' relative paths resolve against it, not the session's later one. */
110 cwd?: string
111}
112
113declare module 'claude-code' {
114 interface PluginState {
115 kittex: {
116 /** The terminal as drawing sees it; null until session.start set it up, or when that failed. */
117 env: KittexEnv | null
118 /** Each streamed block's previews, by MessageDisplay's message_id; null once dropped (past BLOCK_LIMIT). */
119 blocks: StateFamily<KittexBlock | null>
120 /** The message_id each landed block streamed as, by its transcript row's uuid (AssistantMessage's requestId). */
121 requests: StateFamily<string>
122 /** The newest blocks' message_ids, newest last (a landed block that no row links is looked for among them). */
123 recent: string[]
124 }
125 }
126}
127