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
Hooks: one wrapper per $ method, so the validator's calls note is not cut
razorback16c8314a6134d5
diff --git a/docs/development.md b/docs/development.mdindex cd7ef7b..a4898ea 100644--- a/docs/development.md+++ b/docs/development.md@@ -21,7 +21,7 @@ Set `IUI_DEBUG=1` before you start Claude Code. The mod then writes trace lines## 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), `draw.tsx` (the pages of an answer), `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), `copy.ts` (the text under a mouse selection of pictures) and `probe.ts` (the drawn pages, and the words of a page that a copy reads, kept in memory). The values that change are in one object, `S`, in `state.ts`. 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), `draw.tsx` (the pages of an answer), `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), `copy.ts` (the text under a mouse selection of pictures) and `probe.ts` (the drawn pages, and the words of a page that a copy reads, kept in memory). 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 Typst template is `render/md.typ`. The themes are in `render/themes/` (refer to [`render/themes/README.md`](../render/themes/README.md)). The vendored Typst packages are in `render/packages/preview/`.diff --git a/hooks/lib/answer.ts b/hooks/lib/answer.tsindex 85cbf47..f10d089 100644--- a/hooks/lib/answer.ts+++ b/hooks/lib/answer.ts@@ -15,6 +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'// `pages`: draw these (with `bytes` over ssh); `blank`: draw an empty box;// `text`: draw the engine's own row.@@ -77,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 $.fs.read(`${dir}/pages.json`).catch(() => null)+ const text = await fsRead($, `${dir}/pages.json`).catch(() => null)const got = text ? resultOf(text) : nullif (!got) {S.onDisk.delete(key)@@ -157,7 +158,7 @@ export async function pagesOf($: EngineInterface, o: PagesInput): Promise<Drawinconst was = live.get(id)if (!was || changed) {was?.still.cancel()- const still = $.clock.after(S.stepsLive > 0 ? LIVE_STILL_MS : SETTLE_MS, () => finalize($, id, false))+ const still = clockAfter($, 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.tsnew file mode 100644index 0000000..30600f0--- /dev/null+++ b/hooks/lib/api.ts@@ -0,0 +1,166 @@+// 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.+import type {+ AskOptions, CommandSpec, EngineInterface, FsBytes, FsReadBytesOptions, FsReadOptions, FsStatOptions, InvalidatableEventName,+ OpEventOf, 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.+export type EnvName =+ | 'CLAUDE_CODE_FORCE_TERMINAL_IMAGES' | 'CLAUDE_CODE_SESSION_KIND' | 'CLAUDE_CODE_TMPDIR'+ | 'CMUX_SOCKET_PATH' | 'CMUX_SURFACE_ID' | 'CMUX_WORKSPACE_ID' | 'COLORFGBG' | 'GHOSTTY_RESOURCES_DIR' | 'HOME'+ | 'ITERM_PROFILE' | 'ITERM_SESSION_ID' | 'IUI_DEBUG' | 'IUI_FORCE' | 'KITTY_CONFIG_DIRECTORY' | 'KITTY_PID'+ | 'KITTY_WINDOW_ID' | 'LC_TERMINAL' | 'RIO_CONFIG_HOME' | 'SHELL' | 'SSH_CONNECTION' | 'SSH_TTY' | 'STY'+ | 'TERM' | 'TERM_PROGRAM' | 'TMUX' | 'XDG_CONFIG_HOME' | 'ZDOTDIR'++export function clockAfter($: EngineInterface, ms: number, fn: () => void) {+ return $.clock.after(ms, fn)+}++export function clockEvery($: EngineInterface, ms: number, fn: () => void) {+ return $.clock.every(ms, fn)+}++export function commandRegister($: EngineInterface, command: CommandSpec) {+ return $.command.register(command)+}++export function commandRun($: EngineInterface, input: Parameters<EngineInterface['command']['run']>[0]) {+ return $.command.run(input)+}++export function configList($: EngineInterface) {+ return $.config.list()+}++export function envGet($: EngineInterface, name: EnvName): Promise<string | undefined> {+ switch (name) {+ case 'CLAUDE_CODE_FORCE_TERMINAL_IMAGES': return $.env.get('CLAUDE_CODE_FORCE_TERMINAL_IMAGES')+ case 'CLAUDE_CODE_SESSION_KIND': return $.env.get('CLAUDE_CODE_SESSION_KIND')+ case 'CLAUDE_CODE_TMPDIR': return $.env.get('CLAUDE_CODE_TMPDIR')+ case 'CMUX_SOCKET_PATH': return $.env.get('CMUX_SOCKET_PATH')+ case 'CMUX_SURFACE_ID': return $.env.get('CMUX_SURFACE_ID')+ case 'CMUX_WORKSPACE_ID': return $.env.get('CMUX_WORKSPACE_ID')+ case 'COLORFGBG': return $.env.get('COLORFGBG')+ case 'GHOSTTY_RESOURCES_DIR': return $.env.get('GHOSTTY_RESOURCES_DIR')+ case 'HOME': return $.env.get('HOME')+ case 'ITERM_PROFILE': return $.env.get('ITERM_PROFILE')+ case 'ITERM_SESSION_ID': return $.env.get('ITERM_SESSION_ID')+ case 'IUI_DEBUG': return $.env.get('IUI_DEBUG')+ case 'IUI_FORCE': return $.env.get('IUI_FORCE')+ case 'KITTY_CONFIG_DIRECTORY': return $.env.get('KITTY_CONFIG_DIRECTORY')+ case 'KITTY_PID': return $.env.get('KITTY_PID')+ case 'KITTY_WINDOW_ID': return $.env.get('KITTY_WINDOW_ID')+ case 'LC_TERMINAL': return $.env.get('LC_TERMINAL')+ case 'RIO_CONFIG_HOME': return $.env.get('RIO_CONFIG_HOME')+ case 'SHELL': return $.env.get('SHELL')+ case 'SSH_CONNECTION': return $.env.get('SSH_CONNECTION')+ case 'SSH_TTY': return $.env.get('SSH_TTY')+ case 'STY': return $.env.get('STY')+ case 'TERM': return $.env.get('TERM')+ case 'TERM_PROGRAM': return $.env.get('TERM_PROGRAM')+ case 'TMUX': return $.env.get('TMUX')+ case 'XDG_CONFIG_HOME': return $.env.get('XDG_CONFIG_HOME')+ case 'ZDOTDIR': return $.env.get('ZDOTDIR')+ }+}++export function fsExists($: EngineInterface, path: string) {+ return $.fs.exists(path)+}++export function fsList($: 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> {+ return options ? $.fs.read(path, options) : $.fs.read(path)+}++export function fsStat($: EngineInterface, path: string, options?: FsStatOptions) {+ return $.fs.stat(path, options)+}++export function fsWrite($: EngineInterface, path: string, text: string) {+ return $.fs.write(path, text)+}++export function pluginRoot($: EngineInterface) {+ return $.plugin.root+}++export function processRun($: EngineInterface, argv: readonly string[], init?: ProcessRunInit) {+ return $.process.run(argv, init)+}++export function processSpawn($: EngineInterface, request: ProcessSpawnRequest) {+ return $.process.spawn(request)+}++export function promptSubmit($: EngineInterface, input: Parameters<EngineInterface['prompt']['submit']>[0]) {+ return $.prompt.submit(input)+}++export function sessionCwd($: EngineInterface) {+ return $.session.cwd()+}++export function sessionId($: EngineInterface) {+ return $.session.id()+}++export function sessionRoot($: EngineInterface) {+ return $.session.root()+}++export function sessionSurfaces($: EngineInterface) {+ return $.session.surfaces()+}++export function storeGet($: EngineInterface, key: string) {+ return $.store.get(key)+}++export function storeSet($: EngineInterface, key: string, value: unknown) {+ return $.store.set(key, value)+}++export function turnAbort($: EngineInterface, input: OpEventOf['turn.abort']) {+ return $.turn.abort(input)+}++export function uiAsk($: EngineInterface, question: string, options?: readonly string[] | AskOptions) {+ return $.ui.ask(question, options)+}++export function uiCopy($: EngineInterface, args: UiCopyArgs) {+ return $.ui.copy(args)+}++export function uiInvalidate($: EngineInterface, event: InvalidatableEventName) {+ return $.ui.invalidate(event)+}++export function uiLog($: EngineInterface, text: string, options?: UiLogOptions) {+ return $.ui.log(text, options)+}++export function uiResolve<E extends ResolveInput>($: EngineInterface, e: E) {+ return $.ui.resolve(e)+}++export function uiSelection($: EngineInterface) {+ return $.ui.selection()+}++export function uiToast($: EngineInterface, text: string, options?: ToastOptions) {+ return $.ui.toast(text, options)+}diff --git a/hooks/lib/command.ts b/hooks/lib/command.tsindex 092191c..4ab9112 100644--- a/hooks/lib/command.ts+++ b/hooks/lib/command.ts@@ -7,6 +7,7 @@ import {type Height, type Width,} from './settings'import { isThemeName, type ThemeInfo } from './themes'+import { commandRegister } from './api'// `/iui` arguments: on, off, size <80-200>, width [40-400|full],// height [6-200|half|full], details (all Intelligent UI found), grab (copy@@ -130,7 +131,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 $.command.register({+ await commandRegister($, {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), theme [name] (list or switch themes), grab (copy the selected pictures' text), dump (copy diagnostics)",argumentHint: '[on|off|size <percent>|width [columns|full]|height [rows|half|full]|theme [name]|grab|dump]',diff --git a/hooks/lib/designs.ts b/hooks/lib/designs.tsindex ccb5415..a1cf056 100644--- a/hooks/lib/designs.ts+++ b/hooks/lib/designs.ts@@ -16,6 +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'export type { Design } from './state'@@ -70,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 $.fs.read(path).catch(() => null)+ const text = await fsRead($, path).catch(() => null)const design = typeof text === 'string' ? parseDesign(text) : nullkeep(known, key, design, DESIGNS_IN_MEMORY)if (design) touchLater($, path)@@ -84,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 $.fs.exists(path).catch(() => false)) {- const text = await $.fs.read(path).catch(() => null)+ if (await fsExists($, path).catch(() => false)) {+ const text = await fsRead($, path).catch(() => null)const kept = typeof text === 'string' ? parseDesign(text) : nullif (kept) {keep(known, key, kept, DESIGNS_IN_MEMORY)@@ -93,7 +94,7 @@ export async function recordDesign($: EngineInterface, dir: string, key: string,return}}- await $.fs.write(path, designText(design))+ await fsWrite($, 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 b081bd0..d821256 100644--- a/hooks/lib/draw.tsx+++ b/hooks/lib/draw.tsx@@ -8,6 +8,7 @@ import { BODY_PT, bulletOf, GUTTER, MARGIN_TOP, TEMPLATE_VERSION } from './settiimport { INLINE_KEPT, inlined, S, type Cell, type Look, type Metrics, type Result, type Room } from './state'import { FENCE } from './markdown'import { fitBox, fitsInline, roomColumns } from './terminal'+import { fsRead, uiResolve } from './api'// FNV-1a over the parts, twice with different offsets: 16 hex digits.export function hashOf(parts: readonly (string | number)[]): string {@@ -123,7 +124,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 $.fs.read(page.file, { as: 'bytes' }).catch(() => null)+ const got = await fsRead($, 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()) {@@ -159,7 +160,7 @@ export function scaledBulletRow(bulletRow: number, factor: number): number {export function drawPages($: EngineInterface, e: ResolveInput<RenderComponent, 'terminal'> & { viewport?: RenderViewport }, result: Result, inline?: readonly string[], layout: PagesLayout = {},) {- const { Box, Text, Image } = $.ui.resolve(e)+ const { Box, Text, Image } = uiResolve($, e)const gutter = layout.gutter ?? GUTTERconst room = roomColumns(e.viewport)const first = result.pages[0]diff --git a/hooks/lib/env.ts b/hooks/lib/env.tsindex 961e7ba..6f6b11f 100644--- a/hooks/lib/env.ts+++ b/hooks/lib/env.ts@@ -17,6 +17,7 @@ import { readHostMode, termFontOf, watchHost } from './host'import { readFrame, setFrame, watchFrame } from './frame'import { offerSetup } from './setup'import { findTypst, measureFonts } from './typst'+import { configList, envGet, fsList, fsStat, pluginRoot, processRun, sessionCwd, storeGet, uiToast } from './api'// The `isOn` atom, which setUp turns off when the stored setting says so (a// copy of its own: see state.ts).@@ -33,79 +34,79 @@ const CACHE_SH = `d="\${TMPDIR:-/tmp}"; d="\${d%/}/cc-intelligent-ui-$(id -u)";export function setUp($: EngineInterface): Promise<Env> {S.envLoading ??= (async () => {await registerCommand($)- const made = await $.process.run(['sh', '-c', CACHE_SH]).catch(() => null)+ const made = await processRun($, ['sh', '-c', CACHE_SH]).catch(() => null)const [made1 = '', os = '', made3 = ''] = (made?.stdout ?? '').split('\n')const cache = made1.trim() || '/tmp/cc-intelligent-ui'// The key folders on disk now: a key found here is read back at once.- const listed = await $.fs.list(cache).catch(() => [])+ const listed = await fsList($, cache).catch(() => [])S.onDisk = new Set(listed.filter(entry => entry.kind === 'dir' && entry.name !== 'pkg-cache').map(entry => entry.name))- const program = (await $.env.get('TERM_PROGRAM')) ?? ''- const term = (await $.env.get('TERM')) ?? ''- const ssh = !!(await $.env.get('SSH_CONNECTION')) || !!(await $.env.get('SSH_TTY'))+ const program = (await envGet($, 'TERM_PROGRAM')) ?? ''+ const term = (await envGet($, 'TERM')) ?? ''+ const ssh = !!(await envGet($, 'SSH_CONNECTION')) || !!(await envGet($, 'SSH_TTY'))const canDraw = canDrawIn({program,term,- kitty: !!(await $.env.get('KITTY_WINDOW_ID')),- tmux: !!(await $.env.get('TMUX')) || !!(await $.env.get('STY')) || /^tmux|^screen/i.test(term),+ kitty: !!(await envGet($, 'KITTY_WINDOW_ID')),+ tmux: !!(await envGet($, 'TMUX')) || !!(await envGet($, 'STY')) || /^tmux|^screen/i.test(term),ssh,- background: (await $.env.get('CLAUDE_CODE_SESSION_KIND')) === 'bg',- engineForced: isSet(await $.env.get('CLAUDE_CODE_FORCE_TERMINAL_IMAGES')),- modForced: isSet(await $.env.get('IUI_FORCE')),+ background: (await envGet($, 'CLAUDE_CODE_SESSION_KIND')) === 'bg',+ engineForced: isSet(await envGet($, 'CLAUDE_CODE_FORCE_TERMINAL_IMAGES')),+ modForced: isSet(await envGet($, 'IUI_FORCE')),})- const root = $.plugin.root- const template = await $.fs.stat(`${root}/render/md.typ`).catch(() => null)- const rows = await $.config.list().catch(() => [])+ const root = pluginRoot($)+ const template = await fsStat($, `${root}/render/md.typ`).catch(() => null)+ const rows = await configList($).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 $.env.get('ITERM_PROFILE')) || undefined- S.isKitty = /kitty/i.test(term) || !!(await $.env.get('KITTY_WINDOW_ID')) || !!(await $.env.get('KITTY_PID'))+ S.itermProfile = (await envGet($, 'ITERM_PROFILE')) || undefined+ S.isKitty = /kitty/i.test(term) || !!(await envGet($, 'KITTY_WINDOW_ID')) || !!(await envGet($, 'KITTY_PID'))S.isRemote = ssh- S.debug = isSet(await $.env.get('IUI_DEBUG'))+ S.debug = isSet(await envGet($, 'IUI_DEBUG'))S.isIterm = isItermIn({program,profile: S.itermProfile,- session: (await $.env.get('ITERM_SESSION_ID')) || undefined,- lcTerminal: (await $.env.get('LC_TERMINAL')) || undefined,+ session: (await envGet($, 'ITERM_SESSION_ID')) || undefined,+ lcTerminal: (await envGet($, 'LC_TERMINAL')) || undefined,})S.setupNeeded = S.isIterm && !canDraw && !ssh && S.hostOs === 'Darwin' &&- !(await $.env.get('TMUX')) && !(await $.env.get('STY')) && (await $.env.get('CLAUDE_CODE_SESSION_KIND')) !== 'bg'+ !(await envGet($, 'TMUX')) && !(await envGet($, 'STY')) && (await envGet($, 'CLAUDE_CODE_SESSION_KIND')) !== 'bg'if (S.setupNeeded) void offerSetup($).catch(() => undefined)- S.isCmux = !!(await $.env.get('CMUX_SURFACE_ID')) || !!(await $.env.get('CMUX_WORKSPACE_ID')) || !!(await $.env.get('CMUX_SOCKET_PATH'))- S.colorFgBg = (await $.env.get('COLORFGBG')) ?? ''+ S.isCmux = !!(await envGet($, 'CMUX_SURFACE_ID')) || !!(await envGet($, 'CMUX_WORKSPACE_ID')) || !!(await envGet($, 'CMUX_SOCKET_PATH'))+ S.colorFgBg = (await envGet($, 'COLORFGBG')) ?? ''if (S.setting === 'auto') S.host = (await readHostMode($).catch(() => null)) ?? S.hostS.theme = resolveMode(S.setting, S.host)watchHost($)- const kept = Number(await $.store.get('size').catch(() => undefined))+ const kept = Number(await storeGet($, 'size').catch(() => undefined))S.size = kept >= MIN_SIZE && kept <= MAX_SIZE ? kept : DEFAULT_SIZE- const width = await $.store.get('width').catch(() => undefined)+ const width = await storeGet($, 'width').catch(() => undefined)S.width = width === 'full' ? 'full' : Number.isInteger(width) && Number(width) >= MIN_WIDTH && Number(width) <= MAX_WIDTH ? Number(width) : DEFAULT_WIDTH- const height = await $.store.get('height').catch(() => undefined)+ const height = await storeGet($, 'height').catch(() => undefined)S.height = height === 'half' || height === 'full' ? height: Number.isInteger(height) && Number(height) >= MIN_HEIGHT && Number(height) <= MAX_HEIGHT ? Number(height) : DEFAULT_HEIGHT- if ((await $.store.get('enabled').catch(() => undefined)) === false) await update($, isOn, () => false).catch(() => undefined)+ if ((await storeGet($, 'enabled').catch(() => undefined)) === false) await update($, isOn, () => false).catch(() => undefined)const isMac = os.trim() === 'Darwin'setFrame(await readFrame($))if (canDraw) watchFrame($)const typst = await findTypst($)if (!typst) {try {- $.ui.toast(NO_TYPST, { timeoutMs: 8000 })+ uiToast($, NO_TYPST, { timeoutMs: 8000 })} catch {}}const termFont = await termFontOf($, program, isMac).catch(() => '')- const home = (await $.env.get('HOME')) ?? ''+ const home = (await envGet($, 'HOME')) ?? ''const designs = made3.trim() || (home ? `${home}/.cache/cc-intelligent-ui/designs` : `${cache}/designs`)- const stored = await $.store.get('theme-name').catch(() => undefined)+ const stored = await storeGet($, '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 {- $.ui.toast(`Intelligent UI: theme ${wanted} not found, using ${applied.chosen.name}`, { timeoutMs: 8000 })+ uiToast($, `Intelligent UI: theme ${wanted} not found, using ${applied.chosen.name}`, { timeoutMs: 8000 })} catch {}}S.env = {@@ -113,14 +114,14 @@ export function setUp($: EngineInterface): Promise<Env> {canDraw,inline: ssh && canDraw,cache,- cwd: await $.session.cwd().catch(() => '/'),+ cwd: await sessionCwd($).catch(() => '/'),root,isMac,stamp: String(template?.mtimeMs ?? 0),home,claudeTmp: claudeTmpOf({- tmpdir: (await $.env.get('CLAUDE_CODE_TMPDIR')) || undefined,- uid: await $.process.run(['id', '-u']).then(r => (r.exitCode === 0 ? r.stdout : ''), () => ''),+ tmpdir: (await envGet($, 'CLAUDE_CODE_TMPDIR')) || undefined,+ uid: await processRun($, ['id', '-u']).then(r => (r.exitCode === 0 ? r.stdout : ''), () => ''),isMac,}),termFont,diff --git a/hooks/lib/epoch.ts b/hooks/lib/epoch.tsindex fc31d3a..4313344 100644--- a/hooks/lib/epoch.ts+++ b/hooks/lib/epoch.ts@@ -9,6 +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'// 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@@ -46,7 +47,7 @@ export function beginEpoch($: EngineInterface, frame?: Frame | null) {ready = falseoverdue = falsemaxTimer?.cancel()- maxTimer = $.clock.after(COMMIT_MAX_MS, () => {+ maxTimer = clockAfter($, COMMIT_MAX_MS, () => {if (S.epoch !== epoch) returnoverdue = truemaybeCommit($)@@ -72,7 +73,7 @@ export function jobQueued(job: Job) {function armReady($: EngineInterface) {const epoch = S.epochminTimer?.cancel()- minTimer = $.clock.after(COMMIT_MIN_MS, () => {+ minTimer = clockAfter($, COMMIT_MIN_MS, () => {if (S.epoch !== epoch) returnready = truemaybeCommit($)diff --git a/hooks/lib/frame.ts b/hooks/lib/frame.tsindex 416b5e0..dfd325d 100644--- a/hooks/lib/frame.ts+++ b/hooks/lib/frame.ts@@ -15,6 +15,7 @@ import { pump } from './stream'import { columnsFor, sizeOf } from './terminal'import { CELL_SH, perlFor, termFontOf, WATCH_PL } from './host'import { measureFonts } from './typst'+import { clockAfter, processRun, processSpawn } from './api'export type { Cell, Frame } from './state'@@ -95,7 +96,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 $.process.run(['sh', '-c', CELL_SH], { timeoutMs: 5000 }).catch(() => null)+ const tty = await processRun($, ['sh', '-c', CELL_SH], { timeoutMs: 5000 }).catch(() => null)return tty?.exitCode === 0 ? frameOfLine(tty.stdout) : null}@@ -138,7 +139,7 @@ let poke: (() => void) | null = nullfunction burst($: EngineInterface) {poke ??= quietTimer({ms: RESIZE_QUIET_MS,- after: (ms, fn) => $.clock.after(ms, fn),+ after: (ms, fn) => clockAfter($, ms, fn),onStart: holdJobs,onQuiet: stale => void settle($, stale),})@@ -240,7 +241,7 @@ export function watchFrame($: EngineInterface, clip?: ((count: number | null, filet stopped = falselet counted = falseconst kill = () => {- if (stopped && pid) void Promise.resolve($.process.run(['kill', pid], { timeoutMs: 5000 })).catch(() => undefined)+ if (stopped && pid) void Promise.resolve(processRun($, ['kill', pid], { timeoutMs: 5000 })).catch(() => undefined)}const stop = () => {if (stopped) return@@ -250,7 +251,7 @@ export function watchFrame($: EngineInterface, clip?: ((count: number | null, ficonst me: NonNullable<typeof watcher> = { clip: isClip, ended: false, stop }watcher = metry {- const child = $.process.spawn({ argv: [perlFor(S.hostOs === 'Darwin'), '-e', WATCH_PL, ...(isClip ? ['clip'] : [])] })+ const child = processSpawn($, { argv: [perlFor(S.hostOs === 'Darwin'), '-e', WATCH_PL, ...(isClip ? ['clip'] : [])] })void followWatcher(child, line => {if ('pid' in line) {pid = line.pid@@ -268,7 +269,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 {- $.clock.after(WATCH_RESTART_MS, () => {+ clockAfter($, WATCH_RESTART_MS, () => {if (watcher === me) watchFrame($)})} catch {}diff --git a/hooks/lib/host.ts b/hooks/lib/host.tsindex 6b9fe5a..98f56e8 100644--- a/hooks/lib/host.ts+++ b/hooks/lib/host.ts@@ -15,6 +15,7 @@ import {rioConfigDirOf, rioFontOf, rioForcedOf, rioThemeNamesOf, rioThemePath, tomlStringsOf, type CmuxAppearance, type KittyEntries,} from './terminals'import { firstLine } from './markdown'+import { clockEvery, envGet, fsExists, fsRead, processRun } 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))'`@@ -102,18 +103,18 @@ export async function termFontOf($: EngineInterface, program: string, isMac: boo// Over ssh, a config here is not the one of the user's terminal.if (S.isRemote) return ''if (S.isIterm && isMac) {- const profile = await $.env.get('ITERM_PROFILE')+ const profile = await envGet($, 'ITERM_PROFILE')const [marks, guid] = await Promise.all([- $.process.run(['sh', '-c', ITERM_BOOKMARKS_SH], { timeoutMs: 5000 }).catch(() => null),- $.process.run(['sh', '-c', ITERM_DEFAULT_SH], { timeoutMs: 5000 }).catch(() => null),+ processRun($, ['sh', '-c', ITERM_BOOKMARKS_SH], { timeoutMs: 5000 }).catch(() => null),+ processRun($, ['sh', '-c', ITERM_DEFAULT_SH], { timeoutMs: 5000 }).catch(() => null),])const spec = parseFontSpec(itermFontOf(marks?.stdout ?? '', profile, guid?.stdout ?? '') ?? '')if (!spec) return ''- const named = await $.process.run(['osascript', '-l', 'JavaScript', '-e', FAMILY_JXA, spec.name], { timeoutMs: 5000 }).catch(() => null)+ const named = await processRun($, ['osascript', '-l', 'JavaScript', '-e', FAMILY_JXA, spec.name], { timeoutMs: 5000 }).catch(() => null)return named?.exitCode === 0 ? firstLine(named.stdout) : ''}if (/ghostty/i.test(program)) {- const shown = await $.process.run(['sh', '-c', GHOSTTY_SH], { timeoutMs: 5000 }).catch(() => null)+ const shown = await processRun($, ['sh', '-c', GHOSTTY_SH], { timeoutMs: 5000 }).catch(() => null)return ghosttyFontOf(shown?.stdout ?? '') ?? ''}if (S.isKitty) {@@ -122,11 +123,11 @@ export async function termFontOf($: EngineInterface, program: string, isMac: booconst font = kittyFontOf(kittyValueOf((await readKittyConfig($)).entries, 'font_family'))if (font && 'family' in font) return font.familyif (font && isMac) {- const named = await $.process.run(['osascript', '-l', 'JavaScript', '-e', FAMILY_JXA, font.postscript], { timeoutMs: 5000 }).catch(() => null)+ const named = await processRun($, ['osascript', '-l', 'JavaScript', '-e', FAMILY_JXA, font.postscript], { timeoutMs: 5000 }).catch(() => null)return named?.exitCode === 0 ? firstLine(named.stdout) : ''}if (!font && !isMac) {- const got = await $.process.run(['fc-match', 'monospace', '-f', '%{family}'], { timeoutMs: 5000 }).catch(() => null)+ const got = await processRun($, ['fc-match', 'monospace', '-f', '%{family}'], { timeoutMs: 5000 }).catch(() => null)return got?.exitCode === 0 ? (got.stdout.split(',')[0] ?? '').trim() : ''}return ''@@ -165,7 +166,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 $.process.run(['sh', '-c', ITERM_MODE_SH], { timeoutMs: HOST_CHECK_MS }).catch(() => null)+ const got = await processRun($, ['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@@ -176,7 +177,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 $.process.run(['perl', '-e', OSC11_PL], { timeoutMs: HOST_CHECK_MS }).catch(() => null)+ const got = await processRun($, ['perl', '-e', OSC11_PL], { timeoutMs: HOST_CHECK_MS }).catch(() => null)return got && got.exitCode === 0 ? { reply: got.stdout } : null}@@ -184,9 +185,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 $.process.run(['sh', '-c', GHOSTTY_SH], { timeoutMs: HOST_CHECK_MS }).catch(() => null)+ const got = await processRun($, ['sh', '-c', GHOSTTY_SH], { timeoutMs: HOST_CHECK_MS }).catch(() => null)if (!got || got.exitCode !== 0) return null- const home = (await $.env.get('HOME')) ?? ''+ const home = (await envGet($, 'HOME')) ?? ''const own = S.isCmux ? ((await readText($, cmuxGhosttyConfigPath(home))) ?? '') : ''const config = cmuxConfigOf(got.stdout, own)if (S.isCmux && !ghosttyHasColors(config)) {@@ -199,13 +200,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 $.env.get('XDG_CONFIG_HOME')) || undefined,+ xdgConfig: (await envGet($, 'XDG_CONFIG_HOME')) || undefined,home,- resources: (await $.env.get('GHOSTTY_RESOURCES_DIR')) || undefined,+ resources: (await envGet($, 'GHOSTTY_RESOURCES_DIR')) || undefined,}for (const mode of MODES) {for (const path of ghosttyThemePaths(pair[mode], where)) {- const text = await $.fs.read(path).catch(() => null)+ const text = await fsRead($, path).catch(() => null)if (typeof text !== 'string') continuethemeBg[mode] = ghosttyValueOf(text, 'background')break@@ -223,7 +224,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 $.env.get('HOME')) ?? ''+ const home = (await envGet($, 'HOME')) ?? ''const settings = cmuxSettingsOf(jsoncOf((await readText($, `${home}/.config/cmux/cmux.json`)) ?? ''))if (settings.adaptive === false) return nullconst seen = await readCmuxAppearance($, settings.appearance)@@ -234,12 +235,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 $.env.get('HOME')) ?? ''+ const home = (await envGet($, 'HOME')) ?? ''file = cmuxSettingsOf(jsoncOf((await readText($, `${home}/.config/cmux/cmux.json`)) ?? '')).appearance}let saved = ''if (!file && S.hostOs === 'Darwin') {- const got = await $.process.run(['defaults', 'read', 'com.cmuxterm.app', 'appearanceMode'], { timeoutMs: HOST_CHECK_MS }).catch(() => null)+ const got = await processRun($, ['defaults', 'read', 'com.cmuxterm.app', 'appearanceMode'], { timeoutMs: HOST_CHECK_MS }).catch(() => null)saved = got?.exitCode === 0 ? got.stdout : ''}const appearance = cmuxAppearanceOf(file, saved)@@ -252,23 +253,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 $.fs.read(path).catch(() => null)+ const text = await fsRead($, 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 $.env.get('HOME')) ?? ''+ const home = (await envGet($, 'HOME')) ?? ''const dirs = kittyConfigDirsOf({- kittyDir: (await $.env.get('KITTY_CONFIG_DIRECTORY')) || undefined,- xdgConfig: (await $.env.get('XDG_CONFIG_HOME')) || undefined,+ kittyDir: (await envGet($, 'KITTY_CONFIG_DIRECTORY')) || undefined,+ xdgConfig: (await envGet($, '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 $.fs.exists(`${dir}/kitty.conf`).catch(() => false))) continue+ if (!(await fsExists($, `${dir}/kitty.conf`).catch(() => false))) continuereturn { dir, entries: await kittyEntriesOf(`${dir}/kitty.conf`, path => readText($, path), o), home }}return { dir: dirs[0]!, entries: [], home }@@ -280,12 +281,12 @@ 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 => $.fs.exists(`${dir}/${kittyAutoFileOf(s)}`).catch(() => false)))+ const found = await Promise.all(schemes.map(s => fsExists($, `${dir}/${kittyAutoFileOf(s)}`).catch(() => false)))let auto: { file: string; entries: KittyEntries } | null = nullif (found.some(Boolean)) {let scheme: (typeof schemes)[number] | null = nullif (S.hostOs === 'Linux') {- const got = await $.process.run(['gsettings', 'get', 'org.gnome.desktop.interface', 'color-scheme'], { timeoutMs: HOST_CHECK_MS }).catch(() => null)+ const got = await processRun($, ['gsettings', 'get', 'org.gnome.desktop.interface', 'color-scheme'], { timeoutMs: HOST_CHECK_MS }).catch(() => null)scheme = got && got.exitCode === 0 ? kittySchemeOfGnome(got.stdout) : null} else scheme = (await readOsMode($).catch(() => null))?.mode ?? nullif (scheme && found[schemes.indexOf(scheme)]) {@@ -301,9 +302,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 $.env.get('RIO_CONFIG_HOME')) || undefined,- xdgConfig: (await $.env.get('XDG_CONFIG_HOME')) || undefined,- home: (await $.env.get('HOME')) ?? '',+ rioHome: (await envGet($, 'RIO_CONFIG_HOME')) || undefined,+ xdgConfig: (await envGet($, 'XDG_CONFIG_HOME')) || undefined,+ home: (await envGet($, 'HOME')) ?? '',isMac: S.hostOs === 'Darwin',})return { dir, config: tomlStringsOf((await readText($, `${dir}/config.toml`)) ?? '') }@@ -326,11 +327,11 @@ async function readRioMode($: EngineInterface): Promise<HostMode | null> {// The OS appearance: macOS, or GNOME's colour scheme on Linux.async function readOsMode($: EngineInterface): Promise<HostMode | null> {if (S.hostOs === 'Darwin') {- const got = await $.process.run(['defaults', 'read', '-g', 'AppleInterfaceStyle'], { timeoutMs: HOST_CHECK_MS }).catch(() => null)+ const got = await processRun($, ['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') {- const got = await $.process.run(['gsettings', 'get', 'org.gnome.desktop.interface', 'color-scheme'], { timeoutMs: HOST_CHECK_MS }).catch(() => null)+ const got = await processRun($, ['gsettings', 'get', 'org.gnome.desktop.interface', 'color-scheme'], { timeoutMs: HOST_CHECK_MS }).catch(() => null)const mode = got && got.exitCode === 0 ? modeOfGnome(got.stdout) : nullif (mode) return { mode, source: 'GNOME' }}@@ -362,7 +363,7 @@ export function showMode($: EngineInterface) {export function watchHost($: EngineInterface) {if (S.setting === 'auto' && !S.watch) {try {- S.watch = $.clock.every(HOST_POLL_MS, () => void pollHost($).catch(() => undefined))+ S.watch = clockEvery($, HOST_POLL_MS, () => void pollHost($).catch(() => undefined))} catch {S.watch = null}diff --git a/hooks/lib/log.ts b/hooks/lib/log.tsindex c1aaadc..5c5d9c9 100644--- a/hooks/lib/log.ts+++ b/hooks/lib/log.ts@@ -2,10 +2,11 @@import type { EngineInterface } from 'claude-code'import { S } from './state'+import { processRun } from './api'export async function logDebug($: EngineInterface, cache: string, text: string) {const stamp = new Date().toISOString()- await $.process.run(['sh', '-c', 'cat >> "$1"', 'sh', `${cache}/debug.log`], { stdin: `[${stamp}] ${text.trimEnd()}\n` }).catch(() => undefined)+ await processRun($, ['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/pictures.tsx b/hooks/lib/pictures.tsxindex 8aac1ed..87c2e09 100644--- a/hooks/lib/pictures.tsx+++ b/hooks/lib/pictures.tsx@@ -15,6 +15,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, 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 }@@ -33,7 +34,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 $.fs.stat(file).catch(() => null)+ if (!at) return fsStat($, file).catch(() => null)if (statsDone !== at.done || stats.size >= STATS_KEPT) {stats.clear()statsDone = at.done@@ -41,7 +42,7 @@ function statOf($: EngineInterface, file: string, at?: StatAt): Promise<FsStat |const key = `${at.row}\n${file}`let got = stats.get(key)if (!got) {- got = $.fs.stat(file).catch(() => null)+ got = fsStat($, file).catch(() => null)stats.set(key, got)}return got@@ -55,7 +56,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 $.process.run(['sh', '-c', HEADERS_SH, 'sh', file]).catch(() => null)+ const head = await processRun($, ['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)@@ -74,7 +75,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 $.fs.read(p.file, { as: 'bytes' }).catch(() => null)+ const got = await fsRead($, p.file, { as: 'bytes' }).catch(() => null)if (!got) return nullconst base64 = fitsInline(p, got.base64) ? got.base64 : nullinlined.set(key, base64)@@ -140,7 +141,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 $.clock.after(0, () => jobDone($)), () => undefined)+ if (before || epochOpen()) void run.then(() => void clockAfter($, 0, () => jobDone($)), () => undefined)}return before ?? run}@@ -162,20 +163,20 @@ async function hasPngOf($: EngineInterface, file: string, at?: StatAt): Promise<async function convertOnce($: EngineInterface, ready: Env, file: string, stamp: string, box: PixelBox, key: string): Promise<string | null> {const out = convertedPath(ready.cache, file, stamp, box)// Made before (an earlier load): the same file, stamp and box.- const made = await $.fs.stat(out).catch(() => null)+ const made = await fsStat($, 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 $.fs.write(`${dir}/source.txt`, `${file}\n`).catch(() => undefined)+ await fsWrite($, `${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 })const failed = (err: unknown) => ({ exitCode: 1, stdout: '', stderr: `did not run: ${String(err)}` })- const ran = await $.process.run(argv, { timeoutMs: COMPILE_TIMEOUT_MS, env }).catch(failed)- const moved = ran.exitCode === 0 ? await $.process.run(['mv', '-f', part, out]).catch(failed) : null+ 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) : nullif (ran.exitCode !== 0) {await logDebug($, ready.cache, `convert ${file} failed:\n${ran.stderr}`)png = null@@ -197,7 +198,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 $.fs.read(file).catch(() => null) : null+ const got = st.size <= SENT_TEXT_MAX_BYTES ? await fsRead($, file).catch(() => null) : nullconst text = got?.trim() ? got : nullkeep(sentTexts, file, { stamp, text }, PICTURES_KEPT)return text@@ -264,7 +265,7 @@ export function rowsAfter(under: readonly Under[], i: number, room: number): num// The engine's row, then the pictures under it.export function underRow($: EngineInterface, e: RowInput, row: RenderElement, under: readonly Under[]) {- const { Box, Image } = $.ui.resolve(e)+ const { Box, Image } = uiResolve($, e)return (<Box flexDirection="column">{row}@@ -289,20 +290,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 $.session.id()+ const id = await sessionId($)const kept = pasteDirs.get(id)if (kept) return keptconst found = async (dirs: Iterable<string>) => {for (const dir of dirs) {- if (!(await $.fs.exists(dir).catch(() => false))) continue+ if (!(await fsExists($, dir).catch(() => false))) continuepasteDirs.set(id, dir)return dir}return ''}- const root = await $.session.root().catch(() => ready.cwd)+ const root = await sessionRoot($).catch(() => ready.cwd)const named = await found(new Set([ready.cwd, root].map(dir => pasteDirOf(ready.claudeTmp, dir, id))))if (named) return named- const projects = (await $.fs.list(ready.claudeTmp).catch(() => [])).filter(f => f.kind === 'dir')+ const projects = (await fsList($, 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 7f46428..7f0fa6a 100644--- a/hooks/lib/plan.tsx+++ b/hooks/lib/plan.tsx@@ -15,6 +15,7 @@ import { S, writesLive } from './state'import { firstLine } from './markdown'import type { Drawing } from './answer'import { drawPages } from './draw'+import { clockAfter, commandRun, fsRead, processRun, promptSubmit, turnAbort, uiAsk, uiResolve } from './api'// The question's chip and its two wordings.export const PLAN_HEADER = 'Plan'@@ -160,7 +161,7 @@ async function findCode($: EngineInterface): Promise<string> {if (S.planCode !== null) return S.planCodelet found = ''for (const flag of ['-lc', '-c']) {- const got = await $.process.run(['sh', flag, 'command -v code'], { timeoutMs: 5000 }).catch(() => null)+ const got = await processRun($, ['sh', flag, 'command -v code'], { timeoutMs: 5000 }).catch(() => null)const path = got?.exitCode === 0 ? firstLine(got.stdout) : ''if (path.startsWith('/')) {found = path@@ -193,7 +194,7 @@ export async function decidePlan(let answer: stringS.planAsking = questiontry {- answer = await $.ui.ask(question, { header: PLAN_HEADER, options: planOptions(canEdit) })+ answer = await uiAsk($, question, { header: PLAN_HEADER, options: planOptions(canEdit) })} catch {return { kind: 'verdict', verdict: { kind: 'deny', message: PLAN_REJECTED } }} finally {@@ -202,8 +203,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 $.process.run(argv!, { timeoutMs: EDIT_TIMEOUT_MS }).catch(() => null)- const text = await $.fs.read(o.file).catch(() => null)+ await processRun($, argv!, { timeoutMs: EDIT_TIMEOUT_MS }).catch(() => null)+ const text = await fsRead($, o.file).catch(() => null)if (typeof text === 'string' && text.trim() && text !== plan) {plan = textisEdited = text !== o.plan@@ -219,9 +220,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 => $.clock.after(PLAN_WRITE_POLL_MS, resolve))+ await new Promise<void>(resolve => clockAfter($, PLAN_WRITE_POLL_MS, resolve))}- const text = await $.fs.read(file).catch(() => null)+ const text = await fsRead($, file).catch(() => null)return typeof text === 'string' && text.trim() ? text : fallback}@@ -229,10 +230,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) {- $.clock.after(CLEAR_DELAY_MS, async () => {- if (turnId) await $.turn.abort({ turnId }).catch(() => undefined)- await $.command.run({ command: 'clear' }).catch(() => undefined)- await $.prompt.submit({ text: `${PLAN_IMPLEMENT}\n\n${plan}`, asUser: true }).catch(() => undefined)+ clockAfter($, CLEAR_DELAY_MS, async () => {+ if (turnId) await turnAbort($, { turnId }).catch(() => undefined)+ await commandRun($, { command: 'clear' }).catch(() => undefined)+ await promptSubmit($, { text: `${PLAN_IMPLEMENT}\n\n${plan}`, asUser: true }).catch(() => undefined)})}@@ -244,7 +245,7 @@ type Terminal = ResolveInput<RenderComponent, 'terminal'> & { viewport?: RenderV// dim line while they compile; the engine's row alone when they fail).export function drawPlanUse($: EngineInterface, e: Terminal, row: RenderElement, drawing: Drawing): RenderElement {if (drawing.kind === 'text') return row- const { Box, Text } = $.ui.resolve(e)+ const { Box, Text } = uiResolve($, e)return (<Box flexDirection="column">{row}@@ -262,7 +263,7 @@ export function drawPlanUse($: EngineInterface, e: Terminal, row: RenderElement,// The approved plan's result row without the plan (the ToolUse row above// draws it): the engine's header and the plan file's path.export function drawPlanResult($: EngineInterface, e: Terminal, filePath?: string): RenderElement {- const { Box, Text } = $.ui.resolve(e)+ const { Box, Text } = uiResolve($, e)const saved = filePath ? shortPath(filePath, S.env?.home ?? '') : ''return (<Box flexDirection="column" marginTop={1}>@@ -283,7 +284,7 @@ export function drawPlanResult($: EngineInterface, e: Terminal, filePath?: strin// The line Intelligent UI adds above its own question.export function drawAskLine($: EngineInterface, e: ResolveInput<'AskUserQuestion', 'terminal'>, dialog: RenderElement): RenderElement {- const { Box, Text } = $.ui.resolve(e)+ const { Box, Text } = uiResolve($, e)return (<Box flexDirection="column"><Text dimColor wrap="truncate-end">{PLAN_ASK_LINE}</Text>diff --git a/hooks/lib/setup.ts b/hooks/lib/setup.tsindex 6b52684..32b375e 100644--- a/hooks/lib/setup.ts+++ b/hooks/lib/setup.ts@@ -4,6 +4,7 @@ import type { EngineInterface } from 'claude-code'import { S } from './state'import { readText } from './host'+import { envGet, fsWrite, processRun, storeGet, storeSet, uiAsk, uiLog, uiToast } 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@@ -58,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 $.env.get('SHELL')) ?? '',- home: (await $.env.get('HOME')) ?? '',- zdotdir: (await $.env.get('ZDOTDIR')) || undefined,- xdgConfig: (await $.env.get('XDG_CONFIG_HOME')) || undefined,+ shell: (await envGet($, 'SHELL')) ?? '',+ home: (await envGet($, 'HOME')) ?? '',+ zdotdir: (await envGet($, 'ZDOTDIR')) || undefined,+ xdgConfig: (await envGet($, 'XDG_CONFIG_HOME')) || undefined,isMac: S.hostOs === 'Darwin',})}@@ -75,12 +76,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 $.fs.write(rc.path, withoutSetup(text))+ await fsWrite($, 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 $.process.run(['mkdir', '-p', rc.path.replace(/\/[^/]*$/, '')]).catch(() => null)- await $.fs.write(rc.path, withSetup(text, rc.kind))+ if (rc.kind === 'fish') await processRun($, ['mkdir', '-p', rc.path.replace(/\/[^/]*$/, '')]).catch(() => null)+ await fsWrite($, rc.path, withSetup(text, rc.kind))return `Added the Intelligent UI block to ${rc.path}. ${restart} Undo with /iui setup remove.`}@@ -88,22 +89,22 @@ export async function runSetup($: EngineInterface, remove: boolean): Promise<strexport async function offerSetup($: EngineInterface) {if (S.setupAsked) returnS.setupAsked = true- if ((await $.store.get('setup').catch(() => undefined)) === 'never') return+ if ((await storeGet($, 'setup').catch(() => undefined)) === 'never') returnconst rc = await shellRc($)if (rc && hasSetup((await readText($, rc.path)) ?? '')) return- const file = rc ? rc.path.replace((await $.env.get('HOME')) ?? '\u0000', '~') : "your shell's start file"- const answer = await $.ui.ask(+ const file = rc ? rc.path.replace((await envGet($, 'HOME')) ?? '\u0000', '~') : "your shell's start file"+ const answer = await uiAsk($,`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 $.store.set('setup', 'never')+ if (answer === 'Never ask') await storeSet($, '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 {- $.ui.log(said)+ uiLog($, said)} catch {}try {- $.ui.toast(said.startsWith('Added') ? 'Close this tab and open a new iTerm2 tab to see pictures.' : 'See the transcript for the setup.', { timeoutMs: 10000 })+ uiToast($, 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 1e20cb2..f0c6fd7 100644--- a/hooks/lib/state.ts+++ b/hooks/lib/state.ts@@ -9,6 +9,7 @@ import type { HostMode, ThemeSetting } from './mode'import type { PlanVerdict } from './plan'import type { Drawn } from './copy'import { DEFAULT_HEIGHT, DEFAULT_SIZE, DEFAULT_WIDTH, type Height, type Width } from './settings'+import { uiInvalidate } 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@@ -255,5 +256,5 @@ export function keep<T>(cache: Map<string, T>, key: string, value: T, max: numbe// Redraws every reader of `done`; an invalidate where the write is refused.export function refresh($: EngineInterface) {- void update($, done, n => n + 1).catch(() => $.ui.invalidate('ui.render'))+ void update($, done, n => n + 1).catch(() => uiInvalidate($, 'ui.render'))}diff --git a/hooks/lib/stream.ts b/hooks/lib/stream.tsindex f5e80d0..8849c09 100644--- a/hooks/lib/stream.ts+++ b/hooks/lib/stream.ts@@ -11,6 +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'// The order of enqueue calls: a higher `order` is newer.let enqueued = 0@@ -106,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 = $.clock.after(ms, () => {+ entry.timer = clockAfter($, ms, () => {entry.showText = truerefresh($)})diff --git a/hooks/lib/themes.ts b/hooks/lib/themes.tsindex f753b82..79160c6 100644--- a/hooks/lib/themes.ts+++ b/hooks/lib/themes.ts@@ -4,6 +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'// A theme folder's name: letters, digits, `.`, `_`, `-`.export const isThemeName = (name: string) => /^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(name)@@ -105,11 +106,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 $.fs.list(base).catch(() => [])+ const entries = await fsList($, base).catch(() => [])for (const entry of entries) {if (entry.kind === 'file') continueconst dir = `${base}/${entry.name}`- const json = await $.fs.read(`${dir}/theme.json`).catch(() => null)+ const json = await fsRead($, `${dir}/theme.json`).catch(() => null)if (json === null) continueconst one = themeEntry(entry.name, dir, isUser, json)const lost = 'reason' in one ? [] : await missingSyntax($, one)@@ -124,7 +125,7 @@ export async function missingSyntax($: EngineInterface, theme: ThemeInfo) {const lost: string[] = []for (const mode of MODES) {const file = theme.syntax[mode]- if (file && !(await $.fs.exists(`${theme.dir}/${file}`).catch(() => false))) lost.push(file)+ if (file && !(await fsExists($, `${theme.dir}/${file}`).catch(() => false))) lost.push(file)}return lost}@@ -136,7 +137,7 @@ 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 $.fs.stat(file).catch(() => null)+ const stat = await fsStat($, file).catch(() => null)times.push(String(stat?.mtimeMs ?? 0))}return times.join(',')diff --git a/hooks/lib/typst.ts b/hooks/lib/typst.tsindex 5c595b2..de7162a 100644--- a/hooks/lib/typst.ts+++ b/hooks/lib/typst.ts@@ -10,6 +10,7 @@ import { alignFirstLine, firstLineOf, fontFit, sizing } from './draw'import { HEADERS_SH } from './host'import { logDebug } from './log'import { positionsOf, type Mark, type Positions } from './copy'+import { clockAfter, envGet, fsExists, fsList, fsRead, fsWrite, processRun, processSpawn } 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.@@ -102,15 +103,15 @@ export function shouldRetrySafe(exitCode: number): boolean {export async function findTypst($: EngineInterface): Promise<string | null> {for (const flag of ['-lc', '-c']) {- const got = await $.process.run(['sh', flag, 'command -v typst'], { timeoutMs: 5000 }).catch(() => null)+ const got = await processRun($, ['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 $.env.get('HOME').catch(() => undefined)) ?? ''+ const home = (await envGet($, 'HOME').catch(() => undefined)) ?? ''for (const each of TYPST_FALLBACKS) {if (each.startsWith('~/') && !home) continueconst path = each.startsWith('~/') ? `${home}${each.slice(1)}` : each- if (await $.fs.exists(path).catch(() => false)) return path+ if (await fsExists($, path).catch(() => false)) return path}return null}@@ -125,7 +126,7 @@ export const measureCall = (typst: string, root: string, family: string, themeDi// The fonts' metrics from render/measure.typ; the macOS defaults when that fails.export async function measureFonts($: EngineInterface, typst: string, root: string, cache: string, family: string, themeDir: string): Promise<Metrics> {const argv = measureCall(typst, root, family, themeDir)- const got = await $.process.run(argv, { timeoutMs: 10000, env: noNetworkEnv(cache) }).catch(() => null)+ const got = await processRun($, argv, { timeoutMs: 10000, env: noNetworkEnv(cache) }).catch(() => null)try {const m = JSON.parse(got?.stdout ?? '') as Metricsconst ok = (x: FontMetrics | null | undefined) => !!x && x.adv > 0 && x.xh > 0 && x.avg > 0@@ -142,7 +143,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 $.fs.exists(full).catch(() => false)) found.push(path, full)+ if (await fsExists($, full).catch(() => false)) found.push(path, full)}return found}@@ -185,11 +186,11 @@ export function touchLater($: EngineInterface, path: string) {if (toTouch.size >= TOUCH_KEPT && !toTouch.has(path)) returntoTouch.add(path)if (touchTimer) return- touchTimer = $.clock.after(TOUCH_FLUSH_MS, () => {+ touchTimer = clockAfter($, 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($.process.run(['touch', '-c', ...paths], { timeoutMs: 5000 })).catch(() => undefined)+ if (paths.length) void Promise.resolve(processRun($, ['touch', '-c', ...paths], { timeoutMs: 5000 })).catch(() => undefined)if (toTouch.size) touchLater($, toTouch.values().next().value!)})}@@ -228,7 +229,7 @@ export async function runKillable(const killNow = () => {if (!why || !pid || isKillSent) returnisKillSent = true- void Promise.resolve($.process.run(['kill', pid], { timeoutMs: 5000 })).catch(() => undefined)+ void Promise.resolve(processRun($, ['kill', pid], { timeoutMs: 5000 })).catch(() => undefined)}const stop = (reason: 'cancel' | 'timeout') => {if (why) return@@ -237,10 +238,10 @@ export async function runKillable(}const onAbort = () => stop('cancel')o.signal?.addEventListener('abort', onAbort, { once: true })- const timer = $.clock.after(o.timeoutMs, () => stop('timeout'))+ const timer = clockAfter($, o.timeoutMs, () => stop('timeout'))let code: number | null = 1try {- const child = $.process.spawn({ argv: wrapPid(argv), ...(o.env ? { env: o.env } : {}) })+ const child = processSpawn($, { argv: wrapPid(argv), ...(o.env ? { env: o.env } : {}) })for (;;) {const got = await child.next()if (got.done) {@@ -336,7 +337,7 @@ export async function probePage(): Promise<Positions | null> {let segments: unknowntry {- segments = (JSON.parse((await $.fs.read(`${dir}/doc.json`)) as string) as { segments?: unknown }).segments+ segments = (JSON.parse((await fsRead($, `${dir}/doc.json`)) as string) as { segments?: unknown }).segments} catch {return null}@@ -358,13 +359,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 $.fs.list(dir))+ const files = (await fsList($, 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 $.process.run(['sh', '-c', HEADERS_SH, 'sh', ...files])+ const heads = await processRun($, ['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`)@@ -380,7 +381,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 $.fs.read(`${dir}/pages.json`).catch(() => null)+ const kept = await fsRead($, `${dir}/pages.json`).catch(() => null)const keptResult = kept ? resultOf(kept) : nullif (keptResult) {touchLater($, dir)@@ -395,7 +396,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 $.fs.write(`${dir}/doc.json`, JSON.stringify({ base, segments, images }))+ await fsWrite($, `${dir}/doc.json`, JSON.stringify({ base, segments, images }))let tag = 'a'let isSafe = false@@ -426,7 +427,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 $.fs.write(`${dir}/doc.json`, JSON.stringify({ base, segments: cut, images }))+ await fsWrite($, `${dir}/doc.json`, JSON.stringify({ base, segments: cut, images }))const again = await runTypst($, job, cut, 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@@ -439,6 +440,6 @@ export async function compile($: EngineInterface, job: Job, signal?: AbortSignal}const { bulletRow } = alignFirstLine(firstLineOf(segments[0] ?? ''), rowPt)const result: Result = { pages, bulletRow, ...(note ? { note } : {}) }- await $.fs.write(`${dir}/pages.json`, JSON.stringify(result))+ await fsWrite($, `${dir}/pages.json`, JSON.stringify(result))return result}diff --git a/hooks/register.tsx b/hooks/register.tsxindex 8d3124c..8784797 100644--- a/hooks/register.tsx+++ b/hooks/register.tsx@@ -42,6 +42,7 @@ import { frameFor, noteView, stopWatch, watchFrame, watchState } from './lib/fraimport { roomColumns } from './lib/terminal'import { onScreenOf, pastedImagePath, pastedNumbers, sentFiles } from './lib/images'import { pasteDir, rowsAfter, sentOf, shownOf, underRow, type Shown, type Under } from './lib/pictures'+import { fsWrite, processRun, sessionSurfaces, storeSet, uiCopy, uiResolve, uiSelection, uiToast } from './lib/api'import {currentPlan, decidePlan, decisionOf, drawAskLine, drawPlanResult, drawPlanUse, isPlanQuestion, planFileOf, planInputOf, planOf,planShownOf, scheduleClear, type PlanVerdict,@@ -181,7 +182,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 $.session.surfaces().catch(() => [] as readonly string[])+ const surfaces = await sessionSurfaces($).catch(() => [] as readonly string[])if (!surfaces.includes('terminal')) return nullconst ready = S.env ?? (await setUp($).catch(() => null))return ready?.typst && ready.canDraw ? ready : null@@ -235,7 +236,7 @@ async function readCopy($: EngineInterface, raw: string, requestId?: string): Pr// The clipboard now (pbpaste, UTF-8); null when it can not be read.async function clipboardNow($: EngineInterface): Promise<string | null> {- const got = await $.process.run(['pbpaste'], { timeoutMs: 2000, env: { LANG: 'en_US.UTF-8', LC_ALL: 'en_US.UTF-8' } }).catch(() => null)+ const got = await processRun($, ['pbpaste'], { timeoutMs: 2000, env: { LANG: 'en_US.UTF-8', LC_ALL: 'en_US.UTF-8' } }).catch(() => null)return got && got.exitCode === 0 ? got.stdout : null}@@ -251,7 +252,7 @@ async function copyRead($: EngineInterface, raw: string, requestId?: string) {if (!read.resolved) {// Not read again from the clipboard (one toast).clip.seen = raw- $.ui.toast('Intelligent UI: could not read the selected picture (/iui dump says why)')+ uiToast($, 'Intelligent UI: could not read the selected picture (/iui dump says why)')return}if ((await clipboardNow($)) !== raw) {@@ -261,8 +262,8 @@ async function copyRead($: EngineInterface, raw: string, requestId?: string) {}clip.wrote = read.textclip.seen = read.text- await $.ui.copy({ text: read.text })- $.ui.toast(`Intelligent UI: copied ${read.text.length} chars of text`)+ await uiCopy($, { text: read.text })+ uiToast($, `Intelligent UI: copied ${read.text.length} chars of text`)}// A selection and a clipboard text are the same copy (a copy can end in@@ -301,7 +302,7 @@ async function readClipboard($: EngineInterface) {if (text === null || text === clip.seen) continueclip.seen = textif (text === clip.wrote || !hasPlaceholders(text)) continue- const selected = await $.ui.selection().catch(() => undefined)+ const selected = await uiSelection($).catch(() => undefined)if (selected && !sameCopy(selected.text, text)) continueawait copyRead($, text, selected?.requestId)} while (clip.again)@@ -341,7 +342,7 @@ function autoCopyOf(isOn: boolean): string {// /iui grab: the last mouse selection, read and copied.async function grab($: EngineInterface): Promise<string> {- const selected = await $.ui.selection().catch(() => undefined)+ const selected = await uiSelection($).catch(() => undefined)if (!selected) return 'Intelligent UI: no mouse selection (it needs fullscreen mode; select over a picture first).'if (!hasPlaceholders(selected.text)) return `Intelligent UI: the selection has no picture cells; it is ${selected.text.length} chars of text already.`clip.raw = selected.text@@ -350,7 +351,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 $.ui.copy({ text: read.text })+ const copied = await uiCopy($, { text: read.text })return copied.isCopied? `Intelligent UI: copied ${read.text.length} chars (${read.resolved} of ${read.runs} picture runs read${selected.requestId ? `, row ${selected.requestId}` : ''}).`: `Intelligent UI: the copy failed: ${copied.reason}.`@@ -385,7 +386,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 $.fs.write(`${cache}/copy-debug.json`, JSON.stringify(full, null, 1)).catch(() => undefined)+ await fsWrite($, `${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; auto copy ${auto}):`,@@ -419,7 +420,7 @@ export const register: Register = on => {// hold no placeholders and pass on as they are.on('ui.copy', async ($, e, next) => {if (!hasPlaceholders(e.text) || !drawnAnswers.size) return next(e)- const selected = await $.ui.selection().catch(() => undefined)+ const selected = await uiSelection($).catch(() => undefined)clip.raw = e.textclip.rawRow = selected?.text === e.text ? selected.requestId : undefinedconst read = await readCopy($, e.text, clip.rawRow)@@ -447,7 +448,7 @@ export const register: Register = on => {await update($, isOn, () => asked.kind === 'on')// On: the clipboard part starts with the next picture drawn.if (asked.kind === 'off') stopClipboard($)- await $.store.set('enabled', asked.kind === 'on')+ await storeSet($, 'enabled', asked.kind === 'on')return { text: `Intelligent UI is ${asked.kind}.` }}if (asked.kind === 'size') {@@ -455,7 +456,7 @@ export const register: Register = on => {// open (the store write waits for the host).S.size = asked.percentbeginEpoch($)- await $.store.set('size', S.size)+ await storeSet($, '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') {@@ -463,7 +464,7 @@ export const register: Register = on => {else {S.width = asked.widthbeginEpoch($)- await $.store.set('width', S.width)+ await storeSet($, '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'@@ -474,7 +475,7 @@ export const register: Register = on => {else {S.height = asked.heightbeginEpoch($)- await $.store.set('height', S.height)+ await storeSet($, '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).` }@@ -510,7 +511,7 @@ export const register: Register = on => {if (ready.typst && S.look) ready.metrics = await measureFonts($, ready.typst, ready.root, ready.cache, ready.termFont, S.look.dir)beginEpoch($)}- if (asked.name) await $.store.set('theme-name', chosen.name)+ if (asked.name) await storeSet($, 'theme-name', chosen.name)const head = asked.name ? `Intelligent UI uses the theme ${chosen.name}.\n` : ''return { text: `${head}${themeListing(themes, problems, chosen.name, userThemesOf(ready.home))}` }}@@ -642,7 +643,7 @@ export const register: Register = on => {}answers.delete(e.requestId)if (drawing.kind === 'text') return next(e)- const { Box } = $.ui.resolve(e)+ const { Box } = uiResolve($, e)return <Box />})