Claude's answers, rendered: Markdown, math, charts and diagrams drawn in the Claude Code terminal. Independent project, not affiliated with Anthropic.
TypeScript claude-code-mod
Footprint: short wrapper names, and a release gate
razorback161113e84adc9c
diff --git a/docs/development.md b/docs/development.mdindex b9847ad..904444d 100644--- a/docs/development.md+++ b/docs/development.md@@ -16,6 +16,7 @@ sh tests/bold-sh-test.sh # the fake bold of md.typ (term-bold=0) with thesh tests/code-sh-test.sh # code blocks of md.typ (width, header, copy button mark, row grid) with the real Typst (skips with no typst)sh tests/root-sh-test.sh # the Typst root of a compile (STAGE_SH): answer code reads no other file, with the real Typst (its compiles skip with no typst)sh tests/check-sh-test.sh # the skill's check.sh: a private cache folder, and a block reads no other file (skips with no Typst 0.15)+sh tests/footprint-sh-test.sh # release gate: the validator's footprint is whole (no [+N chars] mark, calls line of 850 characters at most)claude plugin validate .```@@ -38,7 +39,7 @@ Picture select writes trace lines that start with `select:`:## Module layout-The hooks module is `hooks/register.tsx`. It connects the hooks to the modules in `hooks/lib/`. Each module has one topic, for example `markdown.ts` (blocks and segments), `mode.ts` (light or dark), `typst.ts` (compile), `fonts.ts` (the lean font set: the fonts that a compile of plain text loads), `draw.tsx` (the pages of an answer and the link rows under them), `links.ts` (the links, file paths and commands of a text), `answer.ts` (one text through the compile and cache steps), `plan.tsx` (the plan approval question and the plan rows), `frame.ts` (the terminal size and the watcher process, which also reports the clipboard changes), `clipboard.ts` (how the clipboard is read and watched for the `/iui grab` toast: macOS, or the Linux tools), `copy.ts` (the text under a mouse selection of pictures), `select.ts` and `blit.ts` (picture select and its highlight), `frames.ts` (the frames of a page: the cell edges, the bands, the row pieces and the frame PNG), `pagecache.ts` (the background page cache: the build queue in slices, and the words probe), `png.ts` (PNG decode, also in steps, and the deflate pieces, in plain JavaScript), `probe.ts` (the drawn pages, and the words of a page that a copy reads, kept in memory) and `updates.ts` (the daily check for a new version). The values that change are in one object, `S`, in `state.ts`. Each `$` method has one call site, a wrapper in `api.ts`; the other modules call the wrappers. This keeps the `calls:` note of `claude plugin validate` short (the validator cuts a note at about 1,000 characters, and the catalogue scan then cannot read the footprint). The tests import from `hooks/register.tsx`, which exports the names that they use.+The hooks module is `hooks/register.tsx`. It connects the hooks to the modules in `hooks/lib/`. Each module has one topic, for example `markdown.ts` (blocks and segments), `mode.ts` (light or dark), `typst.ts` (compile), `fonts.ts` (the lean font set: the fonts that a compile of plain text loads), `draw.tsx` (the pages of an answer and the link rows under them), `links.ts` (the links, file paths and commands of a text), `answer.ts` (one text through the compile and cache steps), `plan.tsx` (the plan approval question and the plan rows), `frame.ts` (the terminal size and the watcher process, which also reports the clipboard changes), `clipboard.ts` (how the clipboard is read and watched for the `/iui grab` toast: macOS, or the Linux tools), `copy.ts` (the text under a mouse selection of pictures), `select.ts` and `blit.ts` (picture select and its highlight), `frames.ts` (the frames of a page: the cell edges, the bands, the row pieces and the frame PNG), `pagecache.ts` (the background page cache: the build queue in slices, and the words probe), `png.ts` (PNG decode, also in steps, and the deflate pieces, in plain JavaScript), `probe.ts` (the drawn pages, and the words of a page that a copy reads, kept in memory) and `updates.ts` (the daily check for a new version). The values that change are in one object, `S`, in `state.ts`. The hook bodies in `register.tsx` call `$` themselves; every other `$` call is a wrapper with a short name in `api.ts` (for example `cat` for `$.fs.read`, `exec` for `$.process.run`). The `calls:` note of `claude plugin validate` names each method with the wrappers that call it (`via cat`), and a method that a hook body calls with none. The validator cuts a note at about 1,000 characters and marks the cut `[+N chars]`; the catalogue scan then cannot read the footprint. `tests/footprint-sh-test.sh` is the release gate for this: it fails on a `[+N chars]` mark in the text or the `--json` report, on a calls line (the text after `calls: `) of more than 850 characters, and on a `$` call in `hooks/` outside `api.ts` and `register.tsx`. The tests import from `hooks/register.tsx`, which exports the names that they use.The skill for Claude is in `skills/intelligent-ui/`: `SKILL.md` (the contract, the workflow and an index), `references/` (one file for each topic: Typst, fletcher, CeTZ, plots and charts) and `scripts/check.sh` (the compile check, with the real template). `TYPST_PROMPT` in `hooks/lib/settings.ts` tells Claude when to load it.diff --git a/hooks/lib/answer.ts b/hooks/lib/answer.tsindex e2f102f..0e9c4a6 100644--- a/hooks/lib/answer.ts+++ b/hooks/lib/answer.ts@@ -15,7 +15,7 @@ import { designInMemory, designKey, loadDesign } from './designs'import { resultOf, touchLater } from './typst'import { enqueue, finalize, forget, waitBlank } from './stream'import { extendEpoch } from './epoch'-import { clockAfter, fsRead } from './api'+import { delay, cat } from './api'// `pages`: draw these (with `bytes` over ssh); `blank`: draw an empty box;// `text`: draw the engine's own row.@@ -78,7 +78,7 @@ async function roomOf($: EngineInterface, o: { hasRoom: boolean; textHash: strinasync function fromDisk($: EngineInterface, env: Env, key: string): Promise<Result | null> {if (!S.onDisk.has(key)) return nullconst dir = `${env.cache}/${key}`- const text = await fsRead($, `${dir}/pages.json`).catch(() => null)+ const text = await cat($, `${dir}/pages.json`).catch(() => null)const got = text ? resultOf(text) : nullif (!got) {S.onDisk.delete(key)@@ -158,7 +158,7 @@ export async function pagesOf($: EngineInterface, o: PagesInput): Promise<Drawinconst was = live.get(id)if (!was || changed) {was?.still.cancel()- const still = clockAfter($, S.stepsLive > 0 ? LIVE_STILL_MS : SETTLE_MS, () => finalize($, id, false))+ const still = delay($, S.stepsLive > 0 ? LIVE_STILL_MS : SETTLE_MS, () => finalize($, id, false))live.set(id, { job, still })} else live.set(id, { job, still: was.still })pending.get(id)?.timer.cancel()diff --git a/hooks/lib/api.ts b/hooks/lib/api.tsindex b878bd8..4c74679 100644--- a/hooks/lib/api.ts+++ b/hooks/lib/api.ts@@ -1,15 +1,20 @@-// The one call site of each `$` method the mod uses: the other modules call-// these wrappers, so the `calls:` note of `claude plugin validate` names one-// function per method and stays short. Each wrapper is a function-// declaration that spells the call `$.noun.method(...)` (the validator-// follows `$` into a declaration only), with the types of EngineInterface.+// The one call site of each `$` method the mod uses outside the hook bodies+// of register.tsx: the other modules call these wrappers. The `calls:` note+// of `claude plugin validate` names each method with the wrappers that call+// it (`via <name>`), and a method that a hook body calls itself with none;+// the validator cuts that note at about 1,000 characters, and the catalogue+// then can not read the footprint. So the names are short, and+// tests/footprint-sh-test.sh keeps the note at 850 characters at most. Each+// wrapper is a function declaration that spells the call `$.noun.method(...)`+// (the validator follows `$` into a declaration only), with the types of+// EngineInterface.import type {AskOptions, CommandSpec, EngineInterface, FsBytes, FsReadBytesOptions, FsReadOptions, FsStatOptions, HttpInit, ImageBlitArgs, InvalidatableEventName,OpEventOf, PaneCloseArgs, PaneOpenArgs, ProcessRunInit, ProcessSpawnRequest, ResolveInput, ToastOptions, UiCopyArgs, UiLogOptions,} from 'claude-code'// The environment variables the mod reads. `$.env.get` takes a literal name-// (the validator lists them), so envGet has one call per name.+// (the validator lists them), so getenv has one call per name.export type EnvName =| 'CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC' | 'CLAUDE_CODE_FORCE_TERMINAL_IMAGES' | 'CLAUDE_CODE_SESSION_KIND' | 'CLAUDE_CODE_TMPDIR'| 'CMUX_SOCKET_PATH' | 'CMUX_SURFACE_ID' | 'CMUX_WORKSPACE_ID' | 'COLORFGBG' | 'DISABLE_AUTOUPDATER' | 'DISABLE_UPDATES' | 'DISPLAY'@@ -18,31 +23,31 @@ export type EnvName =| 'KITTY_WINDOW_ID' | 'LC_TERMINAL' | 'RIO_CONFIG_HOME' | 'SHELL' | 'SSH_CONNECTION' | 'SSH_TTY' | 'STY'| 'TERM' | 'TERM_PROGRAM' | 'TMUX' | 'TYPST_FONT_PATHS' | 'WAYLAND_DISPLAY' | 'XDG_CONFIG_HOME' | 'XDG_CURRENT_DESKTOP' | 'ZDOTDIR'-export function clockAfter($: EngineInterface, ms: number, fn: () => void) {+export function delay($: EngineInterface, ms: number, fn: () => void) {return $.clock.after(ms, fn)}-export function clockEvery($: EngineInterface, ms: number, fn: () => void) {+export function every($: EngineInterface, ms: number, fn: () => void) {return $.clock.every(ms, fn)}-export function clockNow($: EngineInterface) {+export function nowMs($: EngineInterface) {return $.clock.now()}-export function commandAdd($: EngineInterface, command: CommandSpec) {+export function cmd($: EngineInterface, command: CommandSpec) {return $.command.register(command)}-export function commandRun($: EngineInterface, input: Parameters<EngineInterface['command']['run']>[0]) {+export function runCmd($: EngineInterface, input: Parameters<EngineInterface['command']['run']>[0]) {return $.command.run(input)}-export function configs($: EngineInterface) {+export function cfgs($: EngineInterface) {return $.config.list()}-export function envGet($: EngineInterface, name: EnvName): Promise<string | undefined> {+export function getenv($: EngineInterface, name: EnvName): Promise<string | undefined> {switch (name) {case 'CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC': return $.env.get('CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC')case 'CLAUDE_CODE_FORCE_TERMINAL_IMAGES': return $.env.get('CLAUDE_CODE_FORCE_TERMINAL_IMAGES')@@ -81,31 +86,31 @@ export function envGet($: EngineInterface, name: EnvName): Promise<string | unde}}-export function fsExists($: EngineInterface, path: string) {+export function exists($: EngineInterface, path: string) {return $.fs.exists(path)}-export function fsList($: EngineInterface, path?: string) {+export function ls($: EngineInterface, path?: string) {return $.fs.list(path)}// The overloads of `$.fs.read` (FsReadCall): text, or bytes with `{ as: 'bytes' }`.-export function fsRead($: EngineInterface, path: string): Promise<string>-export function fsRead($: EngineInterface, path: string, options: FsReadBytesOptions): Promise<FsBytes>-export function fsRead($: EngineInterface, path: string, options: FsReadOptions): Promise<string | FsBytes>-export function fsRead($: EngineInterface, path: string, options?: FsReadOptions): Promise<string | FsBytes> {+export function cat($: EngineInterface, path: string): Promise<string>+export function cat($: EngineInterface, path: string, options: FsReadBytesOptions): Promise<FsBytes>+export function cat($: EngineInterface, path: string, options: FsReadOptions): Promise<string | FsBytes>+export function cat($: EngineInterface, path: string, options?: FsReadOptions): Promise<string | FsBytes> {return options ? $.fs.read(path, options) : $.fs.read(path)}-export function fsStat($: EngineInterface, path: string, options?: FsStatOptions) {+export function stat($: EngineInterface, path: string, options?: FsStatOptions) {return $.fs.stat(path, options)}-export function fsWrite($: EngineInterface, path: string, text: string) {+export function write($: EngineInterface, path: string, text: string) {return $.fs.write(path, text)}-export function httpFetch($: EngineInterface, url: string, init?: HttpInit) {+export function http($: EngineInterface, url: string, init?: HttpInit) {return $.http.fetch(url, init)}@@ -113,7 +118,7 @@ export function pluginRoot($: EngineInterface) {return $.plugin.root}-export function processRun($: EngineInterface, argv: readonly string[], init?: ProcessRunInit) {+export function exec($: EngineInterface, argv: readonly string[], init?: ProcessRunInit) {return $.process.run(argv, init)}@@ -121,67 +126,67 @@ export function spawn($: EngineInterface, request: ProcessSpawnRequest) {return $.process.spawn(request)}-export function submit($: EngineInterface, input: Parameters<EngineInterface['prompt']['submit']>[0]) {+export function send($: EngineInterface, input: Parameters<EngineInterface['prompt']['submit']>[0]) {return $.prompt.submit(input)}-export function sessionCwd($: EngineInterface) {+export function cwd($: EngineInterface) {return $.session.cwd()}-export function sessionId($: EngineInterface) {+export function sid($: EngineInterface) {return $.session.id()}-export function sessionRoot($: EngineInterface) {+export function root($: EngineInterface) {return $.session.root()}-export function sessionVersion($: EngineInterface) {+export function ver($: EngineInterface) {return $.session.version()}-export function sessionSurfaces($: EngineInterface) {+export function surf($: EngineInterface) {return $.session.surfaces()}-export function storeGet($: EngineInterface, key: string) {+export function load($: EngineInterface, key: string) {return $.store.get(key)}-export function storeSet($: EngineInterface, key: string, value: unknown) {+export function save($: EngineInterface, key: string, value: unknown) {return $.store.set(key, value)}-export function turnAbort($: EngineInterface, input: OpEventOf['turn.abort']) {+export function abort($: EngineInterface, input: OpEventOf['turn.abort']) {return $.turn.abort(input)}-export function uiAsk($: EngineInterface, question: string, options?: readonly string[] | AskOptions) {+export function ask($: EngineInterface, question: string, options?: readonly string[] | AskOptions) {return $.ui.ask(question, options)}-export function uiBlit($: EngineInterface, args: ImageBlitArgs) {+export function paint($: EngineInterface, args: ImageBlitArgs) {return $.ui.blit(args)}-export function uiClose($: EngineInterface, pane: PaneCloseArgs) {+export function hide($: EngineInterface, pane: PaneCloseArgs) {return $.ui.close(pane)}-export function uiCopy($: EngineInterface, args: UiCopyArgs) {+export function copy($: EngineInterface, args: UiCopyArgs) {return $.ui.copy(args)}-export function invalidate($: EngineInterface, event: InvalidatableEventName) {+export function redraw($: EngineInterface, event: InvalidatableEventName) {return $.ui.invalidate(event)}-export function uiLog($: EngineInterface, text: string, options?: UiLogOptions) {+export function log($: EngineInterface, text: string, options?: UiLogOptions) {return $.ui.log(text, options)}-export function uiOpen($: EngineInterface, pane: PaneOpenArgs) {+export function show($: EngineInterface, pane: PaneOpenArgs) {return $.ui.open(pane)}@@ -193,6 +198,6 @@ export function uiSelection($: EngineInterface) {return $.ui.selection()}-export function uiToast($: EngineInterface, text: string, options?: ToastOptions) {+export function toast($: EngineInterface, text: string, options?: ToastOptions) {return $.ui.toast(text, options)}diff --git a/hooks/lib/blit.ts b/hooks/lib/blit.tsindex b6520fb..6938476 100644--- a/hooks/lib/blit.ts+++ b/hooks/lib/blit.ts@@ -23,7 +23,7 @@ import type { DrawnPage } from './copy'import type { SelRow } from './select'import { perlFor } from './host'import { traceDebug } from './log'-import { clockNow, processRun, uiBlit, uiLog } from './api'+import { nowMs, exec, paint, log } from './api'export { bandOf, edgesOf, frameOf, framesOf, over, rgbOf, selectColor, type Frames, type Rgb } from './frames'@@ -115,7 +115,7 @@ function logOnce($: EngineInterface, text: string) {traceDebug($, `select: ${text}`)if (blits.logged.has(text)) returnblits.logged.add(text)- void Promise.resolve(uiLog($, `Intelligent UI: picture select: ${text}`, { to: 'debug' })).catch(() => undefined)+ void Promise.resolve(log($, `Intelligent UI: picture select: ${text}`, { to: 'debug' })).catch(() => undefined)}// The newest frame file's name, and the old ones that can go.@@ -149,14 +149,14 @@ async function showPage($: EngineInterface, id: string, i: number, page: DrawnPablits.shown.set(k, sig)return false}- const now = await clockNow($).catch(() => Date.now())+ const now = await nowMs($).catch(() => Date.now())const t1 = performance.now()const made = frameNow(got.frames, rows)const png = made.pngisWhole = made.isWholeconst t2 = performance.now()const { path, old } = nextFile(env.cache, now)- const ran = await processRun($, [perlFor(env.isMac), '-e', WRITE_PL, path, ...old], { stdin: toBase64(png) }).catch(err => ({ exitCode: -1, stderr: String(err) }))+ const ran = await exec($, [perlFor(env.isMac), '-e', WRITE_PL, path, ...old], { stdin: toBase64(png) }).catch(err => ({ exitCode: -1, stderr: String(err) }))const t3 = performance.now()if (ran.exitCode !== 0) {// No perl: no frame is tried again.@@ -170,7 +170,7 @@ async function showPage($: EngineInterface, id: string, i: number, page: DrawnPatiming = `wait ${ms(got.waitMs)} frame ${ms(t2 - t1)}${isWhole ? '' : ' (part)'} write ${ms(t3 - t2)} ${png.length} bytes`}const t4 = performance.now()- const res = await uiBlit($, { requestId: site.requestId, key, source }).catch(err => ({ deny: String(err) }))+ const res = await paint($, { requestId: site.requestId, key, source }).catch(err => ({ deny: String(err) }))const blit = `blit ${ms(performance.now() - t4)}`if (res.deny) {blits.shown.delete(k)diff --git a/hooks/lib/clipboard.ts b/hooks/lib/clipboard.tsindex 2129146..c6d8a89 100644--- a/hooks/lib/clipboard.ts+++ b/hooks/lib/clipboard.ts@@ -9,7 +9,7 @@import type { EngineInterface } from 'claude-code'import { S } from './state'-import { envGet, processRun } from './api'+import { getenv, exec } from './api'// The tools the choice looks for, in the order it prefers them. `gtk` is// python3 when it can load GTK 3 (gi).@@ -161,11 +161,11 @@ export function findClipWay($: EngineInterface): Promise<ClipWay> {return p}async function lookUp($: EngineInterface): Promise<ClipWay> {- const got = await processRun($, ['sh', '-c', FIND_SH], { timeoutMs: 5000 }).catch(() => null)+ const got = await exec($, ['sh', '-c', FIND_SH], { timeoutMs: 5000 }).catch(() => null)S.clipWay = clipWayOf({- wayland: !!(await envGet($, 'WAYLAND_DISPLAY')),- x11: !!(await envGet($, 'DISPLAY')),- desktop: (await envGet($, 'XDG_CURRENT_DESKTOP')) ?? '',+ wayland: !!(await getenv($, 'WAYLAND_DISPLAY')),+ x11: !!(await getenv($, 'DISPLAY')),+ desktop: (await getenv($, 'XDG_CURRENT_DESKTOP')) ?? '',found: clipToolsOf(got?.stdout ?? ''),})return S.clipWay@@ -176,12 +176,12 @@ async function lookUp($: EngineInterface): Promise<ClipWay> {// password manager's copy, which is never read).export async function clipboardNow($: EngineInterface): Promise<string | null> {if (S.env?.isMac) {- const got = await processRun($, ['/usr/bin/perl', '-e', READ_PL], { timeoutMs: 2000 }).catch(() => null)+ const got = await exec($, ['/usr/bin/perl', '-e', READ_PL], { timeoutMs: 2000 }).catch(() => null)return got && got.exitCode === 0 ? got.stdout : null}const way = S.clipWayif (!way || !('read' in way)) return null- const got = await processRun($, way.read, { timeoutMs: 2000 }).catch(() => null)+ const got = await exec($, way.read, { timeoutMs: 2000 }).catch(() => null)return got && got.exitCode === 0 ? got.stdout : null}diff --git a/hooks/lib/command.ts b/hooks/lib/command.tsindex 98639ec..7e9f443 100644--- a/hooks/lib/command.ts+++ b/hooks/lib/command.ts@@ -7,7 +7,7 @@ import {type Height, type Width,} from './settings'import { isThemeName, type ThemeInfo } from './themes'-import { commandAdd } from './api'+import { cmd } from './api'// `/iui` arguments: on, off, size <80-200>, width [40-400|full],// height [6-200|half|full], grid [on|off], select [on|off], updates@@ -173,7 +173,7 @@ export function commandSuggestions(// /iui; registered at session start and again in setUp, so it is// there after a hot reload too.export async function registerCommand($: EngineInterface) {- await commandAdd($, {+ await cmd($, {name: 'iui',description: "Draw Claude's answers as rendered Markdown pictures: on, off, size <80-200> (text size in % of the terminal's), width [40-400|full] (the most columns a picture takes), height [6-200|half|full] (the most rows an image or a Typst drawing takes), grid [on|off] (each line of text on whole terminal rows), select [on|off] (select and copy picture text with the mouse), updates [on|off] (look for a new version once a day), theme [name] (list or switch themes), grab (copy the text of the selected pictures, or of the picture cells on the clipboard), dump (copy diagnostics)",argumentHint: '[on|off|size <percent>|width [columns|full]|height [rows|half|full]|grid [on|off]|select [on|off]|updates [on|off]|theme [name]|grab|dump]',diff --git a/hooks/lib/designs.ts b/hooks/lib/designs.tsindex a1cf056..b0385b9 100644--- a/hooks/lib/designs.ts+++ b/hooks/lib/designs.ts@@ -16,7 +16,7 @@ import type { EngineInterface } from 'claude-code'import { keep, type Design } from './state'import { hashOf } from './draw'import { touchLater } from './typst'-import { fsExists, fsRead, fsWrite } from './api'+import { exists, cat, write } from './api'export type { Design } from './state'@@ -71,7 +71,7 @@ export function noteDesign(key: string, design: Design) {export async function loadDesign($: EngineInterface, dir: string, key: string): Promise<Design | null> {if (known.has(key)) return known.get(key) ?? nullconst path = designPath(dir, key)- const text = await fsRead($, path).catch(() => null)+ const text = await cat($, path).catch(() => null)const design = typeof text === 'string' ? parseDesign(text) : nullkeep(known, key, design, DESIGNS_IN_MEMORY)if (design) touchLater($, path)@@ -85,8 +85,8 @@ export async function recordDesign($: EngineInterface, dir: string, key: string,try {if (known.get(key) && !unsaved.has(key)) returnconst path = designPath(dir, key)- if (await fsExists($, path).catch(() => false)) {- const text = await fsRead($, path).catch(() => null)+ if (await exists($, path).catch(() => false)) {+ const text = await cat($, path).catch(() => null)const kept = typeof text === 'string' ? parseDesign(text) : nullif (kept) {keep(known, key, kept, DESIGNS_IN_MEMORY)@@ -94,7 +94,7 @@ export async function recordDesign($: EngineInterface, dir: string, key: string,return}}- await fsWrite($, path, designText(design))+ await write($, path, designText(design))keep(known, key, design, DESIGNS_IN_MEMORY)unsaved.delete(key)} catch {}diff --git a/hooks/lib/draw.tsx b/hooks/lib/draw.tsxindex 613035b..1a4ba37 100644--- a/hooks/lib/draw.tsx+++ b/hooks/lib/draw.tsx@@ -13,7 +13,7 @@ import { linksOf, type LinkItem } from './links'import { fitBox, fitsInline, roomColumns } from './terminal'import { clickLinks, selectOn } from './select'import { noteSite } from './blit'-import { fsExists, fsRead, uiCopy, uiResolve, uiToast } from './api'+import { exists, cat, copy, uiResolve, toast } from './api'// FNV-1a over the parts, twice with different offsets: 16 hex digits.export function hashOf(parts: readonly (string | number)[]): string {@@ -162,7 +162,7 @@ export async function inlineOf($: EngineInterface, result: Result): Promise<strifor (const page of result.pages) {if (!fitsInline(page)) return nullif (!inlined.has(page.file)) {- const got = await fsRead($, page.file, { as: 'bytes' }).catch(() => null)+ const got = await cat($, page.file, { as: 'bytes' }).catch(() => null)const base64 = got && fitsInline(page, got.base64) ? got.base64 : nullif (got) inlined.set(page.file, base64)for (const old of inlined.keys()) {@@ -297,7 +297,7 @@ export async function resolveLinks($: EngineInterface, items: readonly LinkItem[const path = home && item.path.startsWith('~/') ? `${home.replace(/\/+$/, '')}${item.path.slice(1)}` : imagePathOf(item.path, base)let isFile = linkFiles.get(path)if (isFile === undefined) {- isFile = await fsExists($, path).catch(() => false)+ isFile = await exists($, path).catch(() => false)keep(linkFiles, path, isFile, LINK_FILES_KEPT)}if (isFile) shown.push({ kind: 'file', label: item.label, path, href: fileHref(path) })@@ -317,8 +317,8 @@ export async function linksFor($: EngineInterface, text: string, base: string):// Copies a command at a press of its row, with a toast.async function copyCommand($: EngineInterface, text: string, surface: RenderSurface) {- const copied = await uiCopy($, { text, surface }).catch(() => null)- uiToast($, copied?.isCopied ? 'Copied' : `Could not copy${copied ? `: ${copied.reason}` : ''}`)+ const copied = await copy($, { text, surface }).catch(() => null)+ toast($, copied?.isCopied ? 'Copied' : `Could not copy${copied ? `: ${copied.reason}` : ''}`)}// One row per link, all dim and cut at the row's end (the copy counts themdiff --git a/hooks/lib/env.ts b/hooks/lib/env.tsindex 6650b03..96d77f5 100644--- a/hooks/lib/env.ts+++ b/hooks/lib/env.ts@@ -19,7 +19,7 @@ import { offerSetup } from './setup'import { findClipWay } from './clipboard'import { findTypst, measureFonts } from './typst'import { checkUpdates } from './updates'-import { configs, envGet, fsList, fsStat, pluginRoot, processRun, sessionCwd, sessionVersion, storeGet, uiToast } from './api'+import { cfgs, getenv, ls, stat, pluginRoot, exec, cwd, ver, load, toast } from './api'// The `isOn` atom, which setUp turns off when the stored setting says so (a// copy of its own: see state.ts).@@ -38,75 +38,75 @@ export const CACHE_SH = `d="\${TMPDIR:-/tmp}"; d="\${d%/}/cc-intelligent-ui-$(idexport function setUp($: EngineInterface): Promise<Env> {S.envLoading ??= (async () => {await registerCommand($)- const made = await processRun($, ['sh', '-c', CACHE_SH]).catch(() => null)+ const made = await exec($, ['sh', '-c', CACHE_SH]).catch(() => null)const [made1 = '', os = '', made3 = '', refused = ''] = (made?.stdout ?? '').split('\n')// No private cache folder: nothing is drawn (no shared folder instead).const cache = made1.trim()S.cacheProblem = cache ? '' : refused.trim() ? `the cache folder ${refused.trim()} is a link, not a folder, or not yours` : 'the cache folder could not be made'// The key folders on disk now: a key found here is read back at once.- const listed = cache ? await fsList($, cache).catch(() => []) : []+ const listed = cache ? await ls($, cache).catch(() => []) : []S.onDisk = new Set(listed.filter(entry => entry.kind === 'dir' && entry.name !== 'pkg-cache').map(entry => entry.name))- const program = (await envGet($, 'TERM_PROGRAM')) ?? ''- const term = (await envGet($, 'TERM')) ?? ''- const ssh = !!(await envGet($, 'SSH_CONNECTION')) || !!(await envGet($, 'SSH_TTY'))+ const program = (await getenv($, 'TERM_PROGRAM')) ?? ''+ const term = (await getenv($, 'TERM')) ?? ''+ const ssh = !!(await getenv($, 'SSH_CONNECTION')) || !!(await getenv($, 'SSH_TTY'))const terminalDraws = canDrawIn({program,term,- kitty: !!(await envGet($, 'KITTY_WINDOW_ID')),- tmux: !!(await envGet($, 'TMUX')) || !!(await envGet($, 'STY')) || /^tmux|^screen/i.test(term),+ kitty: !!(await getenv($, 'KITTY_WINDOW_ID')),+ tmux: !!(await getenv($, 'TMUX')) || !!(await getenv($, 'STY')) || /^tmux|^screen/i.test(term),ssh,- background: (await envGet($, 'CLAUDE_CODE_SESSION_KIND')) === 'bg',- engineForced: isSet(await envGet($, 'CLAUDE_CODE_FORCE_TERMINAL_IMAGES')),- modForced: isSet(await envGet($, 'IUI_FORCE')),+ background: (await getenv($, 'CLAUDE_CODE_SESSION_KIND')) === 'bg',+ engineForced: isSet(await getenv($, 'CLAUDE_CODE_FORCE_TERMINAL_IMAGES')),+ modForced: isSet(await getenv($, 'IUI_FORCE')),})const canDraw = terminalDraws && !!cacheconst root = pluginRoot($)- const template = await fsStat($, `${root}/render/md.typ`).catch(() => null)- const rows = await configs($).catch(() => [])+ const template = await stat($, `${root}/render/md.typ`).catch(() => null)+ const rows = await cfgs($).catch(() => [])const raw = rows.find(row => row.key === 'theme')?.valueS.settingRaw = typeof raw === 'string' ? raw : ''S.setting = settingOf(raw)S.hostOs = os.trim()S.termProgram = programS.termName = term- S.itermProfile = (await envGet($, 'ITERM_PROFILE')) || undefined- S.isKitty = /kitty/i.test(term) || !!(await envGet($, 'KITTY_WINDOW_ID')) || !!(await envGet($, 'KITTY_PID'))+ S.itermProfile = (await getenv($, 'ITERM_PROFILE')) || undefined+ S.isKitty = /kitty/i.test(term) || !!(await getenv($, 'KITTY_WINDOW_ID')) || !!(await getenv($, 'KITTY_PID'))S.isRemote = ssh- S.debug = isSet(await envGet($, 'IUI_DEBUG'))+ S.debug = isSet(await getenv($, 'IUI_DEBUG'))S.isIterm = isItermIn({program,profile: S.itermProfile,- session: (await envGet($, 'ITERM_SESSION_ID')) || undefined,- lcTerminal: (await envGet($, 'LC_TERMINAL')) || undefined,+ session: (await getenv($, 'ITERM_SESSION_ID')) || undefined,+ lcTerminal: (await getenv($, 'LC_TERMINAL')) || undefined,})S.setupNeeded = S.isIterm && !terminalDraws && !ssh && S.hostOs === 'Darwin' &&- !(await envGet($, 'TMUX')) && !(await envGet($, 'STY')) && (await envGet($, 'CLAUDE_CODE_SESSION_KIND')) !== 'bg'+ !(await getenv($, 'TMUX')) && !(await getenv($, 'STY')) && (await getenv($, 'CLAUDE_CODE_SESSION_KIND')) !== 'bg'if (S.setupNeeded) void offerSetup($).catch(() => undefined)- S.isCmux = !!(await envGet($, 'CMUX_SURFACE_ID')) || !!(await envGet($, 'CMUX_WORKSPACE_ID')) || !!(await envGet($, 'CMUX_SOCKET_PATH'))- S.colorFgBg = (await envGet($, 'COLORFGBG')) ?? ''- S.userFontPaths = (await envGet($, 'TYPST_FONT_PATHS')) ?? ''+ S.isCmux = !!(await getenv($, 'CMUX_SURFACE_ID')) || !!(await getenv($, 'CMUX_WORKSPACE_ID')) || !!(await getenv($, 'CMUX_SOCKET_PATH'))+ S.colorFgBg = (await getenv($, 'COLORFGBG')) ?? ''+ S.userFontPaths = (await getenv($, 'TYPST_FONT_PATHS')) ?? ''if (S.setting === 'auto') S.host = (await readHostMode($).catch(() => null)) ?? S.hostS.theme = resolveMode(S.setting, S.host)watchHost($)// The stored settings, but not one an /iui command set meanwhile (settingsSet).- const kept = Number(await storeGet($, 'size').catch(() => undefined))+ const kept = Number(await load($, 'size').catch(() => undefined))if (!settingsSet.has('size')) S.size = kept >= MIN_SIZE && kept <= MAX_SIZE ? kept : DEFAULT_SIZE- const width = await storeGet($, 'width').catch(() => undefined)+ const width = await load($, 'width').catch(() => undefined)if (!settingsSet.has('width')) {S.width = width === 'full' ? 'full' : Number.isInteger(width) && Number(width) >= MIN_WIDTH && Number(width) <= MAX_WIDTH ? Number(width) : DEFAULT_WIDTH}- const height = await storeGet($, 'height').catch(() => undefined)+ const height = await load($, 'height').catch(() => undefined)if (!settingsSet.has('height')) {S.height = height === 'half' || height === 'full' ? height: Number.isInteger(height) && Number(height) >= MIN_HEIGHT && Number(height) <= MAX_HEIGHT ? Number(height) : DEFAULT_HEIGHT}- const grid = (await storeGet($, 'grid').catch(() => undefined)) !== false+ const grid = (await load($, 'grid').catch(() => undefined)) !== falseif (!settingsSet.has('grid')) S.grid = grid- const select = (await storeGet($, 'select').catch(() => undefined)) !== false+ const select = (await load($, 'select').catch(() => undefined)) !== falseif (!settingsSet.has('select')) S.select = select// An engine with no version call is older than picture select.- S.engine = await Promise.resolve().then(() => sessionVersion($)).then(v => v.base ?? v.version, () => '')- const enabled = await storeGet($, 'enabled').catch(() => undefined)+ S.engine = await Promise.resolve().then(() => ver($)).then(v => v.base ?? v.version, () => '')+ const enabled = await load($, 'enabled').catch(() => undefined)if (enabled === false && !settingsSet.has('enabled')) await update($, isOn, () => false).catch(() => undefined)const isMac = os.trim() === 'Darwin'// Linux, on this computer: the clipboard tools, for the copy.@@ -116,23 +116,23 @@ export function setUp($: EngineInterface): Promise<Env> {const typst = await findTypst($)if (S.cacheProblem && terminalDraws) {try {- uiToast($, `Intelligent UI: no pictures, ${S.cacheProblem} (see /iui details)`, { timeoutMs: 8000 })+ toast($, `Intelligent UI: no pictures, ${S.cacheProblem} (see /iui details)`, { timeoutMs: 8000 })} catch {}} else if (!typst) {try {- uiToast($, noTypstOf(isMac), { timeoutMs: 8000 })+ toast($, noTypstOf(isMac), { timeoutMs: 8000 })} catch {}}const termFont = await termFontOf($, isMac).catch(() => '')- const home = (await envGet($, 'HOME')) ?? ''+ const home = (await getenv($, 'HOME')) ?? ''const designs = made3.trim() || (home ? `${home}/.cache/cc-intelligent-ui/designs` : cache ? `${cache}/designs` : '')- const stored = await storeGet($, 'theme-name').catch(() => undefined)+ const stored = await load($, 'theme-name').catch(() => undefined)const wanted = typeof stored === 'string' && stored ? stored : DEFAULT_THEMEconst applied = await applyTheme($, root, home, wanted).catch(() => null)if (!applied) S.look = { name: BASE_THEME, dir: `${root}/render/themes/${BASE_THEME}`, stamp: '0' }else if (applied.chosen.isFallback) {try {- uiToast($, `Intelligent UI: theme ${wanted} not found, using ${applied.chosen.name}`, { timeoutMs: 8000 })+ toast($, `Intelligent UI: theme ${wanted} not found, using ${applied.chosen.name}`, { timeoutMs: 8000 })} catch {}}S.env = {@@ -140,14 +140,14 @@ export function setUp($: EngineInterface): Promise<Env> {canDraw,inline: ssh && canDraw,cache,- cwd: await sessionCwd($).catch(() => '/'),+ cwd: await cwd($).catch(() => '/'),root,isMac,stamp: String(template?.mtimeMs ?? 0),home,claudeTmp: claudeTmpOf({- tmpdir: (await envGet($, 'CLAUDE_CODE_TMPDIR')) || undefined,- uid: await processRun($, ['id', '-u']).then(r => (r.exitCode === 0 ? r.stdout : ''), () => ''),+ tmpdir: (await getenv($, 'CLAUDE_CODE_TMPDIR')) || undefined,+ uid: await exec($, ['id', '-u']).then(r => (r.exitCode === 0 ? r.stdout : ''), () => ''),isMac,}),termFont,diff --git a/hooks/lib/epoch.ts b/hooks/lib/epoch.tsindex c0ff6ee..6c4fcab 100644--- a/hooks/lib/epoch.ts+++ b/hooks/lib/epoch.ts@@ -9,7 +9,7 @@ import type { EngineInterface } from 'claude-code'import { COMMIT_MAX_MS, COMMIT_MIN_MS } from './settings'import { converting, epochOpen, queue, refresh, running, S, type Frame, type Job } from './state'import { traceDebug } from './log'-import { clockAfter } from './api'+import { delay } from './api'// The open epoch: `ready` once COMMIT_MIN_MS passed with no new activity// (a row drawn, a job enqueued: extendEpoch), `overdue` once COMMIT_MAX_MS@@ -47,7 +47,7 @@ export function beginEpoch($: EngineInterface, frame?: Frame | null) {ready = falseoverdue = falsemaxTimer?.cancel()- maxTimer = clockAfter($, COMMIT_MAX_MS, () => {+ maxTimer = delay($, COMMIT_MAX_MS, () => {if (S.epoch !== epoch) returnoverdue = truemaybeCommit($)@@ -73,7 +73,7 @@ export function jobQueued(job: Job) {function armReady($: EngineInterface) {const epoch = S.epochminTimer?.cancel()- minTimer = clockAfter($, COMMIT_MIN_MS, () => {+ minTimer = delay($, COMMIT_MIN_MS, () => {if (S.epoch !== epoch) returnready = truemaybeCommit($)diff --git a/hooks/lib/fonts.ts b/hooks/lib/fonts.tsindex 00b8765..826b017 100644--- a/hooks/lib/fonts.ts+++ b/hooks/lib/fonts.ts@@ -12,7 +12,7 @@ import { leanDirs, type Env, type LeanFonts } from './state'import { FENCE, isTypstInfo } from './markdown'import { hashOf } from './draw'import { logDebug } from './log'-import { fsExists, processRun } from './api'+import { exists, exec } from './api'// The CJK and emoji fonts: large to read, and plain text never needs them.export const SKIPPED_FONTS = /emoji|cjk|pingfang|hiragino|gothic|han sans|han serif|yahei|jhenghei|meiryo|malgun|simsun|simhei|wenquanyi|droid sans fallback/i@@ -156,7 +156,7 @@ export async function leanFontsFor($: EngineInterface, env: Env, segments: readoif (!dir) return ''// The cleanup at start removes the folders not used for 2 days: one gone// is made again.- if (!(await fsExists($, dir).catch(() => false))) {+ if (!(await exists($, dir).catch(() => false))) {leanDirs.delete(want)return ''}@@ -167,14 +167,14 @@ export async function leanFontsFor($: EngineInterface, env: Env, segments: reado// files of the lean set. A failure is kept: no lean set for these fonts in// this session.async function makeLean($: EngineInterface, env: Env, typst: string, fonts: LeanFonts, want: string, vars: Record<string, string>) {- const listed = await processRun($, [typst, 'fonts', '--variants'], { timeoutMs: 10000, env: vars }).catch(() => null)+ const listed = await exec($, [typst, 'fonts', '--variants'], { timeoutMs: 10000, env: vars }).catch(() => null)const files = listed?.exitCode === 0 ? leanFiles(fontListOf(listed.stdout), env.termFont, fonts) : nullif (!files) {await logDebug($, env.cache, 'lean fonts: not used (the font list does not allow it)')return}const dir = leanDirOf(env.cache, files)- const made = await processRun($, ['sh', '-c', LEAN_SH, 'sh', dir, ...files], { timeoutMs: 10000 }).catch(() => null)+ const made = await exec($, ['sh', '-c', LEAN_SH, 'sh', dir, ...files], { timeoutMs: 10000 }).catch(() => null)if (made?.exitCode !== 0) {await logDebug($, env.cache, `lean fonts: the folder ${dir} was not made:\n${made?.stderr ?? ''}`)returndiff --git a/hooks/lib/frame.ts b/hooks/lib/frame.tsindex 4d25322..e4da827 100644--- a/hooks/lib/frame.ts+++ b/hooks/lib/frame.ts@@ -16,7 +16,7 @@ import { columnsFor, isGhosttyHere, sizeOf } from './terminal'import { CELL_SH, perlFor, termFontOf, WATCH_PL } from './host'import { clipWatchArgs } from './clipboard'import { measureFonts } from './typst'-import { clockAfter, processRun, spawn } from './api'+import { delay, exec, spawn } from './api'export type { Cell, Frame } from './state'@@ -97,7 +97,7 @@ const viewNow = (): View | null => (S.viewColumns === null ? null : { columns: S// One read of the tty size as a Frame; null when it fails (no tty, no// pixels).export async function readFrame($: EngineInterface): Promise<Frame | null> {- const tty = await processRun($, ['sh', '-c', CELL_SH], { timeoutMs: 5000 }).catch(() => null)+ const tty = await exec($, ['sh', '-c', CELL_SH], { timeoutMs: 5000 }).catch(() => null)return tty?.exitCode === 0 ? frameOfLine(tty.stdout) : null}@@ -140,7 +140,7 @@ let poke: (() => void) | null = nullfunction burst($: EngineInterface) {poke ??= quietTimer({ms: RESIZE_QUIET_MS,- after: (ms, fn) => clockAfter($, ms, fn),+ after: (ms, fn) => delay($, ms, fn),onStart: holdJobs,onQuiet: stale => void settle($, stale),})@@ -243,7 +243,7 @@ export function watchFrame($: EngineInterface, clip?: ((count: number | null, filet stopped = falselet counted = falseconst kill = () => {- if (stopped && pid && !me.ended) void Promise.resolve(processRun($, ['kill', pid], { timeoutMs: 5000 })).catch(() => undefined)+ if (stopped && pid && !me.ended) void Promise.resolve(exec($, ['kill', pid], { timeoutMs: 5000 })).catch(() => undefined)}const stop = () => {if (stopped) return@@ -272,7 +272,7 @@ export function watchFrame($: EngineInterface, clip?: ((count: number | null, fi// WATCH_RESTART_MS, while it is still the child now.if (stopped || me.final || !me.clip) returntry {- clockAfter($, WATCH_RESTART_MS, () => {+ delay($, WATCH_RESTART_MS, () => {if (watcher === me) watchFrame($)})} catch {}diff --git a/hooks/lib/host.ts b/hooks/lib/host.tsindex 0185748..2ed05f7 100644--- a/hooks/lib/host.ts+++ b/hooks/lib/host.ts@@ -17,7 +17,7 @@ import {} from './terminals'import { firstLine } from './markdown'import { isGhosttyHere } from './terminal'-import { clockEvery, envGet, fsExists, fsRead, processRun } from './api'+import { every, getenv, exists, cat, exec } from './api'// One tty size read: `rows cols xpixel ypixel` (TIOCGWINSZ); exit 1 with no tty.export const CELL_SH = `perl -e 'open(T, "</dev/tty") or exit 1; my $w = " " x 8; ioctl(T, ($^O eq "darwin" ? 0x40087468 : 0x5413), $w) or exit 1; print join(" ", unpack("S4", $w))'`@@ -214,20 +214,20 @@ export const fcPatternOf = (family: string) => family.replace(/[\\\-:,]/g, '\\$&// A family fontconfig gives for a pattern (the first of its names), '' when// fc-match fails. `fc-match` always gives a font, the nearest one.async function fcFamily($: EngineInterface, pattern: string): Promise<string> {- const got = await processRun($, ['fc-match', pattern, '-f', '%{family}'], { timeoutMs: 5000 }).catch(() => null)+ const got = await exec($, ['fc-match', pattern, '-f', '%{family}'], { timeoutMs: 5000 }).catch(() => null)return got?.exitCode === 0 ? familyOfFc(got.stdout) : ''}// The family of the first font that fontconfig lists for a pattern (only// fonts that match it), '' for none.async function fcListFamily($: EngineInterface, pattern: string): Promise<string> {- const got = await processRun($, ['fc-list', pattern, 'family'], { timeoutMs: 5000 }).catch(() => null)+ const got = await exec($, ['fc-list', pattern, 'family'], { timeoutMs: 5000 }).catch(() => null)return got?.exitCode === 0 ? familyOfFc(firstLine(got.stdout)) : ''}// What CoreText says of a family (HAS_FAMILY_JXA), '' when it can't be read.async function macFamily($: EngineInterface, family: string, mono = false): Promise<string> {- const got = await processRun($, ['osascript', '-l', 'JavaScript', '-e', HAS_FAMILY_JXA, family, ...(mono ? ['mono'] : [])], { timeoutMs: 5000 }).catch(() => null)+ const got = await exec($, ['osascript', '-l', 'JavaScript', '-e', HAS_FAMILY_JXA, family, ...(mono ? ['mono'] : [])], { timeoutMs: 5000 }).catch(() => null)return got?.exitCode === 0 ? firstLine(got.stdout) : ''}@@ -237,7 +237,7 @@ async function macFamily($: EngineInterface, family: string, mono = false): Prom// installed; null when that can't be read (then the name is taken as is).async function installedFamily($: EngineInterface, isMac: boolean, family: string, exact = false): Promise<string | null> {if (isMac && exact) {- const got = await processRun($, ['osascript', '-l', 'JavaScript', '-e', FAMILY_NOCASE_JXA, family], { timeoutMs: 5000 }).catch(() => null)+ const got = await exec($, ['osascript', '-l', 'JavaScript', '-e', FAMILY_NOCASE_JXA, family], { timeoutMs: 5000 }).catch(() => null)const line = got?.exitCode === 0 ? firstLine(got.stdout) : ''return line.startsWith('=') ? line.slice(1) : line === 'no' ? '' : null}@@ -245,7 +245,7 @@ async function installedFamily($: EngineInterface, isMac: boolean, family: strinconst seen = await macFamily($, family)return seen === 'yes' ? family : seen === 'no' ? '' : null}- const got = await processRun($, ['fc-list', exact ? ':' : fcPatternOf(family), 'family'], { timeoutMs: 5000 }).catch(() => null)+ const got = await exec($, ['fc-list', exact ? ':' : fcPatternOf(family), 'family'], { timeoutMs: 5000 }).catch(() => null)if (got?.exitCode !== 0) return null// Each line is a font's family names, split by commas, with `\` escapes.const names = got.stdout.split('\n').flatMap(line => line.split(/(?<!\\),/).map(name => name.replace(/\\(.)/g, '$1').trim())).filter(Boolean)@@ -258,7 +258,7 @@ async function installedFamily($: EngineInterface, isMac: boolean, family: strin// such font) or 'failed' (no program, or the copy failed).async function programFont($: EngineInterface, isMac: boolean, o: { tag: string; family: string; name: string; paths: readonly string[] }): Promise<'copied' | 'none' | 'failed'> {const argv = ['sh', '-c', PROGRAM_FONTS_SH, 'sh', perlFor(isMac), PROGRAM_FONTS_PL, o.tag, o.family, o.name, ...o.paths]- const made = await processRun($, argv, { timeoutMs: 10000 }).catch(() => null)+ const made = await exec($, argv, { timeoutMs: 10000 }).catch(() => null)const dir = made?.exitCode === 0 ? firstLine(made.stdout) : ''// No copy now: an older folder (maybe gone) is not given to Typst.if (!dir) S.fontPaths = ''@@ -273,7 +273,7 @@ async function programFont($: EngineInterface, isMac: boolean, o: { tag: string;// when fontconfig has it (Linux), else from a copy of the one in Ghostty's// program (S.fontPaths).async function ghosttyDefaultFont($: EngineInterface, isMac: boolean): Promise<string> {- const got = await processRun($, ['fc-list', '-q', GHOSTTY_DEFAULT_FONT], { timeoutMs: 5000 }).catch(() => null)+ const got = await exec($, ['fc-list', '-q', GHOSTTY_DEFAULT_FONT], { timeoutMs: 5000 }).catch(() => null)if (got?.exitCode === 0) return GHOSTTY_DEFAULT_FONTconst o = { tag: 'ghostty', family: GHOSTTY_DEFAULT_FONT, name: 'ghostty', paths: GHOSTTY_PROGRAMS }return (await programFont($, isMac, o)) === 'copied' ? GHOSTTY_DEFAULT_FONT : ''@@ -302,7 +302,7 @@ async function rioFont($: EngineInterface, isMac: boolean): Promise<string> {const named = rioFontOf((await readRioConfig($)).config)const found = named === RIO_DEFAULT_FONT ? '' : await installedFamily($, isMac, named, true)if (found !== '') return found ?? named- const home = (await envGet($, 'HOME')) ?? ''+ const home = (await getenv($, 'HOME')) ?? ''const copy = await programFont($, isMac, { tag: 'rio', family: RIO_DEFAULT_FONT, name: 'rio', paths: rioProgramsOf(home) })if (copy === 'copied') return RIO_DEFAULT_FONTif (copy === 'none') return RIO_OLD_FONT@@ -312,22 +312,22 @@ async function rioFont($: EngineInterface, isMac: boolean): Promise<string> {// The font that the terminal's own config or profile names.async function configFontOf($: EngineInterface, isMac: boolean): Promise<string> {if (S.isIterm && isMac) {- const profile = await envGet($, 'ITERM_PROFILE')+ const profile = await getenv($, 'ITERM_PROFILE')const [marks, guid] = await Promise.all([- processRun($, ['sh', '-c', ITERM_BOOKMARKS_SH], { timeoutMs: 5000 }).catch(() => null),- processRun($, ['sh', '-c', ITERM_DEFAULT_SH], { timeoutMs: 5000 }).catch(() => null),+ exec($, ['sh', '-c', ITERM_BOOKMARKS_SH], { timeoutMs: 5000 }).catch(() => null),+ exec($, ['sh', '-c', ITERM_DEFAULT_SH], { timeoutMs: 5000 }).catch(() => null),])// A read that failed or no profile: not known.const font = marks?.exitCode === 0 ? itermFontOf(marks.stdout, profile, guid?.stdout ?? '') : nullif (font === null) return ''// An empty or bad profile font, or one that is not installed: iTerm2 draws the user's fixed-pitch font.- const named = await processRun($, ['osascript', '-l', 'JavaScript', '-e', FAMILY_JXA, parseFontSpec(font)?.name ?? '', 'user'], { timeoutMs: 5000 }).catch(() => null)+ const named = await exec($, ['osascript', '-l', 'JavaScript', '-e', FAMILY_JXA, parseFontSpec(font)?.name ?? '', 'user'], { timeoutMs: 5000 }).catch(() => null)return named?.exitCode === 0 ? firstLine(named.stdout) : ''}if (isGhosttyHere()) {- const shown = await processRun($, ['sh', '-c', GHOSTTY_SH], { timeoutMs: 5000 }).catch(() => null)+ const shown = await exec($, ['sh', '-c', GHOSTTY_SH], { timeoutMs: 5000 }).catch(() => null)// cmux loads its own config after Ghostty's; +show-config does not read it.- const own = S.isCmux ? ((await readText($, cmuxGhosttyConfigPath((await envGet($, 'HOME')) ?? ''))) ?? '') : ''+ const own = S.isCmux ? ((await readText($, cmuxGhosttyConfigPath((await getenv($, 'HOME')) ?? ''))) ?? '') : ''return ghosttyFont($, isMac, ghosttyFontsOf(cmuxConfigOf(shown?.stdout ?? '', own)))}if (S.isKitty) {@@ -343,7 +343,7 @@ async function configFontOf($: EngineInterface, isMac: boolean): Promise<string>const seen = 'family' in font ? await macFamily($, name, true) : 'no'if (seen === 'yes' || seen === '') return nameif (seen === 'proportional') return KITTY_MAC_FONT- const named = await processRun($, ['osascript', '-l', 'JavaScript', '-e', FAMILY_JXA, name], { timeoutMs: 5000 }).catch(() => null)+ const named = await exec($, ['osascript', '-l', 'JavaScript', '-e', FAMILY_JXA, name], { timeoutMs: 5000 }).catch(() => null)return named?.exitCode === 0 ? firstLine(named.stdout) || KITTY_MAC_FONT : ''}const found = 'family' in font ? await installedFamily($, isMac, name) : ''@@ -385,7 +385,7 @@ export async function readHostMode($: EngineInterface): Promise<HostMode | null>// The background of the iTerm2 profile in use, on a Mac.async function readItermMode($: EngineInterface): Promise<HostMode | null> {if (!S.isIterm || S.hostOs !== 'Darwin') return null- const got = await processRun($, ['sh', '-c', ITERM_MODE_SH], { timeoutMs: HOST_CHECK_MS }).catch(() => null)+ const got = await exec($, ['sh', '-c', ITERM_MODE_SH], { timeoutMs: HOST_CHECK_MS }).catch(() => null)if (!got || got.exitCode !== 0) return nullconst [style = '', guid = '', marks = ''] = got.stdout.split(/^@\n/m)const appearance = itermAppearanceOf(style) ?? (await readOsMode($).catch(() => null))?.mode ?? null@@ -396,7 +396,7 @@ async function readItermMode($: EngineInterface): Promise<HostMode | null> {// One OSC 11 question to the terminal: its raw answer ('' for none), or null// when the tty could not be opened.export async function probeOsc11($: EngineInterface): Promise<{ reply: string } | null> {- const got = await processRun($, ['perl', '-e', OSC11_PL], { timeoutMs: HOST_CHECK_MS }).catch(() => null)+ const got = await exec($, ['perl', '-e', OSC11_PL], { timeoutMs: HOST_CHECK_MS }).catch(() => null)return got && got.exitCode === 0 ? { reply: got.stdout } : null}@@ -404,9 +404,9 @@ export async function probeOsc11($: EngineInterface): Promise<{ reply: string }// (in cmux, cmux's appearance). In cmux, cmux's own config is read as well.async function readGhosttyMode($: EngineInterface): Promise<HostMode | null> {if (!/ghostty/i.test(S.termProgram + S.termName)) return null- const got = await processRun($, ['sh', '-c', GHOSTTY_SH], { timeoutMs: HOST_CHECK_MS }).catch(() => null)+ const got = await exec($, ['sh', '-c', GHOSTTY_SH], { timeoutMs: HOST_CHECK_MS }).catch(() => null)if (!got || got.exitCode !== 0) return null- const home = (await envGet($, 'HOME')) ?? ''+ const home = (await getenv($, 'HOME')) ?? ''const own = S.isCmux ? ((await readText($, cmuxGhosttyConfigPath(home))) ?? '') : ''const config = cmuxConfigOf(got.stdout, own)if (S.isCmux && !ghosttyHasColors(config)) {@@ -419,13 +419,13 @@ async function readGhosttyMode($: EngineInterface): Promise<HostMode | null> {if (pair) {appearance = S.isCmux ? ((await readCmuxAppearance($).catch(() => null))?.mode ?? null) : ((await readOsMode($).catch(() => null))?.mode ?? null)const where = {- xdgConfig: (await envGet($, 'XDG_CONFIG_HOME')) || undefined,+ xdgConfig: (await getenv($, 'XDG_CONFIG_HOME')) || undefined,home,- resources: (await envGet($, 'GHOSTTY_RESOURCES_DIR')) || undefined,+ resources: (await getenv($, 'GHOSTTY_RESOURCES_DIR')) || undefined,}for (const mode of MODES) {for (const path of ghosttyThemePaths(pair[mode], where)) {- const text = await fsRead($, path).catch(() => null)+ const text = await cat($, path).catch(() => null)if (typeof text !== 'string') continuethemeBg[mode] = ghosttyValueOf(text, 'background')break@@ -443,7 +443,7 @@ async function readGhosttyMode($: EngineInterface): Promise<HostMode | null> {// (terminal.adaptiveDefaultTheme, on unless cmux.json turns it off) follows// cmux's appearance, the OS's when that is system. Null when it is off.async function readCmuxMode($: EngineInterface): Promise<HostMode | null> {- const home = (await envGet($, 'HOME')) ?? ''+ const home = (await getenv($, 'HOME')) ?? ''const settings = cmuxSettingsOf(jsoncOf((await readText($, `${home}/.config/cmux/cmux.json`)) ?? ''))if (settings.adaptive === false) return nullconst seen = await readCmuxAppearance($, settings.appearance)@@ -454,12 +454,12 @@ async function readCmuxMode($: EngineInterface): Promise<HostMode | null> {// mode it gives: the OS's when it is system. Null when that is not known.async function readCmuxAppearance($: EngineInterface, file?: CmuxAppearance): Promise<{ mode: IuiTheme; appearance: CmuxAppearance } | null> {if (file === undefined) {- const home = (await envGet($, 'HOME')) ?? ''+ const home = (await getenv($, 'HOME')) ?? ''file = cmuxSettingsOf(jsoncOf((await readText($, `${home}/.config/cmux/cmux.json`)) ?? '')).appearance}let saved = ''if (!file && S.hostOs === 'Darwin') {- const got = await processRun($, ['defaults', 'read', 'com.cmuxterm.app', 'appearanceMode'], { timeoutMs: HOST_CHECK_MS }).catch(() => null)+ const got = await exec($, ['defaults', 'read', 'com.cmuxterm.app', 'appearanceMode'], { timeoutMs: HOST_CHECK_MS }).catch(() => null)saved = got?.exitCode === 0 ? got.stdout : ''}const appearance = cmuxAppearanceOf(file, saved)@@ -472,23 +472,23 @@ const isRioHere = () => /^rio$/i.test(S.termProgram) || /^rio$/i.test(S.termName// A file's text, or null when it can't be read.export async function readText($: EngineInterface, path: string): Promise<string | null> {- const text = await fsRead($, path).catch(() => null)+ const text = await cat($, path).catch(() => null)return typeof text === 'string' ? text : null}// kitty's config folder and kitty.conf with its includes: the first folder// that has a kitty.conf, else the first folder (auto theme files can be there).async function readKittyConfig($: EngineInterface): Promise<{ dir: string; entries: KittyEntries; home: string }> {- const home = (await envGet($, 'HOME')) ?? ''+ const home = (await getenv($, 'HOME')) ?? ''const dirs = kittyConfigDirsOf({- kittyDir: (await envGet($, 'KITTY_CONFIG_DIRECTORY')) || undefined,- xdgConfig: (await envGet($, 'XDG_CONFIG_HOME')) || undefined,+ kittyDir: (await getenv($, 'KITTY_CONFIG_DIRECTORY')) || undefined,+ xdgConfig: (await getenv($, 'XDG_CONFIG_HOME')) || undefined,home,isMac: S.hostOs === 'Darwin',})const o = { home, vars: { KITTY_OS: S.hostOs === 'Darwin' ? 'macos' : S.hostOs.toLowerCase() } }for (const dir of dirs) {- if (!(await fsExists($, `${dir}/kitty.conf`).catch(() => false))) continue+ if (!(await exists($, `${dir}/kitty.conf`).catch(() => false))) continuereturn { dir, entries: await kittyEntriesOf(`${dir}/kitty.conf`, path => readText($, path), o), home }}return { dir: dirs[0]!, entries: [], home }@@ -500,7 +500,7 @@ async function readKittyMode($: EngineInterface): Promise<HostMode | null> {if (!S.isKitty) return nullconst { dir, entries, home } = await readKittyConfig($)const schemes = ['dark', 'light', 'no-preference'] as const- const found = await Promise.all(schemes.map(s => fsExists($, `${dir}/${kittyAutoFileOf(s)}`).catch(() => false)))+ const found = await Promise.all(schemes.map(s => exists($, `${dir}/${kittyAutoFileOf(s)}`).catch(() => false)))let auto: { file: string; entries: KittyEntries } | null = nullif (found.some(Boolean)) {let scheme: (typeof schemes)[number] | null = null@@ -519,9 +519,9 @@ async function readKittyMode($: EngineInterface): Promise<HostMode | null> {// Rio's config folder and its config.toml's string values.async function readRioConfig($: EngineInterface): Promise<{ dir: string; config: Record<string, string> }> {const dir = rioConfigDirOf({- rioHome: (await envGet($, 'RIO_CONFIG_HOME')) || undefined,- xdgConfig: (await envGet($, 'XDG_CONFIG_HOME')) || undefined,- home: (await envGet($, 'HOME')) ?? '',+ rioHome: (await getenv($, 'RIO_CONFIG_HOME')) || undefined,+ xdgConfig: (await getenv($, 'XDG_CONFIG_HOME')) || undefined,+ home: (await getenv($, 'HOME')) ?? '',isMac: S.hostOs === 'Darwin',})return { dir, config: tomlStringsOf((await readText($, `${dir}/config.toml`)) ?? '') }@@ -545,7 +545,7 @@ async function readRioMode($: EngineInterface): Promise<HostMode | null> {// (readLinuxScheme; no preference is light, as GNOME's default is).async function readOsMode($: EngineInterface): Promise<HostMode | null> {if (S.hostOs === 'Darwin') {- const got = await processRun($, ['defaults', 'read', '-g', 'AppleInterfaceStyle'], { timeoutMs: HOST_CHECK_MS }).catch(() => null)+ const got = await exec($, ['defaults', 'read', '-g', 'AppleInterfaceStyle'], { timeoutMs: HOST_CHECK_MS }).catch(() => null)return got ? { mode: modeOfMacAppearance(got.exitCode, got.stdout), source: 'macOS' } : null}if (S.hostOs === 'Linux') {@@ -569,7 +569,7 @@ type LinuxScheme = { scheme: 'dark' | 'light' | 'no-preference'; source: 'desktoasync function readLinuxScheme($: EngineInterface): Promise<LinuxScheme | null> {const tools = S.portalTool === null ? (['gdbus', 'busctl'] as const) : S.portalTool ? [S.portalTool] : []for (const tool of tools) {- const got = await processRun($, PORTAL_ARGS[tool], { timeoutMs: HOST_CHECK_MS }).catch(() => null)+ const got = await exec($, PORTAL_ARGS[tool], { timeoutMs: HOST_CHECK_MS }).catch(() => null)const scheme = got && got.exitCode === 0 ? schemeOfPortal(got.stdout) : nullif (scheme) {S.portalTool = tool@@ -578,7 +578,7 @@ async function readLinuxScheme($: EngineInterface): Promise<LinuxScheme | null>}if (S.portalTool === null) S.portalTool = ''if (S.portalTool) return null- const got = await processRun($, ['gsettings', 'get', 'org.gnome.desktop.interface', 'color-scheme'], { timeoutMs: HOST_CHECK_MS }).catch(() => null)+ const got = await exec($, ['gsettings', 'get', 'org.gnome.desktop.interface', 'color-scheme'], { timeoutMs: HOST_CHECK_MS }).catch(() => null)const scheme = got && got.exitCode === 0 ? kittySchemeOfGnome(got.stdout) : nullreturn scheme ? { scheme, source: 'GNOME' } : null}@@ -608,7 +608,7 @@ export function showMode($: EngineInterface) {export function watchHost($: EngineInterface) {if (S.setting === 'auto' && !S.watch) {try {- S.watch = clockEvery($, HOST_POLL_MS, () => void pollHost($).catch(() => undefined))+ S.watch = every($, HOST_POLL_MS, () => void pollHost($).catch(() => undefined))} catch {S.watch = null}diff --git a/hooks/lib/log.ts b/hooks/lib/log.tsindex 448ef00..2aa3177 100644--- a/hooks/lib/log.ts+++ b/hooks/lib/log.ts@@ -2,12 +2,12 @@import type { EngineInterface } from 'claude-code'import { S } from './state'-import { processRun } from './api'+import { exec } from './api'export async function logDebug($: EngineInterface, cache: string, text: string) {if (!cache) returnconst stamp = new Date().toISOString()- await processRun($, ['sh', '-c', 'cat >> "$1"', 'sh', `${cache}/debug.log`], { stdin: `[${stamp}] ${text.trimEnd()}\n` }).catch(() => undefined)+ await exec($, ['sh', '-c', 'cat >> "$1"', 'sh', `${cache}/debug.log`], { stdin: `[${stamp}] ${text.trimEnd()}\n` }).catch(() => undefined)}// A trace line, only with IUI_DEBUG set (S.debug, read in setUp).diff --git a/hooks/lib/pagecache.ts b/hooks/lib/pagecache.tsindex 23ce7ab..71dc326 100644--- a/hooks/lib/pagecache.ts+++ b/hooks/lib/pagecache.ts@@ -23,7 +23,7 @@ import { fromBase64 } from './png'import { knownWords, wordsOf } from './probe'import { keep, type Job } from './state'import { traceDebug } from './log'-import { clockAfter, fsRead, uiLog } from './api'+import { delay, cat, log } from './api'// A slice's budget, and a page a down waits for.export const SLICE_MS = 4@@ -263,7 +263,7 @@ export async function needFrames($: EngineInterface, page: DrawnPage, color: strfunction later($: EngineInterface) {const epoch = pages.epochtry {- clockAfter($, 0, () => void slice($, epoch).catch(() => {+ delay($, 0, () => void slice($, epoch).catch(() => {if (epoch === pages.epoch) pages.isPumping = false}))} catch {@@ -316,7 +316,7 @@ async function slice($: EngineInterface, epoch: number) {b = pages.build = { want, steps: null, png: null, slices: [], started, readMs: 0, readyMs: 0, stepMs: 0, isCancelled: false, isReady: false }try {// Kept even when stopped meanwhile: a down can take the build up again.- const { base64 } = await fsRead($, want.page.file, { as: 'bytes' })+ const { base64 } = await cat($, want.page.file, { as: 'bytes' })b.png = fromBase64(base64)} catch (err) {if (epoch === pages.epoch) fail($, b, err)@@ -375,7 +375,7 @@ function fail($: EngineInterface, b: Build, err: unknown) {ready($, b, null)const why = `no highlight for ${b.want.page.file}: ${err instanceof Error ? err.message : String(err)}`traceDebug($, `select: ${why}`)- void Promise.resolve(uiLog($, `Intelligent UI: picture select: ${why}`, { to: 'debug' })).catch(() => undefined)+ void Promise.resolve(log($, `Intelligent UI: picture select: ${why}`, { to: 'debug' })).catch(() => undefined)}// A build done (its tinted rows too): the cache within its budget again, and its trace.diff --git a/hooks/lib/pictures.tsx b/hooks/lib/pictures.tsxindex 842bb6e..2dd783b 100644--- a/hooks/lib/pictures.tsx+++ b/hooks/lib/pictures.tsx@@ -22,7 +22,7 @@ import { convertCall, logDebug, parseOd, pngSize } from './typst'import { pagesOf, type Drawing } from './answer'import { HEADERS_SH } from './host'import { frameFor, pictureColumns, shownFor, type Frame } from './frame'-import { clockAfter, fsExists, fsList, fsRead, fsStat, fsWrite, processRun, sessionId, sessionRoot, uiClose, invalidate, uiOpen, uiResolve } from './api'+import { delay, exists, ls, cat, stat, write, exec, sid, root, hide, redraw, show, uiResolve } from './api'export type Picture = { file: string; stamp: string; bytes: number; width: number; height: number }export type Shown = { source: ImageSource; columns: number; rows: number; alt: string }@@ -52,7 +52,7 @@ const STATS_KEPT = 4096let statsDone: number | undefinedconst stats = new Map<string, Promise<FsStat | null>>()function statOf($: EngineInterface, file: string, at?: StatAt): Promise<FsStat | null> {- if (!at) return fsStat($, file).catch(() => null)+ if (!at) return stat($, file).catch(() => null)if (statsDone !== at.done || stats.size >= STATS_KEPT) {stats.clear()statsDone = at.done@@ -60,7 +60,7 @@ function statOf($: EngineInterface, file: string, at?: StatAt): Promise<FsStat |const key = `${at.row}\n${file}`let got = stats.get(key)if (!got) {- got = fsStat($, file).catch(() => null)+ got = stat($, file).catch(() => null)stats.set(key, got)}return got@@ -74,7 +74,7 @@ export async function pictureOf($: EngineInterface, file: string, at?: StatAt):const stamp = `${st.mtimeMs}:${st.size}`let kept = pictures.get(file)if (kept?.stamp !== stamp) {- const head = await processRun($, ['sh', '-c', HEADERS_SH, 'sh', file]).catch(() => null)+ const head = await exec($, ['sh', '-c', HEADERS_SH, 'sh', file]).catch(() => null)if (!head || head.exitCode !== 0) return nullkept = { stamp, size: pngSize(parseOd(head.stdout)[0] ?? []) }pictures.delete(file)@@ -93,7 +93,7 @@ export async function pictureBytes($: EngineInterface, p: Picture): Promise<striif (!fitsInline(p) || p.bytes > INLINE_MAX_BYTES) return nullconst key = `${p.file}@${p.stamp}`if (inlined.has(key)) return inlined.get(key) ?? null- const got = await fsRead($, p.file, { as: 'bytes' }).catch(() => null)+ const got = await cat($, p.file, { as: 'bytes' }).catch(() => null)if (!got) return nullconst base64 = fitsInline(p, got.base64) ? got.base64 : nullinlined.set(key, base64)@@ -165,7 +165,7 @@ export async function convertedOf($: EngineInterface, ready: Env, file: string,// jobDone one tick later: a run that ends while this row still draws// must not be lost. A run that is waited for (the first PNG, no epoch// open) draws in this render.- if (before || epochOpen()) void run.then(() => void clockAfter($, 0, () => jobDone($)), () => undefined)+ if (before || epochOpen()) void run.then(() => void delay($, 0, () => jobDone($)), () => undefined)}return before ?? run}@@ -210,20 +210,20 @@ async function convertOnce($: EngineInterface, ready: Env, file: string, stamp:// The Typst error of a run that failed (null: made).let error: string | null = null// Made before (an earlier load): the same file, stamp and box.- const made = await fsStat($, out).catch(() => null)+ const made = await stat($, out).catch(() => null)let png: string | null = outif (made?.kind !== 'file' || !made.size) {const dir = out.replace(/\/[^/]*$/, '')// The write makes the key folder; Typst does not (a failed write fails// the run below).- await fsWrite($, `${dir}/source.txt`, `${file}\n`).catch(() => undefined)+ await write($, `${dir}/source.txt`, `${file}\n`).catch(() => undefined)// Typst writes a part file, moved to image.png only once it is whole, so// a run that is killed or fails leaves no image.png for a later load.const part = `${dir}/image.part.png`const { argv, env } = convertCall({ typst: ready.typst!, root: ready.root, cache: ready.cache, file, box, out: part, page: pdf?.page })const failed = (err: unknown) => ({ exitCode: 1, stdout: '', stderr: `did not run: ${String(err)}` })- const ran = await processRun($, argv, { timeoutMs: COMPILE_TIMEOUT_MS, env }).catch(failed)- const moved = ran.exitCode === 0 ? await processRun($, ['mv', '-f', part, out]).catch(failed) : null+ const ran = await exec($, argv, { timeoutMs: COMPILE_TIMEOUT_MS, env }).catch(failed)+ const moved = ran.exitCode === 0 ? await exec($, ['mv', '-f', part, out]).catch(failed) : nullif (ran.exitCode !== 0) {// A PDF's page that is not there is no failure: it tells the last page.if (!pdf || !isNoPageError(ran.stderr)) await logDebug($, ready.cache, `convert ${file} failed:\n${ran.stderr}`)@@ -249,7 +249,7 @@ export async function sentTextOf($: EngineInterface, file: string, at?: StatAt):const stamp = `${st.mtimeMs}:${st.size}`const kept = sentTexts.get(file)if (kept?.stamp === stamp) return kept.text- const got = st.size <= SENT_TEXT_MAX_BYTES ? await fsRead($, file).catch(() => null) : null+ const got = st.size <= SENT_TEXT_MAX_BYTES ? await cat($, file).catch(() => null) : nullconst text = got?.trim() ? got : nullkeep(sentTexts, file, { stamp, text }, PICTURES_KEPT)return text@@ -374,7 +374,7 @@ async function pdfOf(// string: Typst's error for another failure; null when it is not known (no// Typst, a file that is gone).async function pageMade($: EngineInterface, ready: Env, file: string, row: string, page: number, box: PixelBox): Promise<boolean | string | null> {- const st = await fsStat($, file).catch(() => null)+ const st = await stat($, file).catch(() => null)if (!ready.typst || !st || st.kind !== 'file') return nullconst stamp = `${st.mtimeMs}:${st.size}`const known = factsOf(file, stamp)@@ -406,9 +406,9 @@ const PAGE_PANE = 'iui-page'// A press on the page number: the page field, with the page in it.async function askPage($: EngineInterface, line: PageLine) {pageAsk.now = { row: line.row, file: line.file, box: line.box, value: String(line.page), note: '' }- await uiOpen($, { id: PAGE_PANE, title: 'Page', focus: true, closeOnEscape: true, rows: 2, columns: 24 }).catch(() => undefined)+ await show($, { id: PAGE_PANE, title: 'Page', focus: true, closeOnEscape: true, rows: 2, columns: 24 }).catch(() => undefined)// An open field (another row's) draws the new page.- invalidate($, 'ui.render')+ redraw($, 'ui.render')}// Enter in the page field: a page that exists shows in its row and the@@ -417,7 +417,7 @@ async function askPage($: EngineInterface, line: PageLine) {// later Enter makes an earlier one's result go unused.async function submitPage($: EngineInterface, text: string) {const ask = pageAsk.now- if (!ask) return void uiClose($, { id: PAGE_PANE }).catch(() => undefined)+ if (!ask) return void hide($, { id: PAGE_PANE }).catch(() => undefined)const mine = { ...ask, value: text }pageAsk.now = mineconst page = parsePage(text)@@ -426,12 +426,12 @@ async function submitPage($: EngineInterface, text: string) {if (!page || made !== true) {const note = !page ? 'Type a page number' : made === false ? `No page ${page}` : `Page ${page}: ${made ?? 'Typst could not make it'}`pageAsk.now = { ...mine, note }- invalidate($, 'ui.render')+ redraw($, 'ui.render')return}keep(pdfPages, ask.row, page, PICTURES_KEPT)pageAsk.now = null- await uiClose($, { id: PAGE_PANE }).catch(() => undefined)+ await hide($, { id: PAGE_PANE }).catch(() => undefined)refresh($)}@@ -548,20 +548,20 @@ export function underRow($: EngineInterface, e: RowInput, row: RenderElement, un// cwd's folder name is cut). Kept once found; '' while there is none.export async function pasteDir($: EngineInterface, ready: Env): Promise<string> {if (!ready.claudeTmp) return ''- const id = await sessionId($)+ const id = await sid($)const kept = pasteDirs.get(id)if (kept) return keptconst found = async (dirs: Iterable<string>) => {for (const dir of dirs) {- if (!(await fsExists($, dir).catch(() => false))) continue+ if (!(await exists($, dir).catch(() => false))) continuepasteDirs.set(id, dir)return dir}return ''}- const root = await sessionRoot($).catch(() => ready.cwd)- const named = await found(new Set([ready.cwd, root].map(dir => pasteDirOf(ready.claudeTmp, dir, id))))+ const top = await root($).catch(() => ready.cwd)+ const named = await found(new Set([ready.cwd, top].map(dir => pasteDirOf(ready.claudeTmp, dir, id))))if (named) return named- const projects = (await fsList($, ready.claudeTmp).catch(() => [])).filter(f => f.kind === 'dir')+ const projects = (await ls($, ready.claudeTmp).catch(() => [])).filter(f => f.kind === 'dir')return found(projects.map(f => `${ready.claudeTmp}/${f.name}/${id}/images`))}diff --git a/hooks/lib/plan.tsx b/hooks/lib/plan.tsxindex 36a1085..3471f65 100644--- a/hooks/lib/plan.tsx+++ b/hooks/lib/plan.tsx@@ -15,7 +15,7 @@ import { S, writesLive } from './state'import { firstLine } from './markdown'import type { Drawing } from './answer'import { drawPages, type ShownLink } from './draw'-import { clockAfter, commandRun, envGet, fsRead, processRun, submit, turnAbort, uiAsk, uiResolve } from './api'+import { delay, runCmd, getenv, cat, exec, send, abort, ask, uiResolve } from './api'// The question's chip and its two wordings.export const PLAN_HEADER = 'Plan'@@ -178,7 +178,7 @@ async function findCode($: EngineInterface): Promise<string> {if (S.planCode !== null) return S.planCodelet found = ''for (const flag of ['-lc', '-c']) {- const got = await processRun($, ['sh', flag, 'command -v code'], { timeoutMs: 5000 }).catch(() => null)+ const got = await exec($, ['sh', flag, 'command -v code'], { timeoutMs: 5000 }).catch(() => null)const path = got?.exitCode === 0 ? firstLine(got.stdout) : ''if (path.startsWith('/')) {found = path@@ -194,9 +194,9 @@ async function findCode($: EngineInterface): Promise<string> {async function findGuiEditor($: EngineInterface): Promise<string[]> {if (S.planGui !== null) return S.planGuilet found: string[] = []- if ((await envGet($, 'WAYLAND_DISPLAY')) || (await envGet($, 'DISPLAY'))) {+ if ((await getenv($, 'WAYLAND_DISPLAY')) || (await getenv($, 'DISPLAY'))) {for (const flag of ['-lc', '-c']) {- const got = await processRun($, ['sh', flag, GUI_EDITOR_SH], { timeoutMs: 5000 }).catch(() => null)+ const got = await exec($, ['sh', flag, GUI_EDITOR_SH], { timeoutMs: 5000 }).catch(() => null)found = got?.exitCode === 0 ? guiEditorOf(got.stdout) : []if (found.length) break}@@ -229,7 +229,7 @@ export async function decidePlan(let answer: stringS.planAsking = questiontry {- answer = await uiAsk($, question, { header: PLAN_HEADER, options: planOptions(canEdit) })+ answer = await ask($, question, { header: PLAN_HEADER, options: planOptions(canEdit) })} catch {return { kind: 'verdict', verdict: { kind: 'deny', message: PLAN_REJECTED } }} finally {@@ -238,8 +238,8 @@ export async function decidePlan(const choice = choiceOf(answer, canEdit)if (choice.kind === 'feedback') return { kind: 'feedback', message: feedbackOf(choice.text) }if (choice.kind !== 'edit') return { kind: 'verdict', verdict: verdictOf(choice, plan, plan !== o.callPlan)! }- await processRun($, argv!, { timeoutMs: EDIT_TIMEOUT_MS }).catch(() => null)- const text = await fsRead($, o.file).catch(() => null)+ await exec($, argv!, { timeoutMs: EDIT_TIMEOUT_MS }).catch(() => null)+ const text = await cat($, o.file).catch(() => null)if (typeof text === 'string' && text.trim() && text !== plan) {plan = textisEdited = text !== o.plan@@ -256,9 +256,9 @@ export async function decidePlan(export async function currentPlan($: EngineInterface, file: string, fallback: string): Promise<string> {if (!file) return fallbackfor (let waited = 0; (writesLive.get(file) ?? 0) > 0 && waited < PLAN_WRITE_WAIT_MS; waited += PLAN_WRITE_POLL_MS) {- await new Promise<void>(resolve => clockAfter($, PLAN_WRITE_POLL_MS, resolve))+ await new Promise<void>(resolve => delay($, PLAN_WRITE_POLL_MS, resolve))}- const text = await fsRead($, file).catch(() => null)+ const text = await cat($, file).catch(() => null)return typeof text === 'string' && text.trim() ? text : fallback}@@ -266,10 +266,10 @@ export async function currentPlan($: EngineInterface, file: string, fallback: st// /clear and sends the plan as the new context's first prompt. Detached, as// `$.command.run` rejects inside a hook the turn waits on.export function scheduleClear($: EngineInterface, plan: string, turnId: string) {- clockAfter($, CLEAR_DELAY_MS, async () => {- if (turnId) await turnAbort($, { turnId }).catch(() => undefined)- await commandRun($, { command: 'clear' }).catch(() => undefined)- await submit($, { text: `${PLAN_IMPLEMENT}\n\n${plan}`, asUser: true }).catch(() => undefined)+ delay($, CLEAR_DELAY_MS, async () => {+ if (turnId) await abort($, { turnId }).catch(() => undefined)+ await runCmd($, { command: 'clear' }).catch(() => undefined)+ await send($, { text: `${PLAN_IMPLEMENT}\n\n${plan}`, asUser: true }).catch(() => undefined)})}diff --git a/hooks/lib/select.ts b/hooks/lib/select.tsindex 9c761a3..5b901fd 100644--- a/hooks/lib/select.ts+++ b/hooks/lib/select.ts@@ -12,7 +12,7 @@ import { drawnAnswers, S } from './state'import { compareVersions } from './updates'import { joinSegments, pageTopsOf, textOfRun, type Drawn, type Item, type RunLine, type TextBlock } from './copy'import { endFold, foldNew, FRAME_MS, pokeFold, showSelection, startFold } from './blit'-import { clockAfter, clockEvery, uiSelection } from './api'+import { delay, every, uiSelection } from './api'import { targetAt, type PageTarget } from './targets'import type { ShownLink } from './draw'@@ -57,7 +57,7 @@ export const clickLinks = new Map<string, readonly ShownLink[]>()let fold = foldNew()export function redrawSelection($: EngineInterface) {const next = pokeFold(fold, performance.now(), FRAME_MS)- if (next.kind === 'wait') clockAfter($, next.ms, () => void runSelection($))+ if (next.kind === 'wait') delay($, next.ms, () => void runSelection($))else if (next.kind === 'run') void runSelection($)}@@ -120,7 +120,7 @@ export function watchNative($: EngineInterface, clear: () => void) {if (native.timer) returnnative.last = UNREADtry {- native.timer = clockEvery($, NATIVE_POLL_MS, () => void pollNative($, clear).catch(() => undefined))+ native.timer = every($, NATIVE_POLL_MS, () => void pollNative($, clear).catch(() => undefined))} catch {native.timer = nullreturndiff --git a/hooks/lib/setup.ts b/hooks/lib/setup.tsindex a1aee81..b82918b 100644--- a/hooks/lib/setup.ts+++ b/hooks/lib/setup.ts@@ -4,7 +4,7 @@ import type { EngineInterface } from 'claude-code'import { S } from './state'import { readText } from './host'-import { envGet, fsExists, fsWrite, processRun, storeGet, storeSet, uiAsk, uiLog, uiToast } from './api'+import { getenv, exists, write, exec, load, save, ask, log, toast } from './api'// Claude Code turns pictures on by itself in kitty and Ghostty only; iTerm2// needs CLAUDE_CODE_FORCE_TERMINAL_IMAGES=1 when Claude Code starts (a mod's@@ -59,10 +59,10 @@ export function withSetup(text: string, kind: ShellRc['kind']): string {// The shell start file for this user, or null when the shell is not known.async function shellRc($: EngineInterface): Promise<ShellRc | null> {return shellRcOf({- shell: (await envGet($, 'SHELL')) ?? '',- home: (await envGet($, 'HOME')) ?? '',- zdotdir: (await envGet($, 'ZDOTDIR')) || undefined,- xdgConfig: (await envGet($, 'XDG_CONFIG_HOME')) || undefined,+ shell: (await getenv($, 'SHELL')) ?? '',+ home: (await getenv($, 'HOME')) ?? '',+ zdotdir: (await getenv($, 'ZDOTDIR')) || undefined,+ xdgConfig: (await getenv($, 'XDG_CONFIG_HOME')) || undefined,isMac: S.hostOs === 'Darwin',})}@@ -70,7 +70,7 @@ async function shellRc($: EngineInterface): Promise<ShellRc | null> {// The start file's text: '' when it is confirmed missing, null when it// exists (or may exist) but cannot be read. A write over null would lose it.async function readRc($: EngineInterface, path: string): Promise<string | null> {- const there = await fsExists($, path).catch(() => true)+ const there = await exists($, path).catch(() => true)if (!there) return ''return readText($, path)}@@ -91,12 +91,12 @@ export async function runSetup($: EngineInterface, remove: boolean): Promise<strconst restart = 'Close this tab, open a new iTerm2 tab, and start Claude Code there to see pictures.'if (remove) {if (!hasSetup(text)) return `${rc.path} has no Intelligent UI block.`- await fsWrite($, rc.path, withoutSetup(text))+ await write($, rc.path, withoutSetup(text))return `Removed the Intelligent UI block from ${rc.path}. New iTerm2 tabs show answers as text.`}if (hasSetup(text)) return `${rc.path} already has the Intelligent UI block. ${restart}`- if (rc.kind === 'fish') await processRun($, ['mkdir', '-p', rc.path.replace(/\/[^/]*$/, '')]).catch(() => null)- await fsWrite($, rc.path, withSetup(text, rc.kind))+ if (rc.kind === 'fish') await exec($, ['mkdir', '-p', rc.path.replace(/\/[^/]*$/, '')]).catch(() => null)+ await write($, rc.path, withSetup(text, rc.kind))return `Added the Intelligent UI block to ${rc.path}. ${restart} Undo with /iui setup remove.`}@@ -104,24 +104,24 @@ export async function runSetup($: EngineInterface, remove: boolean): Promise<strexport async function offerSetup($: EngineInterface) {if (S.setupAsked) returnS.setupAsked = true- if ((await storeGet($, 'setup').catch(() => undefined)) === 'never') return+ if ((await load($, 'setup').catch(() => undefined)) === 'never') returnconst rc = await shellRc($)const text = rc ? await readRc($, rc.path) : ''if (text === null || (rc && hasSetup(text))) return- const home = (await envGet($, 'HOME')) ?? ''+ const home = (await getenv($, 'HOME')) ?? ''const file = rc ? (home ? rc.path.replace(home, '~') : rc.path) : "your shell's start file"- const answer = await uiAsk($,+ const answer = await ask($,`Intelligent UI draws answers as pictures, but in iTerm2 Claude Code needs CLAUDE_CODE_FORCE_TERMINAL_IMAGES=1 when it starts. Add one line to ${file} that sets it in iTerm2 only (not in tmux or screen)?`,{ header: 'iui', options: ['Add the line', 'Not now', 'Never ask'] },)- if (answer === 'Never ask') await storeSet($, 'setup', 'never')+ if (answer === 'Never ask') await save($, 'setup', 'never')if (answer !== 'Add the line') returnconst said = await runSetup($, false)// The toast box is small: a short line there, the whole text in the transcript.try {- uiLog($, said)+ log($, said)} catch {}try {- uiToast($, said.startsWith('Added') ? 'Close this tab and open a new iTerm2 tab to see pictures.' : 'See the transcript for the setup.', { timeoutMs: 10000 })+ toast($, said.startsWith('Added') ? 'Close this tab and open a new iTerm2 tab to see pictures.' : 'See the transcript for the setup.', { timeoutMs: 10000 })} catch {}}diff --git a/hooks/lib/state.ts b/hooks/lib/state.tsindex bfd3e6f..a999757 100644--- a/hooks/lib/state.ts+++ b/hooks/lib/state.ts@@ -13,7 +13,7 @@ import type { Checked } from './updates'import type { ClipWay } from './clipboard'import type { PdfFacts, PixelBox } from './images'import { DEFAULT_HEIGHT, DEFAULT_SIZE, DEFAULT_WIDTH, type Height, type Width } from './settings'-import { invalidate } from './api'+import { redraw } from './api'// The `done` atom (see types/index.d.ts) for refresh. The state scan of// `claude plugin validate` reads an atom only from a const in the file that@@ -346,5 +346,5 @@ export function keepIn(set: Set<string>, key: string, max: number) {// Redraws every reader of `done`; an invalidate where the write is refused.export function refresh($: EngineInterface) {- void update($, done, n => n + 1).catch(() => invalidate($, 'ui.render'))+ void update($, done, n => n + 1).catch(() => redraw($, 'ui.render'))}diff --git a/hooks/lib/stream.ts b/hooks/lib/stream.tsindex 0f82b0d..fe8b754 100644--- a/hooks/lib/stream.ts+++ b/hooks/lib/stream.ts@@ -11,7 +11,7 @@ import { hashOf } from './draw'import { noteDesign, recordDesign } from './designs'import { compile, logDebug } from './typst'import { extendEpoch, jobDone, jobQueued } from './epoch'-import { clockAfter } from './api'+import { delay } from './api'// The order of enqueue calls: a higher `order` is newer.let enqueued = 0@@ -107,7 +107,7 @@ export function waitBlank($: EngineInterface, requestId: string, textHash: strinif (pending.get(requestId)?.textHash === textHash) returnpending.get(requestId)?.timer.cancel()const entry = { textHash, showText: false, timer: { cancel: () => {} } }- entry.timer = clockAfter($, ms, () => {+ entry.timer = delay($, ms, () => {entry.showText = truerefresh($)})diff --git a/hooks/lib/themes.ts b/hooks/lib/themes.tsindex e48333c..f83f77e 100644--- a/hooks/lib/themes.ts+++ b/hooks/lib/themes.ts@@ -4,7 +4,7 @@ import type { EngineInterface } from 'claude-code'import { BASE_THEME, DEFAULT_THEME, MODES } from './settings'import { S } from './state'-import { fsExists, fsList, fsRead, fsStat } from './api'+import { exists, ls, cat, stat } from './api'// A theme folder's name: letters, digits, `.`, `_`, `-`.export const isThemeName = (name: string) => /^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(name)@@ -110,11 +110,11 @@ export function themeListing(themes: ReadonlyMap<string, ThemeInfo>, problems: rexport async function scanThemes($: EngineInterface, root: string, home: string) {const found: (ThemeInfo | ThemeProblem)[] = []for (const [base, isUser] of [[`${root}/render/themes`, false], [userThemesOf(home), true]] as const) {- const entries = await fsList($, base).catch(() => [])+ const entries = await ls($, base).catch(() => [])for (const entry of entries) {if (entry.kind === 'file') continueconst dir = `${base}/${entry.name}`- const json = await fsRead($, `${dir}/theme.json`).catch(() => null)+ const json = await cat($, `${dir}/theme.json`).catch(() => null)if (json === null) continueconst one = themeEntry(entry.name, dir, isUser, json)const lost = 'reason' in one ? [] : await missingSyntax($, one)@@ -129,7 +129,7 @@ export async function missingSyntax($: EngineInterface, theme: ThemeInfo) {const lost: string[] = []for (const mode of MODES) {const file = theme.syntax[mode]- if (file && !(await fsExists($, `${theme.dir}/${file}`).catch(() => false))) lost.push(file)+ if (file && !(await exists($, `${theme.dir}/${file}`).catch(() => false))) lost.push(file)}return lost}@@ -141,8 +141,8 @@ export const userThemesOf = (home: string) => `${home || '~'}/.claude/cc-intelliexport async function stampTheme($: EngineInterface, files: readonly string[]): Promise<string> {const times: string[] = []for (const file of files) {- const stat = await fsStat($, file).catch(() => null)- times.push(String(stat?.mtimeMs ?? 0))+ const st = await stat($, file).catch(() => null)+ times.push(String(st?.mtimeMs ?? 0))}return times.join(',')}diff --git a/hooks/lib/typst.ts b/hooks/lib/typst.tsindex eac5fed..29f30c8 100644--- a/hooks/lib/typst.ts+++ b/hooks/lib/typst.ts@@ -12,7 +12,7 @@ import { HEADERS_SH } from './host'import { logDebug } from './log'import { positionsOf, type Mark, type Positions } from './copy'import { hasBoldFace, leanFontsFor } from './fonts'-import { clockAfter, envGet, fsExists, fsList, fsRead, fsWrite, processRun, spawn } from './api'+import { delay, getenv, exists, ls, cat, write, exec, spawn } from './api'// The typst command and its environment. Network off (see NO_NETWORK) and a// package cache of our own, so only the vendored packages load, and the@@ -143,7 +143,7 @@ export function svgLinksOf(svg: string, full: string): string[] {async function svgLinks($: EngineInterface, images: readonly string[]): Promise<string[]> {const found: string[] = []for (const full of new Set(imageFullsOf(images).filter(p => /\.svg$/i.test(p)))) {- const svg = await fsRead($, full).catch(() => '')+ const svg = await cat($, full).catch(() => '')if (typeof svg === 'string') found.push(...svgLinksOf(svg, full))}return found@@ -161,12 +161,12 @@ const runFolderIn = (dir: string) => `${dir}/r-${(++runs).toString(36)}${Math.raexport async function inRoot<T>($: EngineInterface, job: Job, dir: string, doc: Doc, use: (run: string) => Promise<T>): Promise<T> {const run = runFolderIn(dir)const args = stageArgs(run, job.env.root, `${dir}/doc.json`, job.themeDir, doc.images, await svgLinks($, doc.images))- const made = await processRun($, ['sh', '-c', STAGE_SH, 'sh', ...args], { stdin: JSON.stringify(doc), timeoutMs: 10000 }).catch(() => null)+ const made = await exec($, ['sh', '-c', STAGE_SH, 'sh', ...args], { stdin: JSON.stringify(doc), timeoutMs: 10000 }).catch(() => null)if (made?.exitCode !== 0) await logDebug($, job.env.cache, `the root ${run} could not be made: ${made?.stderr ?? 'sh did not run'}`)try {return await use(run)} finally {- if (made?.exitCode === 0) void Promise.resolve(processRun($, ['rm', '-rf', run], { timeoutMs: 10000 })).catch(() => undefined)+ if (made?.exitCode === 0) void Promise.resolve(exec($, ['rm', '-rf', run], { timeoutMs: 10000 })).catch(() => undefined)}}@@ -254,15 +254,15 @@ export function shouldRetrySafe(exitCode: number): boolean {export async function findTypst($: EngineInterface): Promise<string | null> {for (const flag of ['-lc', '-c']) {- const got = await processRun($, ['sh', flag, 'command -v typst'], { timeoutMs: 5000 }).catch(() => null)+ const got = await exec($, ['sh', flag, 'command -v typst'], { timeoutMs: 5000 }).catch(() => null)const path = got?.exitCode === 0 ? firstLine(got.stdout) : ''if (path.startsWith('/')) return path}- const home = (await envGet($, 'HOME').catch(() => undefined)) ?? ''+ const home = (await getenv($, 'HOME').catch(() => undefined)) ?? ''for (const each of TYPST_FALLBACKS) {if (each.startsWith('~/') && !home) continueconst path = each.startsWith('~/') ? `${home}${each.slice(1)}` : each- if (await fsExists($, path).catch(() => false)) return path+ if (await exists($, path).catch(() => false)) return path}return null}@@ -288,8 +288,8 @@ export async function measureFonts($: EngineInterface, typst: string, root: striconst argv = measureCall(typst, root, family, themeDir)const env = noNetworkEnv(cache)const [got, listed] = await Promise.all([- processRun($, argv, { timeoutMs: 10000, env }).catch(() => null),- family ? processRun($, [typst, 'fonts', '--variants'], { timeoutMs: 10000, env }).catch(() => null) : null,+ exec($, argv, { timeoutMs: 10000, env }).catch(() => null),+ family ? exec($, [typst, 'fonts', '--variants'], { timeoutMs: 10000, env }).catch(() => null) : null,])try {const m = JSON.parse(got?.stdout ?? '') as Metrics@@ -311,7 +311,7 @@ export async function existingImages($: EngineInterface, segments: readonly striconst found: string[] = []for (const path of new Set(segments.flatMap(localImages))) {const full = imagePathOf(path, base)- if (await fsExists($, full).catch(() => false)) found.push(path, full)+ if (await exists($, full).catch(() => false)) found.push(path, full)}return found}@@ -354,11 +354,11 @@ export function touchLater($: EngineInterface, path: string) {if (toTouch.size >= TOUCH_KEPT && !toTouch.has(path)) returntoTouch.add(path)if (touchTimer) return- touchTimer = clockAfter($, TOUCH_FLUSH_MS, () => {+ touchTimer = delay($, TOUCH_FLUSH_MS, () => {touchTimer = nullconst paths = [...toTouch].slice(0, TOUCH_BATCH)for (const each of paths) toTouch.delete(each)- if (paths.length) void Promise.resolve(processRun($, ['touch', '-c', ...paths], { timeoutMs: 5000 })).catch(() => undefined)+ if (paths.length) void Promise.resolve(exec($, ['touch', '-c', ...paths], { timeoutMs: 5000 })).catch(() => undefined)if (toTouch.size) touchLater($, toTouch.values().next().value!)})}@@ -397,7 +397,7 @@ export async function runKillable(const killNow = () => {if (!why || !pid || isKillSent) returnisKillSent = true- void Promise.resolve(processRun($, ['kill', pid], { timeoutMs: 5000 })).catch(() => undefined)+ void Promise.resolve(exec($, ['kill', pid], { timeoutMs: 5000 })).catch(() => undefined)}const stop = (reason: 'cancel' | 'timeout') => {if (why) return@@ -406,7 +406,7 @@ export async function runKillable(}const onAbort = () => stop('cancel')o.signal?.addEventListener('abort', onAbort, { once: true })- const timer = clockAfter($, o.timeoutMs, () => stop('timeout'))+ const timer = delay($, o.timeoutMs, () => stop('timeout'))let code: number | null = 1try {const child = spawn($, { argv: wrapPid(argv), ...(o.env ? { env: o.env } : {}) })@@ -538,7 +538,7 @@ export async function probePage(): Promise<Positions | null> {let kept: Partial<Doc> | null = nulltry {- kept = JSON.parse((await fsRead($, `${dir}/doc.json`)) as string) as Partial<Doc>+ kept = JSON.parse((await cat($, `${dir}/doc.json`)) as string) as Partial<Doc>} catch {return null}@@ -567,13 +567,13 @@ export async function probePage(// The pages of one run: its PNGs (by tag) in order, with their sizes and// the box each takes. Null when there are none or a size can not be read.async function pagesOfRun($: EngineInterface, job: Job, dir: string, tag: string, segments: readonly string[]): Promise<Page[] | null> {- const files = (await fsList($, dir))+ const files = (await ls($, dir)).filter(f => f.kind === 'file' && f.name.startsWith(`${tag}-`) && f.name.endsWith('.png')).map(f => f.name).sort((x, y) => Number(x.replace(/\D/g, '')) - Number(y.replace(/\D/g, ''))).map(name => `${dir}/${name}`)if (!files.length) return null- const heads = await processRun($, ['sh', '-c', HEADERS_SH, 'sh', ...files])+ const heads = await exec($, ['sh', '-c', HEADERS_SH, 'sh', ...files])const sizes = parseOd(heads.stdout).map(pngSize)if (sizes.length !== files.length || sizes.some(s => !s)) {await logDebug($, job.env.cache, `compile ${job.key}: could not read PNG sizes`)@@ -589,7 +589,7 @@ async function pagesOfRun($: EngineInterface, job: Job, dir: string, tag: string// result: nothing is kept).export async function compile($: EngineInterface, job: Job, signal?: AbortSignal): Promise<Result | 'failed' | 'cancelled'> {const dir = `${job.env.cache}/${job.key}`- const kept = await fsRead($, `${dir}/pages.json`).catch(() => null)+ const kept = await cat($, `${dir}/pages.json`).catch(() => null)const keptResult = kept ? resultOf(kept) : nullif (keptResult) {touchLater($, dir)@@ -604,7 +604,7 @@ export async function compile($: EngineInterface, job: Job, signal?: AbortSignallet segments = splitSegments(job.text, job.columns, job.env.inline ? inlineBudget(job.cell) : SEGMENT_ROWS, job.size, roomRows)const base = job.base ?? job.env.cwdconst images = await existingImages($, segments, base)- await fsWrite($, `${dir}/doc.json`, JSON.stringify({ base, segments, images }))+ await write($, `${dir}/doc.json`, JSON.stringify({ base, segments, images }))let tag = 'a'let isSafe = false@@ -635,7 +635,7 @@ export async function compile($: EngineInterface, job: Job, signal?: AbortSignalconst cut = segments.flatMap((seg, i) => (pages![i]!.rows > MAX_IMAGE_ROWS ? splitInTwo(seg, job.columns, job.size, roomRows) : [seg]))if (cut.length > segments.length) {if (signal?.aborted) return 'cancelled'- await fsWrite($, `${dir}/doc.json`, JSON.stringify({ base, segments: cut, images }))+ await write($, `${dir}/doc.json`, JSON.stringify({ base, segments: cut, images }))const again = await runTypst($, job, { base, segments: cut, images }, dir, isSafe ? 'd' : 'c', isSafe, signal)if (again.isCancelled) return 'cancelled'const split = again.exitCode === 0 ? await pagesOfRun($, job, dir, isSafe ? 'd' : 'c', cut) : null@@ -648,6 +648,6 @@ export async function compile($: EngineInterface, job: Job, signal?: AbortSignal}const { bulletRow } = firstLinePlace(job, segments)const result: Result = { pages, bulletRow, ...(note ? { note } : {}) }- await fsWrite($, `${dir}/pages.json`, JSON.stringify(result))+ await write($, `${dir}/pages.json`, JSON.stringify(result))return result}diff --git a/hooks/lib/updates.ts b/hooks/lib/updates.tsindex 65435c5..71ea5b8 100644--- a/hooks/lib/updates.ts+++ b/hooks/lib/updates.ts@@ -7,7 +7,7 @@ import type { EngineInterface } from 'claude-code'import { S } from './state'import { isSet } from './terminal'-import { clockAfter, clockNow, envGet, fsRead, httpFetch, pluginRoot, sessionSurfaces, storeGet, storeSet, uiToast, type EnvName } from './api'+import { delay, nowMs, getenv, cat, http, pluginRoot, surf, load, save, toast, type EnvName } from './api'// The manifest of the newest release (a release changes its `version`).export const UPDATE_URL = 'https://raw.githubusercontent.com/razorback16/cc-intelligent-ui/main/.claude-plugin/plugin.json'@@ -121,16 +121,16 @@ export function updateNotice(o: UpdateState): string {// read once per load. Never rejects.export function loadUpdates($: EngineInterface): Promise<void> {S.updatesLoading ??= (async () => {- S.updates = (await storeGet($, 'updates').catch(() => undefined)) !== false+ S.updates = (await load($, 'updates').catch(() => undefined)) !== falseS.updatesOff = ''for (const name of UPDATE_ENV) {- if (!isSet(await envGet($, name).catch(() => undefined))) continue+ if (!isSet(await getenv($, name).catch(() => undefined))) continueS.updatesOff = namebreak}- const manifest = await fsRead($, `${pluginRoot($)}/.claude-plugin/plugin.json`).catch(() => '')+ const manifest = await cat($, `${pluginRoot($)}/.claude-plugin/plugin.json`).catch(() => '')S.ownVersion = versionOf(manifest) ?? ''- S.updateChecked = checkedOf(await storeGet($, 'update-check').catch(() => undefined))+ S.updateChecked = checkedOf(await load($, 'update-check').catch(() => undefined))})().catch(() => {S.updatesLoading = null})@@ -145,8 +145,8 @@ export async function fetchLatest($: EngineInterface): Promise<string | null> {const timeout = new Promise<null>(resolve => (late = resolve))let timer: { cancel: () => void } | undefinedtry {- timer = clockAfter($, UPDATE_FETCH_MS, () => late(null))- const got = await Promise.race([httpFetch($, UPDATE_URL).catch(() => null), timeout])+ timer = delay($, UPDATE_FETCH_MS, () => late(null))+ const got = await Promise.race([http($, UPDATE_URL).catch(() => null), timeout])return got?.ok ? versionOf(got.text) : null} catch {return null@@ -159,9 +159,9 @@ export async function fetchLatest($: EngineInterface): Promise<string | null> {async function tellUpdate($: EngineInterface, now: number) {const latest = S.updateChecked?.latest ?? ''if (!latest || !isNewer(latest, S.ownVersion)) return- if (!shouldTell(toldOf(await storeGet($, 'update-told').catch(() => undefined)), latest, now)) return- await storeSet($, 'update-told', { version: latest, at: now }).catch(() => undefined)- uiToast($, updateToast(latest, S.ownVersion), { timeoutMs: UPDATE_TOAST_MS })+ if (!shouldTell(toldOf(await load($, 'update-told').catch(() => undefined)), latest, now)) return+ await save($, 'update-told', { version: latest, at: now }).catch(() => undefined)+ toast($, updateToast(latest, S.ownVersion), { timeoutMs: UPDATE_TOAST_MS })}// Once per load, after the start (the end of setUp, or a turn's start, or@@ -176,22 +176,22 @@ export async function checkUpdates($: EngineInterface): Promise<void> {try {await loadUpdates($)if (!S.updates || S.updatesOff || !S.ownVersion) return- if ((await envGet($, 'CLAUDE_CODE_SESSION_KIND').catch(() => undefined)) === 'bg') {+ if ((await getenv($, 'CLAUDE_CODE_SESSION_KIND').catch(() => undefined)) === 'bg') {S.updateDone = truereturn}// None in a -p run; tried again at the next turn.- const surfaces = await sessionSurfaces($).catch(() => [] as readonly string[])+ const surfaces = await surf($).catch(() => [] as readonly string[])if (!surfaces.includes('terminal')) returnS.updateDone = true- const now = await clockNow($)+ const now = await nowMs($)if (isDue(S.updateChecked, now)) {S.updateChecked = { at: now, latest: S.updateChecked?.latest ?? '' }- await storeSet($, 'update-check', S.updateChecked).catch(() => undefined)+ await save($, 'update-check', S.updateChecked).catch(() => undefined)const found = await fetchLatest($)if (found) {S.updateChecked = { at: now, latest: found }- await storeSet($, 'update-check', S.updateChecked).catch(() => undefined)+ await save($, 'update-check', S.updateChecked).catch(() => undefined)}}await tellUpdate($, now)diff --git a/hooks/register.tsx b/hooks/register.tsxindex 29ea5eb..604af33 100644--- a/hooks/register.tsx+++ b/hooks/register.tsx@@ -52,7 +52,7 @@ import { roomColumns } from './lib/terminal'import { onScreenOf, pastedImagePath, pastedNumbers, sentFiles } from './lib/images'import { drawPageField, pasteDir, pdfPagesOf, rowsAfter, sentOf, shownOf, underRow, type Shown, type Under } from './lib/pictures'import { checkUpdates, loadUpdates, updateLine, updateNotice, type UpdateState } from './lib/updates'-import { clockNow, fsWrite, sessionSurfaces, storeSet, uiCopy, uiLog, uiResolve, uiSelection, uiToast } from './lib/api'+import { nowMs, write, surf, save, copy, uiSelection, toast } from './lib/api'import {currentPlan, decidePlan, decisionOf, drawAskLine, drawPlanResult, drawPlanUse, isPlanQuestion, planFileOf, planInputOf, planOf,planShownOf, scheduleClear, type PlanVerdict,@@ -138,7 +138,7 @@ async function pictureEnv($: EngineInterface, e: { viewport?: RenderViewport }):function tellFullscreen($: EngineInterface) {if (S.fullscreenTold) returnS.fullscreenTold = true- uiToast($, 'Intelligent UI works best in fullscreen mode: run /tui fullscreen', { timeoutMs: 12000 })+ toast($, 'Intelligent UI works best in fullscreen mode: run /tui fullscreen', { timeoutMs: 12000 })}// The env to draw Markdown pictures with (an answer, a plan): as@@ -224,7 +224,7 @@ async function planDrawing(// dialog asks, as with no mod.async function planEnv($: EngineInterface): Promise<Env | null> {if (!(await read($, isOn))) return null- const surfaces = await sessionSurfaces($).catch(() => [] as readonly string[])+ const surfaces = await surf($).catch(() => [] as readonly string[])if (!surfaces.includes('terminal')) return nullconst ready = S.env ?? (await setUp($).catch(() => null))return ready?.typst && ready.canDraw ? ready : null@@ -310,7 +310,7 @@ function hintGrab($: EngineInterface, text: string) {clip.raw = textclip.rawRow = undefinedif (S.debug) traceDebug($, `select: native copy seen: ${decodeSelection(text).filter(seg => seg.kind === 'image').length} picture run(s) on the clipboard`)- uiToast($, 'Intelligent UI: picture cells copied; /iui grab puts their text on the clipboard')+ toast($, 'Intelligent UI: picture cells copied; /iui grab puts their text on the clipboard')}// The clipboard changed: one read (clipboardNow). A clipboard with no@@ -370,7 +370,7 @@ function hintOf(isOn: boolean): string {// The update check's state now, for /iui, /iui details and /iui updates.async function updateState($: EngineInterface): Promise<UpdateState> {await loadUpdates($)- const now = await clockNow($).catch(() => Date.now())+ const now = await nowMs($).catch(() => Date.now())return { on: S.updates, off: S.updatesOff, own: S.ownVersion, checked: S.updateChecked, now }}@@ -426,7 +426,7 @@ async function grab($: EngineInterface): Promise<string> {if (!read.resolved) return `Intelligent UI: found ${read.runs} picture run(s) but could not read them (see /iui dump).`clip.wrote = read.textclip.seen = read.text- const copied = await uiCopy($, { text: read.text })+ const copied = await copy($, { text: read.text })return copied.isCopied? `Intelligent UI: copied ${read.text.length} chars (${read.resolved} of ${read.runs} picture runs read${row ? `, row ${row}` : ''}).`: `Intelligent UI: the copy failed: ${copied.reason}.`@@ -462,7 +462,7 @@ async function dump($: EngineInterface, on: boolean): Promise<string> {const cache = S.env?.cache ?? ''if (cache) {const full = { raw: clip.raw, codePoints: codePointsOf(clip.raw, 100000), ...(clip.last as object) }- await fsWrite($, `${cache}/copy-debug.json`, JSON.stringify(full, null, 1)).catch(() => undefined)+ await write($, `${cache}/copy-debug.json`, JSON.stringify(full, null, 1)).catch(() => undefined)}return [`Intelligent UI: last clipboard with picture cells (${Array.from(clip.raw).length} code points; grab hint ${hint}):`,@@ -575,8 +575,8 @@ async function copyTarget($: EngineInterface, target: Target, surface: RenderSur// The clipboard change of this text is not read again.clip.wrote = textclip.seen = text- const copied = await uiCopy($, { text, surface })- uiToast($, copied.isCopied ? `Intelligent UI: copied the ${name}` : `Intelligent UI: the copy failed: ${copied.reason}`)+ const copied = await copy($, { text, surface })+ toast($, copied.isCopied ? `Intelligent UI: copied the ${name}` : `Intelligent UI: the copy failed: ${copied.reason}`)}// The text of a selection's cells, page by page, as a copy of those cells@@ -604,15 +604,15 @@ async function copySelection($: EngineInterface, d: Drawn & { job?: Job }, sel:if (!(await isNewest($, turn))) returnconst read = performance.now() - tif (text === null) {- uiToast($, 'Intelligent UI: could not read the selected picture')+ toast($, 'Intelligent UI: could not read the selected picture')return}if (!text) return// The clipboard change of this text is not read again.clip.wrote = textclip.seen = text- const copied = await uiCopy($, { text, surface })- uiToast($, copied.isCopied ? `Intelligent UI: copied ${text.length} chars of text` : `Intelligent UI: the copy failed: ${copied.reason}`)+ const copied = await copy($, { text, surface })+ toast($, copied.isCopied ? `Intelligent UI: copied ${text.length} chars of text` : `Intelligent UI: the copy failed: ${copied.reason}`)if (S.debug) void traceCopy($, text, performance.now() - t, read, probed)}@@ -679,7 +679,7 @@ async function setTheme($: EngineInterface, name: string | undefined): Promise<sif (ready.typst && S.look) ready.metrics = await measureFonts($, ready.typst, ready.root, ready.cache, ready.termFont, S.look.dir)beginEpoch($)}- if (name) await storeSet($, 'theme-name', chosen.name)+ if (name) await save($, 'theme-name', chosen.name)const head = name ? `Theme set to ${chosen.name}.\n\n` : ''return `${head}${themeListing(themes, problems, chosen.name, userThemesOf(ready.home), ready.home)}`}@@ -713,7 +713,7 @@ export const register: Register = on => {return next(e)}if (S.debug) traceDebug($, 'select: native copy seen: a $.ui.copy with picture cells (read as their text)')- const selection = uiSelection($).catch(() => undefined)+ const selection = $.ui.selection().catch(() => undefined)const turn = takeTurn($, selection.then(nativeKey))const selected = await selectionclip.raw = e.text@@ -746,7 +746,7 @@ export const register: Register = on => {releaseSelect($)// The rows drawn again with no Client.refresh($)- void Promise.resolve(uiLog($, `Intelligent UI: picture select is off (${e.phase}: ${e.reason})`, { to: 'debug' })).catch(() => undefined)+ void Promise.resolve($.ui.log(`Intelligent UI: picture select is off (${e.phase}: ${e.reason})`, { to: 'debug' })).catch(() => undefined)}return next(e)}).catch(($, e, next) => next(e))@@ -789,7 +789,7 @@ export const register: Register = on => {stopClipboard($)releaseSelect($)}- await storeSet($, 'enabled', asked.kind === 'on')+ await $.store.set('enabled', asked.kind === 'on')return { text: `Intelligent UI is ${asked.kind}.` }}if (asked.kind === 'size') {@@ -798,7 +798,7 @@ export const register: Register = on => {S.size = asked.percentsettingsSet.add('size')beginEpoch($)- await storeSet($, 'size', S.size)+ await $.store.set('size', S.size)return { text: `Intelligent UI draws text at ${S.size}% of the terminal's text size (100% matches it).` }}if (asked.kind === 'width') {@@ -807,7 +807,7 @@ export const register: Register = on => {S.width = asked.widthsettingsSet.add('width')beginEpoch($)- await storeSet($, 'width', S.width)+ await $.store.set('width', S.width)}const most = typeof S.width === 'number' && S.width > IMAGE_MAX_COLUMNS ? ` (a picture is ${IMAGE_MAX_COLUMNS} columns at most)` : ''const head = asked.width === undefined ? 'The most columns a picture takes' : 'Intelligent UI pictures now take at most'@@ -819,7 +819,7 @@ export const register: Register = on => {S.height = asked.heightsettingsSet.add('height')beginEpoch($)- await storeSet($, 'height', S.height)+ await $.store.set('height', S.height)}const head = asked.height === undefined ? 'The most rows an image or a Typst drawing takes' : 'Intelligent UI images and Typst drawings now take at most'return { text: `${head}: ${heightText(S.height)}. This applies to images (sent or pasted) and to Typst drawings in answers. Use /iui height half (the default), /iui height full, or /iui height <${MIN_HEIGHT}-${MAX_HEIGHT}> (never more than full).` }@@ -830,7 +830,7 @@ export const register: Register = on => {S.grid = asked.gridsettingsSet.add('grid')beginEpoch($)- await storeSet($, 'grid', S.grid)+ await $.store.set('grid', S.grid)}const head = asked.grid === undefined ? 'The row grid is' : 'The row grid is now'return { text: `${head} ${gridText(S.grid)}. With the grid on, a mouse selection over a picture covers the lines it copies. Use /iui grid on (the default), or /iui grid off.` }@@ -842,7 +842,7 @@ export const register: Register = on => {settingsSet.add('select')if (!S.select) releaseSelect($)refresh($)- await storeSet($, 'select', S.select)+ await $.store.set('select', S.select)}const head = asked.on === undefined ? 'Picture select is' : 'Picture select is now'return { text: `${head} ${selectText(S.select)}. When on, a mouse drag over a picture selects its text and copies it. Use /iui select on (the default), or /iui select off.` }@@ -851,7 +851,7 @@ export const register: Register = on => {await loadUpdates($)if (asked.on !== undefined) {S.updates = asked.on- await storeSet($, 'updates', S.updates)+ await $.store.set('updates', S.updates)// On: the check of this load, if it did not run (it waits 24 h after the last one).if (S.updates) void checkUpdates($)}@@ -1018,7 +1018,7 @@ export const register: Register = on => {}answers.delete(e.requestId)if (drawing.kind === 'text') return next(e)- const { Box } = uiResolve($, e)+ const { Box } = $.ui.resolve(e)return <Box />})diff --git a/tests/footprint-sh-test.sh b/tests/footprint-sh-test.shnew file mode 100644index 0000000..f54fcc3--- /dev/null+++ b/tests/footprint-sh-test.sh@@ -0,0 +1,49 @@+#!/bin/sh+# Release gate: the footprint that `claude plugin validate` reports is whole.+# The validator cuts a note at about 1,000 characters and marks the cut+# `[+N chars]`; the catalogue then can not read the footprint. Checks: no+# such mark in the text or the --json report, the `register.tsx calls:` line+# (the text after `calls: `) is 850 characters at most, and no `$.noun.method(`+# call is in hooks/ outside hooks/lib/api.ts and hooks/register.tsx.+# Usage: sh tests/footprint-sh-test.sh (exit 0 when all pass; skips with no claude)+set -u+here=$(cd "$(dirname "$0")/.." && pwd)+max=850+pass=0+fail=0+ok() { pass=$((pass + 1)); }+bad() { fail=$((fail + 1)); echo "FAIL: $*"; }++if ! command -v claude >/dev/null 2>&1; then+ echo "footprint-sh-test: skipped (no claude on PATH)"+ exit 0+fi++text=$(claude plugin validate "$here" 2>&1) && ok || bad "validate (text) failed"+json=$(claude plugin validate "$here" --json 2>&1) && ok || bad "validate (--json) failed"++# 1. No cut note in either report.+uncut() {+ cut=$(printf '%s\n' "$2" | perl -CS -ne 'print "$1\n" if /(.{0,40}\[\+\d+ chars?\])/' | head -n 1)+ [ -z "$cut" ] && ok || bad "the $1 report has a cut note: $cut"+}+uncut text "$text"+uncut --json "$json"++# 2. The calls line, in characters (not bytes). No line is a fail.+calls=$(printf '%s\n' "$text" | grep -E 'register\.tsx calls: ' | head -n 1)+if [ -z "$calls" ]; then+ bad "no 'register.tsx calls:' line in the report"+ length=0+else+ length=$(printf '%s' "${calls#*calls: }" | perl -CS -ne 'print length')+ [ "$length" -le "$max" ] && ok || bad "the calls line is $length characters, over $max"+fi++# 3. The engine calls only in api.ts and register.tsx (a comment line is no call).+others=$(cd "$here" && grep -rnE '\$\.[a-z]+\.[a-zA-Z]+(<[^(]*>)?\(' hooks | grep -vE '^hooks/(lib/api\.ts|register\.tsx):' | grep -vE '^[^:]+:[0-9]+:[[:space:]]*//')+[ -z "$others" ] && ok || bad "engine calls outside hooks/lib/api.ts and hooks/register.tsx (add a wrapper to api.ts):+$others"++echo "footprint-sh-test: $pass passed, $fail failed (calls line $length/$max characters)"+[ "$fail" = 0 ]