repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

extensions/q/index.ts

Raw
File outline
import { randomUUID } from "node:crypto";
import {
	BorderedLoader,
	type ExtensionAPI,
	type ExtensionCommandContext,
	type ExtensionContext,
	SettingsManager,
} from "@earendil-works/pi-coding-agent";
import { truncateToWidth } from "@earendil-works/pi-tui";
import { DISCUSSION_WIDGET_ID, RETURN_FAILURE_CHOICES } from "./constants.js";
import { openEditor } from "./editor.js";
import {
	heuristicExtract,
	lastAssistant,
	lastMarkedAnswer,
	llmExtract,
	textOfAssistantMessage,
} from "./extract.js";
import {
	appendCustom,
	formatFinalAnswer,
	latestDiscussion,
	snapshot,
	validationErrors,
} from "./session-state.js";
import type {
	DiscussionEntryData,
	QuestionItem,
	ReturnPayload,
	SendAnswer,
	WizardState,
} from "./types.js";
import { runWizard } from "./wizard-ui.js";

type ExtractionOutcome =
	| { status: "ok"; questions: QuestionItem[] }
	| { status: "cancelled" }
	| { status: "error"; message: string };

function readSettings(cwd = process.cwd()): { model: string | undefined } {
	const manager = SettingsManager.create(cwd);
	const global = manager.getGlobalSettings() as Record<string, unknown>;
	const project = manager.getProjectSettings() as Record<string, unknown>;
	const q = {
		...(global.q && typeof global.q === "object" && !Array.isArray(global.q)
			? (global.q as Record<string, unknown>)
			: {}),
		...(project.q && typeof project.q === "object" && !Array.isArray(project.q)
			? (project.q as Record<string, unknown>)
			: {}),
	};
	return {
		model:
			typeof q.model === "string" && q.model.trim()
				? q.model.trim()
				: undefined,
	};
}

function randomNoQuestionsMessage(): string {
	const msgs = [
		"๐Ÿพ no questions found uwu โ€” paws empty",
		"๐Ÿซง no questions found uwu โ€” just vibes",
		"๐ŸŒธ no questions found uwu โ€” bloom later",
		"๐Ÿฆ no questions found uwu โ€” trash panda found nada",
		"โœจ no questions found uwu โ€” sparkle only",
	] as const;
	return msgs[Math.floor(Math.random() * msgs.length)];
}

function newWizardState(
	questions: QuestionItem[],
	sourceAssistantEntryId: string,
): WizardState {
	return {
		wizardId: randomUUID(),
		questions,
		answers: Array.from({ length: questions.length }, () => null),
		index: 0,
		sourceAssistantEntryId,
	};
}

async function extractQuestions(
	ctx: ExtensionContext,
	text: string,
	modelRef?: string,
): Promise<QuestionItem[]> {
	const questions = heuristicExtract(text);
	if (questions.length === 0) return [];
	if (questions.every((q) => q.suggestions.length > 0)) return questions;

	const extracted = await llmExtractWithLoader(ctx, text, modelRef);
	return mergeSuggestions(questions, extracted);
}

async function llmExtractWithLoader(
	ctx: ExtensionContext,
	text: string,
	modelRef?: string,
): Promise<QuestionItem[]> {
	const outcome = await ctx.ui.custom<ExtractionOutcome>(
		(tui, theme, _kb, done) => {
			const loader = new BorderedLoader(
				tui,
				theme,
				"Extracting answer suggestions...",
				{ cancellable: true },
			);
			let settled = false;
			const finish = (result: ExtractionOutcome) => {
				if (settled) return;
				settled = true;
				done(result);
			};
			loader.onAbort = () => finish({ status: "cancelled" });

			llmExtract(ctx, text, modelRef, loader.signal)
				.then((extracted) => finish({ status: "ok", questions: extracted }))
				.catch((err) => {
					if (loader.signal.aborted) finish({ status: "cancelled" });
					else finish({ status: "error", message: (err as Error).message });
				});
			return loader;
		},
	);

	if (outcome.status === "cancelled") throw new Error("cancelled");
	if (outcome.status === "error") throw new Error(outcome.message);
	return outcome.questions;
}

function mergeSuggestions(
	questions: QuestionItem[],
	extracted: QuestionItem[],
): QuestionItem[] {
	return questions.map((question, index) => ({
		...question,
		suggestions:
			question.suggestions.length > 0
				? question.suggestions
				: suggestionsFor(question, extracted, index),
	}));
}

function suggestionsFor(
	question: QuestionItem,
	extracted: QuestionItem[],
	index: number,
): string[] {
	const exact = extracted.find(
		(candidate) =>
			normalizeQuestion(candidate.question) ===
			normalizeQuestion(question.question),
	);
	return exact?.suggestions ?? extracted[index]?.suggestions ?? [];
}

function normalizeQuestion(question: string): string {
	return question.toLowerCase().replace(/\s+/g, " ").trim();
}

