repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

extensions/tldr/index.ts

Raw
File outline
import type {
	Model,
	ProviderHeaders,
	UserMessage,
} from "@earendil-works/pi-ai";
import {
	type ExtensionAPI,
	type ExtensionContext,
	SettingsManager,
} from "@earendil-works/pi-coding-agent";

type TldrSettings = {
	model?: string;
};

type TimerScheduler = {
	setTimeout(callback: () => void, delayMs: number): unknown;
	clearTimeout(handle: unknown): void;
};

type GenerateTldr = typeof import("@earendil-works/pi-ai/compat").complete;

const generateTldr: GenerateTldr = async (...args) =>
	(await import("@earendil-works/pi-ai/compat")).complete(...args);

type TldrPriority = "immediate" | "normal" | "final";

type TldrActivityType =
	| "user"
	| "assistant_update"
	| "tool_call"
	| "tool_start"
	| "tool_update"
	| "tool_end"
	| "tool_result"
	| "assistant_final"
	| "assistant_failure";

type TldrActivity = {
	index: number;
	type: TldrActivityType;
	priority: TldrPriority;
	text: string;
};

type TldrCheckpoint = {
	index: number;
	text: string;
};

type TldrModelRef = {
	provider: string;
	id: string;
};

type TldrAuth = {
	model: Model<any>;
	apiKey?: string;
	headers?: ProviderHeaders;
};

type TldrEngineOptions = {
	facts: FactCollector;
	generate?: GenerateTldr;
	scheduler?: TimerScheduler;
	configuredModelRef?: string;
};

const WIDGET_KEY = "tldr";
const TLDR_ICON = "󰦩";
const STATUS_UNAVAILABLE = "tldr unavailable";
const DEFAULT_MAX_ACTIVITIES = 128;
const DEFAULT_MAX_ACTIVITY_CHARS = 1_500;
const MAX_TLDR_CHARS = 160;
const MAX_CONTEXT_CHECKPOINTS = 6;
const NORMAL_COALESCE_MS = 350;
const TLDR_MAX_TOKENS = 120;
const TLDR_TIMEOUT_MS = 2_000;
const IN_PROGRESS_TENSE = "Start with a present-tense -ing verb.";
const COMPLETED_TENSE = "Start with a past-tense verb.";

function tldrSystemPrompt(tenseInstruction: string): string {
	return `Write one plain-English TLDR for a Pi coding agent.
Use the prior TLDRs for context and the new activity for the update.
Describe the work progress as if a human developer were doing it.
Focus on the task activity and current outcome, not agent mechanics.
Do not mention tools, tool calls, prompts, messages, model output, or implementation details.
Summarize only activity up to the requested index.
If context is sparse, still summarize the available activity.
Never ask for more information or say there is not enough context.
Return exactly one complete sentence under 80 characters.
Use third person. Do not address the user.
Plain text only; no markdown, JSON, code, bullets, quotes, or file/tool names.
${tenseInstruction}`;
}

const ANSI_RE =
	/\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~]|\][^\x07]*(?:\x07|\x1B\\))/g;
const CONTROL_RE = /[\x00-\x1F\x7F-\x9F]/g;

const defaultScheduler: TimerScheduler = {
	setTimeout(callback, delayMs) {
		return setTimeout(callback, delayMs);
	},
	clearTimeout(handle) {
		clearTimeout(handle as ReturnType<typeof setTimeout>);
	},
};

function isRecord(value: unknown): value is Record<string, unknown> {
	return value !== null && typeof value === "object" && !Array.isArray(value);
}

function textFromContent(content: unknown): string {
	if (typeof content === "string") return content;
	if (!Array.isArray(content)) return "";
	return content
		.map((part) =>
			isRecord(part) && part.type === "text" && typeof part.text === "string"
				? part.text
				: "",
		)
		.filter(Boolean)
		.join("\n");
}

function formatPayload(value: unknown): string {
	if (value === undefined || value === null) return "";
	if (typeof value === "string") return value;
	if (isRecord(value)) {
		const content = textFromContent(value.content);
		if (content) return content;
		if (typeof value.text === "string") return value.text;
	}
	try {
		return JSON.stringify(value) ?? String(value);
	} catch {
		return String(value);
	}
}

