@casualjim/pi-pretty 0.7.0 → 0.7.1

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 CHANGED
@@ -13,31 +13,31 @@ import { Text as TuiText, truncateToWidth } from "@earendil-works/pi-tui";
13
13
  import { codeToANSI } from "@shikijs/cli";
14
14
  import { type BundledLanguage, type BundledTheme, bundledThemes } from "shiki";
15
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,
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
33
  } from "./config.js";
34
34
  import {
35
- CHARS_KEY,
36
- compactErrorLines,
37
- ELAPSED_KEY,
38
- formatCharCount,
39
- formatElapsedMs,
40
- normalizeLineEndings,
35
+ CHARS_KEY,
36
+ compactErrorLines,
37
+ ELAPSED_KEY,
38
+ formatCharCount,
39
+ formatElapsedMs,
40
+ normalizeLineEndings,
41
41
  } from "./helpers.js";
42
42
  import type { RenderCtxLike as RenderContext, TextLike, ThemeLike } from "./types.js";
43
43
 
@@ -48,15 +48,15 @@ import type { RenderCtxLike as RenderContext, TextLike, ThemeLike } from "./type
48
48
  const DEFAULT_THEME: BundledTheme = "github-dark";
49
49
 
50
50
  function isBundledTheme(name: string): name is BundledTheme {
51
- return Object.hasOwn(bundledThemes, name);
51
+ return Object.hasOwn(bundledThemes, name);
52
52
  }
53
53
 
54
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;
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
60
  }
61
61
 
62
62
  /**
@@ -70,18 +70,18 @@ function pickValidTheme(candidate: string, source: string): BundledTheme {
70
70
  * to plain text.
71
71
  */
72
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
- }
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
85
  }
86
86
 
87
87
  let _theme: BundledTheme | undefined;
@@ -93,50 +93,50 @@ let _theme: BundledTheme | undefined;
93
93
  * take effect, and the result is cached (at most one warning per source).
94
94
  */
95
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;
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
110
  }
111
111
 
112
112
  const _cache = new Map<string, string[]>();
113
113
 
114
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;
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
123
  }
124
124
 
125
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
- }
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
140
  }
141
141
 
142
142
  const ESC_RE = "\u001b";
@@ -144,18 +144,18 @@ const ANSI_CAPTURE_RE = new RegExp(`${ESC_RE}\\[([0-9;]*)m`, "g");
144
144
  const FG_MUTED = "\x1b[38;2;139;148;158m";
145
145
 
146
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;
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
155
  }
156
156
 
157
157
  function normalizeShikiContrast(ansi: string): string {
158
- return ansi.replace(ANSI_CAPTURE_RE, (seq, params: string) => (isLowContrastShikiFg(params) ? FG_MUTED : seq));
158
+ return ansi.replace(ANSI_CAPTURE_RE, (seq, params: string) => (isLowContrastShikiFg(params) ? FG_MUTED : seq));
159
159
  }
160
160
 
161
161
  // ---------------------------------------------------------------------------
@@ -165,61 +165,61 @@ function normalizeShikiContrast(ansi: string): string {
165
165
  export const RESET_WITHOUT_BG = "\x1b[22;23;24;25;27;28;29;39m";
166
166
 
167
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
- });
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
201
  }
202
202
 
203
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");
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
218
  }
219
219
 
220
220
  /** Add exactly the missing terminal row after a rendered tool body. */
221
221
  export function fillToolBody(text: string, bg = BG_BASE, width?: number): string {
222
- return fillToolBackground(text.endsWith("\n") ? text : `${text}\n`, bg, width);
222
+ return fillToolBackground(text.endsWith("\n") ? text : `${text}\n`, bg, width);
223
223
  }
224
224
 
225
225
  const TOOL_TITLE_STATE_KEY = "__piPrettyToolTitle";
@@ -228,22 +228,22 @@ type ToolTitleState = { component: TextLike; render: ToolTitleRenderer };
228
228
 
229
229
  /** Keep a self-rendered tool's call title mutable while its result arrives. */
230
230
  export function rememberToolTitle(ctx: RenderContext, component: TextLike, render: ToolTitleRenderer): void {
231
- ctx.state[TOOL_TITLE_STATE_KEY] = { component, render } satisfies ToolTitleState;
231
+ ctx.state[TOOL_TITLE_STATE_KEY] = { component, render } satisfies ToolTitleState;
232
232
  }
233
233
 
234
234
  /** Move collapsed result metadata into the call title and hide the result slot. */
235
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;
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
242
  }
243
243
 