function notifyAvailableQuestions(ctx: ExtensionContext, text: string) {
	const count = heuristicExtract(text).length;
	if (count === 0) return;
	ctx.ui.notify(
		`Tip: press Alt+Q or run /q to render ${count} ${count === 1 ? "question" : "questions"}.`,
		"info",
	);
}

function hasWaitForIdle(
	ctx: ExtensionContext,
): ctx is ExtensionContext & Pick<ExtensionCommandContext, "waitForIdle"> {
	return typeof (ctx as { waitForIdle?: unknown }).waitForIdle === "function";
}

function hasFork(ctx: ExtensionContext): ctx is ExtensionCommandContext {
	return typeof (ctx as { fork?: unknown }).fork === "function";
}

async function startQ(
	_args: string,
	ctx: ExtensionContext,
	sendAnswer: SendAnswer,
	modelRef?: string,
) {
	if (!ctx.hasUI) return ctx.ui.notify("/q requires interactive mode", "error");
	if (hasWaitForIdle(ctx)) await ctx.waitForIdle();
	else if (!ctx.isIdle())
		return ctx.ui.notify(
			"Alt+Q requires idle agent; run /q after it stops",
			"warning",
		);

	const assistant = lastAssistant(ctx);
	if (!assistant) return ctx.ui.notify("No assistant message found", "error");
	if (assistant.stopReason && assistant.stopReason !== "stop")
		return ctx.ui.notify(
			`Last assistant message incomplete (${assistant.stopReason})`,
			"error",
		);

	let questions: Awaited<ReturnType<typeof extractQuestions>>;
	try {
		questions = await extractQuestions(ctx, assistant.text, modelRef);
	} catch (err) {
		if ((err as Error).message === "cancelled")
			return ctx.ui.notify("/q cancelled", "info");
		ctx.ui.notify(
			`question extraction failed: ${(err as Error).message}`,
			"error",
		);
		return;
	}
	if (questions.length === 0)
		return ctx.ui.notify(randomNoQuestionsMessage(), "info");

	await continueWizard(
		ctx,
		newWizardState(questions, assistant.entryId),
		sendAnswer,
	);
}

async function continueWizard(
	ctx: ExtensionContext,
	state: WizardState,
	sendAnswer: SendAnswer,
) {
	const result = await runWizard(ctx, state);
	if (result.type === "cancel") return ctx.ui.notify("/q cancelled", "info");
	if (result.type === "fork") {
		if (!hasFork(ctx))
			return ctx.ui.notify(
				"Discussion forks require /q; run /q to discuss.",
				"warning",
			);
		return forkForQuestion(ctx, result.state);
	}

	const answer = formatFinalAnswer(result.state);
	if (!answer) return ctx.ui.notify("Answer set incomplete", "warning");
	appendCustom(ctx, { kind: "q-wizard", status: "completed", ...result.state });
	ctx.ui.notify("sending answer", "info");
	await sendAnswer(answer);
}

async function forkForQuestion(
	ctx: ExtensionCommandContext,
	state: WizardState,
) {
	if (!ctx.sessionManager.getSessionFile())
		return ctx.ui.notify("/q fork requires a persisted session", "error");

	const questionIndex = state.index;
	const question = state.questions[questionIndex]?.question;
	if (!question)
		return ctx.ui.notify("No current question to discuss", "error");

	const pendingId = appendCustom(ctx, {
		kind: "q-wizard",
		status: "waiting-fork",
		...state,
	});
	const target = snapshot(ctx, pendingId);
	if (!target)
		return ctx.ui.notify("/q fork requires a persisted session", "error");
	const discussion: DiscussionEntryData = {
		kind: "q-discuss",
		...state,
		questionIndex,
		question,
		snapshot: target,
	};
	const result = await ctx.fork(pendingId, {
		position: "at",
		withSession: async (forkCtx) => {
			appendCustom(forkCtx, discussion);
			setDiscussionWidget(forkCtx, discussion);
			forkCtx.ui.notify(
				"Discuss answer. Ask the model to finish with <q-answer>...</q-answer>, then run /b.",
				"info",
			);
		},
	});
	if (result.cancelled) ctx.ui.notify("fork cancelled", "info");
}

function setDiscussionWidget(
	ctx: ExtensionContext,
	meta: DiscussionEntryData | undefined,
) {
	if (!meta) return ctx.ui.setWidget(DISCUSSION_WIDGET_ID, undefined);
	ctx.ui.setWidget(
		DISCUSSION_WIDGET_ID,
		(_tui, theme) => ({
			render(width: number) {
				const title = `q ${meta.questionIndex + 1}/${meta.questions.length}: ${meta.question}`;
				return [theme.fg("accent", truncateToWidth(title, width))];
			},
			invalidate() {},
		}),
		{ placement: "aboveEditor" },
	);
}

function discussionPrompt(meta: DiscussionEntryData): string {
	return `\n\nWe are discussing this question right now:\n\n${meta.question}\n\nGoal: output a concise answer to the question based on discussion. When you have the final answer, output exactly:\n\n<q-answer>\nconcise answer here\n</q-answer>\n\nDo not use <q-answer> for drafts.`;
}

