@oh-my-pi/pi-tui 18.14.2 → 18.15.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.
Files changed (37) hide show
  1. package/CHANGELOG.md +29 -33
  2. package/README.md +1 -1
  3. package/dist/types/chat/transcript-render-helpers.d.ts +8 -0
  4. package/dist/types/chrome/transcript-status.d.ts +2 -2
  5. package/dist/types/overlays/hook-editor.d.ts +2 -0
  6. package/dist/types/overlays/jobs-panel.d.ts +4 -0
  7. package/dist/types/render/render-utils.d.ts +17 -0
  8. package/dist/types/terminal-capabilities.d.ts +1 -1
  9. package/dist/types/tools/grouped-file-output.d.ts +76 -8
  10. package/dist/types/tools/hashline-format.d.ts +5 -0
  11. package/dist/types/tools/native-view.d.ts +2 -0
  12. package/dist/types/tools/read.d.ts +10 -0
  13. package/dist/types/tools/wait.d.ts +2 -0
  14. package/package.json +9 -9
  15. package/src/chat/chat-transcript-builder.ts +4 -2
  16. package/src/chat/read-tool-group.ts +48 -21
  17. package/src/chat/transcript-render-helpers.ts +36 -2
  18. package/src/chrome/transcript-status.ts +5 -3
  19. package/src/overlays/hook-editor.ts +6 -0
  20. package/src/overlays/jobs-panel.ts +45 -19
  21. package/src/render/file-list.ts +4 -7
  22. package/src/render/render-utils.ts +31 -3
  23. package/src/terminal-capabilities.ts +5 -0
  24. package/src/tmux.ts +1 -0
  25. package/src/tools/ast-edit.ts +48 -93
  26. package/src/tools/ast-grep.ts +22 -66
  27. package/src/tools/edit.ts +11 -2
  28. package/src/tools/find.ts +6 -3
  29. package/src/tools/glob.ts +2 -1
  30. package/src/tools/grep.ts +43 -287
  31. package/src/tools/grouped-file-output.ts +250 -64
  32. package/src/tools/hashline-format.ts +5 -0
  33. package/src/tools/lsp.ts +15 -15
  34. package/src/tools/native-view.ts +11 -5
  35. package/src/tools/proc-render.ts +2 -2
  36. package/src/tools/read.ts +14 -0
  37. package/src/tools/wait.ts +6 -3
@@ -1,13 +1,21 @@
1
1
  import * as path from "node:path";
2
2
 
3
- import { buildPathTree, isUrlLikePath, type PathTreeInput, walkPathTree } from "@oh-my-pi/pi-utils";
3
+ import {
4
+ buildPathTree,
5
+ isRecord,
6
+ isUrlLikePath,
7
+ type PathTreeInput,
8
+ sanitizeText,
9
+ walkPathTree,
10
+ } from "@oh-my-pi/pi-utils";
4
11
  import type { TspTone } from "@oh-my-pi/pi-wire";
5
12
  import { code, col, keyed } from "../native/describe";
6
13
  import type { NativeNode } from "../native/node";
7
14
  import { getLanguageFromPath } from "../lang-from-path";
8
- import { replaceTabs } from "../render/render-utils";
15
+ import { fileHyperlink, uriHyperlink } from "../render/hyperlink";
16
+ import { FILE_NAME_COLOR, formatMoreItems, formatStyledPath, replaceTabs } from "../render/render-utils";
9
17
  import { highlightCode, isHighlightLanguage, type Theme, type ThemeColor } from "../theme/theme";
10
- import { formatHashlineHeader } from "./hashline-format";
18
+ import { formatHashlineHeader, HASHLINE_TAG_SUFFIX_RE } from "./hashline-format";
11
19
  import { fileRow } from "./native-view";
12
20
 
13
21
  // =============================================================================