244
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}`;
245
+ const v = String(n);
246
+ return `${FG_LNUM}${" ".repeat(Math.max(0, w - v.length))}${v}${RST}`;
247
247
  }
248
248
 
249
249
  // ---------------------------------------------------------------------------
@@ -251,17 +251,17 @@ function lnum(n: number, w: number): string {
251
251
  // ---------------------------------------------------------------------------
252
252
 
253
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}`;
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
260
  }
261
261
 
262
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);
263
+ const details = result.details as Record<string, unknown> | undefined;
264
+ return formatElapsedMs(details?.[ELAPSED_KEY] as number | undefined);
265
265
  }
266
266
 
267
267
  // ---------------------------------------------------------------------------
@@ -269,10 +269,10 @@ export function renderToolDuration(result: AgentToolResult<Record<string, unknow
269
269
  // ---------------------------------------------------------------------------
270
270
 
271
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);
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
276
  }
277
277
 
278
278
  // ---------------------------------------------------------------------------
@@ -280,41 +280,25 @@ export function renderToolError(error: string, theme: ThemeLike): string {
280
280
  // ---------------------------------------------------------------------------
281
281
 
282
282
  export async function renderFileContent(
283
- content: string,
284
- filePath: string,
285
- offset = 0,
286
- maxLines = MAX_PREVIEW_LINES,
287
- width?: number,
283
+ content: string,
284
+ filePath: string,
285
+ offset = 0,
286
+ maxLines = MAX_PREVIEW_LINES,
287
+ width?: number,
288
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;
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");
318
302
  }
319
303
 
320
304
  // ---------------------------------------------------------------------------
@@ -322,29 +306,29 @@ export function renderBashOutput(text: string): string {
322
306
  // ---------------------------------------------------------------------------
323
307
 
324
308
  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");
309
+ const lines = text.trim().split("\n").filter(Boolean);
310
+ if (!lines.length) return `${FG_DIM}(empty directory)${RST}`;
311
+
312
+ const out: string[] = [];
313
+ const total = lines.length;
314
+ const show = lines.slice(0, MAX_PREVIEW_LINES);
315
+
316
+ for (let i = 0; i < show.length; i++) {
317
+ const entry = show[i].trim();
318
+ const isLast = i === show.length - 1 && total <= MAX_PREVIEW_LINES;
319
+ const prefix = isLast ? "└── " : "├── ";
320
+ const connector = `${FG_RULE}${prefix}${RST}`;
321
+ const isDir = entry.endsWith("/");
322
+ const name = isDir ? entry.slice(0, -1) : entry;
323
+ const icon = isDir ? dirIcon() : "";
324
+ out.push(`${connector}${icon}${isDir ? `${FG_BLUE}\x1b[1m${name}${RST}` : name}`);
325
+ }
326
+
327
+ if (total > MAX_PREVIEW_LINES) {
328
+ out.push(`${FG_RULE}└── ${RST}${FG_DIM}… ${total - MAX_PREVIEW_LINES} more entries${RST}`);
329
+ }
330
+
331
+ return out.join("\n");
348
332
  }
349
333
 
350
334
  // ---------------------------------------------------------------------------
@@ -352,40 +336,40 @@ export function renderTree(text: string, _basePath: string): string {
352
336
  // ---------------------------------------------------------------------------
353
337
 
354
338
  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");
339
+ const lines = text.trim().split("\n").filter(Boolean);
340
+ if (!lines.length) return theme ? theme.fg("dim", "(no matches)") : `${FG_DIM}(no matches)${RST}`;
341
+
342
+ const groups = new Map<string, string[]>();
343
+ for (const line of lines) {
344
+ const trimmed = line.trim();
345
+ const dir = dirname(trimmed) || ".";
346
+ const file = basename(trimmed);
347
+ if (!groups.has(dir)) groups.set(dir, []);
348
+ const bucket = groups.get(dir);
349
+ if (bucket) bucket.push(file);
350
+ }
351
+
352
+ const out: string[] = [];
353
+ let count = 0;
354
+
355
+ for (const [dir, files] of groups) {
356
+ if (count > 0) out.push("");
357
+ const dirColored = theme ? theme.fg("accent", theme.bold(`${dir}/`)) : `${FG_BLUE}\x1b[1m${dir}/${RST}`;
358
+ out.push(dirColored);
359
+ for (let i = 0; i < files.length; i++) {
360
+ if (count >= MAX_PREVIEW_LINES) {
361
+ const more = theme
362
+ ? theme.fg("dim", `… ${lines.length - count} more files`)
363
+ : `${FG_DIM}… ${lines.length - count} more files${RST}`;
364
+ out.push(`${TOOL_RESULT_INDENT}${more}`);
365
+ return out.join("\n");
366
+ }
367
+ out.push(`${TOOL_RESULT_INDENT}${files[i]}`);
368
+ count++;
369
+ }
370
+ }
371
+
372
+ return out.join("\n");
389
373
  }
390
374
 
391
375
  // ---------------------------------------------------------------------------
@@ -393,47 +377,47 @@ export function renderFindResults(text: string, theme?: ThemeLike): string {
393
377
  // ---------------------------------------------------------------------------
394
378
 
395
379
  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");
380
+ const lines = normalizeLineEndings(text).split("\n");
381
+ if (!lines.length || (lines.length === 1 && !lines[0].trim())) return `${FG_DIM}(no matches)${RST}`;
382
+
383
+ const out: string[] = [];
384
+ let currentFile = "";
385
+ let count = 0;
386
+
387
+ let re: RegExp | null = null;
388
+ try {
389
+ re = new RegExp(`(${pattern})`, "gi");
390
+ } catch {
391
+ /* skip highlighting */
392
+ }
393
+
394
+ for (const line of lines) {
395
+ if (count >= MAX_PREVIEW_LINES) {
396
+ out.push(`${FG_DIM} … more matches${RST}`);
397
+ break;
398
+ }
399
+ const fileMatch = line.match(/^(.+?)[:-](\d+)[:-](.*)$/);
400
+ if (fileMatch) {
401
+ const [, file, lineNo, content] = fileMatch;
402
+ if (file !== currentFile) {
403
+ if (currentFile) out.push("");
404
+ out.push(`${FG_BLUE}\x1b[1m${file}${RST}`);
405
+ currentFile = file;
406
+ }
407
+ const nw = Math.max(3, lineNo.length);
408
+ let display = content;
409
+ if (re) display = content.replace(re, `${RST}${FG_YELLOW}\x1b[1m$1${RST}`);
410
+ out.push(`${TOOL_RESULT_INDENT}${lnum(Number(lineNo), nw)} ${FG_RULE}│${RST} ${display}${RST}`);
411
+ count++;
412
+ } else if (line.trim() === "--") {
413
+ out.push(`${TOOL_RESULT_INDENT}${FG_DIM} ···${RST}`);
414
+ } else if (line.trim()) {
415
+ out.push(line);
416
+ count++;
417
+ }
418
+ }
419
+
420
+ return out.join("\n");
437
421
  }
438
422
 
439
423
  // ---------------------------------------------------------------------------
@@ -441,48 +425,48 @@ export async function renderGrepResults(text: string, pattern: string): Promise<
441
425
  // ---------------------------------------------------------------------------
442
426
 
443
427
  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
- };
428
+ return (args: Record<string, unknown>, theme: ThemeLike, ctx: RenderContext) => {
429
+ resolveBaseBackground(theme);
430
+ const text = ctx.lastComponent ?? new TuiText("", 0, 0);
431
+ const bg = ctx.isError ? BG_ERROR : undefined;
432
+ text.setText(fillToolBackground(`${theme.fg("toolTitle", theme.bold(toolName))}`, bg));
433
+ return text;
434
+ };
451
435
  }
