Luigit
repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by admin

extensions/lsp/src/result.ts

Raw
import {
	DocumentSymbol,
	Hover,
	Location,
	LocationLink,
	MarkedString,
	MarkupContent,
	Range,
} from "vscode-languageserver-protocol/node.js";
import { type Client, callItem, type Operation } from "./client.ts";
import {
	convertRange,
	LspFailure,
	localPath,
	snapshot,
	sourceLine,
	uri,
} from "./source.ts";

export interface Evidence {
	status: string;
	operation: string;
	server: string;
	scope: string;
	readiness: "unknown";
	workspaceFreshness: "unknown";
	serverCompleteness: "unknown";
	serverReportedLimits: "not_reported";
	sourceRevision: "not_server_revision_verified";
	toolTruncated: boolean;
	interruptedPartialResponse: boolean;
	items: unknown[];
	hover?: string;
	range?: unknown;
	message?: string;
}

export function base(operation: string, scope: string): Evidence {
	return {
		status: "ok",
		operation,
		server: "gopls",
		scope,
		readiness: "unknown",
		workspaceFreshness: "unknown",
		serverCompleteness: "unknown",
		serverReportedLimits: "not_reported",
		sourceRevision: "not_server_revision_verified",
		toolTruncated: false,
		interruptedPartialResponse: false,
		items: [],
	};
}

export function safeText(value: string): string {
	return value.replace(/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/gu, "");
}