function truncateChars(text: string, maxChars: number): string {
	const chars = Array.from(text);
	if (chars.length <= maxChars) return text;
	if (maxChars <= 1) return "…";
	return `${chars.slice(0, maxChars - 1).join("")}…`;
}

function sanitizeTldrText(text: string, maxChars = MAX_TLDR_CHARS): string {
	return truncateChars(
		text
			.replace(ANSI_RE, "")
			.replace(CONTROL_RE, " ")
			.replace(/\s+/g, " ")
			.trim(),
		maxChars,
	);
}

function wrapText(text: string, width: number): string[] {
	const lines: string[] = [];
	let current = "";

	for (const word of text.split(" ")) {
		let rest = word;
		while (Array.from(rest).length > width) {
			if (current) {
				lines.push(current);
				current = "";
			}
			const chars = Array.from(rest);
			lines.push(chars.slice(0, width).join(""));
			rest = chars.slice(width).join("");
		}
		if (!rest) continue;

		const candidate = current ? `${current} ${rest}` : rest;
		if (Array.from(candidate).length <= width) {
			current = candidate;
		} else {
			if (current) lines.push(current);
			current = rest;
		}
	}

	if (current) lines.push(current);
	return lines.length ? lines : [""];
}

function boxLines(text: string, terminalWidth = 80): string[] {
	const safe = sanitizeTldrText(text);
	if (!safe) return [];
	const contentWidth = Math.max(1, terminalWidth - 4);
	return wrapText(safe, contentWidth).map(
		(line, index) => `${index === 0 ? TLDR_ICON : " "}  ${line}`,
	);
}

function showTldr(ctx: ExtensionContext, text: string): void {
	if (!ctx.hasUI) return;
	const safe = sanitizeTldrText(text);
	if (!safe) {
		clearTldr(ctx);
		return;
	}
	ctx.ui.setWidget(WIDGET_KEY, ((_tui: any, _theme: any) => ({
		render(width: number): string[] {
			return boxLines(safe, width);
		},
	})) as any);
}

function clearTldr(ctx: ExtensionContext): void {
	if (!ctx.hasUI) return;
	ctx.ui.setWidget(WIDGET_KEY, undefined);
}

function settingsFrom(cwd = process.cwd()): TldrSettings {
	const manager = SettingsManager.create(cwd);
	const global = manager.getGlobalSettings() as Record<string, unknown>;
	const project = manager.getProjectSettings() as Record<string, unknown>;
	const tldr = {
		...(isRecord(global.tldr) ? global.tldr : {}),
		...(isRecord(project.tldr) ? project.tldr : {}),
	};
	return {
		model:
			typeof tldr.model === "string" && tldr.model.trim()
				? tldr.model.trim()
				: undefined,
	};
}

function parseModelRef(value: string | undefined): TldrModelRef | undefined {
	const trimmed = value?.trim() ?? "";
	const separator = trimmed.indexOf("/");
	if (separator <= 0 || separator === trimmed.length - 1) return undefined;
	return {
		provider: trimmed.slice(0, separator),
		id: trimmed.slice(separator + 1),
	};
}

async function authForModel(
	ctx: ExtensionContext,
	model: Model<any> | undefined,
): Promise<TldrAuth | undefined> {
	if (!model) return undefined;
	const auth = await ctx.modelRegistry.getApiKeyAndHeaders(model);
	return auth.ok
		? { model, apiKey: auth.apiKey, headers: auth.headers }
		: undefined;
}

async function resolveTldrModel(
	ctx: ExtensionContext,
	modelRef: string | undefined,
): Promise<TldrAuth | undefined> {
	const parsed = parseModelRef(modelRef);
	if (parsed) {
		const configured = ctx.modelRegistry.find(parsed.provider, parsed.id);
		const configuredAuth = await authForModel(ctx, configured);
		if (configuredAuth) return configuredAuth;
	}
	return authForModel(ctx, ctx.model);
}

class FactCollector {
	private nextIndex = 1;
	private readonly activities: TldrActivity[] = [];
	constructor(
		private readonly maxActivities = DEFAULT_MAX_ACTIVITIES,
		private readonly maxActivityChars = DEFAULT_MAX_ACTIVITY_CHARS,
	) {}

