import path from "node:path"; import process from "node:process"; import { commandExists, commandPathValue } from "./command.js"; import { collectSupportedFiles, resolveRoot } from "./files.js"; import { lspAutoInstallEnabled } from "./lsp-install.js"; import type { LspServerAdapter } from "./types.js"; export type LspAction = "diagnostics" | "fix"; export interface DiagnosticRoute { adapter: LspServerAdapter; reason: string; files: string[]; } export interface DiagnosticRouteParams { root?: string; paths?: string[]; limit?: number; server?: string | string[]; /** Set to false to disable best-effort auto-install of missing servers. */ autoInstall?: boolean; } export const SUPPORTED_SERVER_DESCRIPTION = "Supported LSP servers are defined by pi-lsp config and selected by file extension."; export function selectDiagnosticRoutes( adapters: LspServerAdapter[], params: DiagnosticRouteParams, defaultLimit: number, ) { const root = resolveRoot(params.root); const candidates = filterAdapters(adapters, params.server); const skipped: DiagnosticRoute[] = []; const runnableCandidates = params.server ? candidates : candidates.filter((adapter) => { if (!adapter.isDefault) return true; // Auto-installable servers stay runnable: the install attempt happens // in withLspClient, and failure surfaces as that lane's honest error. if (lspAutoInstallEnabled(adapter, params.autoInstall)) return true; const command = adapter.defaultCommand; if (commandExists(command.command, root, commandPathValue(adapter.env))) return true; skipped.push({ adapter, reason: `${adapter.name} command missing`, files: [], }); return false; }); const filesByPolicy = new Map(); const routes = runnableCandidates .map((adapter) => { const key = diagnosticFilePolicyKey(adapter); let files = filesByPolicy.get(key); if (!files) { files = collectSupportedFiles( adapter, root, params.paths, params.limit ?? defaultLimit, ); filesByPolicy.set(key, files); } return { adapter, reason: `${adapter.name} diagnostics`, files }; }) .filter((route) => route.files.length > 0); if (routes.length === 0 && skipped.length === 0) { const scope = params.paths?.length ? ` in requested paths: ${params.paths.join(", ")}` : ""; throw new Error( `No supported files found${scope}. ${SUPPORTED_SERVER_DESCRIPTION}`, ); } return { root, routes, skipped }; } export interface FixRoute { adapter: LspServerAdapter; files: string[]; } export interface MultiFileFixRouteParams { root?: string; paths: string[]; server?: string; } /** * Resolve fix routes for one or more files, grouped per adapter so each * LSP server is spawned once for all of its files. */ export function selectFixRoutes( adapters: LspServerAdapter[], params: MultiFileFixRouteParams, ) { const root = resolveRoot(params.root); const filesByAdapter = new Map(); const seenFiles = new Set(); for (const filePath of params.paths) { const file = path.resolve(root, filePath); // Duplicates are the same work twice; with write: true a // non-idempotent fix could even be applied to the rewritten copy. const dedupeKey = process.platform === "win32" ? file.toLowerCase() : file; if (seenFiles.has(dedupeKey)) continue; seenFiles.add(dedupeKey); const candidates = filterAdapters(adapters, params.server).filter( (adapter) => adapter.isSupportedFile(file), ); if (candidates.length === 0) throw unsupportedFileError("fix", filePath, params.server); if (!params.server && candidates.length > 1) { throw new Error( `Multiple LSP servers support ${filePath}: ${candidates.map((adapter) => adapter.name).join(", ")}. ` + "Specify the server parameter for lsp_fix.", ); } const adapter = candidates[0]; const files = filesByAdapter.get(adapter) ?? []; files.push(file); filesByAdapter.set(adapter, files); } return { root, routes: [...filesByAdapter.entries()].map(([adapter, files]) => ({ adapter, reason: `${adapter.name} fix (${files.length} file(s))`, files, })), }; } function diagnosticFilePolicyKey(adapter: LspServerAdapter) { return JSON.stringify([ adapter.extensions, [...adapter.skipDirectories].sort((left, right) => left.localeCompare(right), ), ]); } /** Restrict adapters by name; unknown or blank names fail loudly with the configured names. */ export function filterAdapters( adapters: LspServerAdapter[], selected: string | string[] | undefined, ) { if (!selected) return adapters; const names = [ ...new Set( (Array.isArray(selected) ? selected : [selected]).map((name) => name.trim(), ), ), ].filter((name) => name.length > 0); if (names.length === 0) throw new Error("LSP server parameter must not be blank."); // Server names match case-insensitively: tool callers routinely pass // capitalized names copied from prose ("Biome", "rust-analyzer"). const lowerNames = names.map((name) => name.toLowerCase()); const matched = adapters.filter((adapter) => lowerNames.includes(adapter.name.toLowerCase()), ); const missing = names.filter( (name) => !adapters.some( (adapter) => adapter.name.toLowerCase() === name.toLowerCase(), ), ); if (missing.length) { const configured = adapters.map((adapter) => adapter.name).join(", ") || "none"; throw new Error( `Unknown LSP server(s): ${missing.join(", ")}. Configured LSP servers: ${configured}. ` + "Omit the server parameter to select matching servers automatically.", ); } return matched; } function unsupportedFileError( action: LspAction, filePath: string, server: string | undefined, ) { const override = server ? ` for server '${server}'` : ""; return new Error( `No ${action} route supports ${filePath}${override}. ${SUPPORTED_SERVER_DESCRIPTION}`, ); }