@casualjim/pi-pretty 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/render.ts ADDED
@@ -0,0 +1,488 @@
1
+ /**
2
+ * pi-pretty: rendering functions for all tools.
3
+ *
4
+ * These produce ANSI-colored terminal output strings.
5
+ * They are async only when Shiki syntax highlighting is involved.
6
+ */
7
+
8
+ import { basename, dirname } from "node:path";
9
+ import type { AgentToolResult } from "@earendil-works/pi-coding-agent";
10
+ // Top-level value import so jiti's pi-tui alias applies (it only rewrites
11
+ // static top-level import/require, not function-body require — see tui-text.ts).
12
+ import { Text as TuiText, truncateToWidth } from "@earendil-works/pi-tui";
13
+ import { codeToANSI } from "@shikijs/cli";
14
+ import { type BundledLanguage, type BundledTheme, bundledThemes } from "shiki";
15
+ import {
16
+ BG_BASE,
17
+ BG_ERROR,
18
+ CACHE_LIMIT,
19
+ detectLang,
20
+ dirIcon,
21
+ FG_BLUE,
22
+ FG_DIM,
23
+ FG_LNUM,
24
+ FG_RULE,
25
+ FG_YELLOW,
26
+ loadConfig,
27
+ MAX_HL_CHARS,
28
+ MAX_PREVIEW_LINES,
29
+ RST,
30
+ resolveBaseBackground,
31
+ TOOL_RESULT_INDENT,
32
+ termWidth,
33
+ } from "./config.js";
34
+ import {
35
+ CHARS_KEY,
36
+ compactErrorLines,
37
+ ELAPSED_KEY,
38
+ formatCharCount,
39
+ formatElapsedMs,
40
+ normalizeLineEndings,
41
+ } from "./helpers.js";
42
+ import type { RenderCtxLike as RenderContext, TextLike, ThemeLike } from "./types.js";
43
+
44
+ // ---------------------------------------------------------------------------
45
+ // Shiki ANSI cache
46
+ // ---------------------------------------------------------------------------
47
+
48
+ const DEFAULT_THEME: BundledTheme = "github-dark";
49
+
50
+ function isBundledTheme(name: string): name is BundledTheme {
51
+ return Object.hasOwn(bundledThemes, name);
52
+ }
53
+
54
+ function pickValidTheme(candidate: string, source: string): BundledTheme {
55
+ if (isBundledTheme(candidate)) return candidate;
56
+ console.warn(
57
+ `pi-pretty: theme "${candidate}" from ${source} is not a bundled Shiki theme; falling back to "${DEFAULT_THEME}"`,
58
+ );
59
+ return DEFAULT_THEME;
60
+ }
61
+
62
+ /**
63
+ * Resolve the Shiki theme used for syntax highlighting.
64
+ *
65
+ * `~/.pi/agent/settings.json`'s `theme` field is pi's TUI appearance setting
66
+ * (e.g. `dark`, `light`, or a custom pi theme name), which is not a valid
67
+ * Shiki theme for native users. Validate the candidate against Shiki's
68
+ * bundled themes; warn once and fall back to {@link DEFAULT_THEME} when it is
69
+ * not a bundled theme, instead of silently degrading every highlighted block
70
+ * to plain text.
71
+ */
72
+ export function resolveTheme(env = process.env.PRETTY_THEME, home = process.env.HOME): BundledTheme {
73
+ if (env) return pickValidTheme(env, "PRETTY_THEME");
74
+ try {
75
+ if (!home) return DEFAULT_THEME;
76
+ const settings = JSON.parse(
77
+ require("node:fs").readFileSync(require("node:path").join(home, ".pi/agent/settings.json"), "utf8"),
78
+ );
79
+ const candidate = settings.theme;
80
+ if (typeof candidate === "string") return pickValidTheme(candidate, "~/.pi/agent/settings.json");
81
+ return DEFAULT_THEME;
82
+ } catch {
83
+ return DEFAULT_THEME;
84
+ }
85
+ }
86
+
87
+ let _theme: BundledTheme | undefined;
88
+
89
+ /**
90
+ * Resolve the effective theme once per session: `PRETTY_THEME` env →
91
+ * `pi-pretty.json` → `~/.pi/agent/settings.json` → {@link DEFAULT_THEME}.
92
+ * Resolution is lazy so config-file values applied at extension activation
93
+ * take effect, and the result is cached (at most one warning per source).
94
+ */
95
+ export function getTheme(): BundledTheme {
96
+ if (_theme) return _theme;
97
+ const env = process.env.PRETTY_THEME;
98
+ let theme: BundledTheme;
99
+ if (env) {
100
+ theme = resolveTheme(env, "");
101
+ } else {
102
+ const configTheme = loadConfig().theme;
103
+ theme =
104
+ typeof configTheme === "string"
105
+ ? pickValidTheme(configTheme, "pi-pretty.json")
106
+ : resolveTheme(undefined, process.env.HOME);
107
+ }
108
+ _theme = theme;
109
+ return theme;
110
+ }
111
+
112
+ const _cache = new Map<string, string[]>();
113
+
114
+ function _touch(k: string, v: string[]): string[] {
115
+ _cache.delete(k);
116
+ _cache.set(k, v);
117
+ while (_cache.size > CACHE_LIMIT) {
118
+ const first = _cache.keys().next().value;
119
+ if (first === undefined) break;
120
+ _cache.delete(first);
121
+ }
122
+ return v;
123
+ }
124
+
125
+ async function hlBlock(code: string, language: BundledLanguage | undefined): Promise<string[]> {
126
+ if (!code) return [""];
127
+ if (!language || code.length > MAX_HL_CHARS) return code.split("\n");
128
+
129
+ const k = `${getTheme()}\0${language}\0${code}`;
130
+ const hit = _cache.get(k);
131
+ if (hit) return _touch(k, hit);
132
+
133
+ try {
134
+ const ansi = normalizeShikiContrast(await codeToANSI(code, language, getTheme()));
135
+ const out = (ansi.endsWith("\n") ? ansi.slice(0, -1) : ansi).split("\n");
136
+ return _touch(k, out);
137
+ } catch {
138
+ return code.split("\n");
139
+ }
140
+ }
141
+
142
+ const ESC_RE = "\u001b";
143
+ const ANSI_CAPTURE_RE = new RegExp(`${ESC_RE}\\[([0-9;]*)m`, "g");
144
+ const FG_MUTED = "\x1b[38;2;139;148;158m";
145
+
146
+ export function isLowContrastShikiFg(params: string): boolean {
147
+ if (params === "30" || params === "90") return true;
148
+ if (params === "38;5;0" || params === "38;5;8") return true;
149
+ if (!params.startsWith("38;2;")) return false;
150
+ const parts = params.split(";").map(Number);
151
+ if (parts.length !== 5 || parts.some((n) => !Number.isFinite(n))) return false;
152
+ const [, , r, g, b] = parts;
153
+ const luminance = 0.2126 * r + 0.7152 * g + 0.0722 * b;
154
+ return luminance < 72;
155
+ }
156
+
157
+ function normalizeShikiContrast(ansi: string): string {
158
+ return ansi.replace(ANSI_CAPTURE_RE, (seq, params: string) => (isLowContrastShikiFg(params) ? FG_MUTED : seq));
159
+ }
160
+
161
+ // ---------------------------------------------------------------------------
162
+ // Box background helpers
163
+ // ---------------------------------------------------------------------------
164
+
165
+ export const RESET_WITHOUT_BG = "\x1b[22;23;24;25;27;28;29;39m";
166
+
167
+ export function preserveBoxBackground(ansi: string): string {
168
+ return ansi.replace(ANSI_CAPTURE_RE, (_seq, params: string) => {
169
+ if (!params || params === "0") return RESET_WITHOUT_BG;
170
+ const parts = params.split(";").filter(Boolean);
171
+ const kept: string[] = [];
172
+ let i = 0;
173
+ while (i < parts.length) {
174
+ const code = Number(parts[i]);
175
+ if (code === 38) {
176
+ // Foreground extended — keep entire sequence
177
+ kept.push(parts[i]);
178
+ if (parts[i + 1] === "5") {
179
+ kept.push(parts[i + 1]);
180
+ i += 2;
181
+ } else if (parts[i + 1] === "2") {
182
+ kept.push(parts[i + 1], parts[i + 2], parts[i + 3], parts[i + 4]);
183
+ i += 5;
184
+ } else {
185
+ i++;
186
+ }
187
+ } else if (code === 48) {
188
+ // Background extended — skip entirely
189
+ if (parts[i + 1] === "5") i += 3;
190
+ else if (parts[i + 1] === "2") i += 6;
191
+ else i++;
192
+ } else if (code === 49 || (code >= 40 && code <= 47) || (code >= 100 && code <= 107)) {
193
+ i++;
194
+ } else {
195
+ kept.push(parts[i]);
196
+ i++;
197
+ }
198
+ }
199
+ return kept.length ? `\x1b[${kept.join(";")}m` : "";
200
+ });
201
+ }
202
+
203
+ export function fillToolBackground(text: string, bg = BG_BASE, width?: number): string {
204
+ return text
205
+ .split("\n")
206
+ .map((line) => {
207
+ if (!width) {
208
+ const stripped = preserveBoxBackground(line);
209
+ return bg ? bg + stripped : stripped;
210
+ }
211
+ const plainLead = line.replace(ANSI_CAPTURE_RE, "");
212
+ const skipPad = line.startsWith(TOOL_RESULT_INDENT) || plainLead.startsWith(TOOL_RESULT_INDENT);
213
+ const fitted = truncateToWidth(line, width, "", !skipPad);
214
+ const stripped = preserveBoxBackground(fitted);
215
+ return bg ? bg + stripped : stripped;
216
+ })
217
+ .join("\n");
218
+ }
219
+
220
+ /** Add exactly the missing terminal row after a rendered tool body. */
221
+ export function fillToolBody(text: string, bg = BG_BASE, width?: number): string {
222
+ return fillToolBackground(text.endsWith("\n") ? text : `${text}\n`, bg, width);
223
+ }
224
+
225
+ const TOOL_TITLE_STATE_KEY = "__piPrettyToolTitle";
226
+ type ToolTitleRenderer = (suffix?: string) => string;
227
+ type ToolTitleState = { component: TextLike; render: ToolTitleRenderer };
228
+
229
+ /** Keep a self-rendered tool's call title mutable while its result arrives. */
230
+ export function rememberToolTitle(ctx: RenderContext, component: TextLike, render: ToolTitleRenderer): void {
231
+ ctx.state[TOOL_TITLE_STATE_KEY] = { component, render } satisfies ToolTitleState;
232
+ }
233
+
234
+ /** Move collapsed result metadata into the call title and hide the result slot. */
235
+ export function setCollapsedToolTitle(ctx: RenderContext, result: TextLike, suffix: string): boolean {
236
+ if (ctx.expanded) return false;
237
+ const title = ctx.state[TOOL_TITLE_STATE_KEY] as ToolTitleState | undefined;
238
+ if (!title || typeof title.render !== "function") return false;
239
+ title.component.setText(title.render(suffix));
240
+ result.setText("");
241
+ return true;
242
+ }
243
+
244
+ function lnum(n: number, w: number): string {
245
+ const v = String(n);
246
+ return `${FG_LNUM}${" ".repeat(Math.max(0, w - v.length))}${v}${RST}`;
247
+ }
248
+
249
+ // ---------------------------------------------------------------------------
250
+ // Tool metrics line
251
+ // ---------------------------------------------------------------------------
252
+
253
+ export function renderToolMetrics(result: AgentToolResult<Record<string, unknown>>): string {
254
+ const details = result.details as Record<string, unknown> | undefined;
255
+ if (!details) return "";
256
+ const elapsed = formatElapsedMs(details[ELAPSED_KEY] as number | undefined);
257
+ const chars = formatCharCount(details[CHARS_KEY] as number | undefined);
258
+ if (!elapsed && !chars) return "";
259
+ return `${FG_DIM}· ${[elapsed, chars].filter(Boolean).join(" · ")}${RST}`;
260
+ }
261
+
262
+ export function renderToolDuration(result: AgentToolResult<Record<string, unknown>>): string {
263
+ const details = result.details as Record<string, unknown> | undefined;
264
+ return formatElapsedMs(details?.[ELAPSED_KEY] as number | undefined);
265
+ }
266
+
267
+ // ---------------------------------------------------------------------------
268
+ // Error renderer
269
+ // ---------------------------------------------------------------------------
270
+
271
+ export function renderToolError(error: string, theme: ThemeLike): string {
272
+ const body = compactErrorLines(error)
273
+ .map((line) => `${TOOL_RESULT_INDENT}${line ? theme.fg("error", line) : ""}`)
274
+ .join("\n");
275
+ return fillToolBody(body, BG_ERROR);
276
+ }
277
+
278
+ // ---------------------------------------------------------------------------
279
+ // Read — syntax-highlighted file content
280
+ // ---------------------------------------------------------------------------
281
+
282
+ export async function renderFileContent(
283
+ content: string,
284
+ filePath: string,
285
+ offset = 0,
286
+ maxLines = MAX_PREVIEW_LINES,
287
+ width?: number,
288
+ ): Promise<string> {
289
+ const normalizedContent = normalizeLineEndings(content);
290
+ const lines = normalizedContent.split("\n");
291
+ const show = lines.slice(0, maxLines);
292
+ const lg = detectLang(filePath);
293
+ const hl = await hlBlock(show.join("\n"), lg);
294
+
295
+ const tw = width ?? termWidth();
296
+
297
+ const out: string[] = [];
298
+ for (const line of hl) {
299
+ out.push(truncateToWidth(line ?? "", Math.max(1, tw), `${FG_DIM}›`));
300
+ }
301
+ return out.join("\n");
302
+ }
303
+
304
+ // ---------------------------------------------------------------------------
305
+ // Bash — colored exit status
306
+ // ---------------------------------------------------------------------------
307
+
308
+ export function renderBashOutput(text: string): string {
309
+ const lines = text.split("\n");
310
+ const maxShow = MAX_PREVIEW_LINES;
311
+ const show = lines.slice(0, maxShow);
312
+ const remaining = lines.length - maxShow;
313
+
314
+ let body = show.join("\n");
315
+ if (remaining > 0) body += `\n${TOOL_RESULT_INDENT}${FG_DIM}… ${remaining} more lines${RST}`;
316
+
317
+ return body;
318
+ }
319
+
320
+ // ---------------------------------------------------------------------------
321
+ // Ls — tree view with icons
322
+ // ---------------------------------------------------------------------------
323
+
324
+ export function renderTree(text: string, _basePath: string): string {
325
+ const lines = text.trim().split("\n").filter(Boolean);
326
+ if (!lines.length) return `${FG_DIM}(empty directory)${RST}`;
327
+
328
+ const out: string[] = [];
329
+ const total = lines.length;
330
+ const show = lines.slice(0, MAX_PREVIEW_LINES);
331
+
332
+ for (let i = 0; i < show.length; i++) {
333
+ const entry = show[i].trim();
334
+ const isLast = i === show.length - 1 && total <= MAX_PREVIEW_LINES;
335
+ const prefix = isLast ? "└── " : "├── ";
336
+ const connector = `${FG_RULE}${prefix}${RST}`;
337
+ const isDir = entry.endsWith("/");
338
+ const name = isDir ? entry.slice(0, -1) : entry;
339
+ const icon = isDir ? dirIcon() : "";
340
+ out.push(`${connector}${icon}${isDir ? `${FG_BLUE}\x1b[1m${name}${RST}` : name}`);
341
+ }
342
+
343
+ if (total > MAX_PREVIEW_LINES) {
344
+ out.push(`${FG_RULE}└── ${RST}${FG_DIM}… ${total - MAX_PREVIEW_LINES} more entries${RST}`);
345
+ }
346
+
347
+ return out.join("\n");
348
+ }
349
+
350
+ // ---------------------------------------------------------------------------
351
+ // Find — grouped file list (plain, no tree characters or icons)
352
+ // ---------------------------------------------------------------------------
353
+
354
+ export function renderFindResults(text: string, theme?: ThemeLike): string {
355
+ const lines = text.trim().split("\n").filter(Boolean);
356
+ if (!lines.length) return theme ? theme.fg("dim", "(no matches)") : `${FG_DIM}(no matches)${RST}`;
357
+
358
+ const groups = new Map<string, string[]>();
359
+ for (const line of lines) {
360
+ const trimmed = line.trim();
361
+ const dir = dirname(trimmed) || ".";
362
+ const file = basename(trimmed);
363
+ if (!groups.has(dir)) groups.set(dir, []);
364
+ const bucket = groups.get(dir);
365
+ if (bucket) bucket.push(file);
366
+ }
367
+
368
+ const out: string[] = [];
369
+ let count = 0;
370
+
371
+ for (const [dir, files] of groups) {
372
+ if (count > 0) out.push("");
373
+ const dirColored = theme ? theme.fg("accent", theme.bold(`${dir}/`)) : `${FG_BLUE}\x1b[1m${dir}/${RST}`;
374
+ out.push(dirColored);
375
+ for (let i = 0; i < files.length; i++) {
376
+ if (count >= MAX_PREVIEW_LINES) {
377
+ const more = theme
378
+ ? theme.fg("dim", `… ${lines.length - count} more files`)
379
+ : `${FG_DIM}… ${lines.length - count} more files${RST}`;
380
+ out.push(`${TOOL_RESULT_INDENT}${more}`);
381
+ return out.join("\n");
382
+ }
383
+ out.push(`${TOOL_RESULT_INDENT}${files[i]}`);
384
+ count++;
385
+ }
386
+ }
387
+
388
+ return out.join("\n");
389
+ }
390
+
391
+ // ---------------------------------------------------------------------------
392
+ // Grep — highlighted matches with line numbers
393
+ // ---------------------------------------------------------------------------
394
+
395
+ export async function renderGrepResults(text: string, pattern: string): Promise<string> {
396
+ const lines = normalizeLineEndings(text).split("\n");
397
+ if (!lines.length || (lines.length === 1 && !lines[0].trim())) return `${FG_DIM}(no matches)${RST}`;
398
+
399
+ const out: string[] = [];
400
+ let currentFile = "";
401
+ let count = 0;
402
+
403
+ let re: RegExp | null = null;
404
+ try {
405
+ re = new RegExp(`(${pattern})`, "gi");
406
+ } catch {
407
+ /* skip highlighting */
408
+ }
409
+
410
+ for (const line of lines) {
411
+ if (count >= MAX_PREVIEW_LINES) {
412
+ out.push(`${FG_DIM} … more matches${RST}`);
413
+ break;
414
+ }
415
+ const fileMatch = line.match(/^(.+?)[:-](\d+)[:-](.*)$/);
416
+ if (fileMatch) {
417
+ const [, file, lineNo, content] = fileMatch;
418
+ if (file !== currentFile) {
419
+ if (currentFile) out.push("");
420
+ out.push(`${FG_BLUE}\x1b[1m${file}${RST}`);
421
+ currentFile = file;
422
+ }
423
+ const nw = Math.max(3, lineNo.length);
424
+ let display = content;
425
+ if (re) display = content.replace(re, `${RST}${FG_YELLOW}\x1b[1m$1${RST}`);
426
+ out.push(`${TOOL_RESULT_INDENT}${lnum(Number(lineNo), nw)} ${FG_RULE}│${RST} ${display}${RST}`);
427
+ count++;
428
+ } else if (line.trim() === "--") {
429
+ out.push(`${TOOL_RESULT_INDENT}${FG_DIM} ···${RST}`);
430
+ } else if (line.trim()) {
431
+ out.push(line);
432
+ count++;
433
+ }
434
+ }
435
+
436
+ return out.join("\n");
437
+ }
438
+
439
+ // ---------------------------------------------------------------------------
440
+ // Generic renderCall / renderResult for custom tools
441
+ // ---------------------------------------------------------------------------
442
+
443
+ export function makeRenderCall(toolName: string) {
444
+ return (args: Record<string, unknown>, theme: ThemeLike, ctx: RenderContext) => {
445
+ resolveBaseBackground(theme);
446
+ const text = ctx.lastComponent ?? new TuiText("", 0, 0);
447
+ const bg = ctx.isError ? BG_ERROR : undefined;
448
+ text.setText(fillToolBackground(`${theme.fg("toolTitle", theme.bold(toolName))}`, bg));
449
+ return text;
450
+ };
451
+ }
452
+
453
+ export function makeRenderResult() {
454
+ return (result: AgentToolResult<Record<string, unknown>>, _opt: unknown, theme: ThemeLike, ctx: RenderContext) => {
455
+ resolveBaseBackground(theme);
456
+ const text = ctx.lastComponent ?? new TuiText("", 0, 0);
457
+ if (ctx.isError) {
458
+ text.setText(renderToolError(getTextContent(result) || "Error", theme));
459
+ return text;
460
+ }
461
+ const content = getTextContent(result);
462
+ if (content) {
463
+ const renderWidth = termWidth();
464
+ const lines = content.split("\n");
465
+ const maxShow = ctx.expanded ? lines.length : Math.min(lines.length, MAX_PREVIEW_LINES);
466
+ const preview = lines.slice(0, maxShow).join("\n");
467
+ const more = lines.length > maxShow ? `\n${FG_DIM}... ${lines.length - maxShow} more lines${RST}` : "";
468
+ const metrics = renderToolMetrics(result);
469
+ text.setText(
470
+ fillToolBody(
471
+ `${TOOL_RESULT_INDENT}${preview}${more}${metrics ? `\n${TOOL_RESULT_INDENT}${metrics}` : ""}`,
472
+ undefined,
473
+ renderWidth,
474
+ ),
475
+ );
476
+ } else {
477
+ text.setText(fillToolBody(`${TOOL_RESULT_INDENT}${theme.fg("dim", "(no text output)")}`));
478
+ }
479
+ return text;
480
+ };
481
+ }
482
+
483
+ function getTextContent(result: AgentToolResult<Record<string, unknown>>): string {
484
+ return (result.content ?? [])
485
+ .filter((c: any) => c.type === "text")
486
+ .map((c: any) => c.text ?? "")
487
+ .join("\n");
488
+ }
@@ -0,0 +1,172 @@
1
+ /**
2
+ * Per-session accent color — port of oh-my-pi's `utils/session-color.ts`
3
+ * (OKLCH essence, no native dependencies).
4
+ *
5
+ * omp derives a stable per-session accent: the session name hash picks only
6
+ * the *hue* (djb2, walked along a dark-theme-safe arc that excludes hues
7
+ * which darken badly); lightness and chroma live in OKLCH so every hue
8
+ * renders with equal perceived weight (the reason omp carries the theme
9
+ * accent through per-hue gamut cusps — constant OKLCH L/C achieves the same
10
+ * uniformity without theme introspection, which pi's extension API does not
11
+ * expose). The spinner variant dims the accent exactly like omp's
12
+ * `adjustHsv(hex, { s: 0.55, v: 0.65 })`.
13
+ *
14
+ * Skipped from the omp original (requires host theme internals pi does not
15
+ * expose to extensions): per-hue gamut cusps, WCAG contrast bisection against
16
+ * the surface, hue-collision avoidance against theme colors.
17
+ */
18
+
19
+ // ─── omp session-color.ts constants ──────────────────────────────────────────
20
+
21
+ /** omp MIN_CHROMA / MAX_CHROMA: readable floor, "not a highlighter set" ceiling. */
22
+ const MIN_CHROMA = 0.05;
23
+ const MAX_CHROMA = 0.21;
24
+
25
+ /** omp dark-theme lightness band (visible on dark surfaces). */
26
+ const LIGHTNESS = 0.75;
27
+
28
+ /**
29
+ * Dark-theme hue arc. omp computes these intervals from per-hue gamut cusps;
30
+ * its doc comment pins the always-excluded bands — the yellow/chartreuse core
31
+ * (≈94–138°, darkens to mustard) and the over-light cyan peak (≈158–200°) —
32
+ * for every theme, so the arc below hardcodes the full wheel minus those two.
33
+ */
34
+ const DARK_HUE_INTERVALS: ReadonlyArray<readonly [number, number]> = [
35
+ [0, 93],
36
+ [139, 157],
37
+ [201, 359],
38
+ ];
39
+ const ARC_LENGTH = DARK_HUE_INTERVALS.reduce((n, [a, b]) => n + (b - a + 1), 0);
40
+
41
+ /** omp nameToHash: stable 32-bit djb2. */
42
+ function nameToHash(name: string): number {
43
+ let hash = 5381;
44
+ for (let i = 0; i < name.length; i++) {
45
+ hash = ((hash << 5) + hash) ^ name.charCodeAt(i);
46
+ hash = hash >>> 0;
47
+ }
48
+ return hash;
49
+ }
50
+
51
+ /** Map a name to its OKLCH hue on the dark-safe arc. */
52
+ export function sessionAccentHue(name: string): number {
53
+ let pos = nameToHash(name) % ARC_LENGTH;
54
+ for (const [a, b] of DARK_HUE_INTERVALS) {
55
+ const n = b - a + 1;
56
+ if (pos < n) return a + pos;
57
+ pos -= n;
58
+ }
59
+ return DARK_HUE_INTERVALS[DARK_HUE_INTERVALS.length - 1]?.[1] ?? 0;
60
+ }
61
+
62
+ // ─── OKLCH ↔ sRGB (Björn Ottosson's published matrices) ─────────────────────
63
+
64
+ function oklchToSrgb(l: number, c: number, hDeg: number): [number, number, number] {
65
+ const h = (hDeg * Math.PI) / 180;
66
+ const a = c * Math.cos(h);
67
+ const b = c * Math.sin(h);
68
+ const l_ = l + 0.3963377774 * a + 0.2158037573 * b;
69
+ const m_ = l - 0.1055613458 * a - 0.0638541728 * b;
70
+ const s_ = l - 0.0894841775 * a - 1.291485548 * b;
71
+ const ll = l_ * l_ * l_;
72
+ const mm = m_ * m_ * m_;
73
+ const ss = s_ * s_ * s_;
74
+ return [
75
+ 4.0767416621 * ll - 3.3077115913 * mm + 0.2309699292 * ss,
76
+ -1.2684380046 * ll + 2.6097574011 * mm - 0.3413193965 * ss,
77
+ -0.0041960863 * ll - 0.7034186147 * mm + 1.707614701 * ss,
78
+ ];
79
+ }
80
+
81
+ const transfer = (x: number): number => (x <= 0.0031308 ? 12.92 * x : 1.055 * x ** (1 / 2.4) - 0.055);
82
+ const clamp01 = (x: number): number => Math.max(0, Math.min(1, x));
83
+
84
+ /** Largest chroma ≤ `c` whose color is inside the sRGB gamut (chroma bisection). */
85
+ function clampChroma(l: number, c: number, hDeg: number, iterations = 12): number {
86
+ let lo = 0;
87
+ let hi = c;
88
+ const inGamut = (chroma: number): boolean => oklchToSrgb(l, chroma, hDeg).every((x) => x >= -1e-4 && x <= 1 + 1e-4);
89
+ if (inGamut(hi)) return hi;
90
+ for (let i = 0; i < iterations; i++) {
91
+ const mid = (lo + hi) / 2;
92
+ if (inGamut(mid)) lo = mid;
93
+ else hi = mid;
94
+ }
95
+ return lo;
96
+ }
97
+
98
+ function oklchToHex(l: number, c: number, hDeg: number): string {
99
+ const chroma = clampChroma(l, c, hDeg);
100
+ const [r, g, b] = oklchToSrgb(l, chroma, hDeg);
101
+ const hex = (x: number): string =>
102
+ Math.round(clamp01(transfer(clamp01(x))) * 255)
103
+ .toString(16)
104
+ .padStart(2, "0");
105
+ return `#${hex(r)}${hex(g)}${hex(b)}`;
106
+ }
107
+
108
+ // ─── Public surface ──────────────────────────────────────────────────────────
109
+
110
+ /** Stable per-session accent hex at a fixed OKLCH lightness/chroma band. */
111
+ export function sessionAccentHex(name: string): string {
112
+ return oklchToHex(LIGHTNESS, Math.max(MIN_CHROMA, Math.min(MAX_CHROMA, 0.14)), sessionAccentHue(name));
113
+ }
114
+
115
+ function hexToRgb(hex: string): [number, number, number] | undefined {
116
+ const m = hex.trim().match(/^#?([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/);
117
+ if (!m) return undefined;
118
+ return [Number.parseInt(m[1], 16), Number.parseInt(m[2], 16), Number.parseInt(m[3], 16)];
119
+ }
120
+
121
+ /** RGB(0-1) → HSV; exactly the inverse legs omp's adjustHsv needs. */
122
+ function rgbToHsv(r: number, g: number, b: number): [number, number, number] {
123
+ const max = Math.max(r, g, b);
124
+ const min = Math.min(r, g, b);
125
+ const d = max - min;
126
+ let h: number;
127
+ if (d === 0) h = 0;
128
+ else if (max === r) h = ((g - b) / d) % 6;
129
+ else if (max === g) h = (b - r) / d + 2;
130
+ else h = (r - g) / d + 4;
131
+ h = (h * 60 + 360) % 360;
132
+ return [h, max === 0 ? 0 : d / max, max];
133
+ }
134
+
135
+ function hsvToHex(h: number, s: number, v: number): string {
136
+ const c = v * s;
137
+ const hp = h / 60;
138
+ const x = c * (1 - Math.abs((hp % 2) - 1));
139
+ const m = v - c;
140
+ let rgb: [number, number, number];
141
+ if (hp < 1) rgb = [c, x, 0];
142
+ else if (hp < 2) rgb = [x, c, 0];
143
+ else if (hp < 3) rgb = [0, c, x];
144
+ else if (hp < 4) rgb = [0, x, c];
145
+ else if (hp < 5) rgb = [x, 0, c];
146
+ else rgb = [c, 0, x];
147
+ const hex = (x: number): string =>
148
+ Math.round((x + m) * 255)
149
+ .toString(16)
150
+ .padStart(2, "0");
151
+ return `#${hex(rgb[0])}${hex(rgb[1])}${hex(rgb[2])}`;
152
+ }
153
+
154
+ /**
155
+ * Dim variant for the spinner — identical transform to omp's
156
+ * `adjustHsv(hex, { s: 0.55, v: 0.65 })`. Unparseable input returns
157
+ * the input unchanged.
158
+ */
159
+ export function dimAccentHex(hex: string): string {
160
+ const rgb = hexToRgb(hex);
161
+ if (!rgb) return hex;
162
+ const [r, g, b] = rgb.map((x) => x / 255) as [number, number, number];
163
+ const [h, s, v] = rgbToHsv(r, g, b);
164
+ return hsvToHex(h, s * 0.55, v * 0.65);
165
+ }
166
+
167
+ /** Truecolor ANSI foreground open sequence for a `#rrggbb` hex. */
168
+ export function hexToAnsiFg(hex: string): string {
169
+ const rgb = hexToRgb(hex);
170
+ if (!rgb) return "";
171
+ return `\x1b[38;2;${rgb[0]};${rgb[1]};${rgb[2]}m`;
172
+ }
@@ -0,0 +1,21 @@
1
+ /* Declaration boundary for @casualjim/pi-pretty/bash-renderers.
2
+ *
3
+ * Consumers (pi-heimdall) type-check against this file — their strict tsconfig
4
+ * flags do not apply to it (skipLibCheck). The runtime entry stays bash.ts. */
5
+
6
+ import type { AgentToolResult } from "@earendil-works/pi-coding-agent";
7
+
8
+ type Result = AgentToolResult<Record<string, unknown>>;
9
+
10
+ export interface BashRenderers {
11
+ renderShell: "self";
12
+ /** Renders the `$ command` call header; returns the host Text component. */
13
+ renderCall: (args: any, theme: any, ctx: any) => unknown;
14
+ /** Renders bash output with pi-pretty styling; returns the host Text component. */
15
+ renderResult: (result: Result, options: unknown, theme: any, ctx: any) => unknown;
16
+ }
17
+
18
+ /** Build pi-pretty's bash renderers. TextComp is the host TUI Text class; when omitted, pi-tui's Text is used. */
19
+ export declare function createBashRenderers(
20
+ TextComp?: new (t?: string, x?: number, y?: number) => { setText(v: string): void },
21
+ ): BashRenderers;