repositories / dotfiles
dotfiles
bugabingas dorkfiles
owned by bugabinga
pi/agent/extensions/ghost/overlay.ts
RawFile outline
- DEFAULT_STATUS line 23
- MIN_FRAME_WIDTH line 24
- MIN_FRAME_HEIGHT line 25
- MIN_TRANSCRIPT_ROWS line 26
- FRAME_CHROME_ROWS line 27
- HEIGHT_RATIO line 28
- DEFAULT_VERTICAL_MARGIN line 29
- DEFAULT_WIDTH_RATIO line 30
- DEFAULT_MAX_HEIGHT line 31
- PAGE_SCROLL_ROWS line 32
- BOTTOM_SCROLL line 33
- MessageStartEvent line 35
- MessageUpdateEvent line 36
- MessageEndEvent line 37
- ToolUpdateEvent line 38
- ToolEndEvent line 39
- GhostOverlayLayout line 41
- innerWidth line 42
- frameHeight line 43
- inputLines line 44
- transcriptRows line 45
- transcriptLines line 46
- maxScroll line 47
- GhostOverlayOptions line 50
- tui line 51
- theme line 52
- sessionCwd line 53
- modelLabel line 54
- maxHeight line 55
- margin line 56
- onSubmitMessage line 57
- onHideOverlay line 58
- onCloseOverlay line 59
- GhostOverlayComponent line 62
- transcriptContainer line 63
- input line 64
- tui line 65
- theme line 66
- sessionCwd line 67
- modelLabel line 68
- maxHeight line 69
- verticalMargin line 70
- onSubmitMessage line 71
- onHideOverlay line 72
- onCloseOverlay line 73
- streamingComponent line 74
- pendingTools line 75
- statusText line 76
- scrollOffset line 77
- followMode line 78
- cachedTranscriptLines line 79
- cachedTranscriptWidth line 80
- lastInnerWidth line 81
- _focused line 82
- focused line 84
- focused line 88
- constructor line 93
- submit line 108
- invalidateTranscriptCache line 117
- markTranscriptChanged line 122
- scrollToBottom line 127
- getFrameHeight line 132
- getFallbackInnerWidth line 139
- getTranscriptLines line 144
- getCurrentMaxScroll line 157
- setStatus line 162
- handleInput line 167
- tryHandleScrollKey line 175
- scrollBy line 185
- scrollHome line 204
- scrollEnd line 211
- handleSessionEvent line 217
- handleMessageStart line 245
- handleMessageUpdate line 264
- handleMessageEnd line 271
- finishPendingTools line 281
- failPendingTools line 292
- handleToolStart line 302
- handleToolUpdate line 324
- handleToolEnd line 335
- handleAgentEnd line 348
- invalidate line 356
- render line 362
- calculateLayout line 388
- updateScroll line 405
- renderTiny line 415
- renderCompact line 419
- renderHeader line 426
- renderTranscript line 436
- renderFooter line 443
- borderLine line 459
- boxedLine line 463
- fitLine line 468
- extractMessageText line 475
- text line 481
- type line 481
- formatGhostCwd line 489
- Remaining entries omitted.
import {
type AgentSessionEvent,
AssistantMessageComponent,
getMarkdownTheme,
ToolExecutionComponent,
UserMessageComponent,
} from "@mariozechner/pi-coding-agent";
import type { AssistantMessage } from "@mariozechner/pi-ai";
import {
Container,
type Focusable,
Input,
Key,
matchesKey,
type OverlayMargin,
type SizeValue,
type TUI,
truncateToWidth,
visibleWidth,
} from "@mariozechner/pi-tui";
import type { ExtensionCommandContext } from "@mariozechner/pi-coding-agent";
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 = 0.85;
const DEFAULT_MAX_HEIGHT: SizeValue = "55%";
const PAGE_SCROLL_ROWS = 10;
const BOTTOM_SCROLL = Number.MAX_SAFE_INTEGER;
type MessageStartEvent = Extract<AgentSessionEvent, { type: "message_start" }>;
type MessageUpdateEvent = Extract<AgentSessionEvent, { type: "message_update" }>;
type MessageEndEvent = Extract<AgentSessionEvent, { type: "message_end" }>;
type ToolUpdateEvent = Extract<AgentSessionEvent, { type: "tool_execution_update" }>;
type ToolEndEvent = Extract<AgentSessionEvent, { type: "tool_execution_end" }>;
interface GhostOverlayLayout {
innerWidth: number;
frameHeight: number;
inputLines: string[];
transcriptRows: number;
transcriptLines: string[];
maxScroll: number;
}
export interface GhostOverlayOptions {
tui: TUI;
theme: ExtensionCommandContext["ui"]["theme"];
sessionCwd: string;
modelLabel: string;
maxHeight?: SizeValue;
margin?: OverlayMargin;
onSubmitMessage(text: string): void;
onHideOverlay(): void;
onCloseOverlay(): void;
}
export class GhostOverlayComponent implements Focusable {
private readonly transcriptContainer = new Container();
private readonly input = new Input();
private readonly tui: TUI;
private readonly theme: ExtensionCommandContext["ui"]["theme"];
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?: AssistantMessageComponent;
private pendingTools = new Map<string, ToolExecutionComponent>();
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.onCloseOverlay();
}
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.onHideOverlay();
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 UserMessageComponent(extractMessageText(message), getMarkdownTheme()),
);
this.setStatus("Thinking...");
this.markTranscriptChanged();
return;
}
if (message.role !== "assistant") return;
this.streamingComponent = new AssistantMessageComponent(undefined, false, getMarkdownTheme());
this.transcriptContainer.addChild(this.streamingComponent);
this.streamingComponent.updateContent(message);
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: string | Array<{ type: string; text?: string }> },
): string {
if (typeof message.content === "string") return message.content.trim();
return message.content
.filter((part): part is { type: "text"; text: string } =>
part.type === "text" && typeof part.text === "string"
)
.map((part) => part.text)
.join("\n")
.trim();
}
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 marginHeight(margin: OverlayMargin | undefined): number {
return Math.max(
DEFAULT_VERTICAL_MARGIN,
Math.max(0, margin?.top ?? 0) + Math.max(0, margin?.bottom ?? 0),
);
}