import { randomUUID } from "node:crypto"; import type { ExtensionAPI, ExtensionCommandContext, ExtensionContext, } 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, } 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"; function sendAnswerWith(pi: ExtensionAPI): SendAnswer { return (answer) => pi.sendUserMessage([{ type: "text", text: answer }]); } const NO_QUESTIONS_MESSAGES = [ "🐾 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; function randomItem(items: readonly string[]): string { return items[Math.floor(Math.random() * items.length)] ?? items[0] ?? ""; } function randomNoQuestionsMessage(): string { return randomItem(NO_QUESTIONS_MESSAGES); } 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: ExtensionCommandContext, text: string, ): Promise { const questions = heuristicExtract(text); if (questions.length === 0) return []; if (questions.every((q) => q.suggestions.length > 0)) return questions; const extracted = await llmExtract(ctx, text); return mergeSuggestions(questions, extracted); } 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(); } async function startQ( _args: string, ctx: ExtensionCommandContext, sendAnswer: SendAnswer, ) { if (!ctx.hasUI) return ctx.ui.notify("/q requires interactive mode", "error"); await ctx.waitForIdle(); const assistant = lastAssistant(ctx); if (!assistant) return ctx.ui.notify("No assistant message found", "error"); let questions: Awaited>; try { questions = await extractQuestions(ctx, assistant.text); } catch (err) { 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: ExtensionCommandContext, 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") 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 ..., 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\nconcise answer here\n\n\nDo not use 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 ... or /b ", "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 { 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) }; }); pi.registerCommand("q", { description: "Answer question suggestions from last assistant message", handler: (args, ctx) => startQ(args, ctx, sendAnswerWith(pi)), }); pi.registerCommand("b", { description: "Return answer from /q discussion fork. Usage: /b, /b edit, /b ", 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 };