repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

extensions/q/extract.ts

Raw
File outline
import { complete, type Message } from "@earendil-works/pi-ai";
import type {
	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;
const CHOICE_HEADING_RE =
	/^\s*(?:options|choices|possible answers?|decision|pick one|choose one)\s*[::]\s*$/i;
const LABELLED_INLINE_CHOICE_RE =
	/(?:^|[,;:]\s*|\bor\s+)([A-Z])[.)]?\s+([^,?]+?)(?=\s*,\s*[A-Z][.)]?\s+|\s*,?\s+or\s+[A-Z][.)]?\s+|[?;]|$)/g;
const PAREN_CHOICE_RE = /\(([^()]{1,160})\)/g;
const BINARY_QUESTION_RE =
	/^(?:approve|confirm|proceed|continue|cancel|abort|should (?:i|we)|shall (?:i|we)|want me to|do you want me to|can i)\b/i;
const MAX_QUESTION_CHARS = 500;
const INTERNAL_NOTE_RE = /^(?:Need|Maybe|But|Cross platform|Wait|So)\b/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\x1B]|\u200B|\u200C|\u200D|\uFEFF|\u00A0| {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 textOfAssistantMessage(msg: unknown): string | undefined {
	if (typeof msg !== "object" || msg === null || !("role" in msg))
		return undefined;
	if (msg.role !== "assistant" || !("content" in msg)) return undefined;
	if (!Array.isArray(msg.content)) return undefined;
	return (
		msg.content
			.filter(
				(c): c is { type: "text"; text: string } =>
					typeof c === "object" &&
					c !== null &&
					"type" in c &&
					c.type === "text" &&
					"text" in c &&
					typeof c.text === "string",
			)
			.map((c) => c.text)
			.join("\n")
			.trim() || undefined
	);
}

export function textOfAssistant(entry: SessionEntry): string | undefined {
	if (entry.type !== "message") return undefined;
	return textOfAssistantMessage(entry.message);
}

export function lastAssistant(
	ctx: ExtensionContext,
): { text: string; entryId: string; stopReason?: string } | undefined {
	const branch = ctx.sessionManager.getBranch();
	for (let i = branch.length - 1; i >= 0; i--) {
		const entry = branch[i];
		const text = textOfAssistant(entry);
		if (!text) continue;
		const stopReason =
			entry.type === "message" &&
			"stopReason" in entry.message &&
			typeof entry.message.stopReason === "string"
				? entry.message.stopReason
				: undefined;
		return { text, entryId: entry.id, stopReason };
	}
	return undefined;
}

// S4: get last marked answer via exec loop
export function extractMarkedAnswer(text: string): string | undefined {
	let last: string | undefined;
	for (let match = ANSWER_RE.exec(text); match; match = ANSWER_RE.exec(text))
		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<string>();
	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;
}

function inlineSuggestions(question: string): string[] {
	const labelled = labelledChoices(question);
	return unique([
		...parenthesizedChoices(question),
		...labelled,
		...(labelled.length > 0 ? [] : simpleOrChoices(question)),
		...binaryChoices(question),
	]);
}

function parenthesizedChoices(question: string): string[] {
	const out: string[] = [];
	for (
		let match = PAREN_CHOICE_RE.exec(question);
		match;
		match = PAREN_CHOICE_RE.exec(question)
	) {
		const body = match[1] ?? "";
		if (!/[|/]/.test(body) || /https?:|\.\.?\//i.test(body)) continue;
		const parts = body.split(/[|/]/).map(cleanInlineChoice).filter(Boolean);
		if (parts.length >= 2 && parts.length <= MAX_SUGGESTIONS)
			out.push(...parts);
	}
	return out;
}

function labelledChoices(question: string): string[] {
	const out: string[] = [];
	for (
		let match = LABELLED_INLINE_CHOICE_RE.exec(question);
		match;
		match = LABELLED_INLINE_CHOICE_RE.exec(question)
	) {
		const choice = cleanInlineChoice(match[2] ?? "");
		if (choice) out.push(choice);
	}
	return out.length >= 2 ? out : [];
}

function simpleOrChoices(question: string): string[] {
	const stripped = question.replace(/[?؟?⸮]\s*$/, "");
	if (/https?:|\//i.test(stripped)) return [];
	const parts = stripped.split(/\s+or\s+/i);
	if (parts.length !== 2) return [];
	const leftRaw = cleanInlineChoice(parts[0] ?? "");
	if (
		/^(?:apply to|use|choose|pick|select|keep|take|go with|set|switch to)$/i.test(
			leftRaw,
		)
	)
		return [];
	const left = leftRaw.replace(
		/^(?:apply to|use|choose|pick|select|keep|take|go with|set|switch to)\s+/i,
		"",
	);
	const right = cleanInlineChoice(parts[1] ?? "");
	return left && right ? [left, right] : [];
}

function binaryChoices(question: string): string[] {
	return BINARY_QUESTION_RE.test(question) ? ["yes", "no"] : [];
}

function hasQuestionSignal(line: string): boolean {
	let depth = 0;
	let inInlineCode = false;
	const chars = [...line];
	for (let index = 0; index < chars.length; index++) {
		const char = chars[index] ?? "";
		if (char === "`") {
			inInlineCode = !inInlineCode;
			continue;
		}
		if (inInlineCode) continue;
		if (char === "(") {
			depth++;
			continue;
		}
		if (char === ")" && depth > 0) {
			depth--;
			continue;
		}
		if (depth === 0 && QUESTION_MARK_RE.test(char)) {
			const tail = chars.slice(index + 1).join("");
			if (/^\s*["'”’]?\s*→/.test(tail)) continue;
			if (/^\s*!/.test(tail)) continue;
			if (/^\s*\//.test(tail)) continue;
			return true;
		}
	}
	return false;
}

function cleanInlineChoice(choice: string): string {
	return safeDisplayText(
		choice
			.replace(/[?؟?⸮]\s*$/, "")
			.replace(/^['"`]|['"`]$/g, "")
			.replace(/\s+/g, " "),
	);
}

function collectSuggestionBlock(
	lines: string[],
	startIndex: number,
): { suggestions: string[]; nextIndex: number } {
	const suggestions: string[] = [];
	let index = startIndex;
	for (; index < lines.length; index++) {
		const line = lines[index]?.replace(/\r$/, "").trim() ?? "";
		if (!line) continue;
		const suggestion = cleanSuggestion(line);
		if (!suggestion || hasQuestionMark(suggestion)) break;
		suggestions.push(suggestion);
	}
	return { suggestions, nextIndex: index };
}

/** 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[] {
	if (INTERNAL_NOTE_RE.test(text.trim())) return [];
	const questions: QuestionItem[] = [];
	let current: QuestionItem | undefined;
	let inFence = false;
	let pendingSuggestions: string[] = [];
	const lines = text.split("\n");

	for (let index = 0; index < lines.length; index++) {
		const line = lines[index]?.replace(/\r$/, "").trim() ?? "";
		if (FENCE_RE.test(line)) {
			inFence = !inFence;
			continue;
		}
		if (inFence) continue;
		if (!line || TABLE_LINE_RE.test(line)) continue;

		if (!current && CHOICE_HEADING_RE.test(line)) {
			const block = collectSuggestionBlock(lines, index + 1);
			if (block.suggestions.length >= 2) {
				current = {
					question: "Choose an option?",
					suggestions: block.suggestions,
				};
				questions.push(current);
				index = block.nextIndex - 1;
				pendingSuggestions = [];
				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 &&
				/[\p{L}\p{N}]/u.test(question) &&
				question.length <= MAX_QUESTION_CHARS &&
				!INTERNAL_NOTE_RE.test(question) &&
				hasQuestionSignal(question)
			) {
				const suggestions = inlineSuggestions(question);
				if (!current && pendingSuggestions.length >= 2)
					suggestions.push(...pendingSuggestions);
				current = { question, suggestions };
				questions.push(current);
				pendingSuggestions = [];
				continue;
			}
		}

		const suggestion = cleanSuggestion(line);
		if (suggestion && !hasQuestionMark(suggestion)) {
			if (current) current.suggestions.push(suggestion);
			else pendingSuggestions.push(suggestion);
			continue;
		}
		if (!current) pendingSuggestions = [];
	}

	// Deduplicate and cap suggestions
	for (const question of questions) {
		question.suggestions = unique(question.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: ExtensionContext,
	text: string,
	modelRef?: string,
	signal?: AbortSignal,
): Promise<QuestionItem[]> {
	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) throw new Error(auth.error ?? "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: 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);
}