main
  1/**
  2 * Custom Footer Extension
  3 *
  4 * Shows comprehensive status in the footer:
  5 * - Hostname
  6 * - Abbreviated folder path (~/s/home for ~/src/home)
  7 * - Git branch (with dirty indicator)
  8 * - Model name
  9 * - Context usage
 10 * - Current time
 11 *
 12 * Format: ️ kyushu  ~/s/home  main  sonnet-4  76.2%/200k  16:10
 13 */
 14
 15import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
 16import { truncateToWidth } from "@earendil-works/pi-tui";
 17import { hostname } from "node:os";
 18import { execSync } from "node:child_process";
 19import path from "node:path";
 20
 21const CONTEXT_WARNING_TOKENS = 150_000;
 22const CACHE_COLD_CONTEXT_TOKENS = 50_000;
 23// ponytail: provider cache TTLs differ; use provider-specific values if Pi exposes them.
 24const CACHE_TTL_MS = 5 * 60_000;
 25const PROVIDER_NAMES: Record<string, string> = {
 26	"github-copilot": "gh", "google-vertex": "vx", "anthropic-vertex": "av", google: "g", "llama-cpp": "local",
 27};
 28
 29// =============================================================================
 30// Path Abbreviation
 31// =============================================================================
 32
 33/**
 34 * Abbreviate path to ~/s/h format (first letter of each directory)
 35 * Dotfiles preserve the dot prefix (.local → .l).
 36 * ~/src/home -> ~/s/home
 37 * ~/src/tektoncd/pipeline -> ~/s/t/pipeline
 38 * ~/.local/share/worktrees/foo -> ~/.l/s/w/foo
 39 */
 40function abbreviatePath(fullPath: string): string {
 41	const home = process.env.HOME || "";
 42	let displayPath = fullPath;
 43
 44	// Replace home with ~
 45	if (home && fullPath.startsWith(home)) {
 46		displayPath = "~" + fullPath.slice(home.length);
 47	}
 48
 49	// Split path
 50	const parts = displayPath.split(path.sep).filter(Boolean);
 51	if (parts.length <= 2) {
 52		// Short enough already (e.g., ~/home or ~/src)
 53		return displayPath;
 54	}
 55
 56	// Abbreviate middle directories, keep last full
 57	const abbreviated = parts.map((part, i) => {
 58		// Keep first part (~) and last part full
 59		if (i === 0 || i === parts.length - 1) {
 60			return part;
 61		}
 62		// Keep dot prefix for hidden dirs (.local → .l)
 63		if (part.startsWith(".")) {
 64			return "." + part[1];
 65		}
 66		// Abbreviate middle parts to first letter
 67		return part[0];
 68	});
 69
 70	return abbreviated.join(path.sep);
 71}
 72
 73// =============================================================================
 74// Git Info
 75// =============================================================================
 76
 77// Git info caching to avoid running git commands on every render
 78// Without caching, git status would run potentially hundreds of times per second
 79// during typing/rendering, causing performance issues and UI lag
 80let cachedGitBranch: string | null = null;
 81let cachedGitDirty: boolean = false;
 82let cachedGitWorktree: boolean = false;
 83let gitCacheTime = 0;
 84const GIT_CACHE_MS = 30000; // Cache for 30 seconds - balance between freshness and performance
 85
 86function getGitInfo(): { branch: string; dirty: boolean; worktree: boolean } {
 87	const now = Date.now();
 88	if (now - gitCacheTime < GIT_CACHE_MS && cachedGitBranch !== null) {
 89		return { branch: cachedGitBranch, dirty: cachedGitDirty, worktree: cachedGitWorktree };
 90	}
 91
 92	try {
 93		// Get branch
 94		const branch = execSync("git rev-parse --abbrev-ref HEAD 2>/dev/null", {
 95			encoding: "utf-8",
 96			timeout: 1000,
 97		}).trim();
 98
 99		// Check if dirty (uncommitted changes)
100		const status = execSync("git status --porcelain 2>/dev/null", {
101			encoding: "utf-8",
102			timeout: 1000,
103		}).trim();
104
105		// Check if we're in a worktree (git-dir contains /worktrees/)
106		const gitDir = execSync("git rev-parse --git-dir 2>/dev/null", {
107			encoding: "utf-8",
108			timeout: 1000,
109		}).trim();
110
111		cachedGitBranch = branch || "";
112		cachedGitDirty = status.length > 0;
113		cachedGitWorktree = gitDir.includes("/worktrees/");
114		gitCacheTime = now;
115
116		return { branch: cachedGitBranch, dirty: cachedGitDirty, worktree: cachedGitWorktree };
117	} catch {
118		cachedGitBranch = "";
119		cachedGitDirty = false;
120		cachedGitWorktree = false;
121		gitCacheTime = now;
122		return { branch: "", dirty: false, worktree: false };
123	}
124}
125
126// =============================================================================
127// Model Name Shortening
128// =============================================================================
129
130function getShortModelName(modelId: string): string {
131	// Remove @date suffix if present (e.g., claude-sonnet-4-5@20250929 -> claude-sonnet-4-5)
132	const baseId = modelId.split("@")[0];
133	
134	const shortNames: Record<string, string> = {
135		"claude-sonnet-4-6": "sonnet-4.6",
136		"claude-sonnet-4-5": "sonnet-4.5",
137		"claude-sonnet-4-5-20250514": "sonnet-4.5",
138		"claude-sonnet-4": "sonnet-4",
139		"claude-sonnet-4-20250514": "sonnet-4",
140		"claude-3-5-sonnet-20241022": "sonnet-3.5",
141		"claude-3-5-sonnet": "sonnet-3.5",
142		"claude-sonnet": "sonnet",
143		"claude-opus-4-5": "opus-4.5",
144		"claude-opus-4": "opus-4",
145		"claude-opus-4-20250514": "opus-4",
146		"claude-3-opus": "opus-3",
147		"claude-opus": "opus",
148		"claude-haiku-4": "haiku-4",
149		"claude-haiku": "haiku",
150		"claude-3-haiku": "haiku-3",
151		"gpt-4o": "4o",
152		"gpt-4o-mini": "4o-mini",
153		"gpt-4-turbo": "4-turbo",
154		"gpt-4": "gpt4",
155		"gpt-3.5-turbo": "3.5",
156		"gemini-2.0-flash-exp": "flash-2-exp",
157		"gemini-2.0-flash": "flash-2",
158		"gemini-2.0-pro-exp": "pro-2-exp",
159		"gemini-2.0-pro": "pro-2",
160		"gemini-1.5-pro": "pro-1.5",
161		"gemini-1.5-flash": "flash-1.5",
162	};
163
164	// Try exact match first, then base ID without @date
165	return shortNames[modelId] || shortNames[baseId] || baseId;
166}
167
168// =============================================================================
169// Formatting Helpers
170// =============================================================================
171
172function formatNumber(n: number): string {
173	if (n < 1000) return `${n}`;
174	if (n < 10000) return `${(n / 1000).toFixed(1)}k`;
175	if (n < 1000000) return `${Math.floor(n / 1000)}k`;
176	return `${(n / 1000000).toFixed(1)}M`;
177}
178
179// =============================================================================
180// Provider Info
181// =============================================================================
182
183function getProviderName(model: any): string {
184	const provider = model?.provider || "unknown";
185	return PROVIDER_NAMES[provider] || provider;
186}
187
188// =============================================================================
189// Thinking Level
190// =============================================================================
191
192function getThinkingInfo(pi: any): { emoji: string; level: string } | null {
193	// Get thinking level from pi API
194	const thinkingLevel = pi.getThinkingLevel?.();
195	
196	if (!thinkingLevel || thinkingLevel === "off") return null;
197	
198	// Map thinking levels to short display names
199	const levelMap: Record<string, string> = {
200		"minimal": "min",
201		"low": "low",
202		"medium": "med", 
203		"high": "high",
204		"xhigh": "ext",
205	};
206	
207	return {
208		emoji: "🧠",
209		level: levelMap[thinkingLevel] || thinkingLevel,
210	};
211}
212
213// =============================================================================
214// Mode Display
215// =============================================================================
216
217/** Convert hex color (#rrggbb) to 24-bit ANSI foreground escape sequence */
218function hexToAnsi(hex: string): string {
219	const h = hex.replace("#", "");
220	const r = parseInt(h.substring(0, 2), 16);
221	const g = parseInt(h.substring(2, 4), 16);
222	const b = parseInt(h.substring(4, 6), 16);
223	return `\x1b[38;2;${r};${g};${b}m`;
224}
225
226function getModeText(modeName: string, hexColor: string | undefined, theme: any): string {
227	const label = `[${modeName}]`;
228	if (hexColor && /^#[0-9a-fA-F]{6}$/.test(hexColor)) {
229		return `${hexToAnsi(hexColor)}${label}\x1b[39m`;
230	}
231	return theme.fg("dim", label);
232}
233
234// =============================================================================
235// Context Usage
236// =============================================================================
237
238function getContextInfo(ctx: any, autoCompact: boolean, theme: any): string | null {
239	try {
240		const usage = ctx.getContextUsage?.();
241		if (!usage || !usage.contextWindow || usage.contextWindow === 0) return null;
242		const warnings: string[] = [];
243		if (usage.tokens >= CONTEXT_WARNING_TOKENS) warnings.push(theme.fg("warning", "⚠"));
244		const lastAssistant = [...ctx.sessionManager.getBranch()].reverse().find((entry: any) => entry.type === "message" && entry.message.role === "assistant");
245		const timestamp = lastAssistant?.message.timestamp ?? Date.parse(lastAssistant?.timestamp || "");
246		if (usage.tokens > CACHE_COLD_CONTEXT_TOKENS && Number.isFinite(timestamp) && Date.now() - timestamp > CACHE_TTL_MS) warnings.push(theme.fg("warning", "⚠cold"));
247		return `${((usage.tokens / usage.contextWindow) * 100).toFixed(1)}%/${formatNumber(usage.contextWindow)}${autoCompact ? " (auto)" : ""}${warnings.join("")}`;
248	} catch { return null; }
249}
250
251// =============================================================================
252// Extension
253// =============================================================================
254
255export default function (pi: ExtensionAPI) {
256	let timeUpdateInterval: NodeJS.Timeout | null = null;
257	let autoCompactEnabled = false;
258
259	// Track auto-compact status
260	pi.on("session_start", async (_event, ctx) => {
261		// Check if auto-compact is enabled from settings
262		autoCompactEnabled = ctx.sessionManager.getAutoCompact?.() || false;
263	});
264
265	pi.on("session_start", async (_event, ctx) => {
266		// Footer only makes sense in TUI mode (hasUI is also true in RPC).
267		if (ctx.mode !== "tui") return;
268		// Clear any existing interval
269		if (timeUpdateInterval) {
270			clearInterval(timeUpdateInterval);
271		}
272
273		ctx.ui.setFooter((tui, theme, footerData) => {
274			const unsub = footerData.onBranchChange(() => tui.requestRender());
275
276			// Update time and status every 10 seconds
277			// This also ensures extension statuses appear promptly
278			timeUpdateInterval = setInterval(() => {
279				tui.requestRender();
280			}, 10000); // 10 seconds
281
282			return {
283				dispose: () => {
284					unsub();
285					if (timeUpdateInterval) {
286						clearInterval(timeUpdateInterval);
287						timeUpdateInterval = null;
288					}
289				},
290				invalidate() {},
291				render(width: number): string[] {
292					try {
293					// Get all info
294					const host = process.env.SSH_CONNECTION ? hostname() : "";
295					const folder = abbreviatePath(ctx.cwd);
296					const git = getGitInfo();
297					const modelId = ctx.model?.id || "no-model";
298					const provider = getProviderName(ctx.model);
299					const modelName = getShortModelName(modelId);
300					const thinking = getThinkingInfo(pi);
301					const contextInfo = getContextInfo(ctx, autoCompactEnabled, theme);
302
303					// Build components
304					const hostIcon = host ? theme.fg("accent", "🖥️") : "";
305					const hostText = host ? theme.fg("accent", host) : "";
306					const folderText = theme.fg("dim", folder);
307					
308					const gitBranch = git.branch
309						? theme.fg("success", git.branch + (git.dirty ? "*" : "") + (git.worktree ? " 🌳" : ""))
310						: "";
311					
312					// Provider/Model format: google-vertex/sonnet-4.5
313					const providerModel = theme.fg("accent", `${provider}/${modelName}`);
314					
315					// Thinking indicator (only if enabled)
316					const thinkingText = thinking 
317						? theme.fg("accent", `${thinking.emoji} ${thinking.level}`)
318						: "";
319					
320					// Context usage: 76.2%/200k (auto)
321					const contextText = contextInfo ? theme.fg("dim", contextInfo) : "";
322					
323					// Extension statuses (from setStatus calls)
324					// getExtensionStatuses() returns ReadonlyMap<string, string>
325					const extensionStatuses = footerData.getExtensionStatuses?.() || new Map();
326					
327					// Extract mode separately for custom positioning and coloring
328					const modeRaw = extensionStatuses.get("mode");
329					const modeColor = extensionStatuses.get("mode-color");
330					const modeText = modeRaw ? getModeText(modeRaw, modeColor, theme) : "";
331
332					// Remaining statuses (exclude mode internals)
333					const statusTexts = Array.from(extensionStatuses.entries())
334						.filter(([key, val]: [string, string]) => key !== "mode" && key !== "mode-color" && Boolean(val))
335						.map(([, val]: [string, string]) => val);
336
337					// Adaptive footer: progressively drop components on narrow terminals
338					const hostSegment = host ? `${hostIcon} ${hostText}` : "";
339					const components = width < 60
340						? [modeText, contextText]
341						: width < 80
342						? [folderText, gitBranch, modeText, providerModel, contextText]
343						: width < 100
344						? [hostSegment, folderText, gitBranch, modeText, providerModel, contextText]
345						: [hostSegment, folderText, gitBranch, modeText, providerModel, thinkingText, contextText, ...statusTexts];
346
347					const separator = theme.fg("dim", "  ");
348					const footer = components.filter(Boolean).join(separator);
349
350					return [truncateToWidth(footer, width)];
351					} catch { return [""]; }
352				},
353			};
354		});
355	});
356
357	pi.on("session_switch", async (_event, ctx) => {
358		// Re-setup footer on session switch
359		if (ctx.mode !== "tui") return;
360		if (timeUpdateInterval) {
361			clearInterval(timeUpdateInterval);
362		}
363
364		ctx.ui.setFooter((tui, theme, footerData) => {
365			const unsub = footerData.onBranchChange(() => tui.requestRender());
366
367			timeUpdateInterval = setInterval(() => {
368				tui.requestRender();
369			}, 60000);
370
371			return {
372				dispose: () => {
373					unsub();
374					if (timeUpdateInterval) {
375						clearInterval(timeUpdateInterval);
376						timeUpdateInterval = null;
377					}
378				},
379				invalidate() {},
380				render(width: number): string[] {
381					try {
382					// Get all info
383					const host = process.env.SSH_CONNECTION ? hostname() : "";
384					const folder = abbreviatePath(ctx.cwd);
385					const git = getGitInfo();
386					const modelId = ctx.model?.id || "no-model";
387					const provider = getProviderName(ctx.model);
388					const modelName = getShortModelName(modelId);
389					const thinking = getThinkingInfo(pi);
390					const contextInfo = getContextInfo(ctx, autoCompactEnabled, theme);
391
392					// Build components
393					const hostIcon = host ? theme.fg("accent", "🖥️") : "";
394					const hostText = host ? theme.fg("accent", host) : "";
395					const folderText = theme.fg("dim", folder);
396					
397					const gitBranch = git.branch
398						? theme.fg("success", git.branch + (git.dirty ? "*" : "") + (git.worktree ? " 🌳" : ""))
399						: "";
400					
401					// Provider/Model format: google-vertex/sonnet-4.5
402					const providerModel = theme.fg("accent", `${provider}/${modelName}`);
403					
404					// Thinking indicator (only if enabled)
405					const thinkingText = thinking 
406						? theme.fg("accent", `${thinking.emoji} ${thinking.level}`)
407						: "";
408					
409					// Context usage: 76.2%/200k (auto)
410					const contextText = contextInfo ? theme.fg("dim", contextInfo) : "";
411
412					// Extension statuses
413					const extensionStatuses = footerData.getExtensionStatuses?.() || new Map();
414					const modeRaw = extensionStatuses.get("mode");
415					const modeColor = extensionStatuses.get("mode-color");
416					const modeText = modeRaw ? getModeText(modeRaw, modeColor, theme) : "";
417					const statusTexts = Array.from(extensionStatuses.entries())
418						.filter(([key, val]: [string, string]) => key !== "mode" && key !== "mode-color" && Boolean(val))
419						.map(([, val]: [string, string]) => val);
420					// Adaptive footer: progressively drop components on narrow terminals
421					const hostSegment = host ? `${hostIcon} ${hostText}` : "";
422					const components = width < 60
423						? [modeText, contextText]
424						: width < 80
425						? [folderText, gitBranch, modeText, providerModel, contextText]
426						: width < 100
427						? [hostSegment, folderText, gitBranch, modeText, providerModel, contextText]
428						: [hostSegment, folderText, gitBranch, modeText, providerModel, thinkingText, contextText, ...statusTexts];
429
430					const separator = theme.fg("dim", "  ");
431					const footer = components.filter(Boolean).join(separator);
432
433					return [truncateToWidth(footer, width)];
434					} catch { return [""]; }
435				},
436			};
437		});
438	});
439
440	pi.on("session_shutdown", async () => {
441		if (timeUpdateInterval) {
442			clearInterval(timeUpdateInterval);
443			timeUpdateInterval = null;
444		}
445	});
446}