Luigit
repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by admin

extensions/lsp/index.ts

Raw
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
import { Type } from "typebox";
import { closeDebug, dbg } from "./src/debug.ts";
import { defineIntegerSetting, resolveSetting } from "./src/pi-ext-settings.ts";
import { bounded, LspFailure } from "./src/source.ts";
import type { Service } from "./src/tool.ts";

const TIMEOUT = defineIntegerSetting({
	key: "lsp.timeoutMs",
	label: "Query timeout",
	description:
		"Whole-call deadline in milliseconds; invalid configuration fails the query.",
	range: { min: 100, max: 60000 },
	default: 15000,
	env: "PI_LSP_TIMEOUT_MS",
});

export default function lsp(pi: ExtensionAPI): void {
	let service: Promise<Service> | undefined;
	let stopped = false;
	const active = new Set<AbortController>();
	pi.on("session_start", () => {
		dbg?.("session.start");
	});
	pi.on("session_shutdown", async () => {
		stopped = true;
		for (const controller of active)
			controller.abort(
				new LspFailure("cancelled", "cancelled: Session shutdown."),
			);
		try {
			await (await service)?.close();
		} finally {
			dbg?.("session.shutdown");
			await closeDebug();
		}
	});
	pi.registerTool({
		name: "lsp",
		label: "LSP",
		description:
			"Semantic definition, references, hover, type_definition, implementations, document_symbols, workspace_symbols, one-hop incoming_calls/outgoing_calls through installed Go/TypeScript/C++ language servers. Ambiguous calls return candidate selection tokens; retry same query with selection. Symbols need no position; workspace_symbols needs query and server. Disk files authoritative; one-based line, Unicode-scalar column. No installation, edits or command execution. Freshness/readiness/completeness unknown; snippets not server-revision-verified.",
		parameters: Type.Object(
			{
				operation: Type.Union([
					Type.Literal("definition"),
					Type.Literal("references"),
					Type.Literal("hover"),
					Type.Literal("type_definition"),
					Type.Literal("implementations"),
					Type.Literal("document_symbols"),
					Type.Literal("workspace_symbols"),
					Type.Literal("incoming_calls"),
					Type.Literal("outgoing_calls"),
				]),
				file: Type.Optional(Type.String({ minLength: 1, maxLength: 4096 })),
				line: Type.Optional(Type.Integer({ minimum: 1 })),
				column: Type.Optional(Type.Integer({ minimum: 1 })),
				selection: Type.Optional(
					Type.String({
						minLength: 1,
						maxLength: 64,
						description:
							"Opaque call candidate token; repeat same file/position/workspace/server. Expires on source/config/session changes or after 5 minutes.",
					}),
				),
				query: Type.Optional(Type.String({ maxLength: 256 })),
				server: Type.Optional(Type.String({ minLength: 1, maxLength: 64 })),
				workspace: Type.Optional(
					Type.String({
						minLength: 1,
						maxLength: 4096,
						description:
							"Explicit workspace root; otherwise discover profile root markers within Pi cwd. Multiple roots require workspace.",
					}),
				),
				timeout_ms: Type.Optional(
					Type.Integer({ minimum: 100, maximum: 60000 }),
				),
				max_results: Type.Optional(Type.Integer({ minimum: 1, maximum: 100 })),
				max_bytes: Type.Optional(
					Type.Integer({ minimum: 2048, maximum: 32768 }),
				),
			},
			{ additionalProperties: false },
		),
		async execute(_id, input, signal, _update, ctx) {
			const controller = new AbortController();
			const cancel = () =>
				controller.abort(
					new LspFailure("cancelled", "cancelled: Query cancelled."),
				);
			signal?.addEventListener("abort", cancel, { once: true });
			if (signal?.aborted || stopped) cancel();
			active.add(controller);
			let timer: ReturnType<typeof setTimeout> | undefined;
			try {
				const setting = resolveSetting(pi, ctx, TIMEOUT);
				if (!setting.ok) throw new Error(`invalid_config: ${setting.error}`);
				const timeout = input.timeout_ms ?? setting.value;
				for (const [name, value, min, max] of [
					["timeout_ms", timeout, 100, 60000],
					["max_results", input.max_results ?? 50, 1, 100],
					["max_bytes", input.max_bytes ?? 16384, 2048, 32768],
				] as const) {
					if (!Number.isSafeInteger(value) || value < min || value > max)
						throw new Error(`invalid_input: ${name} outside supported bounds.`);
				}
				timer = setTimeout(
					() =>
						controller.abort(
							new LspFailure(
								"timeout",
								"timeout: Whole-call deadline exceeded.",
							),
						),
					timeout,
				);
				if (controller.signal.aborted) throw controller.signal.reason;
				service ??= import("./src/tool.ts").then(
					({ Service }) => new Service(),
				);
				const runtime = await bounded(service, controller.signal);
				if (controller.signal.aborted) throw controller.signal.reason;
				const result = await runtime.query(input, ctx.cwd, controller.signal);
				if (
					Buffer.byteLength(JSON.stringify(result)) > (input.max_bytes ?? 16384)
				)
					throw new LspFailure(
						"resource_limit",
						"resource_limit: Result metadata exceeds output budget.",
					);
				dbg?.("query.finish", { ok: result.status === "ok" });
				return {
					content: [{ type: "text", text: JSON.stringify(result) }],
					details: result,
					isError: !["ok", "no_result"].includes(result.status),
				};
			} catch (error) {
				const message = (
					error instanceof Error ? error.message : "server_failure"
				).slice(0, 512);
				const status =
					[
						"cancelled",
						"timeout",
						"invalid_config",
						"invalid_input",
						"resource_limit",
					].find((value) => message.startsWith(`${value}:`)) ??
					"server_failure";
				const result = {
					status,
					operation: input.operation,
					server: input.server ?? "unselected",
					scope: ctx.cwd.length <= 128 ? ctx.cwd : "omitted: output budget",
					message,
					readiness: "unknown",
					workspaceFreshness: "unknown",
					serverCompleteness: "unknown",
					serverReportedLimits: "not_reported",
					sourceRevision: "not_server_revision_verified",
					toolTruncated: false,
					interruptedPartialResponse:
						status === "cancelled" || status === "timeout",
					items: [],
				};
				dbg?.("query.finish", { ok: false });
				return {
					content: [{ type: "text", text: JSON.stringify(result) }],
					details: result,
					isError: true,
				};
			} finally {
				if (timer) clearTimeout(timer);
				signal?.removeEventListener("abort", cancel);
				active.delete(controller);
			}
		},
	});
}