	private add(
		type: TldrActivityType,
		priority: TldrPriority,
		text: string,
	): TldrActivity {
		const activity = {
			index: this.nextIndex++,
			type,
			priority,
			text: truncateChars(
				sanitizeTldrText(text, this.maxActivityChars),
				this.maxActivityChars,
			),
		};
		this.activities.push(activity);
		if (this.activities.length > this.maxActivities)
			this.activities.splice(0, this.activities.length - this.maxActivities);
		return activity;
	}

	reset(): void {
		this.nextIndex = 1;
		this.activities.splice(0);
	}

	recordUser(prompt: string): TldrActivity {
		return this.add("user", "immediate", `User asked: ${prompt}`);
	}
	recordAssistantUpdate(message: unknown): TldrActivity | undefined {
		const text = textFromContent(
			isRecord(message) ? message.content : undefined,
		);
		return text
			? this.add("assistant_update", "normal", `Assistant draft: ${text}`)
			: undefined;
	}
	recordToolCall(toolName: string, input: unknown): TldrActivity {
		return this.add(
			"tool_call",
			"normal",
			`Preparing ${toolName}: ${formatPayload(input)}`,
		);
	}
	recordToolStart(toolName: string, input: unknown): TldrActivity {
		return this.add(
			"tool_start",
			"normal",
			`Running ${toolName}: ${formatPayload(input)}`,
		);
	}
	recordToolUpdate(toolName: string, update: unknown): TldrActivity {
		return this.add(
			"tool_update",
			"normal",
			`Still running ${toolName}: ${formatPayload(update)}`,
		);
	}
	recordToolEnd(
		toolName: string,
		isError: boolean,
		result: unknown,
	): TldrActivity {
		return this.add(
			"tool_end",
			"normal",
			`${toolName} ${isError ? "failed" : "finished"}: ${formatPayload(result)}`,
		);
	}
	recordToolResult(
		toolName: string,
		isError: boolean,
		content: unknown,
	): TldrActivity {
		return this.add(
			"tool_result",
			"normal",
			`${toolName} ${isError ? "errored" : "returned"}: ${textFromContent(content) || formatPayload(content)}`,
		);
	}
	recordFinal(text: string): TldrActivity {
		return this.add(
			"assistant_final",
			"final",
			`Assistant final response: ${text}`,
		);
	}
	recordFailure(reason: string): TldrActivity {
		return this.add(
			"assistant_failure",
			"final",
			`Assistant failed: ${reason}`,
		);
	}

	activitiesAfter(
		previousIndex: number,
		throughIndex: number,
	): readonly TldrActivity[] {
		return this.activities.filter(
			(activity) =>
				activity.index > previousIndex && activity.index <= throughIndex,
		);
	}

	discardThrough(index: number): void {
		const keepFrom = this.activities.findIndex(
			(activity) => activity.index > index,
		);
		if (keepFrom === -1) this.activities.splice(0);
		else if (keepFrom > 0) this.activities.splice(0, keepFrom);
	}
}

function usesCompletedTense(type: TldrActivityType): boolean {
	return (
		type === "tool_end" ||
		type === "tool_result" ||
		type === "assistant_final" ||
		type === "assistant_failure"
	);
}

function buildTldrPrompt(
	activities: readonly TldrActivity[],
	checkpoints: readonly TldrCheckpoint[],
	throughIndex: number,
): { systemPrompt: string; message: UserMessage } {
	const previous = checkpoints.length
		? checkpoints
				.slice(-MAX_CONTEXT_CHECKPOINTS)
				.map(
					(checkpoint) =>
						`- Through activity ${checkpoint.index}: ${checkpoint.text}`,
				)
				.join("\n")
		: "none";
	const raw = activities
		.map((activity) => `[${activity.index}] ${activity.type}: ${activity.text}`)
		.join("\n");
	const lastActivity = activities.at(-1);
	const tense =
		lastActivity && usesCompletedTense(lastActivity.type)
			? COMPLETED_TENSE
			: IN_PROGRESS_TENSE;
	return {
		systemPrompt: tldrSystemPrompt(tense),
		message: {
			role: "user",
			content: [
				{
					type: "text",
					text: [
						"Previous generated TLDR checkpoints:",
						previous,
						"",
						"New raw activity since the latest accepted checkpoint:",
						raw,
						"",
						`Write the next TLDR through activity ${throughIndex}.`,
					].join("\n"),
				},
			],
			timestamp: Date.now(),
		},
	};
}

