import type { AssistantMessage } from "@earendil-works/pi-ai"; import type { ExtensionContext } from "@earendil-works/pi-coding-agent"; import { type AgentSessionEvent, ToolExecutionComponent, } from "@earendil-works/pi-coding-agent"; import { Container, type Focusable, Input, Key, matchesKey, type OverlayMargin, type SizeValue, Text, type TUI, truncateToWidth, visibleWidth, } from "@earendil-works/pi-tui"; const DEFAULT_STATUS = "Ask something quick."; const MIN_FRAME_WIDTH = 4; const MIN_FRAME_HEIGHT = 6; const MIN_TRANSCRIPT_ROWS = 0; const FRAME_CHROME_ROWS = 5; const HEIGHT_RATIO = 0.55; const DEFAULT_VERTICAL_MARGIN = 2; const DEFAULT_WIDTH_RATIO = 1; const DEFAULT_MAX_HEIGHT: SizeValue = "55%"; const PAGE_SCROLL_ROWS = 10; const BOTTOM_SCROLL = Number.MAX_SAFE_INTEGER; type GhostHistoryMessage = { role: string; content: unknown; }; type GhostTheme = ExtensionContext["ui"]["theme"]; type MessageStartEvent = Extract; type MessageUpdateEvent = Extract< AgentSessionEvent, { type: "message_update" } >; type MessageEndEvent = Extract; type ToolUpdateEvent = Extract< AgentSessionEvent, { type: "tool_execution_update" } >; type ToolEndEvent = Extract; function safeDisplayText(text: string): string { return text .replace( /\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~]|\][^\x07]*(?:\x07|\x1B\\))/g, "", ) .replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F-\x9F]/g, " ") .trim(); } interface GhostOverlayLayout { innerWidth: number; frameHeight: number; inputLines: string[]; transcriptRows: number; transcriptLines: string[]; maxScroll: number; } export interface GhostOverlayOptions { tui: TUI; theme: GhostTheme; sessionCwd: string; modelLabel: string; maxHeight?: SizeValue; margin?: OverlayMargin; onSubmitMessage(text: string): void; onHideOverlay(): void; onCloseOverlay(): void; } class GhostMessageComponent { private readonly text = new Text("", 0, 0); constructor( private readonly role: "user" | "assistant", private readonly theme: GhostTheme, message: { content: unknown }, ) { this.updateContent(message); } updateContent(message: { content: unknown }): void { const label = this.role === "user" ? this.theme.fg("accent", "you") : this.theme.fg("muted", "ghost"); const body = extractMessageText(message); this.text.setText(body ? `${label} ${body}` : label); } render(width: number): string[] { return this.text.render(width); } invalidate(): void { this.text.invalidate(); } } export class GhostOverlayComponent implements Focusable { private readonly transcriptContainer = new Container(); private readonly input = new Input(); private readonly tui: TUI; private readonly theme: GhostTheme; private readonly sessionCwd: string; private readonly modelLabel: string; private readonly maxHeight: SizeValue; private readonly verticalMargin: number; private readonly onSubmitMessage: (text: string) => void; private readonly onHideOverlay: () => void; private readonly onCloseOverlay: () => void; private streamingComponent?: GhostMessageComponent; private pendingTools = new Map(); private statusText = DEFAULT_STATUS; private scrollOffset = BOTTOM_SCROLL; private followMode = true; private cachedTranscriptLines?: string[]; private cachedTranscriptWidth?: number; private lastInnerWidth = 0; private _focused = false; get focused(): boolean { return this._focused; } set focused(value: boolean) { this._focused = value; this.input.focused = value; } constructor(options: GhostOverlayOptions) { this.tui = options.tui; this.theme = options.theme; this.sessionCwd = options.sessionCwd; this.modelLabel = options.modelLabel; this.maxHeight = options.maxHeight ?? DEFAULT_MAX_HEIGHT; this.verticalMargin = marginHeight(options.margin); this.onSubmitMessage = options.onSubmitMessage; this.onHideOverlay = options.onHideOverlay; this.onCloseOverlay = options.onCloseOverlay; this.input.onSubmit = (value) => this.submit(value); this.input.onEscape = () => this.closeOverlay("close"); } loadMessages(messages: readonly unknown[], isStreaming = false): void { this.resetTranscript(); const history = messages.map(toHistoryMessage); const lastAssistantIndex = findLastAssistantIndex(history); for (let index = 0; index < history.length; index++) { const message = history[index]; if (!message) continue; if (message.role === "user") { this.transcriptContainer.addChild( new GhostMessageComponent("user", this.theme, message), ); continue; } if (message.role !== "assistant") continue; const component = new GhostMessageComponent( "assistant", this.theme, message, ); this.transcriptContainer.addChild(component); if (isStreaming && index === lastAssistantIndex) this.streamingComponent = component; } this.setStatus(isStreaming ? "Streaming response..." : DEFAULT_STATUS); this.markTranscriptChanged(); } loadEvents(events: readonly AgentSessionEvent[]): void { this.resetTranscript(); for (const event of events) this.handleSessionEvent(event); this.tui.requestRender(true); } private resetTranscript(): void { this.transcriptContainer.clear(); this.streamingComponent = undefined; this.pendingTools.clear(); this.statusText = DEFAULT_STATUS; this.invalidateTranscriptCache(); this.scrollToBottom(); } private closeOverlay(result: "hide" | "close"): void { if (result === "hide") this.onHideOverlay(); else this.onCloseOverlay(); this.tui.requestRender(true); } private submit(value: string): void { const text = value.trim(); if (!text) return; this.input.setValue(""); this.scrollToBottom(); this.onSubmitMessage(text); } private invalidateTranscriptCache(): void { this.cachedTranscriptLines = undefined; this.cachedTranscriptWidth = undefined; } private markTranscriptChanged(): void { this.invalidateTranscriptCache(); if (this.followMode) this.scrollToBottom(); } private scrollToBottom(): void { this.followMode = true; this.scrollOffset = BOTTOM_SCROLL; } private getFrameHeight(): number { const rows = Math.max(1, this.tui.terminal.rows); const available = Math.max(1, rows - this.verticalMargin); const configured = parseSize(this.maxHeight, rows) ?? Math.floor(rows * HEIGHT_RATIO); return Math.max(1, Math.min(configured, available)); } private getFallbackInnerWidth(): number { const columns = Math.max(MIN_FRAME_WIDTH, this.tui.terminal.columns); return Math.max(1, Math.floor(columns * DEFAULT_WIDTH_RATIO) - 2); } private getTranscriptLines(width: number): string[] { if (this.cachedTranscriptLines && this.cachedTranscriptWidth === width) { return this.cachedTranscriptLines; } const lines = this.transcriptContainer .render(width) .map((line) => fitLine(line, width).trimEnd()); this.cachedTranscriptLines = lines; this.cachedTranscriptWidth = width; return lines; } private getCurrentMaxScroll(): number { const innerWidth = this.lastInnerWidth || this.getFallbackInnerWidth(); return this.calculateLayout(innerWidth + 2).maxScroll; } setStatus(text: string): void { this.statusText = text; this.tui.requestRender(); } handleInput(data: string): void { if (matchesKey(data, Key.ctrl("s"))) return this.closeOverlay("hide"); if (this.tryHandleScrollKey(data)) return; this.input.handleInput(data); this.tui.requestRender(); } private tryHandleScrollKey(data: string): boolean { if (matchesKey(data, Key.up)) return this.scrollBy(-1); if (matchesKey(data, Key.down)) return this.scrollBy(1); if (matchesKey(data, Key.pageUp)) return this.scrollBy(-PAGE_SCROLL_ROWS); if (matchesKey(data, Key.pageDown)) return this.scrollBy(PAGE_SCROLL_ROWS); if (matchesKey(data, Key.home)) return this.scrollHome(); if (matchesKey(data, Key.end)) return this.scrollEnd(); return false; } private scrollBy(delta: number): true { const maxScroll = this.getCurrentMaxScroll(); if (delta < 0) { this.followMode = false; this.scrollOffset = Math.max( 0, Math.min(this.scrollOffset, maxScroll) + delta, ); this.tui.requestRender(); return true; } if (!this.followMode) { this.scrollOffset = Math.min(maxScroll, this.scrollOffset + delta); if (this.scrollOffset >= maxScroll) this.scrollToBottom(); } this.tui.requestRender(); return true; } private scrollHome(): true { this.followMode = false; this.scrollOffset = 0; this.tui.requestRender(); return true; } private scrollEnd(): true { this.scrollToBottom(); this.tui.requestRender(); return true; } handleSessionEvent(event: AgentSessionEvent): void { switch (event.type) { case "message_start": this.handleMessageStart(event.message); break; case "message_update": this.handleMessageUpdate(event.message); break; case "message_end": this.handleMessageEnd(event.message); break; case "tool_execution_start": this.handleToolStart(event.toolCallId, event.toolName, event.args); break; case "tool_execution_update": this.handleToolUpdate(event.toolCallId, event.partialResult); break; case "tool_execution_end": this.handleToolEnd(event.toolCallId, event.result, event.isError); break; case "agent_end": this.handleAgentEnd(); return; } this.tui.requestRender(); } private handleMessageStart(message: MessageStartEvent["message"]): void { if (message.role === "user") { this.transcriptContainer.addChild( new GhostMessageComponent("user", this.theme, message), ); this.setStatus("Thinking..."); this.markTranscriptChanged(); return; } if (message.role !== "assistant") return; this.streamingComponent = new GhostMessageComponent( "assistant", this.theme, message, ); this.transcriptContainer.addChild(this.streamingComponent); this.setStatus("Streaming response..."); this.markTranscriptChanged(); } private handleMessageUpdate(message: MessageUpdateEvent["message"]): void { if (message.role !== "assistant" || !this.streamingComponent) return; this.streamingComponent.updateContent(message); this.markTranscriptChanged(); } private handleMessageEnd(message: MessageEndEvent["message"]): void { if (message.role !== "assistant") return; this.streamingComponent?.updateContent(message); this.finishPendingTools(message); this.streamingComponent = undefined; this.setStatus(DEFAULT_STATUS); this.markTranscriptChanged(); } private finishPendingTools(message: AssistantMessage): void { if (!this.pendingTools.size) return; if (message.stopReason === "aborted" || message.stopReason === "error") { this.failPendingTools(message.errorMessage || "Error"); return; } for (const component of this.pendingTools.values()) component.setArgsComplete(); } private failPendingTools(errorMessage: string): void { for (const component of this.pendingTools.values()) { component.updateResult({ content: [{ type: "text", text: errorMessage }], isError: true, }); } this.pendingTools.clear(); } private handleToolStart( toolCallId: string, toolName: string, args: unknown, ): void { let component = this.pendingTools.get(toolCallId); if (!component) { component = new ToolExecutionComponent( toolName, toolCallId, args, { showImages: true }, undefined, this.tui, this.sessionCwd, ); this.transcriptContainer.addChild(component); this.pendingTools.set(toolCallId, component); } component.markExecutionStarted(); this.setStatus(`Running ${toolName}...`); this.markTranscriptChanged(); } private handleToolUpdate( toolCallId: string, partialResult: ToolUpdateEvent["partialResult"], ): void { const component = this.pendingTools.get(toolCallId); if (!component) return; component.updateResult({ ...partialResult, isError: false }, true); this.markTranscriptChanged(); } private handleToolEnd( toolCallId: string, result: ToolEndEvent["result"], isError: boolean, ): void { const component = this.pendingTools.get(toolCallId); if (!component) return; component.updateResult({ ...result, isError }); this.pendingTools.delete(toolCallId); this.markTranscriptChanged(); } private handleAgentEnd(): void { this.streamingComponent = undefined; this.pendingTools.clear(); this.setStatus(DEFAULT_STATUS); this.markTranscriptChanged(); this.tui.requestRender(); } invalidate(): void { this.transcriptContainer.invalidate(); this.input.invalidate(); this.invalidateTranscriptCache(); } render(width: number): string[] { if (width <= 0) return []; if (width < MIN_FRAME_WIDTH) return this.renderTiny(width); const layout = this.calculateLayout(width); if (layout.frameHeight < MIN_FRAME_HEIGHT) return this.renderCompact(width, layout.frameHeight); this.lastInnerWidth = layout.innerWidth; this.updateScroll(layout.maxScroll); const transcript = layout.transcriptLines.slice( this.scrollOffset, this.scrollOffset + layout.transcriptRows, ); return [ this.renderHeader(layout.innerWidth), this.borderLine("├", "┤", layout.innerWidth), ...this.renderTranscript( transcript, layout.transcriptRows, layout.innerWidth, ), this.borderLine("├", "┤", layout.innerWidth), this.renderFooter(layout), ...layout.inputLines.map((line) => this.boxedLine(line, layout.innerWidth), ), this.borderLine("╰", "╯", layout.innerWidth), ].slice(0, layout.frameHeight); } private calculateLayout(width: number): GhostOverlayLayout { const innerWidth = Math.max(1, width - 2); const frameHeight = this.getFrameHeight(); const maxInputRows = Math.max( 1, frameHeight - FRAME_CHROME_ROWS - MIN_TRANSCRIPT_ROWS, ); const inputLines = this.input .render(innerWidth) .slice(-maxInputRows) .map((line) => fitLine(line, innerWidth).trimEnd()); const transcriptRows = Math.max( MIN_TRANSCRIPT_ROWS, frameHeight - FRAME_CHROME_ROWS - inputLines.length, ); const transcriptLines = this.getTranscriptLines(innerWidth); const maxScroll = Math.max(0, transcriptLines.length - transcriptRows); return { innerWidth, frameHeight, inputLines, transcriptRows, transcriptLines, maxScroll, }; } private updateScroll(maxScroll: number): void { if (this.followMode) { this.scrollOffset = maxScroll; return; } this.scrollOffset = Math.max(0, Math.min(this.scrollOffset, maxScroll)); if (this.scrollOffset >= maxScroll) this.scrollToBottom(); } private renderTiny(width: number): string[] { return [truncateToWidth(this.theme.fg("accent", "ghost"), width, "")]; } private renderCompact(width: number, height: number): string[] { const content = `${this.theme.fg("accent", "ghost")} ${this.theme.fg("dim", this.statusText)}`; return Array.from({ length: Math.max(1, height) }, (_, index) => index === 0 ? fitLine(content, width) : fitLine("", width), ); } private renderHeader(innerWidth: number): string { const content = truncateToWidth( this.theme.fg("accent", ` ${this.theme.bold("ghost pi")} `) + this.theme.fg( "dim", "same model • ephemeral session • ↑↓ scroll • ctrl+s hide • esc close", ), innerWidth, ); const pad = "─".repeat(Math.max(0, innerWidth - visibleWidth(content))); return ( this.theme.fg("border", "╭") + content + this.theme.fg("border", pad + "╮") ); } private renderTranscript( lines: string[], rowCount: number, innerWidth: number, ): string[] { const rows: string[] = []; for (const line of lines) rows.push(this.boxedLine(line, innerWidth)); while (rows.length < rowCount) rows.push(this.boxedLine("", innerWidth)); return rows; } private renderFooter(layout: GhostOverlayLayout): string { const info = layout.transcriptLines.length > layout.transcriptRows && layout.transcriptRows > 0 ? `${this.scrollOffset + 1}-${Math.min(this.scrollOffset + layout.transcriptRows, layout.transcriptLines.length)}/${layout.transcriptLines.length}` : `${layout.transcriptLines.length}L`; const followIcon = this.followMode ? this.theme.fg("success", "●") : this.theme.fg("dim", "○"); const content = [ this.theme.fg("dim", this.statusText), this.theme.fg("accent", this.modelLabel), this.theme.fg("dim", formatGhostCwd(this.sessionCwd)), this.theme.fg("dim", info), followIcon, ].join(` ${this.theme.fg("border", "│")} `); return this.boxedLine(content, layout.innerWidth); } private borderLine(left: string, right: string, innerWidth: number): string { return this.theme.fg("border", left + "─".repeat(innerWidth) + right); } private boxedLine(line: string, innerWidth: number): string { return ( this.theme.fg("border", "│") + fitLine(line, innerWidth) + this.theme.fg("border", "│") ); } } export function fitLine(line: string, width: number): string { if (width <= 0) return ""; const truncated = truncateToWidth(line, width, ""); return truncated + " ".repeat(Math.max(0, width - visibleWidth(truncated))); } export function extractMessageText(message: { content: unknown }): string { if (typeof message.content === "string") return safeDisplayText(message.content); if (!Array.isArray(message.content)) return ""; return safeDisplayText( message.content .filter( (part): part is { type: "text"; text: string } => typeof part === "object" && part !== null && (part as { type?: unknown }).type === "text" && typeof (part as { text?: unknown }).text === "string", ) .map((part) => part.text) .join("\n"), ); } export function formatGhostCwd(cwd: string): string { const home = process.env.HOME; if (home && cwd.startsWith(home)) { return `~${cwd.slice(home.length)}` || "~"; } return cwd; } function parseSize(value: SizeValue, reference: number): number | undefined { if (typeof value === "number") return Math.floor(value); const match = /^(\d+(?:\.\d+)?)%$/.exec(value); if (!match) return undefined; return Math.floor((reference * Number(match[1])) / 100); } function toHistoryMessage(message: unknown): GhostHistoryMessage | undefined { if (typeof message !== "object" || message === null) return undefined; const candidate = message as { role?: unknown; content?: unknown }; if (typeof candidate.role !== "string") return undefined; return { role: candidate.role, content: candidate.content }; } function findLastAssistantIndex( messages: readonly (GhostHistoryMessage | undefined)[], ): number { for (let index = messages.length - 1; index >= 0; index--) { if (messages[index]?.role === "assistant") return index; } return -1; } function marginHeight(margin: OverlayMargin | undefined): number { return Math.max( DEFAULT_VERTICAL_MARGIN, Math.max(0, margin?.top ?? 0) + Math.max(0, margin?.bottom ?? 0), ); }