452
436
 
453
437
  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
- };
438
+ return (result: AgentToolResult<Record<string, unknown>>, _opt: unknown, theme: ThemeLike, ctx: RenderContext) => {
439
+ resolveBaseBackground(theme);
440
+ const text = ctx.lastComponent ?? new TuiText("", 0, 0);
441
+ if (ctx.isError) {
442
+ text.setText(renderToolError(getTextContent(result) || "Error", theme));
443
+ return text;
444
+ }
445
+ const content = getTextContent(result);
446
+ if (content) {
447
+ const renderWidth = termWidth();
448
+ const lines = content.split("\n");
449
+ const maxShow = ctx.expanded ? lines.length : Math.min(lines.length, MAX_PREVIEW_LINES);
450
+ const preview = lines.slice(0, maxShow).join("\n");
451
+ const more = lines.length > maxShow ? `\n${FG_DIM}... ${lines.length - maxShow} more lines${RST}` : "";
452
+ const metrics = renderToolMetrics(result);
453
+ text.setText(
454
+ fillToolBody(
455
+ `${TOOL_RESULT_INDENT}${preview}${more}${metrics ? `\n${TOOL_RESULT_INDENT}${metrics}` : ""}`,
456
+ undefined,
457
+ renderWidth,
458
+ ),
459
+ );
460
+ } else {
461
+ text.setText(fillToolBody(`${TOOL_RESULT_INDENT}${theme.fg("dim", "(no text output)")}`));
462
+ }
463
+ return text;
464
+ };
481
465
  }
482
466
 
483
467
  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");
468
+ return (result.content ?? [])
469
+ .filter((c: any) => c.type === "text")
470
+ .map((c: any) => c.text ?? "")
471
+ .join("\n");
488
472
  }