@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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 huynhgiabuu
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,48 @@
1
+ # @casualjim/pi-pretty
2
+
3
+ Fork of [@heyhuynhgiabuu/pi-pretty](https://github.com/heyhuynhgiabuu/pi-pretty)
4
+ (MIT) that composes with
5
+ [@casualjim/pi-heimdall](https://github.com/casualjim/pi-mimir/tree/main/packages/pi-heimdall):
6
+ pretty rendering AND the heimdall sandbox on the same `bash` tool.
7
+
8
+ ## How they compose
9
+
10
+ Since pi 0.87.1, two extensions registering the same tool or flag is a hard
11
+ load error, so exactly one extension may own `bash`:
12
+
13
+ - **pi-heimdall** owns the `bash` tool (sandboxed execute via
14
+ `@casualjim/heimdall-sandbox`) and the `--no-sandbox` flag.
15
+ - **pi-pretty** never registers `bash` or any flag. It exports its bash
16
+ renderers from the `@casualjim/pi-pretty/bash-renderers` subpath, and
17
+ pi-heimdall attaches them to its tool — so `bash` output keeps pi-pretty
18
+ styling while executing through the sandbox.
19
+
20
+ Load order does not matter. All other pi-pretty features (shiki `read`
21
+ previews, `ls` icons, FFF-powered `find`/`grep`, working indicator, thinking
22
+ shimmer) are unchanged.
23
+
24
+ Trade-offs of heimdall owning `bash`:
25
+
26
+ - bash rows show no elapsed-time line (the sandboxed execute does not record
27
+ pretty's timing metadata)
28
+ - pi-pretty's extra ripgrep prompt guidance for bash is gone; the tool keeps
29
+ the host SDK's description and guidelines
30
+ - mid-session `/sandbox on|off` works — the toggle and the tool live in the
31
+ same extension now
32
+
33
+ ## Install
34
+
35
+ ```bash
36
+ pi install git:github.com/casualjim/pi-mimir#subdirectory=packages/pi-heimdall
37
+ pi install git:github.com/casualjim/pi-mimir#subdirectory=packages/pi-pretty
38
+ ```
39
+
40
+ Do not load upstream `@heyhuynhgiabuu/pi-pretty` at the same time as this fork.
41
+
42
+ ## Sandbox resolution
43
+
44
+ Entirely pi-heimdall's concern: config levels
45
+ (`~/.config/heimdall/default.jsonc`, `~/.config/heimdall/config.jsonc`,
46
+ `<repo>/.config/heimdall.json`), the `--no-sandbox` flag, and binary
47
+ resolution all live there. See the
48
+ [pi-heimdall README](https://github.com/casualjim/pi-mimir/tree/main/packages/pi-heimdall).
package/package.json ADDED
@@ -0,0 +1,71 @@
1
+ {
2
+ "name": "@casualjim/pi-pretty",
3
+ "version": "0.7.0",
4
+ "description": "Pretty terminal output for pi built-in tools, composed with pi-heimdall — the bash tool renders like pi-pretty and executes through the heimdall sandbox.",
5
+ "keywords": [
6
+ "pi",
7
+ "pi-extension",
8
+ "pi-package",
9
+ "pretty-print",
10
+ "shiki",
11
+ "syntax-highlighting",
12
+ "terminal",
13
+ "heimdall",
14
+ "sandbox"
15
+ ],
16
+ "homepage": "https://github.com/casualjim/pi-mimir/tree/main/packages/pi-pretty",
17
+ "license": "MIT",
18
+ "author": "casualjim",
19
+ "repository": {
20
+ "type": "git",
21
+ "url": "https://github.com/casualjim/pi-mimir"
22
+ },
23
+ "files": [
24
+ "src/",
25
+ "README.md",
26
+ "LICENSE"
27
+ ],
28
+ "type": "module",
29
+ "exports": {
30
+ ".": "./src/index.ts",
31
+ "./bash-renderers": {
32
+ "types": "./src/tools/bash.d.ts",
33
+ "default": "./src/tools/bash.ts"
34
+ }
35
+ },
36
+ "engines": {
37
+ "node": ">=22.0.0"
38
+ },
39
+ "publishConfig": {
40
+ "access": "public"
41
+ },
42
+ "scripts": {
43
+ "typecheck": "tsc --noEmit",
44
+ "check:pack": "pnpm pack --dry-run",
45
+ "test": "vitest run"
46
+ },
47
+ "pi": {
48
+ "extensions": [
49
+ "./src/index.ts"
50
+ ]
51
+ },
52
+ "peerDependencies": {
53
+ "@earendil-works/pi-ai": "*",
54
+ "@earendil-works/pi-coding-agent": "*",
55
+ "@earendil-works/pi-tui": "*"
56
+ },
57
+ "devDependencies": {
58
+ "@earendil-works/pi-ai": "^0.87.1",
59
+ "@earendil-works/pi-coding-agent": "^0.87.1",
60
+ "@earendil-works/pi-tui": "^0.87.0",
61
+ "@types/node": "^24.13.4",
62
+ "jiti": "^2.7.0",
63
+ "typescript": "^7.0.2",
64
+ "vitest": "^5.0.0"
65
+ },
66
+ "dependencies": {
67
+ "@ff-labs/fff-node": "^0.10.0",
68
+ "@shikijs/cli": "^4.0.2",
69
+ "shiki": "4.0.2"
70
+ }
71
+ }
@@ -0,0 +1,91 @@
1
+ /**
2
+ * pi-pretty: FFF-backed @-mention autocomplete provider.
3
+ *
4
+ * Wraps the built-in autocomplete provider and replaces the @-mention file
5
+ * suggestions with FFF frecency-ranked file search results.
6
+ */
7
+
8
+ import type { AutocompleteItem, AutocompleteProvider, AutocompleteSuggestions } from "@earendil-works/pi-tui";
9
+ import type { FileFinder } from "@ff-labs/fff-node";
10
+
11
+ /** How many @-mention suggestions to show at most. */
12
+ const MAX_SUGGESTIONS = 20;
13
+
14
+ /**
15
+ * Extract the query after a `@` character before the cursor.
16
+ * Returns the query string (empty string if bare `@`), or undefined if no `@` trigger.
17
+ */
18
+ function extractAtPrefix(textBeforeCursor: string): string | undefined {
19
+ const match = textBeforeCursor.match(/(?:^|[ \t])@([^\s@]*)$/);
20
+ return match?.[1];
21
+ }
22
+
23
+ export function createFffAutocompleteProvider(
24
+ current: AutocompleteProvider,
25
+ getFinder: () => FileFinder | null,
26
+ ): AutocompleteProvider {
27
+ return {
28
+ async getSuggestions(
29
+ lines: string[],
30
+ cursorLine: number,
31
+ cursorCol: number,
32
+ options: { signal: AbortSignal; force?: boolean },
33
+ ): Promise<AutocompleteSuggestions | null> {
34
+ const currentLine = lines[cursorLine] ?? "";
35
+ const textBeforeCursor = currentLine.slice(0, cursorCol);
36
+ const query = extractAtPrefix(textBeforeCursor);
37
+
38
+ // Not an @-mention — delegate
39
+ if (query === undefined) {
40
+ return current.getSuggestions(lines, cursorLine, cursorCol, options);
41
+ }
42
+
43
+ const finder = getFinder();
44
+ if (!finder) {
45
+ // FFF not available — delegate to built-in
46
+ return current.getSuggestions(lines, cursorLine, cursorCol, options);
47
+ }
48
+
49
+ try {
50
+ const result = finder.fileSearch(query, {
51
+ pageSize: MAX_SUGGESTIONS,
52
+ });
53
+
54
+ if (result.ok) {
55
+ const items: AutocompleteItem[] = result.value.items.map((item) => ({
56
+ value: toMentionValue(item.relativePath),
57
+ label: item.fileName,
58
+ description: item.relativePath.slice(0, -(item.fileName.length + 1)),
59
+ }));
60
+
61
+ if (items.length > 0) {
62
+ return { items, prefix: `@${query}` };
63
+ }
64
+ }
65
+ } catch {
66
+ // FFF search failed — fall through to built-in
67
+ }
68
+
69
+ // FFF returned no results or failed — let built-in handle it
70
+ return current.getSuggestions(lines, cursorLine, cursorCol, options);
71
+ },
72
+
73
+ applyCompletion(
74
+ lines: string[],
75
+ cursorLine: number,
76
+ cursorCol: number,
77
+ item: AutocompleteItem,
78
+ prefix: string,
79
+ ): { lines: string[]; cursorLine: number; cursorCol: number } {
80
+ return current.applyCompletion(lines, cursorLine, cursorCol, item, prefix);
81
+ },
82
+
83
+ shouldTriggerFileCompletion(lines: string[], cursorLine: number, cursorCol: number): boolean {
84
+ return current.shouldTriggerFileCompletion?.(lines, cursorLine, cursorCol) ?? true;
85
+ },
86
+ };
87
+ }
88
+
89
+ function toMentionValue(path: string): string {
90
+ return /\s/.test(path) ? `@"${path.replaceAll('"', '\\"')}"` : `@${path}`;
91
+ }
package/src/config.ts ADDED
@@ -0,0 +1,468 @@
1
+ /**
2
+ * pi-pretty: ANSI codes, icons, theme, and environment config.
3
+ */
4
+
5
+ import { readFileSync } from "node:fs";
6
+ import { basename, extname, join } from "node:path";
7
+
8
+ // ---------------------------------------------------------------------------
9
+ // ANSI
10
+ // ---------------------------------------------------------------------------
11
+
12
+ /** Left indent for rendered tool result lines (was two spaces; one matches tighter TUI layout). */
13
+ export const TOOL_RESULT_INDENT = " ";
14
+
15
+ export let RST = "\x1b[0m";
16
+
17
+ export const FG_LNUM = "\x1b[38;2;100;100;100m";
18
+ export const FG_DIM = "\x1b[38;2;80;80;80m";
19
+ export const FG_RULE = "\x1b[38;2;50;50;50m";
20
+ export const FG_GREEN = "\x1b[38;2;100;180;120m";
21
+ export const FG_RED = "\x1b[38;2;200;100;100m";
22
+ export const FG_YELLOW = "\x1b[38;2;220;180;80m";
23
+ export const FG_BLUE = "\x1b[38;2;100;140;220m";
24
+ export const FG_MUTED = "\x1b[38;2;139;148;158m";
25
+
26
+ const BG_DEFAULT = "\x1b[49m";
27
+ export let BG_BASE = BG_DEFAULT;
28
+ export let BG_ERROR = BG_DEFAULT;
29
+
30
+ // ---------------------------------------------------------------------------
31
+ // Theme
32
+ // ---------------------------------------------------------------------------
33
+
34
+ type BgThemeLike = {
35
+ getBgAnsi?: (key: string) => string;
36
+ bg?: (key: string, text: string) => string;
37
+ };
38
+
39
+ const ESC_RE = "\u001b";
40
+
41
+ function parseAnsiRgb(ansi: string): { r: number; g: number; b: number } | null {
42
+ const m = ansi.match(new RegExp(`${ESC_RE}\\[(?:38|48);2;(\\d+);(\\d+);(\\d+)m`));
43
+ return m ? { r: +m[1], g: +m[2], b: +m[3] } : null;
44
+ }
45
+
46
+ function getThemeBgAnsi(theme: BgThemeLike, key: string): string | null {
47
+ try {
48
+ const direct = theme.getBgAnsi?.(key);
49
+ if (direct && parseAnsiRgb(direct)) return direct;
50
+
51
+ const marker = "\0";
52
+ const styled = theme.bg?.(key, marker);
53
+ const markerIndex = styled?.indexOf(marker) ?? -1;
54
+ const ansi = markerIndex > 0 ? styled?.slice(0, markerIndex) : null;
55
+ return ansi && parseAnsiRgb(ansi) ? ansi : null;
56
+ } catch {
57
+ return null;
58
+ }
59
+ }
60
+
61
+ function hexToAnsiBg(hex: string): string | null {
62
+ const m = hex.match(/^#?([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/);
63
+ if (!m) return null;
64
+ const r = Number.parseInt(m[1], 16);
65
+ const g = Number.parseInt(m[2], 16);
66
+ const b = Number.parseInt(m[3], 16);
67
+ return `\x1b[48;2;${r};${g};${b}m`;
68
+ }
69
+
70
+ export interface WorkingIndicatorConfig {
71
+ enabled?: boolean;
72
+ /** One phrase or a list of phrases rotated across sweeps. */
73
+ text?: string | string[];
74
+ mode?: "shimmer" | "kitt" | "static";
75
+ /** Tier colors: a pi theme color name or a `#rrggbb` hex. */
76
+ low?: string;
77
+ mid?: string;
78
+ high?: string;
79
+ bold?: boolean;
80
+ /** @deprecated Retained for config compatibility; the working row no longer renders this hint. */
81
+ hint?: boolean;
82
+ /** Tint the indicator with a stable per-session accent color. */
83
+ sessionAccent?: boolean;
84
+ }
85
+
86
+ export interface ThinkingIndicatorConfig {
87
+ enabled?: boolean;
88
+ }
89
+
90
+ export interface FffConfig {
91
+ /** Allow FFF to index the user's home directory when Pi starts there. */
92
+ enableHomeScanning?: boolean;
93
+ /** Allow FFF to index the filesystem root when Pi starts there. */
94
+ enableRootScanning?: boolean;
95
+ }
96
+
97
+ export interface FffScanSettings {
98
+ enableHomeScanning: boolean;
99
+ enableRootScanning: boolean;
100
+ }
101
+
102
+ export interface PrettyConfig {
103
+ background?: {
104
+ tool?: string;
105
+ error?: string;
106
+ };
107
+ theme?: string;
108
+ icons?: string;
109
+ enableTools?: string[];
110
+ disableTools?: string[];
111
+ maxHlChars?: number;
112
+ maxPreviewLines?: number;
113
+ cacheLimit?: number;
114
+ workingIndicator?: WorkingIndicatorConfig;
115
+ thinkingIndicator?: ThinkingIndicatorConfig;
116
+ fff?: FffConfig;
117
+ }
118
+
119
+ /** Normalize a comma-separated env value or JSON array into tool names. */
120
+ export function normalizeToolList(value: unknown): string[] {
121
+ if (!Array.isArray(value)) return [];
122
+ return value
123
+ .filter((v): v is string => typeof v === "string")
124
+ .map((v) => v.trim().toLowerCase())
125
+ .filter(Boolean);
126
+ }
127
+
128
+ function positiveInt(value: unknown): number | undefined {
129
+ return typeof value === "number" && Number.isInteger(value) && value > 0 ? value : undefined;
130
+ }
131
+
132
+ /**
133
+ * Read and validate `pi-pretty.json` from the config directory. Invalid
134
+ * fields are silently skipped, matching the historical `background`
135
+ * behavior. The file is re-read on each call; callers that need a stable
136
+ * value (extension activation, theme resolution) cache the result.
137
+ */
138
+ export function loadConfig(agentDir = getConfigDir()): PrettyConfig {
139
+ if (!agentDir) return {};
140
+ try {
141
+ const parsed = JSON.parse(readFileSync(join(agentDir, "pi-pretty.json"), "utf8")) as PrettyConfig;
142
+ const config: PrettyConfig = {};
143
+ if (parsed.background) {
144
+ const background: NonNullable<PrettyConfig["background"]> = {};
145
+ if (parsed.background.tool && hexToAnsiBg(parsed.background.tool)) {
146
+ background.tool = parsed.background.tool;
147
+ }
148
+ if (parsed.background.error && hexToAnsiBg(parsed.background.error)) {
149
+ background.error = parsed.background.error;
150
+ }
151
+ if (background.tool || background.error) config.background = background;
152
+ }
153
+ if (typeof parsed.theme === "string" && parsed.theme.trim() !== "") config.theme = parsed.theme;
154
+ if (typeof parsed.icons === "string") config.icons = parsed.icons;
155
+ const enableTools = normalizeToolList(parsed.enableTools);
156
+ const disableTools = normalizeToolList(parsed.disableTools);
157
+ if (enableTools.length) config.enableTools = enableTools;
158
+ if (disableTools.length) config.disableTools = disableTools;
159
+ const maxHlChars = positiveInt(parsed.maxHlChars);
160
+ const maxPreviewLines = positiveInt(parsed.maxPreviewLines);
161
+ const cacheLimit = positiveInt(parsed.cacheLimit);
162
+ if (maxHlChars) config.maxHlChars = maxHlChars;
163
+ if (maxPreviewLines) config.maxPreviewLines = maxPreviewLines;
164
+ if (cacheLimit) config.cacheLimit = cacheLimit;
165
+ const fff = parsed.fff;
166
+ if (fff && typeof fff === "object") {
167
+ const fffConfig: FffConfig = {};
168
+ const src = fff as Record<string, unknown>;
169
+ if (typeof src.enableHomeScanning === "boolean") fffConfig.enableHomeScanning = src.enableHomeScanning;
170
+ if (typeof src.enableRootScanning === "boolean") fffConfig.enableRootScanning = src.enableRootScanning;
171
+ if (Object.keys(fffConfig).length > 0) config.fff = fffConfig;
172
+ }
173
+ const workingIndicator = parsed.workingIndicator;
174
+ if (workingIndicator && typeof workingIndicator === "object") {
175
+ const wi: WorkingIndicatorConfig = {};
176
+ const src = workingIndicator as Record<string, unknown>;
177
+ if (typeof src.enabled === "boolean") wi.enabled = src.enabled;
178
+ if (typeof src.text === "string" && src.text.trim() !== "") wi.text = src.text;
179
+ else if (Array.isArray(src.text)) {
180
+ const list = src.text.filter((item) => typeof item === "string" && item.trim() !== "");
181
+ if (list.length > 0) wi.text = list;
182
+ }
183
+ if (src.mode === "shimmer" || src.mode === "kitt" || src.mode === "static") wi.mode = src.mode;
184
+ for (const tier of ["low", "mid", "high"] as const) {
185
+ const value = src[tier];
186
+ if (typeof value === "string" && value.trim() !== "") wi[tier] = value;
187
+ }
188
+ if (typeof src.bold === "boolean") wi.bold = src.bold;
189
+ if (typeof src.hint === "boolean") wi.hint = src.hint;
190
+ if (typeof src.sessionAccent === "boolean") wi.sessionAccent = src.sessionAccent;
191
+ if (Object.keys(wi).length > 0) config.workingIndicator = wi;
192
+ }
193
+ const thinkingIndicator = parsed.thinkingIndicator;
194
+ if (thinkingIndicator && typeof thinkingIndicator === "object") {
195
+ const ti: ThinkingIndicatorConfig = {};
196
+ const src = thinkingIndicator as Record<string, unknown>;
197
+ if (typeof src.enabled === "boolean") ti.enabled = src.enabled;
198
+ if (Object.keys(ti).length > 0) config.thinkingIndicator = ti;
199
+ }
200
+ return config;
201
+ } catch {
202
+ return {};
203
+ }
204
+ }
205
+
206
+ export function getConfigDir(): string | undefined {
207
+ return process.env.PRETTY_CONFIG_DIR ?? getDefaultAgentDir();
208
+ }
209
+
210
+ function parseBooleanOverride(value: unknown): boolean | undefined {
211
+ if (typeof value === "boolean") return value;
212
+ if (typeof value !== "string") return undefined;
213
+ const normalized = value.trim().toLowerCase();
214
+ if (normalized === "1" || normalized === "true" || normalized === "on") return true;
215
+ if (normalized === "0" || normalized === "false" || normalized === "off") return false;
216
+ return undefined;
217
+ }
218
+
219
+ export function resolveFffScanSettings(
220
+ config: Pick<PrettyConfig, "fff">,
221
+ flags: {
222
+ enableHomeScanning?: boolean | string;
223
+ enableRootScanning?: boolean | string;
224
+ } = {},
225
+ env: NodeJS.ProcessEnv = process.env,
226
+ ): FffScanSettings {
227
+ const resolve = (
228
+ flagValue: boolean | string | undefined,
229
+ envName: string,
230
+ configValue: boolean | undefined,
231
+ ): boolean => parseBooleanOverride(flagValue) ?? parseBooleanOverride(env[envName]) ?? configValue ?? false;
232
+
233
+ return {
234
+ enableHomeScanning: resolve(flags.enableHomeScanning, "PRETTY_FFF_HOME_SCAN", config.fff?.enableHomeScanning),
235
+ enableRootScanning: resolve(flags.enableRootScanning, "PRETTY_FFF_ROOT_SCAN", config.fff?.enableRootScanning),
236
+ };
237
+ }
238
+
239
+ /**
240
+ * Merge env tool sets with config-file tool lists: a non-empty env set wins
241
+ * over the config file (12-factor precedence); otherwise config applies.
242
+ */
243
+ export function resolveToolSets(
244
+ envDisabled: Set<string>,
245
+ envEnabled: Set<string>,
246
+ config: Pick<PrettyConfig, "disableTools" | "enableTools">,
247
+ ): { disabledTools: Set<string>; enabledTools: Set<string> } {
248
+ return {
249
+ disabledTools: envDisabled.size > 0 ? envDisabled : new Set(config.disableTools ?? []),
250
+ enabledTools: envEnabled.size > 0 ? envEnabled : new Set(config.enableTools ?? []),
251
+ };
252
+ }
253
+
254
+ function applyPrettyConfigBg(agentDir?: string): boolean {
255
+ const config = loadConfig(agentDir);
256
+ if (!config.background?.tool) return false;
257
+ const toolBg = hexToAnsiBg(config.background.tool);
258
+ if (!toolBg) return false;
259
+ BG_BASE = toolBg;
260
+ BG_ERROR = config.background.error ? (hexToAnsiBg(config.background.error) ?? toolBg) : toolBg;
261
+ RST = "\x1b[0m";
262
+ return true;
263
+ }
264
+
265
+ export function resolveBaseBackground(theme: BgThemeLike | null | undefined): void {
266
+ const configDir = getConfigDir();
267
+ if (applyPrettyConfigBg(configDir)) return;
268
+ if (!theme?.getBgAnsi && !theme?.bg) return;
269
+ BG_BASE =
270
+ getThemeBgAnsi(theme, "toolSuccessBg") ??
271
+ getThemeBgAnsi(theme, "toolBg") ??
272
+ getThemeBgAnsi(theme, "background") ??
273
+ BG_DEFAULT;
274
+ BG_ERROR = getThemeBgAnsi(theme, "toolErrorBg") ?? BG_BASE;
275
+ RST = "\x1b[0m";
276
+ }
277
+
278
+ // ---------------------------------------------------------------------------
279
+ // Terminal
280
+ // ---------------------------------------------------------------------------
281
+
282
+ export function termWidth(): number {
283
+ if (process.stdout.columns) return Math.max(1, Math.min(process.stdout.columns, 210));
284
+ const raw =
285
+ (process.stderr as NodeJS.WriteStream & { columns?: number }).columns ||
286
+ Number.parseInt(process.env.COLUMNS ?? "", 10) ||
287
+ 200;
288
+ return Math.max(1, Math.min(raw - 4, 210));
289
+ }
290
+
291
+ // ---------------------------------------------------------------------------
292
+ // File-type icons — Nerd Font glyphs
293
+ // ---------------------------------------------------------------------------
294
+
295
+ const ICONS_MODE = (process.env.PRETTY_ICONS ?? "nerd").toLowerCase();
296
+ export let USE_ICONS = ICONS_MODE !== "none" && ICONS_MODE !== "off";
297
+
298
+ export const NF_DIR = `${FG_BLUE}\ue5ff${RST}`;
299
+ export const NF_DEFAULT = `${FG_DIM}\uf15b${RST}`;
300
+
301
+ const EXT_ICON: Record<string, string> = {
302
+ ts: `\x1b[38;2;49;120;198m\ue628${RST}`,
303
+ tsx: `\x1b[38;2;49;120;198m\ue7ba${RST}`,
304
+ js: `\x1b[38;2;241;224;90m\ue74e${RST}`,
305
+ jsx: `\x1b[38;2;97;218;251m\ue7ba${RST}`,
306
+ mjs: `\x1b[38;2;241;224;90m\ue74e${RST}`,
307
+ cjs: `\x1b[38;2;241;224;90m\ue74e${RST}`,
308
+ py: `\x1b[38;2;55;118;171m\ue73c${RST}`,
309
+ rs: `\x1b[38;2;222;165;132m\ue7a8${RST}`,
310
+ go: `\x1b[38;2;0;173;216m\ue724${RST}`,
311
+ java: `\x1b[38;2;204;62;68m\ue738${RST}`,
312
+ swift: `\x1b[38;2;255;172;77m\ue755${RST}`,
313
+ rb: `\x1b[38;2;204;52;45m\ue739${RST}`,
314
+ kt: `\x1b[38;2;126;103;200m\ue634${RST}`,
315
+ c: `\x1b[38;2;85;154;211m\ue61e${RST}`,
316
+ cpp: `\x1b[38;2;85;154;211m\ue61d${RST}`,
317
+ cs: `\x1b[38;2;104;33;122m\ue648${RST}`,
318
+ html: `\x1b[38;2;228;77;38m\ue736${RST}`,
319
+ css: `\x1b[38;2;66;165;245m\ue749${RST}`,
320
+ scss: `\x1b[38;2;207;100;154m\ue749${RST}`,
321
+ vue: `\x1b[38;2;65;184;131m\ue6a0${RST}`,
322
+ svelte: `\x1b[38;2;255;62;0m\ue697${RST}`,
323
+ json: `\x1b[38;2;241;224;90m\ue60b${RST}`,
324
+ yaml: `\x1b[38;2;160;116;196m\ue6a8${RST}`,
325
+ yml: `\x1b[38;2;160;116;196m\ue6a8${RST}`,
326
+ toml: `\x1b[38;2;160;116;196m\ue6b2${RST}`,
327
+ xml: `\x1b[38;2;228;77;38m\ue619${RST}`,
328
+ md: `\x1b[38;2;66;165;245m\ue73e${RST}`,
329
+ mdx: `\x1b[38;2;66;165;245m\ue73e${RST}`,
330
+ sql: `\x1b[38;2;218;218;218m\ue706${RST}`,
331
+ sh: `\x1b[38;2;137;180;130m\ue795${RST}`,
332
+ bash: `\x1b[38;2;137;180;130m\ue795${RST}`,
333
+ zsh: `\x1b[38;2;137;180;130m\ue795${RST}`,
334
+ lua: `\x1b[38;2;81;160;207m\ue620${RST}`,
335
+ php: `\x1b[38;2;137;147;186m\ue73d${RST}`,
336
+ dart: `\x1b[38;2;87;182;240m\ue798${RST}`,
337
+ png: `\x1b[38;2;160;116;196m\uf1c5${RST}`,
338
+ jpg: `\x1b[38;2;160;116;196m\uf1c5${RST}`,
339
+ svg: `\x1b[38;2;255;180;50m\uf1c5${RST}`,
340
+ webp: `\x1b[38;2;160;116;196m\uf1c5${RST}`,
341
+ lock: `\x1b[38;2;130;130;130m\uf023${RST}`,
342
+ env: `\x1b[38;2;241;224;90m\ue615${RST}`,
343
+ graphql: `\x1b[38;2;224;51;144m\ue662${RST}`,
344
+ dockerfile: `\x1b[38;2;56;152;236m\ue7b0${RST}`,
345
+ };
346
+
347
+ const NAME_ICON: Record<string, string> = {
348
+ "package.json": `\x1b[38;2;137;180;130m\ue71e${RST}`,
349
+ "package-lock.json": `\x1b[38;2;130;130;130m\ue71e${RST}`,
350
+ "tsconfig.json": `\x1b[38;2;49;120;198m\ue628${RST}`,
351
+ ".gitignore": `\x1b[38;2;222;165;132m\ue702${RST}`,
352
+ ".env": `\x1b[38;2;241;224;90m\ue615${RST}`,
353
+ dockerfile: `\x1b[38;2;56;152;236m\ue7b0${RST}`,
354
+ makefile: `\x1b[38;2;130;130;130m\ue615${RST}`,
355
+ "readme.md": `\x1b[38;2;66;165;245m\ue73e${RST}`,
356
+ license: `\x1b[38;2;218;218;218m\ue60a${RST}`,
357
+ };
358
+
359
+ export function fileIcon(fp: string): string {
360
+ if (!USE_ICONS) return "";
361
+ const base = basename(fp).toLowerCase();
362
+ if (NAME_ICON[base]) return `${NAME_ICON[base]} `;
363
+ const ext = extname(fp).slice(1).toLowerCase();
364
+ return EXT_ICON[ext] ? `${EXT_ICON[ext]} ` : `${NF_DEFAULT} `;
365
+ }
366
+
367
+ export function dirIcon(): string {
368
+ return USE_ICONS ? `${NF_DIR} ` : "";
369
+ }
370
+
371
+ // ---------------------------------------------------------------------------
372
+ // Language detection
373
+ // ---------------------------------------------------------------------------
374
+
375
+ import type { BundledLanguage } from "shiki";
376
+
377
+ const EXT_LANG: Record<string, BundledLanguage> = {
378
+ ts: "typescript",
379
+ tsx: "tsx",
380
+ js: "javascript",
381
+ jsx: "jsx",
382
+ mjs: "javascript",
383
+ cjs: "javascript",
384
+ py: "python",
385
+ rb: "ruby",
386
+ rs: "rust",
387
+ go: "go",
388
+ java: "java",
389
+ c: "c",
390
+ cpp: "cpp",
391
+ h: "c",
392
+ hpp: "cpp",
393
+ cs: "csharp",
394
+ swift: "swift",
395
+ kt: "kotlin",
396
+ html: "html",
397
+ css: "css",
398
+ scss: "scss",
399
+ less: "css",
400
+ json: "json",
401
+ jsonc: "jsonc",
402
+ yaml: "yaml",
403
+ yml: "yaml",
404
+ toml: "toml",
405
+ md: "markdown",
406
+ mdx: "mdx",
407
+ sql: "sql",
408
+ sh: "bash",
409
+ bash: "bash",
410
+ zsh: "bash",
411
+ lua: "lua",
412
+ php: "php",
413
+ dart: "dart",
414
+ xml: "xml",
415
+ graphql: "graphql",
416
+ svelte: "svelte",
417
+ vue: "vue",
418
+ dockerfile: "dockerfile",
419
+ makefile: "make",
420
+ zig: "zig",
421
+ nim: "nim",
422
+ elixir: "elixir",
423
+ };
424
+
425
+ export function detectLang(fp: string): BundledLanguage | undefined {
426
+ const base = basename(fp).toLowerCase();
427
+ if (base === "dockerfile") return "dockerfile";
428
+ if (base === "makefile" || base === "gnumakefile") return "make";
429
+ return EXT_LANG[extname(fp).slice(1).toLowerCase()];
430
+ }
431
+
432
+ // ---------------------------------------------------------------------------
433
+ // Env helpers
434
+ // ---------------------------------------------------------------------------
435
+
436
+ export function envInt(name: string, fallback: number): number {
437
+ const v = Number.parseInt(process.env[name] ?? "", 10);
438
+ return Number.isFinite(v) && v > 0 ? v : fallback;
439
+ }
440
+
441
+ export let MAX_HL_CHARS = envInt("PRETTY_MAX_HL_CHARS", 80_000);
442
+ export let MAX_PREVIEW_LINES = envInt("PRETTY_MAX_PREVIEW_LINES", 80);
443
+ export let CACHE_LIMIT = envInt("PRETTY_CACHE_LIMIT", 128);
444
+
445
+ /**
446
+ * Apply `pi-pretty.json` values to the env-backed module bindings. An env
447
+ * var wins over the config file whenever it is set to a non-empty value;
448
+ * empty strings are treated as unset. Call once at extension activation,
449
+ * before any render reads the bindings.
450
+ */
451
+ export function applyConfig(config: PrettyConfig): void {
452
+ if (!process.env.PRETTY_MAX_HL_CHARS && config.maxHlChars) MAX_HL_CHARS = config.maxHlChars;
453
+ if (!process.env.PRETTY_MAX_PREVIEW_LINES && config.maxPreviewLines) MAX_PREVIEW_LINES = config.maxPreviewLines;
454
+ if (!process.env.PRETTY_CACHE_LIMIT && config.cacheLimit) CACHE_LIMIT = config.cacheLimit;
455
+ if (!process.env.PRETTY_ICONS && config.icons) {
456
+ const mode = config.icons.toLowerCase();
457
+ USE_ICONS = mode !== "none" && mode !== "off";
458
+ }
459
+ }
460
+
461
+ // ---------------------------------------------------------------------------
462
+ // Agent directory helpers
463
+ // ---------------------------------------------------------------------------
464
+
465
+ export function getDefaultAgentDir(): string | undefined {
466
+ const home = process.env.HOME ?? "";
467
+ return home ? join(home, ".pi/agent") : undefined;
468
+ }