async function returnFromFork(args: string, ctx: ExtensionCommandContext) {
	const meta = latestDiscussion(ctx);
	if (!meta) return ctx.ui.notify("not in a /q discussion fork", "warning");

	const answer = getReturnAnswer(args, ctx);
	if (!answer)
		return ctx.ui.notify(
			"no final answer. Use <q-answer>...</q-answer> or /b <answer>",
			"warning",
		);

	const payload: ReturnPayload = {
		...meta,
		answer,
		questionIndex: meta.questionIndex,
		snapshot: meta.snapshot,
	};
	const result = await ctx.switchSession(meta.snapshot.originalSessionFile, {
		withSession: async (originalCtx) => {
			await applyReturnedAnswer(originalCtx, payload, true, (finalAnswer) =>
				originalCtx.sendUserMessage([{ type: "text", text: finalAnswer }]),
			);
		},
	});
	if (result.cancelled) ctx.ui.notify("return cancelled", "info");
}

function getReturnAnswer(
	args: string,
	ctx: ExtensionCommandContext,
): string | undefined {
	const trimmed = args.trim();
	if (trimmed && trimmed !== "edit") return trimmed;

	const marked = lastMarkedAnswer(ctx);
	if (trimmed !== "edit") return marked;

	const draft = marked ?? lastAssistant(ctx)?.text;
	if (!draft) {
		ctx.ui.notify("no assistant answer to edit", "warning");
		return undefined;
	}
	const edited = openEditor(draft);
	if (!edited) ctx.ui.notify("editor cancelled or failed", "warning");
	return edited;
}

async function applyReturnedAnswer(
	ctx: ExtensionCommandContext,
	payload: ReturnPayload,
	validate: boolean,
	sendAnswer: SendAnswer,
) {
	if (validate && !(await validateReturn(ctx, payload))) return;

	const next = returnedWizardState(payload);
	appendCustom(ctx, {
		kind: "q-wizard",
		status: "active",
		...next,
		snapshot: payload.snapshot,
	});

	if (next.index < next.questions.length)
		return continueWizard(ctx, next, sendAnswer);
	appendCustom(ctx, {
		kind: "q-wizard",
		status: "completed",
		...next,
		snapshot: payload.snapshot,
	});
	const answer = formatFinalAnswer(next);
	if (!answer) return ctx.ui.notify("Answer set incomplete", "warning");
	await sendAnswer(answer);
}

async function validateReturn(
	ctx: ExtensionCommandContext,
	payload: ReturnPayload,
): Promise<boolean> {
	const errors = validationErrors(ctx, payload);
	if (errors.length === 0) return true;

	const choice = await ctx.ui.select(`q return blocked: ${errors.join(", ")}`, [
		...RETURN_FAILURE_CHOICES,
	]);
	if (choice === "put answer in editor") ctx.ui.setEditorText(payload.answer);
	return false;
}

function returnedWizardState(payload: ReturnPayload): WizardState {
	const answers = [...payload.answers];
	answers[payload.questionIndex] = payload.answer;
	return {
		wizardId: payload.wizardId,
		questions: payload.questions,
		answers,
		index: payload.questionIndex + 1,
		sourceAssistantEntryId: payload.sourceAssistantEntryId,
	};
}

export default function qExtension(pi: ExtensionAPI) {
	pi.on("session_start", (_event, ctx) =>
		setDiscussionWidget(ctx, latestDiscussion(ctx)),
	);
	pi.on("session_shutdown", (_event, ctx) =>
		ctx.ui.setWidget(DISCUSSION_WIDGET_ID, undefined),
	);
	pi.on("before_agent_start", (event, ctx) => {
		const meta = latestDiscussion(ctx);
		if (!meta) return;
		return { systemPrompt: event.systemPrompt + discussionPrompt(meta) };
	});

	const settings = readSettings();

	pi.on("message_end", (event, ctx) => {
		const text = textOfAssistantMessage(event.message);
		if (text) notifyAvailableQuestions(ctx, text);
	});

	pi.registerShortcut("alt+q", {
		description: "Answer question suggestions from last assistant message",
		handler: (ctx) =>
			startQ(
				"",
				ctx,
				(a) => pi.sendUserMessage([{ type: "text", text: a }]),
				settings.model,
			),
	});

	pi.registerCommand("q", {
		description: "Answer question suggestions from last assistant message",
		handler: (args, ctx) =>
			startQ(
				args,
				ctx,
				(a) => pi.sendUserMessage([{ type: "text", text: a }]),
				settings.model,
			),
	});

	pi.registerCommand("b", {
		description:
			"Return answer from /q discussion fork. Usage: /b, /b edit, /b <answer>",
		getArgumentCompletions(prefix) {
			return "edit".startsWith(prefix.trim())
				? [
						{
							value: "edit",
							label: "edit",
							description: "edit marked answer before returning",
						},
					]
				: null;
		},
		handler: returnFromFork,
	});
}

export type { ReturnPayload };
export { applyReturnedAnswer, returnedWizardState };