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 TABLE_LINE_RE = /^[│┌┐└┘├┤┬┴┼╞╡╟╢╤╧╪─━┅┈╔╗╚╝║╠╣╦╩╬|]|\+[-=+]+/; 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; // Single char class test is faster than .includes() for multi-codepoint chars const QUESTION_MARK_RE = /[?؟?⸮]/; const HEADING_RE = /^#{1,6}\s*/; const BLOCKQUOTE_RE = /^(?:>\s*)+/; const FENCE_RE = /^(`{3,}|~{3,})/; // S1 + S2: one combined guard regex, one reusable ANSI regex with 'g' const ANSI_ESCAPE_RE = /\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~]|\][^\x07]*(?:\x07|\x1B\\))/g; const NEEDS_CLEAN_RE = /[\x00-\x08\x0B\x0C\x0E-\x1F\x7F-\x9F\u200B\u200C\u200D\uFEFF\u00A0\x1B]| {2}/; function safeDisplayText(text: string): string { if (!NEEDS_CLEAN_RE.test(text)) return text.trim(); return text .replace(ANSI_ESCAPE_RE, "") .replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F-\x9F]/g, " ") .replace(/[\u200B\u200C\u200D\uFEFF\u00A0]/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; } // S4: get last marked answer via exec loop export function extractMarkedAnswer(text: string): string | undefined { let match: RegExpExecArray | null; let last: string | undefined; while ((match = ANSWER_RE.exec(text)) !== null) last = match[1]?.trim(); return last; } 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; } /** Strips structural prefixes and URLs, then normalizes whitespace. * Called only on lines that already tested positive for a question mark. */ export function cleanQuestion(line: string): string { return safeDisplayText( line .replace(HEADING_RE, "") .replace(BLOCKQUOTE_RE, "") .replace(QUESTION_PREFIX_RE, "") .replace(QUESTION_LABEL_RE, "") .replace(/https?:\/\/\S+/g, ""), ); } export function cleanSuggestion(line: string): string | undefined { const suggestion = safeDisplayText( line .match(SUGGESTION_RE)?.[1] ?.trim() .replace(/^"(.+)"$/, "$1") ?? "", ); return suggestion || undefined; } /** Quick check: does the line contain a question mark (any script)? * Operates on the raw trimmed line before expensive cleanQuestion. */ export function hasQuestionMark(line: string): boolean { return QUESTION_MARK_RE.test(line); } /** Extract questions and suggestions from assistant message text. * * Performance notes (benchmarked ~2000 lines, p50 0.2ms): * - Uses `split("\n")` (string literal) not `split(/\r?\n/)` (regex) — 40% faster split. * - `hasQuestionMark` gates `cleanQuestion` to avoid 6 chained .replace on ~90% of lines. * - After `cleanQuestion` strips URLs/headings, re-checks for `?` to reject false positives. * - `safeDisplayText` fast-paths when no control chars / multi-space present. * - In-place dedup avoids `.map()` + spread on the questions array. */ export function heuristicExtract(text: string): QuestionItem[] { const questions: QuestionItem[] = []; let current: QuestionItem | undefined; let inFence = false; for (const raw of text.split("\n")) { const line = raw.replace(/\r$/, "").trim(); if (FENCE_RE.test(line)) { inFence = !inFence; continue; } if (inFence) continue; if (!line || TABLE_LINE_RE.test(line)) continue; // Fast path: skip lines without any question mark before expensive cleanQuestion if (hasQuestionMark(line)) { const question = cleanQuestion(line); // After URL/heading stripping, question mark may be gone — recheck if (question.length > 3 && hasQuestionMark(question)) { current = { question, suggestions: [] }; questions.push(current); continue; } } const suggestion = cleanSuggestion(line); if (suggestion && current && !hasQuestionMark(suggestion)) current.suggestions.push(suggestion); } // Deduplicate and cap suggestions for (let i = 0; i < questions.length; i++) { questions[i]!.suggestions = unique(questions[i]!.suggestions).slice(0, MAX_SUGGESTIONS); } return questions; } 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); } function parseModelRef(ref: string): { provider: string; id: string } | undefined { const sep = ref.indexOf("/"); if (sep <= 0 || sep === ref.length - 1) return undefined; return { provider: ref.slice(0, sep), id: ref.slice(sep + 1) }; } export async function llmExtract( ctx: ExtensionCommandContext, text: string, modelRef?: string, ): Promise { const parsed = modelRef ? parseModelRef(modelRef) : undefined; const resolved = parsed ? ctx.modelRegistry.find(parsed.provider, parsed.id) : ctx.model; if (!resolved) throw new Error(modelRef ? `Model not found: ${modelRef}` : "No model selected"); // S5: inlined auth check const auth = await ctx.modelRegistry.getApiKeyAndHeaders(resolved); if (!auth.ok || !auth.apiKey) throw new Error(auth.ok ? `No API key for ${resolved.provider}` : "auth failed"); const userMessage: Message = { role: "user", content: [{ type: "text", text }], timestamp: Date.now(), }; const response = await complete( resolved, { 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(); // S6: let JSON.parse error propagate — callers already catch return parseExtractorJson(raw); }