import * as os from "node:os"; import { pathToFileURL } from "node:url"; import type { ImageContent, TextContent } from "@earendil-works/pi-ai"; import { getCapabilities, hyperlink } from "@earendil-works/pi-tui"; import { Theme } from "@earendil-works/pi-coding-agent"; import { resolvePath } from "./paths.ts"; export function shortenPath(path: unknown): string { if (typeof path !== "string") return ""; const home = os.homedir(); if (path.startsWith(home)) { return `~${path.slice(home.length)}`; } return path; } export function linkPath(styledText: string, rawPath: string, cwd: string): string { if (!getCapabilities().hyperlinks) return styledText; const absolutePath = resolvePath(rawPath, cwd); return hyperlink(styledText, pathToFileURL(absolutePath).href); } export function str(value: unknown): string | null { if (typeof value === "string") return value; if (value == null) return ""; return null; } export function replaceTabs(text: string): string { return text.replace(/\t/g, " "); } export function normalizeDisplayText(text: string): string { return text.replace(/\r/g, ""); } export type ToolRenderResultLike = { content: (TextContent | ImageContent)[]; details: TDetails; }; export function invalidArgText(theme: Theme): string { return theme.fg("error", "[invalid arg]"); } export function renderToolPath( rawPath: string | null, theme: Theme, cwd: string, options?: { emptyFallback?: string }, ): string { if (rawPath === null) return invalidArgText(theme); const value = rawPath || options?.emptyFallback; if (!value) return theme.fg("toolOutput", "..."); return linkPath(theme.fg("accent", shortenPath(value)), value, cwd); }