Luigit
repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by admin

extensions/lsp/src/tool.ts

Raw
import { realpath, stat } from "node:fs/promises";
import { resolve } from "node:path";
import { Client, type Operation } from "./client.ts";
import { executable, profile } from "./registry.ts";
import { base, type Evidence, normalize, safeText } from "./result.ts";
import { bounded, check, LspFailure, target } from "./source.ts";

async function workspaceRoot(cwd: string, workspace?: string): Promise<string> {
	const root = await realpath(resolve(cwd, workspace ?? "."));
	if (!(await stat(root)).isDirectory())
		throw new LspFailure("invalid_input", "Workspace must be a directory.");
	return root;
}

export interface Query {
	operation: Operation;
	file?: string;
	line?: number;
	column?: number;
	query?: string;
	server?: string;
	selection?: string;
	workspace?: string;
	timeout_ms?: number;
	max_results?: number;
	max_bytes?: number;
}

export class Service {
	private readonly clients = new Map<string, Client>();
	private stopped = false;
	private active = 0;

	async query(
		input: Query,
		cwd: string,
		signal: AbortSignal,
	): Promise<Evidence> {
		let scope = cwd;
		let server = input.server ?? "unselected";
		let client: Client | undefined;
		let reserved = false;
		try {
			check(signal);
			if (this.stopped)
				throw new LspFailure("cancelled", "Session shutting down.");
			if (this.active >= 2)
				throw new LspFailure(
					"resource_limit",
					"At most two active lsp calls; retry after current calls settle.",
				);
			this.active++;
			reserved = true;
			if (
				![
					"definition",
					"references",
					"hover",
					"type_definition",
					"implementations",
					"document_symbols",
					"workspace_symbols",
					"incoming_calls",
					"outgoing_calls",
				].includes(input.operation)
			)
				throw new LspFailure("unsupported", "Unsupported lsp operation.");
			const symbols =
				input.operation === "workspace_symbols" ||
				input.operation === "document_symbols";
			if (
				!symbols &&
				(!Number.isSafeInteger(input.line) ||
					(input.line ?? 0) < 1 ||
					!Number.isSafeInteger(input.column) ||
					(input.column ?? 0) < 1)
			)
				throw new LspFailure(
					"invalid_input",
					"Position queries require positive one-based line and column.",
				);
			if (
				input.operation === "workspace_symbols" &&
				(typeof input.query !== "string" || input.query.length > 256)
			)
				throw new LspFailure(
					"invalid_input",
					"workspace_symbols requires query (≤256 characters).",
				);
			if (input.operation !== "workspace_symbols" && !input.file)
				throw new LspFailure("invalid_input", "file is required.");
			const config = await bounded(profile(input.file, input.server), signal);
			const selected =
				input.operation === "workspace_symbols"
					? { file: "", root: await workspaceRoot(cwd, input.workspace) }
					: await bounded(
							target(cwd, input.file ?? "", input.workspace, config.roots),
							signal,
						);
			scope = selected.root;
			server = config.id;
			const launch = await bounded(executable(config.command), signal);
			check(signal);
			// Identity includes the effective executable, never project launch overrides.
			const key = JSON.stringify([scope, config, launch]);
			client = this.clients.get(key);
			if (client?.dead) {
				await bounded(client.close(), signal);
				if (this.clients.get(key) === client) this.clients.delete(key);
				client = this.clients.get(key);
			}
			check(signal);
			if (this.stopped)
				throw new LspFailure("cancelled", "Session shutting down.");
			if (!client) {
				if (this.clients.size >= 2)
					throw new LspFailure(
						"resource_limit",
						"Two workspace/config sessions already owned; restart Pi session to release them.",
					);
				client = new Client(scope, config, launch);
				this.clients.set(key, client);
			}
			if (client.busy) {
				client = undefined;
				throw new LspFailure(
					"resource_limit",
					"Workspace already has an active request; retry after it settles.",
				);
			}
			client.busy = true;
			const owned = client;
			const work = (async () => {
				const raw = await owned.query(
					input.operation,
					selected.file,
					input.line ?? 0,
					input.column ?? 0,
					signal,
					input.query,
					input.selection,
				);
				check(signal);
				return normalize(
					owned,
					input.operation,
					selected.file,
					raw,
					input.max_results ?? 50,
					input.max_bytes ?? 16384,
					signal,
				);
			})();
			const result = await bounded(work, signal);
			check(signal);
			return result;
		} catch (error) {
			if (
				client &&
				(signal.aborted ||
					!(error instanceof LspFailure) ||
					![
						"unsupported",
						"invalid_input",
						"resource_limit",
						"stale_selection",
					].includes(error.status))
			)
				void client.close();
			const failure = base(input.operation, scope);
			failure.server = server;
			const actual = signal.aborted ? signal.reason : error;
			failure.status =
				actual instanceof LspFailure
					? actual.status
					: ["ENOENT", "ENOTDIR", "EISDIR", "EACCES"].includes(
								(actual as NodeJS.ErrnoException)?.code ?? "",
							)
						? "invalid_input"
						: "server_failure";
			failure.message = safeText(
				actual instanceof Error ? actual.message : "Unknown server failure",
			).slice(0, 512);
			failure.interruptedPartialResponse =
				failure.status === "cancelled" || failure.status === "timeout";
			return failure;
		} finally {
			if (client) client.busy = false;
			if (reserved) this.active--;
		}
	}

	async close(): Promise<void> {
		this.stopped = true;
		const results = await Promise.allSettled(
			[...this.clients.values()].map((client) => client.close()),
		);
		const failed = results.find((result) => result.status === "rejected");
		if (failed?.status === "rejected") throw failed.reason;
		this.clients.clear();
	}
}