Luigit
repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by admin

extensions/pipi/live.ts

Raw
import type { AssistantMessage } from "@earendil-works/pi-ai";
import {
	type AgentSession,
	type AgentSessionEvent,
	AssistantMessageComponent,
	getMarkdownTheme,
	type Theme,
	ToolExecutionComponent,
} from "@earendil-works/pi-coding-agent";
import {
	type Component,
	sliceByColumn,
	stripTerminalSequences,
	type TUI,
} from "@earendil-works/pi-tui";
import { collapsedPreview, type KeyHints, safe } from "./render.ts";

// Retain foreground styling, never child backgrounds or terminal commands.
function safeRenderedLine(line: string): string {
	// Self-framed renderers (notably edit) paint backgrounds even without a shell.
	return line
		.replace(/\u001b\[(?:4[0-9]|10[0-7]|48;(?:5;\d+|2;\d+;\d+;\d+))m/gu, "")
		.split(/(\u001b\[[0-9;:]*m)/u)
		.map((part) =>
			/^\u001b\[[0-9;:]*m$/u.test(part)
				? part
				: safe(part, Number.MAX_SAFE_INTEGER),
		)
		.join("");
}

/** One live child activity; never persisted with tool result details. */
export class LiveTaskPreview implements Component {
	private assistant: AssistantMessageComponent | undefined;
	private tool:
		| { id: string; component: ToolExecutionComponent; finished: boolean }
		| undefined;
	private readonly activeTools = new Map<
		string,
		{ id: string; component: ToolExecutionComponent; finished: boolean }
	>();
	private current: Component | undefined;
	private lastVisible: Component | undefined;
	private expanded = false;
	private hideThinking?: boolean;
	private theme?: Theme;
	private hints: KeyHints | undefined;
	private status = "Starting child task…";

	constructor(
		private readonly host: () => TUI | undefined,
		private readonly thinkingHidden: () => boolean,
	) {}

	configure(expanded: boolean, theme: Theme, hints?: KeyHints): this {
		this.theme = theme;
		this.hints = hints;
		try {
			if (this.expanded !== expanded) {
				this.expanded = expanded;
				for (const tool of this.activeTools.values())
					tool.component.setExpanded(expanded);
				if (this.tool?.finished) this.tool.component.setExpanded(expanded);
			}
		} catch {
			this.dispose();
			this.status = "Preview unavailable";
		}
		return this;
	}

	update(event: AgentSessionEvent, child: AgentSession): boolean {
		if (
			(event.type === "message_start" ||
				event.type === "message_update" ||
				event.type === "message_end") &&
			event.message.role === "assistant"
		) {
			if (event.type === "message_start" || !this.assistant) {
				this.assistant = new AssistantMessageComponent(
					undefined,
					this.thinkingHidden(),
					getMarkdownTheme(),
					undefined,
					0,
					child.extensionRunner.getMarkdownTransformers(),
				);
			}
			const message: AssistantMessage = {
				...event.message,
				content: event.message.content.map((part) =>
					part.type === "text"
						? { ...part, text: safe(part.text, Number.MAX_SAFE_INTEGER) }
						: part.type === "thinking"
							? {
									...part,
									thinking: safe(part.thinking, Number.MAX_SAFE_INTEGER),
								}
							: part,
				),
				...(event.message.errorMessage
					? {
							errorMessage: safe(
								event.message.errorMessage,
								Number.MAX_SAFE_INTEGER,
							),
						}
					: {}),
			};
			const useful =
				message.content.some(
					(part) =>
						(part.type === "text" && part.text.trim()) ||
						(part.type === "thinking" &&
							part.thinking.trim() &&
							(!this.thinkingHidden() || !this.current)),
				) ||
				message.stopReason === "error" ||
				message.stopReason === "aborted" ||
				message.stopReason === "length";
			if (!useful) return false;
			this.assistant.updateContent(message, event.type !== "message_end");
			this.releaseTools();
			this.current = this.assistant;
			return true;
		}
		if (event.type === "tool_execution_start") {
			const host = this.host();
			if (!host) return false;
			const renderers = child.extensionRunner.resolveToolRenderers(
				event.toolName,
				() => child.getToolDefinition(event.toolName),
			);
			const component = new ToolExecutionComponent(
				event.toolName,
				event.toolCallId,
				event.args,
				{ showImages: false, outputPad: 0 },
				// PiPi owns the outer shell; keep native content without a second box.
				{ ...renderers, renderShell: "self" },
				host,
				child.sessionManager.getCwd(),
			);
			component.setExpanded(this.expanded);
			component.setArgsComplete();
			component.markExecutionStarted();
			this.assistant = undefined;
			this.tool = { id: event.toolCallId, component, finished: false };
			this.activeTools.set(event.toolCallId, this.tool);
			this.current = component;
			return true;
		}
		if (
			event.type === "tool_execution_update" ||
			event.type === "tool_execution_end"
		) {
			const tool = this.activeTools.get(event.toolCallId);
			if (!tool) return false;
			if (event.type === "tool_execution_update") {
				tool.component.updateResult(
					{ ...event.partialResult, isError: false },
					true,
				);
				this.tool = tool;
			} else {
				tool.component.updateResult({
					...event.result,
					isError: event.isError,
				});
				tool.finished = true;
				this.activeTools.delete(event.toolCallId);
				this.tool = [...this.activeTools.values()].at(-1) ?? tool;
			}
			this.tool.component.setExpanded(this.expanded);
			this.current = this.tool.component;
			return true;
		}
		return false;
	}

	render(width: number): string[] {
		if (width <= 0) return [];
		try {
			return this.renderContent(width);
		} catch {
			this.dispose();
			this.status = "Preview unavailable";
			return this.expanded
				? [sliceByColumn(this.status, 0, width, true)]
				: collapsedPreview([this.status], width, this.hints);
		}
	}

	private renderContent(width: number): string[] {
		const hidden = this.thinkingHidden();
		if (this.hideThinking !== hidden) {
			this.hideThinking = hidden;
			for (const component of new Set([
				this.assistant,
				this.current,
				this.lastVisible,
			])) {
				if (component instanceof AssistantMessageComponent)
					component.setHideThinkingBlock(hidden);
			}
		}
		// Also removes nested assistant shell-integration markers before cropping.
		const render = (component: Component | undefined) => {
			const lines = (component?.render(width) ?? []).map(safeRenderedLine);
			while (lines.length && !stripTerminalSequences(lines[0] ?? "").trim())
				lines.shift();
			while (lines.length && !stripTerminalSequences(lines.at(-1) ?? "").trim())
				lines.pop();
			return lines;
		};
		let lines = render(this.current);
		if (lines.length) this.lastVisible = this.current;
		else if (this.lastVisible !== this.current)
			lines = render(this.lastVisible);
		if (!lines.length)
			lines = [this.theme?.fg("muted", safe(this.status)) ?? safe(this.status)];
		return this.expanded
			? lines.map((line) => sliceByColumn(line, 0, width, true))
			: collapsedPreview(lines, width, this.hints);
	}

	invalidate(): void {
		try {
			this.current?.invalidate();
		} catch {
			this.dispose();
			this.status = "Preview unavailable";
		}
	}

	private releaseTools(): void {
		// Finalize abandoned native rows so their partial-result timers stop.
		for (const tool of this.activeTools.values()) {
			try {
				tool.component.updateResult({ content: [], isError: true });
			} catch {
				/* Broken child renderers are nonfatal. */
			}
		}
		this.activeTools.clear();
		this.tool = undefined;
	}

	dispose(): void {
		this.releaseTools();
		this.assistant = undefined;
		this.current = undefined;
		this.lastVisible = undefined;
	}
}