export async function normalize(
	client: Client,
	operation: Operation,
	file: string,
	raw: unknown,
	maxResults: number,
	maxBytes: number,
	signal: AbortSignal,
): Promise<Evidence> {
	signal.throwIfAborted();
	const output = base(operation, client.root);
	output.server = client.config?.id ?? "gopls";
	if (raw === null || (Array.isArray(raw) && raw.length === 0)) {
		output.status = "no_result";
		return output;
	}
	if (operation === "incoming_calls" || operation === "outgoing_calls") {
		const value = raw as {
			phase?: string;
			candidates?: { item: unknown; selection: string }[];
			item?: unknown;
			relationships?: unknown[];
		};
		if (value?.phase === "prepare_no_result") {
			output.status = "no_result";
			output.message = "No prepared target; readiness unknown.";
			return output;
		}
		if (value?.phase === "ambiguous" && Array.isArray(value.candidates)) {
			output.status = "ambiguous";
			output.message =
				"Repeat same file/position/workspace/server with candidate selection; tokens expire after 5 minutes or source/config/session changes.";
			output.toolTruncated = value.candidates.length > maxResults;
			for (const candidate of value.candidates.slice(0, maxResults)) {
				if (!callItem(candidate.item))
					throw new LspFailure("server_failure", "Malformed call candidate.");
				const item = candidate.item;
				const location = await normalize(
					client,
					"definition",
					file,
					{ uri: item.uri, range: item.selectionRange },
					1,
					maxBytes,
					signal,
				);
				output.toolTruncated ||= location.toolTruncated;
				if (!location.items.length) continue;
				output.items.push({
					name: safeText(item.name).slice(0, 256),
					kind: item.kind,
					selection: candidate.selection,
					...(location.items[0] as object),
				});
			}
		} else if (
			value?.phase === "relationships" &&
			callItem(value.item) &&
			Array.isArray(value.relationships)
		) {
			output.message = value.relationships.length
				? "One-hop server relationships; not a runtime call graph."
				: "Prepared target succeeded; server found no relationships.";
			output.toolTruncated = value.relationships.length > maxResults;
			let siteBudget = maxResults;
			for (const rawEdge of value.relationships.slice(0, maxResults)) {
				const edge = rawEdge as {
					from?: unknown;
					to?: unknown;
					fromRanges?: unknown[];
				};
				const target = operation === "incoming_calls" ? edge?.from : edge?.to;
				if (!callItem(target) || !Array.isArray(edge.fromRanges))
					throw new LspFailure(
						"server_failure",
						"Malformed call relationship.",
					);
				const location = await normalize(
					client,
					"definition",
					file,
					{ uri: target.uri, range: target.selectionRange },
					1,
					maxBytes,
					signal,
				);
				output.toolTruncated ||= location.toolTruncated;
				if (!location.items.length) continue;
				const owner = operation === "incoming_calls" ? target : value.item;
				const ranges = edge.fromRanges.slice(0, siteBudget);
				if (!ranges.every((range) => Range.is(range)))
					throw new LspFailure("server_failure", "Malformed call-site range.");
				const sites = ranges.length
					? await normalize(
							client,
							"references",
							file,
							ranges.map((range) => ({ uri: owner.uri, range })),
							siteBudget,
							maxBytes,
							signal,
						)
					: undefined;
				siteBudget -= ranges.length;
				output.toolTruncated ||=
					edge.fromRanges.length > ranges.length || !!sites?.toolTruncated;
				output.items.push({
					name: safeText(target.name).slice(0, 256),
					kind: target.kind,
					...(location.items[0] as object),
					callSites: sites?.items ?? [],
				});
			}
		} else throw new LspFailure("server_failure", "Malformed call result.");
	} else if (operation === "hover") {
		if (!Hover.is(raw))
			throw new LspFailure("server_failure", "Malformed hover response.");
		const contents = Array.isArray(raw.contents)
			? raw.contents
			: [raw.contents];
		if (contents.length > 128) output.toolTruncated = true;
		output.hover = contents
			.slice(0, 128)
			.map((content) => {
				if (typeof content === "string") return safeText(content);
				if (MarkupContent.is(content) || MarkedString.is(content))
					return safeText(content.value);
				throw new LspFailure("server_failure", "Malformed hover content.");
			})
			.join("\n");
		if (!output.hover) output.status = "no_result";
		if (raw.range)
			output.range = convertRange(
				await snapshot(file, signal),
				raw.range,
				client.encoding,
			);
	} else {
		const symbols =
			operation === "document_symbols" || operation === "workspace_symbols";
		const metadata: { name: string; kind: number; qualifiedName: string }[] =
			[];
		let locations = Array.isArray(raw) ? raw : [raw];
		if (symbols) {
			if (!Array.isArray(raw))
				throw new LspFailure("server_failure", "Malformed symbol response.");
			locations = [];
			const stack = [{ items: raw, index: 0, parent: "" }];
			while (stack.length && locations.length <= maxResults) {
				const frame = stack[stack.length - 1];
				if (!frame) break;
				if (frame.index >= frame.items.length) {
					stack.pop();
					continue;
				}
				const item = frame.items[frame.index++];
				if (operation === "document_symbols" && DocumentSymbol.is(item)) {
					const qualifiedName = frame.parent
						? frame.parent + "." + item.name
						: item.name;
					locations.push({ uri: uri(file), range: item.selectionRange });
					metadata.push({
						name: safeText(item.name).slice(0, 256),
						kind: item.kind,
						qualifiedName: safeText(qualifiedName).slice(0, 512),
					});
					if (item.children?.length) {
						if (stack.length >= 64) {
							output.toolTruncated = true;
							break;
						}
						stack.push({
							items: item.children,
							index: 0,
							parent: qualifiedName.slice(0, 512),
						});
					}
				} else if (
					item &&
					typeof item.name === "string" &&
					Number.isInteger(item.kind) &&
					item.kind >= 1 &&
					item.kind <= 26 &&
					item.location &&
					typeof item.location.uri === "string" &&
					(item.containerName === undefined ||
						typeof item.containerName === "string")
				) {
					locations.push(item.location);
					metadata.push({
						name: safeText(item.name).slice(0, 256),
						kind: item.kind,
						qualifiedName: safeText(
							item.containerName
								? item.containerName + "." + item.name
								: item.name,
						).slice(0, 512),
					});
				} else
					throw new LspFailure("server_failure", "Malformed symbol response.");
			}
		}
		output.toolTruncated ||= locations.length > maxResults;
		// Count each JSON-encoded item once, retaining exact UTF-8 envelope/comma costs.
		let bytes = Buffer.byteLength(JSON.stringify(output));
		const append = (item: Record<string, unknown>): boolean => {
			const added =
				Buffer.byteLength(JSON.stringify(item)) + (output.items.length ? 1 : 0);
			if (bytes + added > maxBytes) {
				output.toolTruncated = true;
				return false;
			}
			output.items.push(item);
			bytes += added;
			return true;
		};
		let index = 0;
		// One bounded, query-local snapshot; never retain source between queries.
		let source: { path: string; text: string } | undefined;
		for (const item of locations.slice(0, maxResults)) {
			const meta = metadata[index++];
			if (
				symbols &&
				item &&
				typeof item === "object" &&
				"uri" in item &&
				!("range" in item)
			) {
				if (
					!append({
						...meta,
						file: localPath(String(item.uri)),
						range: null,
						locationUnresolved: true,
					})
				)
					break;
				continue;
			}
			if (!Location.is(item) && !LocationLink.is(item))
				throw new LspFailure("server_failure", "Malformed location response.");
			const path = localPath("targetUri" in item ? item.targetUri : item.uri);
			const range =
				"targetUri" in item ? item.targetSelectionRange : item.range;
			signal.throwIfAborted();
			let text = source?.path === path ? source.text : undefined;
			if (text === undefined) {
				try {
					text = await snapshot(path, signal);
					source = { path, text };
				} catch (error) {
					signal.throwIfAborted();
					if (error instanceof LspFailure && error.status !== "invalid_input")
						throw error;
				}
			}
			signal.throwIfAborted();
			const context =
				text === undefined
					? {
							range: null,
							snippet: null,
							sourceUnavailable: true,
							serverRange: range,
							serverPositionEncoding: client.encoding,
						}
					: {
							range: convertRange(text, range, client.encoding),
							snippet: safeText(
								(sourceLine(text, range.start.line) ?? "").slice(0, 240),
							),
						};
			if (text !== undefined) await client.remember(path);
			signal.throwIfAborted();
			if (!append({ ...meta, file: path, ...context })) break;
		}
	}
	while (Buffer.byteLength(JSON.stringify(output)) > maxBytes) {
		output.toolTruncated = true;
		if (output.hover && output.hover.length > 1)
			output.hover = output.hover.slice(0, Math.floor(output.hover.length / 2));
		else if (output.items.length) output.items.pop();
		else
			throw new LspFailure(
				"resource_limit",
				"Result metadata exceeds output budget.",
			);
	}
	return output;
}