class TldrEngine {
	private runId = 0;
	private latestAcceptedIndex = 0;
	private inFlight: { index: number; runId: number } | undefined;
	private readonly queue: Array<{
		index: number;
		priority: TldrPriority;
		runId: number;
	}> = [];
	private readonly checkpoints: TldrCheckpoint[] = [];
	private pendingNormal:
		| { index: number; priority: TldrPriority; runId: number }
		| undefined;
	private normalTimer: unknown;
	private readonly facts: FactCollector;
	private readonly generate: GenerateTldr;
	private readonly scheduler: TimerScheduler;
	private readonly configuredModelRef?: string;

	constructor(options: TldrEngineOptions) {
		this.facts = options.facts;
		this.generate = options.generate ?? generateTldr;
		this.scheduler = options.scheduler ?? defaultScheduler;
		this.configuredModelRef = options.configuredModelRef;
	}

	startFreshRun(ctx?: ExtensionContext): void {
		this.runId++;
		this.latestAcceptedIndex = 0;
		this.queue.splice(0);
		this.checkpoints.splice(0);
		this.inFlight = undefined;
		this.clearNormalTimer();
		if (ctx) clearTldr(ctx);
	}

	enqueue(ctx: ExtensionContext, activity: TldrActivity): void {
		if (!ctx.hasUI) return;
		const job = {
			index: activity.index,
			priority: activity.priority,
			runId: this.runId,
		};
		if (activity.priority === "normal") {
			this.pendingNormal = job;
			this.clearNormalTimer();
			this.normalTimer = this.scheduler.setTimeout(() => {
				this.normalTimer = undefined;
				const pending = this.pendingNormal;
				this.pendingNormal = undefined;
				if (!pending || pending.runId !== this.runId) return;
				this.queue.splice(0, this.queue.length, pending);
				this.pump(ctx);
			}, NORMAL_COALESCE_MS);
			return;
		}
		this.clearNormalTimer();
		this.pendingNormal = undefined;
		if (activity.priority === "immediate") this.queue.splice(0);
		this.queue.push(job);
		this.pump(ctx);
	}

	private clearNormalTimer(): void {
		if (this.normalTimer === undefined) return;
		this.scheduler.clearTimeout(this.normalTimer);
		this.normalTimer = undefined;
	}

	private pump(ctx: ExtensionContext): void {
		if (this.inFlight) return;
		const job = this.queue.shift();
		if (!job) return;
		if (job.runId !== this.runId || job.index <= this.latestAcceptedIndex) {
			this.pump(ctx);
			return;
		}
		this.inFlight = { index: job.index, runId: job.runId };
		void this.generateCheckpoint(ctx, job);
	}

	private async generateCheckpoint(
		ctx: ExtensionContext,
		job: { index: number; priority: TldrPriority; runId: number },
	): Promise<void> {
		try {
			const activities = this.facts.activitiesAfter(
				this.latestAcceptedIndex,
				job.index,
			);
			if (activities.length === 0) return;
			const auth = await resolveTldrModel(ctx, this.configuredModelRef);
			if (!this.isCurrent(job)) return;
			if (!auth) {
				showTldr(ctx, STATUS_UNAVAILABLE);
				return;
			}
			const prompt = buildTldrPrompt(activities, this.checkpoints, job.index);
			const response = await this.generate(
				auth.model,
				{ systemPrompt: prompt.systemPrompt, messages: [prompt.message] },
				{
					apiKey: auth.apiKey,
					headers: auth.headers,
					maxTokens: TLDR_MAX_TOKENS,
					maxRetries: 0,
					cacheRetention: "none",
					timeoutMs: TLDR_TIMEOUT_MS,
					signal: ctx.signal,
				},
			);
			if (!this.isCurrent(job)) return;
			if (response.stopReason !== "stop") return;
			const text = sanitizeTldrText(textFromContent(response.content));
			if (!text) return;
			this.latestAcceptedIndex = job.index;
			this.checkpoints.push({ index: job.index, text });
			if (this.checkpoints.length > MAX_CONTEXT_CHECKPOINTS)
				this.checkpoints.splice(
					0,
					this.checkpoints.length - MAX_CONTEXT_CHECKPOINTS,
				);
			this.facts.discardThrough(job.index);
			showTldr(ctx, text);
		} catch {
			// Best effort. Later activity can recover.
		} finally {
			if (
				this.inFlight?.index === job.index &&
				this.inFlight.runId === job.runId
			)
				this.inFlight = undefined;
			this.pump(ctx);
		}
	}

