import { complete, type Message } from "@earendil-works/pi-ai"; import type { ExtensionCommandContext, ExtensionContext, SessionEntry, } from "@earendil-works/pi-coding-agent"; import { ANSWER_RE, MAX_SUGGESTIONS } from "./constants.js"; import type { QuestionItem } from "./types.js"; const QUESTION_PREFIX_RE = /^\s*(?:[-*+]\s+|\d+[.)]\s+|[A-Za-z][.)]\s+)/; const QUESTION_LABEL_RE = /^\s*(?:Q(?:uestion)?\s*[:.-]\s*)/i; const SUGGESTION_RE = /^\s*(?:[-*+]\s+|\d+[.)]\s+|[A-Za-z][.)]\s+|(?:Option|Answer|Choice)\s+[A-Za-z0-9]+\s*[:.)-]\s*)(.+?)\s*$/i; const QUESTION_WORD_RE = /^(?:should|do|does|did|can|could|would|will|which|what|when|where|why|how)\b/i; function safeDisplayText(text: string): string { return text .replace( /\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~]|\][^\x07]*(?:\x07|\x1B\\))/g, "", ) .replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F-\x9F]/g, " ") .replace(/\s+/g, " ") .trim(); } export const EXTRACTOR_PROMPT = `Extract questions and predefined answer suggestions from the assistant message. Return ONLY JSON with this shape: { "questions": [ { "question": "...", "suggestions": ["..."] } ] } Rules: - Keep order. - Preserve concise wording. - suggestions are only explicit predefined answers/options present in the text. - If no questions exist, return {"questions":[]}. - No markdown fences.`; export function textOfAssistant(entry: SessionEntry): string | undefined { if (entry.type !== "message") return undefined; const msg = entry.message; if (!("role" in msg) || msg.role !== "assistant") return undefined; return ( msg.content .filter((c): c is { type: "text"; text: string } => c.type === "text") .map((c) => c.text) .join("\n") .trim() || undefined ); } export function lastAssistant( ctx: ExtensionContext, ): { text: string; entryId: string } | undefined { const branch = ctx.sessionManager.getBranch(); for (let i = branch.length - 1; i >= 0; i--) { const text = textOfAssistant(branch[i]); if (text) return { text, entryId: branch[i].id }; } return undefined; } export function extractMarkedAnswer(text: string): string | undefined { let found: string | undefined; for (const match of text.matchAll(ANSWER_RE)) found = match[1]?.trim(); return found || undefined; } export function lastMarkedAnswer(ctx: ExtensionContext): string | undefined { const branch = ctx.sessionManager.getBranch(); for (let i = branch.length - 1; i >= 0; i--) { const answer = extractMarkedAnswer(textOfAssistant(branch[i]) ?? ""); if (answer) return answer; } return undefined; } export function unique(values: string[]): string[] { const seen = new Set(); const out: string[] = []; for (const value of values) { const key = value.toLowerCase(); if (seen.has(key)) continue; seen.add(key); out.push(value); } return out; } export function cleanQuestion(line: string): string { return safeDisplayText( line.replace(QUESTION_PREFIX_RE, "").replace(QUESTION_LABEL_RE, ""), ); } export function cleanSuggestion(line: string): string | undefined { const suggestion = safeDisplayText( line .match(SUGGESTION_RE)?.[1] ?.trim() .replace(/^"(.+)"$/, "$1") ?? "", ); return suggestion || undefined; } export function looksLikeQuestion(line: string): boolean { const cleaned = cleanQuestion(line); return cleaned.includes("?") || QUESTION_WORD_RE.test(cleaned); } export function heuristicExtract(text: string): QuestionItem[] { const questions: QuestionItem[] = []; let current: QuestionItem | undefined; for (const raw of text.split(/\r?\n/)) { const line = raw.trim(); if (!line) continue; const question = looksLikeQuestion(line) ? cleanQuestion(line) : undefined; if (question && question.length > 3) { current = { question, suggestions: [] }; questions.push(current); continue; } const suggestion = cleanSuggestion(line); if (suggestion && current && !looksLikeQuestion(suggestion)) current.suggestions.push(suggestion); } return questions.map((q) => ({ ...q, suggestions: unique(q.suggestions).slice(0, MAX_SUGGESTIONS), })); } function authFailureMessage(auth: { ok: boolean }, provider: string): string { return auth.ok ? `No API key for ${provider}` : "auth failed"; } function parseExtractorJson(raw: string): QuestionItem[] { const json = raw.match(/\{[\s\S]*\}/)?.[0] ?? raw; const parsed = JSON.parse(json) as { questions?: Array<{ question?: unknown; suggestions?: unknown }>; }; return (parsed.questions ?? []) .map((q) => ({ question: typeof q.question === "string" ? safeDisplayText(q.question) : "", suggestions: Array.isArray(q.suggestions) ? unique( q.suggestions .filter((s): s is string => typeof s === "string") .map(safeDisplayText) .filter(Boolean), ).slice(0, MAX_SUGGESTIONS) : [], })) .filter((q) => q.question.length > 0); } export async function llmExtract( ctx: ExtensionCommandContext, text: string, ): Promise { if (!ctx.model) throw new Error("No model selected"); const auth = await ctx.modelRegistry.getApiKeyAndHeaders(ctx.model); if (!auth.ok || !auth.apiKey) throw new Error(authFailureMessage(auth, ctx.model.provider)); const userMessage: Message = { role: "user", content: [{ type: "text", text }], timestamp: Date.now(), }; const response = await complete( ctx.model, { systemPrompt: EXTRACTOR_PROMPT, messages: [userMessage] }, { apiKey: auth.apiKey, headers: auth.headers, signal: ctx.signal, reasoning: "low", cacheRetention: "none", }, ); const raw = response.content .filter((c): c is { type: "text"; text: string } => c.type === "text") .map((c) => c.text) .join("\n") .trim(); try { return parseExtractorJson(raw); } catch (err) { throw new Error( `LLM extractor returned invalid JSON: ${(err as Error).message}`, ); } }