@@ -151,20 +159,37 @@ export function formatFileMatches(
151
159
 
152
160
  const GROUPED_HEADER_RE = /^(#+)\s+(.*)$/;
153
161
  const HEADER_SUFFIX_RE = /\s+\([^)]*\)\s*$/;
154
- const HEADER_HASH_TAG_RE = /#[0-9a-f]+$/i;
162
+ /** `*12│text`, ` 12|text`, `*12:text`: optional match marker, line number, gutter, content. */
163
+ const GROUPED_NUMBERED_LINE_RE = /^\s*(\*?)(\d+)(?:│|[:|])(.*)$/;
164
+ const GROUPED_MATCH_ROW_RE = /^\s*\*\d+(?:│|[:|])/;
165
+
166
+ /** Whether a row of grouped output is a code-frame row the search matched (`*12│…`). */
167
+ export function isMatchRow(line: string): boolean {
168
+ return GROUPED_MATCH_ROW_RE.test(line);
169
+ }
155
170
 
156
- /** Per-line classification of grouped output, used by renderers for hyperlinks. */
171
+ /** Per-line classification of grouped output, used by renderers for file rows and hyperlinks. */
157
172
  export interface GroupedLineContext {
158
173
  /** Directory header, file header, or any non-header body/content line. */
159
174
  kind: "dir" | "file" | "content";
160
175
  /** Number of leading `#` for headers; 0 for content lines. */
161
176
  depth: number;
162
- /** Resolved absolute path of the dir/file a header points at (when resolvable). */
177
+ /** Resolved absolute path of the file a header points at (when resolvable). */
163
178
  headerPath?: string;
179
+ /**
180
+ * For file headers, the full display path: the folded directory chain joined
181
+ * with the name, without `#` markers or the hashline tag.
182
+ */
183
+ displayPath?: string;
184
+ /** For file headers, a trailing parenthesized note such as `(2 replacements)`. */
185
+ suffix?: string;
164
186
  /** For content lines, the absolute path of the owning file (line hyperlinks). */
165
187
  filePath?: string;
166
- /** Header is an internal/url-like target the caller resolves itself. */
167
- isUrl?: boolean;
188
+ /**
189
+ * The internal or url-like target, as written, that a header names or a
190
+ * content line belongs to; the caller resolves it (no filesystem path).
191
+ */
192
+ url?: string;
168
193
  }
169
194
 
170
195
  function resolveGroupedPath(parent: string | undefined, name: string): string | undefined {
@@ -177,7 +202,8 @@ function resolveGroupedPath(parent: string | undefined, name: string): string |
177
202
 
178
203
  /**
179
204
  * Walk grouped output lines, tracking a directory stack keyed by header depth, so
180
- * each header and body line can be linked back to its absolute filesystem path.
205
+ * each header and body line can be linked back to its absolute filesystem path
206
+ * and each file header to its full display path.
181
207
  * Reconstruction is stack-based (not per-blank-group) so nested directory headers
182
208
  * resolve correctly across the whole output.
183
209
  *
@@ -186,7 +212,9 @@ function resolveGroupedPath(parent: string | undefined, name: string): string |
186
212
  * formatted relative to cwd regardless of the (sub)directory the search was
187
213
  * scoped to. `fileScope` is the initial owning file for body lines that appear
188
214
  * before any header (single-file scopes have no `#` headers); it defaults to
189
- * `headerBase` and should be passed the scoped file's absolute path.
215
+ * `headerBase` and should be passed the scoped file's absolute path. A URL base
216
+ * or scope (`local://…`) is no filesystem path: headerless lines belong to the
217
+ * URL, and headers under a URL base get no path.
190
218
  */
191
219
  export function classifyGroupedLines(
192
220
  lines: readonly string[],
@@ -194,49 +222,224 @@ export function classifyGroupedLines(
194
222
  fileScope: string | undefined = headerBase,
195
223
  ): GroupedLineContext[] {
196
224
  const result: GroupedLineContext[] = [];
197
- const dirAtDepth = new Map<number, string>();
198
- // Body lines before any header (single-file scopes) link to the scoped file.
199
- let currentFile = fileScope;
200
-
201
- const clearDeeper = (depth: number) => {
202
- for (const key of dirAtDepth.keys()) {
203
- if (key >= depth) dirAtDepth.delete(key);
204
- }
205
- };
225
+ const base = headerBase !== undefined && isUrlLikePath(headerBase) ? undefined : headerBase;
226
+ // Per depth (index `depth - 1`): each directory's absolute path, and its display
227
+ // name with the trailing `/`, so the `# /` root of absolute paths keeps its separator.
228
+ const dirAtDepth: (string | undefined)[] = [];
229
+ const displayDirAtDepth: string[] = [];
230
+ // Body lines before any header (single-file scopes) belong to the scoped file or URL.
231
+ const scopeIsUrl = fileScope !== undefined && isUrlLikePath(fileScope);
232
+ let currentFile = scopeIsUrl ? undefined : fileScope;
233
+ let currentUrl = scopeIsUrl ? fileScope : undefined;
206
234
 
207
235
  for (const line of lines) {
208
236
  const match = GROUPED_HEADER_RE.exec(line);
209
237
  if (!match) {
210
- result.push({ kind: "content", depth: 0, filePath: currentFile });
238
+ result.push({ kind: "content", depth: 0, filePath: currentFile, url: currentUrl });
211
239
  continue;
212
240
  }
213
241
  const depth = match[1]!.length;
214
242
  const rest = match[2]!.trimEnd();
215
- if (isUrlLikePath(rest)) {
216
- clearDeeper(depth);
217
- currentFile = undefined;
218
- result.push({ kind: "file", depth, isUrl: true });
243
+ const parent = depth > 1 ? dirAtDepth[depth - 2] : base;
244
+ const url = isUrlLikePath(rest);
245
+ dirAtDepth.length = displayDirAtDepth.length = depth - 1;
246
+ currentFile = currentUrl = undefined;
247
+ if (!url && rest.endsWith("/")) {
248
+ // Directory headers are always `name/`: a trailing `(…)` is part of the name, not a suffix.
249
+ const name = rest.slice(0, -1);
250
+ dirAtDepth.push(resolveGroupedPath(parent, name));
251
+ displayDirAtDepth.push(`${name}/`);
252
+ result.push({ kind: "dir", depth });
219
253
  continue;
220
254
  }
221
- const parent = depth > 1 ? dirAtDepth.get(depth - 1) : headerBase;
222
- if (rest.endsWith("/")) {
223
- const name = rest.slice(0, -1).replace(HEADER_SUFFIX_RE, "");
224
- const abs = resolveGroupedPath(parent, name);
225
- clearDeeper(depth);
226
- if (abs !== undefined) dirAtDepth.set(depth, abs);
227
- currentFile = undefined;
228
- result.push({ kind: "dir", depth, headerPath: abs });
255
+ const suffix = HEADER_SUFFIX_RE.exec(rest);
256
+ const target = suffix ? rest.slice(0, suffix.index) : rest;
257
+ const name = target.replace(HASHLINE_TAG_SUFFIX_RE, "");
258
+ const note = suffix?.[0].trim();
259
+ if (url) {
260
+ currentUrl = target;
261
+ result.push({ kind: "file", depth, url: target, displayPath: name, suffix: note });
229
262
  continue;
230
263
  }
231
- const name = rest.replace(HEADER_SUFFIX_RE, "").replace(HEADER_HASH_TAG_RE, "");
232
- const abs = name ? resolveGroupedPath(parent, name) : undefined;
233
- currentFile = abs;
234
- result.push({ kind: "file", depth, headerPath: abs });
264
+ currentFile = name ? resolveGroupedPath(parent, name) : undefined;
265
+ const displayPath = displayDirAtDepth.join("") + name;
266
+ result.push({ kind: "file", depth, headerPath: currentFile, displayPath, suffix: note });
235
267
  }
236
268
 
237
269
  return result;
238
270
  }
239
271
 
272
+ /**
273
+ * Line groups with one file per group, for terminal tree lists: `# dir/`
274
+ * header rows are dropped (each file row carries its full path), and every
275
+ * file row starts a group of its own, so each file gets its own branch instead
276
+ * of hanging under the previous file of its directory. Rows before a group's
277
+ * first file row (notes, a single-file scope's matches) keep their group.
278
+ */
279
+ export function groupsByFile(
280
+ groups: readonly (readonly number[])[],
281
+ contexts: readonly GroupedLineContext[],
282
+ ): number[][] {
283
+ const result: number[][] = [];
284
+ for (const group of groups) {
285
+ let current: number[] = [];
286
+ for (const index of group) {
287
+ const kind = contexts[index]!.kind;
288
+ if (kind === "dir") continue;
289
+ if (kind === "file" && current.length > 0) {
290
+ result.push(current);
291
+ current = [];
292
+ }
293
+ current.push(index);
294
+ }
295
+ if (current.length > 0) result.push(current);
296
+ }
297
+ return result;
298
+ }
299
+
300
+ function stringField(record: Record<string, unknown>, key: string): string | undefined {
301
+ const value = record[key];
302
+ return typeof value === "string" ? value : undefined;
303
+ }
304
+
305
+ function stringRecordField(record: Record<string, unknown>, key: string): Record<string, string> | undefined {
306
+ const value = record[key];
307
+ if (!isRecord(value)) return undefined;
308
+ for (const entry in value) if (typeof value[entry] !== "string") return undefined;
309
+ return value as Record<string, string>;
310
+ }
311
+
312
+ /** Details fields a grouped-output tool records for links: the display base paths and resolved URL targets. */
313
+ export interface GroupedLinkDetails {
314
+ cwd?: string;
315
+ searchPath?: string;
316
+ displayTargets?: Record<string, string>;
317
+ }
318
+
319
+ /**
320
+ * Link targets for the rows of sanitized grouped output: a file row's file, a
321
+ * body row's owning file, and for an internal URL the file `displayTargets`
322
+ * resolves it to. Destinations keep the original path bytes: while the raw
323
+ * `displayContent` still aligns line-for-line with the sanitized `displayText`,
324
+ * a row takes its raw classification's target. Raw text never links a row the
325
+ * sanitized output leaves unlinked.
326
+ */
327
+ export function groupedLinkTargets(
328
+ contexts: readonly GroupedLineContext[],
329
+ displayText: string,
330
+ details: GroupedLinkDetails | undefined,
331
+ rawDetails: unknown,
332
+ ): (index: number) => string | undefined {
333
+ const targetOf = (ctx: GroupedLineContext, urlTargets: Record<string, string> | undefined) =>
334
+ (ctx.kind === "file" ? ctx.headerPath : ctx.filePath) ?? (ctx.url ? urlTargets?.[ctx.url] : undefined);
335
+ // Detail sanitization keeps record keys raw; the display rows carry sanitized URLs.
336
+ const displayTargets = details?.displayTargets
337
+ ? Object.fromEntries(Object.entries(details.displayTargets).map(([url, file]) => [sanitizeText(url), file]))
338
+ : undefined;
339
+ const raw = rawDetails !== details && isRecord(rawDetails) ? rawDetails : undefined;
340
+ const rawContent = raw && stringField(raw, "displayContent");
341
+ const rawLines = rawContent?.split("\n");
342
+ const rawContexts =
343
+ raw && rawLines?.length === contexts.length && sanitizeText(rawContent!) === displayText
344
+ ? classifyGroupedLines(
345
+ rawLines,
346
+ stringField(raw, "cwd") ?? stringField(raw, "searchPath"),
347
+ stringField(raw, "searchPath"),
348
+ )
349
+ : undefined;
350
+ const rawTargets = raw && stringRecordField(raw, "displayTargets");
351
+ return index => {
352
+ const ctx = contexts[index]!;
353
+ const target = targetOf(ctx, displayTargets);
354
+ const rawContext = rawContexts?.[index];
355
+ if (!target || rawContext?.kind !== ctx.kind || rawContext.depth !== ctx.depth) return target;
356
+ return targetOf(rawContext, rawTargets) ?? target;
357
+ };
358
+ }
359
+
360
+ /**
361
+ * A memoized styler for the rows of grouped output, so a collapsed preview
362
+ * styles only the rows it shows. A file row is its full path (dim directory,
363
+ * name in {@link FILE_NAME_COLOR}; a URL whole in that color) and any dim
364
+ * suffix, linked to `linkTarget`'s file or, for an unresolved URL, the URL.
365
+ * Body rows come from `styleBody`, tabs expanded; with `linkLines` a numbered
366
+ * code-frame row links to its line in the owning file.
367
+ */
368
+ export function createGroupedRowStyler(
369
+ lines: readonly string[],
370
+ contexts: readonly GroupedLineContext[],
371
+ theme: Theme,
372
+ options: {
373
+ linkTarget: (index: number) => string | undefined;
374
+ styleBody: (index: number) => string;
375
+ linkLines?: boolean;
376
+ },
377
+ ): (index: number) => string {
378
+ const styled: string[] = [];
379
+ return index => {
380
+ const cached = styled[index];
381
+ if (cached !== undefined) return cached;
382
+ const ctx = contexts[index]!;
383
+ const target = options.linkTarget(index);
384
+ let row: string;
385
+ if (ctx.kind === "file") {
386
+ const name = replaceTabs(ctx.displayPath ?? "");
387
+ const label = ctx.url ? theme.fg(FILE_NAME_COLOR, name) : formatStyledPath(name, theme);
388
+ const suffix = ctx.suffix ? ` ${theme.fg("dim", replaceTabs(ctx.suffix))}` : "";
389
+ const linked = target ? fileHyperlink(target, label) : ctx.url ? uriHyperlink(ctx.url, label) : label;
390
+ row = linked + suffix;
391
+ } else {
392
+ row = replaceTabs(options.styleBody(index));
393
+ const line = options.linkLines && target ? GROUPED_NUMBERED_LINE_RE.exec(lines[index]!)?.[2] : undefined;
394
+ if (line) row = fileHyperlink(target!, row, { line: Number(line) });
395
+ }
396
+ styled[index] = row;
397
+ return row;
398
+ };
399
+ }
400
+
401
+ /**
402
+ * Fit line groups (one file each) into `budget` rows, the `… N more` summary row
403
+ * included: whole groups first, then the next group cut short when it can still
404
+ * show a row under its file row (the first group always shows its head). The
405
+ * summary counts the `unit`s left out, the rows `isUnit` accepts, out of `total`
406
+ * when the caller knows it; with none left out it counts hidden lines. `gap`
407
+ * rows separate shown groups (framed lists put a blank line between files).
408
+ */
409
+ export function fitGroupsToBudget(
410
+ groups: readonly (readonly number[])[],
411
+ budget: number,
412
+ options: { isUnit: (index: number) => boolean; unit: string; total?: number; gap?: number },
413
+ ): { shown: (readonly number[])[]; summary: string } {
414
+ const gap = options.gap ?? 0;
415
+ let totalLines = Math.max(groups.length - 1, 0) * gap;
416
+ for (const group of groups) totalLines += group.length;
417
+ if (totalLines <= budget) return { shown: [...groups], summary: "" };
418
+ if (budget <= 0) return { shown: [], summary: "" };
419
+
420
+ const room = budget - 1;
421
+ const shown: (readonly number[])[] = [];
422
+ let used = 0;
423
+ let shownUnits = 0;
424
+ for (const group of groups) {
425
+ const lead = shown.length > 0 ? gap : 0;
426
+ const take = Math.min(group.length, room - used - lead);
427
+ if (take <= 0 || (take < Math.min(group.length, 2) && shown.length > 0)) break;
428
+ const part = take === group.length ? group : group.slice(0, take);
429
+ shown.push(part);
430
+ used += lead + take;
431
+ for (const index of part) if (options.isUnit(index)) shownUnits++;
432
+ if (part !== group) break;
433
+ }
434
+
435
+ let allUnits = options.total ?? 0;
436
+ if (!allUnits) for (const group of groups) for (const index of group) if (options.isUnit(index)) allUnits++;
437
+ const hiddenUnits = allUnits - shownUnits;
438
+ if (hiddenUnits > 0) return { shown, summary: formatMoreItems(hiddenUnits, options.unit) };
439
+ const hiddenLines = totalLines - used;
440
+ return { shown, summary: hiddenLines > 0 ? formatMoreItems(hiddenLines, "line") : "" };
441
+ }
442
+
240
443
  /**
241
444
  * Split line indices into blank-line-separated groups, mirroring
242
445
  * `splitGroupsByBlankLine`: when any blank line is present, break on runs of
@@ -312,12 +515,6 @@ function parseNumberedCodeFrame(line: string): NumberedCodeFrame | undefined {
312
515
  return { row: { gutter: line.slice(0, line.length - source.length), source }, n: Number(match[2]) };
313
516
  }
314
517
 
315
- /** The file a grouped file header names, without its suffix and hashline tag: `## a.ts#3f2a (2)` → `a.ts`. */
316
- function groupedHeaderName(line: string): string {
317
- const rest = GROUPED_HEADER_RE.exec(line)?.[2]?.trimEnd() ?? "";
318
- return rest.replace(HEADER_SUFFIX_RE, "").replace(HEADER_HASH_TAG_RE, "");
319
- }
320
-
321
518
  /**
322
519
  * Source rows highlighted together. A run longer than this (a huge AST match) highlights chunk by chunk as rows
323
520
  * are requested, so a collapsed view never tokenizes source it hides; a string or comment spanning a chunk
@@ -350,7 +547,7 @@ export function createCodeFrameStyler(
350
547
  langs.push(langOverride ?? (ctx.filePath ? getLanguageFromPath(ctx.filePath) : headerLang));
351
548
  continue;
352
549
  }
353
- headerLang = ctx.kind === "file" ? getLanguageFromPath(groupedHeaderName(lines[index]!)) : undefined;
550
+ headerLang = ctx.kind === "file" ? getLanguageFromPath(ctx.displayPath ?? "") : undefined;
354
551
  langs.push(undefined);
355
552
  }
356
553
 
@@ -410,34 +607,23 @@ export type GroupedOutputEvent =
410
607
 
411
608
  /**
412
609
  * Walk grouped output (`# dir/`, `## file.ts (suffix)`, body lines), resolving
413
- * each file header to its full display path (the folded directory chain
414
- * joined with the name) and dropping blank separator lines.
610
+ * each file header to its full display path (see {@link classifyGroupedLines})
611
+ * and dropping blank separator lines.
415
612
  */
416
613
  export function* walkGroupedOutput(lines: readonly string[]): Generator<GroupedOutputEvent> {
417
- const dirAtDepth: string[] = [];
418
- for (const line of lines) {
419
- const header = GROUPED_HEADER_RE.exec(line);
420
- if (!header) {
421
- if (line.trim().length > 0) yield { kind: "line", text: line };
422
- continue;
423
- }
424
- const depth = header[1]!.length;
425
- const rest = header[2]!.trimEnd();
426
- dirAtDepth.length = depth - 1;
427
- if (rest.endsWith("/") && !isUrlLikePath(rest)) {
428
- dirAtDepth[depth - 1] = rest.slice(0, -1).replace(HEADER_SUFFIX_RE, "");
614
+ const contexts = classifyGroupedLines(lines, undefined);
615
+ for (const [index, ctx] of contexts.entries()) {
616
+ if (ctx.kind === "dir") {
429
617
  yield { kind: "dir" };
430
- continue;
618
+ } else if (ctx.kind === "file") {
619
+ yield { kind: "file", path: ctx.displayPath ?? "", suffix: ctx.suffix };
620
+ } else {
621
+ const text = lines[index]!;
622
+ if (text.trim().length > 0) yield { kind: "line", text };
431
623
  }
432
- const suffix = HEADER_SUFFIX_RE.exec(rest)?.[0].trim();
433
- const name = rest.replace(HEADER_SUFFIX_RE, "").replace(HEADER_HASH_TAG_RE, "");
434
- const prefix = dirAtDepth.filter(Boolean).join("/");
435
- yield { kind: "file", path: prefix ? `${prefix}/${name}` : name, suffix };
436
624
  }
437
625
  }
438
626
 
439
- /** `*12│text`, ` 12|text`, `*12:text`: optional match marker, line number, gutter, content. */
440
- const GROUPED_NUMBERED_LINE_RE = /^\s*(\*?)(\d+)(?:│|[:|])(.*)$/;
441
627
  /** ` │...`: grep's gap between non-adjacent context runs (Tern draws it from the jump in {@link numberedCode}'s numbers). */
442
628
  const GROUPED_GAP_LINE_RE = /^\s*│\.\.\.$/;
443
629
 
@@ -14,6 +14,11 @@ export const HL_FILE_SUFFIX = "]";
14
14
  export const HL_FILE_HASH_SEP = "#";
15
15
  /** Number of characters in a displayed file hash. */
16
16
  export const HL_FILE_HASH_LENGTH = 4;
17
+ /**
18
+ * A trailing `#TAG` file hash exactly as the hashline store writes it (uppercase
19
+ * hex), so a name's own `#dead` or `#v2` ending survives stripping.
20
+ */
21
+ export const HASHLINE_TAG_SUFFIX_RE = new RegExp(`${HL_FILE_HASH_SEP}[0-9A-F]{${HL_FILE_HASH_LENGTH}}$`);
17
22
  /** Keyword identifying a file move operation. */
18
23
  export const HL_MOVE_KEYWORD = "MV";
19
24
  /** Keyword identifying a file removal operation. */
package/src/tools/lsp.ts CHANGED
@@ -19,6 +19,7 @@ import {
19
19
  formatExpandHint,
20
20
  formatMoreItems,
21
21
  formatStatusIcon,
22
+ formatStyledPath,
22
23
  PREVIEW_LIMITS,
23
24
  type ParsedDiagnostic,
24
25
  parseDiagnosticMessage,
@@ -205,7 +206,7 @@ export function renderResult(
205
206
  const request = args ?? result.details?.request;
206
207
  const requestLines: string[] = [];
207
208
  if (request?.file) {
208
- requestLines.push(theme.fg("toolOutput", request.file));
209
+ requestLines.push(formatStyledPath(request.file, theme));
209
210
  }
210
211
  if (request?.line !== undefined) {
211
212
  requestLines.push(theme.fg("dim", `line ${request.line}`));
@@ -386,10 +387,16 @@ function renderHover(
386
387
  // Diagnostics Rendering
387
388
  // =============================================================================
388
389
 
390
+ /** A diagnostic's location: the muted file-type icon, the styled path and the muted `:line:col`. */
389
391
  function formatDiagnosticLocation(file: string, line: number, col: number, theme: Theme): string {
390
392
  const lang = getLanguageFromPath(file);
391
393
  const icon = theme.fg("muted", theme.getLangIcon(lang));
392
- return `${icon} ${file}:${line}:${col}`;
394
+ return `${icon} ${formatStyledPath(file, theme)}${theme.fg("muted", `:${line}:${col}`)}`;
395
+ }
396
+
397
+ /** The `[severity]` tag in its severity's color: the path no longer carries it. */
398
+ function formatSeverityTag(severity: ParsedDiagnostic["severity"], theme: Theme): string {
399
+ return theme.fg(severityToColor(severity), `[${severity}]`);
393
400
  }
394
401
 
395
402
  /**
@@ -443,12 +450,8 @@ function renderDiagnostics(
443
450
  output += `\n ${theme.fg("dim", branch)} ${theme.fg("muted", item.raw)}`;
444
451
  continue;
445
452
  }
446
- const severityColor = severityToColor(item.severity);
447
453
  const location = formatDiagnosticLocation(item.filePath, item.line, item.col, theme);
448
- output += `\n ${theme.fg("dim", branch)} ${theme.fg(severityColor, location)} ${theme.fg(
449
- "dim",
450
- `[${item.severity}]`,
451
- )}`;
454
+ output += `\n ${theme.fg("dim", branch)} ${location} ${formatSeverityTag(item.severity, theme)}`;
452
455
  const message = formatDiagnosticMessage(item);
453
456
  if (message) {
454
457
  output += `\n ${theme.fg("dim", detailPrefix)}${theme.fg("muted", message)}`;
@@ -473,13 +476,12 @@ function renderDiagnostics(
473
476
  output += `\n ${theme.fg("dim", branch)} ${theme.fg("muted", item.raw)}`;
474
477
  continue;
475
478
  }
476
- const severityColor = severityToColor(item.severity);
477
479
  const location = formatDiagnosticLocation(item.filePath, item.line, item.col, theme);
478
480
  const diagnosticMessage = formatDiagnosticMessage(item);
479
481
  const message = diagnosticMessage
480
482
  ? ` ${theme.fg("muted", truncateToWidth(diagnosticMessage, TRUNCATE_LENGTHS.CONTENT))}`
481
483
  : "";
482
- output += `\n ${theme.fg("dim", branch)} ${theme.fg(severityColor, location)}${message}`;
484
+ output += `\n ${theme.fg("dim", branch)} ${location} ${formatSeverityTag(item.severity, theme)}${message}`;
483
485
  }
484
486
  if (remaining > 0) {
485
487
  output += `\n ${theme.fg("dim", theme.tree.last)} ${theme.fg("muted", `… ${remaining} more`)}`;
@@ -529,7 +531,7 @@ function renderReferences(refMatch: RegExpMatchArray, lines: string[], expanded:
529
531
  const fileCont = isLastFile ? " " : `${theme.tree.vertical} `;
530
532
 
531
533
  const fileMeta = `${locs.length} reference${locs.length !== 1 ? "s" : ""}`;
532
- output += `\n ${theme.fg("dim", fileBranch)} ${theme.fg("accent", file)} ${theme.fg("dim", fileMeta)}`;
534
+ output += `\n ${theme.fg("dim", fileBranch)} ${formatStyledPath(file, theme)} ${theme.fg("dim", fileMeta)}`;
533
535
 
534
536
  if (maxLocsPerFile > 0) {
535
537
  const locsToShow = locs.slice(0, maxLocsPerFile);
@@ -543,10 +545,8 @@ function renderReferences(refMatch: RegExpMatchArray, lines: string[], expanded:
543
545
  `line ${line}, col ${col}`,
544
546
  )}`;
545
547
  if (expanded) {
546
- output += `\n ${theme.fg("dim", fileCont)}${theme.fg("dim", locCont)}${theme.fg(
547
- "muted",
548
- `at ${file}:${line}:${col}`,
549
- )}`;
548
+ const at = `${theme.fg("muted", "at ")}${formatStyledPath(file, theme)}${theme.fg("muted", `:${line}:${col}`)}`;
549
+ output += `\n ${theme.fg("dim", fileCont)}${theme.fg("dim", locCont)}${at}`;
550
550
  }
551
551
  }
552
552
  if (locs.length > maxLocsPerFile) {
@@ -645,7 +645,7 @@ function renderLocations(parsed: LspLocations, expanded: boolean, theme: Theme):
645
645
  const branch = isLast ? theme.tree.last : theme.tree.branch;
646
646
  const rail = isLast ? " " : `${theme.tree.vertical} `;
647
647
  const position = theme.fg("muted", `:${location.line}:${location.col}`);
648
- const file = theme.fg("accent", replaceTabs(shortenPath(location.file)));
648
+ const file = formatStyledPath(replaceTabs(shortenPath(location.file)), theme);
649
649
  rows.push(` ${theme.fg("dim", branch)} ${file}${position}`);
650
650
 
651
651
  const numberWidth = location.context.reduce((width, line) => Math.max(width, String(line.n).length), 0);
@@ -8,7 +8,7 @@ import type { TspSpan, TspText, TspTone } from "@oh-my-pi/pi-wire";
8
8
  import { ansi, code, compact, keyed, node, row, span, text } from "../native/describe";
9
9
  import type { NativeChild, NativeNode } from "../native/node";
10
10
  import { tryFileUri } from "../render/hyperlink";
11
- import { type ParsedDiagnostic, parseDiagnosticMessage, shortenPath } from "../render/render-utils";
11
+ import { type ParsedDiagnostic, parseDiagnosticMessage, pathNameStart, shortenPath } from "../render/render-utils";
12
12
  import { plainText } from "../native/spans";
13
13
  import type { FileDiagnosticsResult } from "./lsp";
14
14
  import { formatArtifactErrorNotice, formatTruncationMetaNotice, type OutputMeta } from "./output-meta";
@@ -28,6 +28,13 @@ export function fileHref(filePath: string | undefined): string | undefined {
28
28
  return filePath && path.isAbsolute(filePath) ? tryFileUri(filePath) : undefined;
29
29
  }
30
30
 
31
+ /** Link for a head target that is a web URL (`www.` gains `https://`), else undefined. */
32
+ export function urlHref(target: string | undefined): string | undefined {
33
+ if (!target) return undefined;
34
+ const candidate = /^www\./i.test(target) ? `https://${target}` : target;
35
+ return /^https?:\/\/\S+$/i.test(candidate) ? candidate : undefined;
36
+ }
37
+
31
38
  /** Diff stats as one head `meta` string, `+8 −1` (U+2212 minus), or undefined when nothing changed. */
32
39
  export function diffStatsMeta(added: number, removed: number): string | undefined {
33
40
  const parts: string[] = [];
@@ -74,11 +81,10 @@ export function fileRow(
74
81
  } = {},
75
82
  ): NativeNode {
76
83
  const isDir = filePath.endsWith("/");
77
- const bare = isDir ? filePath.slice(0, -1) : filePath;
78
- const cut = bare.lastIndexOf("/") + 1;
84
+ const cut = pathNameStart(filePath);
79
85
  const spans: TspSpan[] = [];
80
- if (cut > 0) spans.push(span(bare.slice(0, cut), "dim"));
81
- spans.push(span(`${bare.slice(cut) || "…"}${isDir ? "/" : ""}`, "strong", p.href ? { href: p.href } : undefined));
86
+ if (cut > 0) spans.push(span(filePath.slice(0, cut), "dim"));
87
+ spans.push(span(filePath.slice(cut) || "…", "strong", p.href ? { href: p.href } : undefined));
82
88
  if (p.range) spans.push(span(p.range, "muted"));
83
89
  const children: NativeChild[] = [
84
90
  p.lead ?? node("icon", { name: p.icon ?? (isDir ? "folder" : "file"), tone: p.tone }),
@@ -141,7 +141,7 @@ function jobRow(job: JobSnapshot, theme: Theme): string {
141
141
  : "done",
142
142
  theme,
143
143
  );
144
- return `${icon} ${formatBadge(job.type, job.status === "failed" ? "error" : job.status === "cancelled" ? "warning" : "accent", theme)} ${theme.fg("toolOutput", safe(job.id))} ${theme.fg("dim", safe(job.label))} ${theme.fg("dim", formatDuration(job.durationMs))}`;
144
+ return `${icon} ${formatBadge(job.type, job.status === "failed" ? "error" : job.status === "cancelled" ? "warning" : "accent", theme)} ${theme.fg("toolOutput", safe(job.id))} ${theme.fg("dim", safe(job.intent || job.label))} ${theme.fg("dim", formatDuration(job.durationMs))}`;
145
145
  }
146
146
 
147
147
  /** Render live and completed process writes with the URL-selected operation. */
@@ -303,7 +303,7 @@ function jobItem(job: JobSnapshot, badge?: { text: string; tone: TspTone }): Nat
303
303
  "item",
304
304
  {
305
305
  label: [span(job.type, "accent"), span(" "), span(safe(job.id), "toolOutput")],
306
- detail: [span(safe(job.label), "muted")],
306
+ detail: [span(safe(job.intent || job.label), "muted")],
307
307
  value: badge ? [span(badge.text, badge.tone)] : [span(formatDuration(job.durationMs), "muted")],
308
308
  tone: badge?.tone ?? jobTone(job.status),
309
309
  },
package/src/tools/read.ts CHANGED
@@ -242,6 +242,20 @@ export function splitInternalUrlSel(
242
242
  return { path, sel: chunks.join(":") };
243
243
  }
244
244
 
245
+ /** A read query after a filesystem path: `?key=` (`?q=…`, `?limit=…&where=…`), not a `\\?\` long-path prefix. */
246
+ const READ_QUERY_RE = /(?<!^\\\\)\?\w+=/;
247
+
248
+ /**
249
+ * Split a filesystem read target from its query (`data.json?q=.items` →
250
+ * `data.json`, `?q=.items`), the display twin of the read tool's JSON, SQLite
251
+ * and image-question parsers. URLs own their query string and stay whole, as
252
+ * does a `?` inside a file name.
253
+ */
254
+ export function splitReadQuery(readPath: string): { path: string; query?: string } {
255
+ const at = splitUrlScheme(readPath) ? -1 : readPath.search(READ_QUERY_RE);
256
+ return at > 0 ? { path: readPath.slice(0, at), query: readPath.slice(at) } : { path: readPath };
257
+ }
258
+
245
259
  /** Recognize HTTP URLs and www-prefixed external read targets. */
246
260
  export function isReadableUrlPath(value: string): boolean {
247
261
  return /^https?:\/\/?/i.test(value) || /^www\./i.test(value);
package/src/tools/wait.ts CHANGED
@@ -51,6 +51,8 @@ export interface JobSnapshot {
51
51
  type: "bash" | "task" | "eval";
52
52
  status: "running" | "completed" | "failed" | "cancelled";
53
53
  label: string;
54
+ /** What the job is for, in the model's words (a process job's `label` is its command line). */
55
+ intent?: string;
54
56
  durationMs: number;
55
57
  /** Process exit status when the job reports one. */
56
58
  exitCode?: number;
@@ -213,9 +215,10 @@ function flattenStructuredPreview(text: string): string {
213
215
  return text.slice(0, PREVIEW_LINES_EXPANDED * PREVIEW_LINE_WIDTH * 2).replace(/\s+/g, " ");
214
216
  }
215
217
 
216
- /** The row label: a running task's own stage line when it reports one, else the job's label. */
218
+ /** The row label: a running task's own stage line when it reports one, else what the job is for, else its label. */
217
219
  function jobRowLabel(job: JobSnapshot): string {
218
- return job.type === "task" && job.status === "running" && job.stage?.trim() ? job.stage : job.label;
220
+ if (job.type === "task" && job.status === "running" && job.stage?.trim()) return job.stage;
221
+ return job.intent || job.label;
219
222
  }
220
223
 
221
224
  /** A job as its tile; `live` while the card's clocks run. */
@@ -224,7 +227,7 @@ function jobTile(job: JobSnapshot, live: boolean): JobTile {
224
227
  id: job.id,
225
228
  type: job.type,
226
229
  status: job.status,
227
- label: job.label,
230
+ label: job.intent || job.label,
228
231
  durationMs: job.durationMs,
229
232
  live: live && job.status === "running",
230
233
  ...(job.widget ? { widget: job.widget } : {}),