	private isCurrent(job: { index: number; runId: number }): boolean {
		return (
			this.inFlight?.index === job.index &&
			this.inFlight.runId === job.runId &&
			job.runId === this.runId
		);
	}
}

function assistantEndActivity(
	facts: FactCollector,
	message: unknown,
): TldrActivity | undefined {
	if (!isRecord(message)) return undefined;
	const stopReason =
		typeof message.stopReason === "string" ? message.stopReason : "";
	if (stopReason === "toolUse") return undefined;
	if (stopReason === "stop") {
		const text = textFromContent(message.content);
		return text ? facts.recordFinal(text) : undefined;
	}
	return stopReason
		? facts.recordFailure(
				typeof message.errorMessage === "string"
					? message.errorMessage
					: stopReason,
			)
		: undefined;
}

function registerTldrCommand(
	pi: ExtensionAPI,
	state: { enabled: boolean; settings: TldrSettings; engine: TldrEngine },
): void {
	pi.registerCommand("tldr", {
		description: "Toggle live TLDR widget",
		handler: async (args, ctx) => {
			const action = args.trim().toLowerCase();
			if (action === "status") {
				ctx.ui.notify(
					`tldr ${state.enabled ? "on" : "off"}\nmodel: ${state.settings.model ?? "current"}`,
					"info",
				);
				return;
			}
			if (action === "help") {
				ctx.ui.notify("/tldr [on|off|toggle|status|help]", "info");
				return;
			}
			if (action === "on") state.enabled = true;
			else if (action === "off") state.enabled = false;
			else state.enabled = !state.enabled;
			if (!state.enabled) clearTldr(ctx);
			ctx.ui.notify(`tldr ${state.enabled ? "on" : "off"}`, "info");
		},
	});
}

function createTldrExtension(
	deps: { generate?: GenerateTldr; scheduler?: TimerScheduler } = {},
) {
	return function tldrExtension(pi: ExtensionAPI) {
		const facts = new FactCollector();
		const settings = settingsFrom();
		const engine = new TldrEngine({
			facts,
			generate: deps.generate,
			scheduler: deps.scheduler,
			configuredModelRef: settings.model,
		});
		const state = { enabled: true, settings, engine };

		const maybe = (
			ctx: ExtensionContext,
			activity: TldrActivity | undefined,
		) => {
			if (!state.enabled || !activity) return;
			engine.enqueue(ctx, activity);
		};

		registerTldrCommand(pi, state);

		pi.on("session_start", (_event, ctx) => {
			facts.reset();
			engine.startFreshRun(ctx);
		});
		pi.on("session_shutdown", (_event, ctx) => {
			facts.reset();
			engine.startFreshRun(ctx);
		});
		pi.on("before_agent_start", (event, ctx) => {
			facts.reset();
			engine.startFreshRun(ctx);
			maybe(ctx, facts.recordUser(event.prompt));
		});
		pi.on("message_update", (event, ctx) =>
			maybe(ctx, facts.recordAssistantUpdate(event.message)),
		);
		pi.on("tool_call", (event, ctx) =>
			maybe(ctx, facts.recordToolCall(event.toolName, event.input)),
		);
		pi.on("tool_execution_start", (event, ctx) =>
			maybe(ctx, facts.recordToolStart(event.toolName, event.args)),
		);
		pi.on("tool_execution_update", (event, ctx) =>
			maybe(ctx, facts.recordToolUpdate(event.toolName, event.partialResult)),
		);
		pi.on("tool_execution_end", (event, ctx) =>
			maybe(
				ctx,
				facts.recordToolEnd(event.toolName, event.isError, event.result),
			),
		);
		pi.on("tool_result", (event, ctx) =>
			maybe(
				ctx,
				facts.recordToolResult(event.toolName, event.isError, event.content),
			),
		);
		pi.on("message_end", (event, ctx) =>
			maybe(ctx, assistantEndActivity(facts, event.message)),
		);
	};
}

export { createTldrExtension };
export const __test = {
	FactCollector,
	TldrEngine,
	sanitizeTldrText,
	buildTldrPrompt,
	parseModelRef,
	resolveTldrModel,
	boxLines,
	settingsFrom,
};
export default createTldrExtension();