import { type ChildProcessWithoutNullStreams, spawn } from "node:child_process"; import path from "node:path"; import process from "node:process"; import { cmdShellSpawnSpec, commandPathValue, mergeEnvironment, resolveSpawnableCommandPath, } from "./command.js"; import { directoryUri, documentKey } from "./files.js"; import { killProcessTree } from "./runners/helpers.js"; import { positionAt } from "./text-edits.js"; import type { CodeAction, JsonRpcMessage, LspDiagnostic, LspServerAdapter, ServerCommand, } from "./types.js"; export function resolveSpawnCommand( command: ServerCommand, platform: NodeJS.Platform = process.platform, comSpec = process.env.ComSpec, ): ServerCommand { return cmdShellSpawnSpec(command.command, command.args, platform, comSpec); } /** * Distinguishes "the server was still working when the budget ran out" * from exits/errors: pull diagnostics may degrade to already-published * push results on this rejection, never on a server crash. */ export class LspRequestTimedOutError extends Error { static is(error: unknown): error is LspRequestTimedOutError { return error instanceof LspRequestTimedOutError; } } // Quiet period (ms) after each publish before treating push diagnostics as settled. const PUBLISHED_DIAGNOSTICS_SETTLE_MS = 800; const PROCESS_EXIT_GRACE_MS = 500; // Budget for the shutdown round-trip itself: a server that accepted the // connection but stopped responding must not stretch every call's cleanup // to the full per-request timeout before close() kills it. const SHUTDOWN_REQUEST_TIMEOUT_MS = 2_000; // Server stderr is only used to enrich error messages; chatty servers must // not grow it without bound within a call. const STDERR_CAP_BYTES = 64 * 1024; // Cap on the unparsed receive buffer: a server that floods stdout with // non-LSP data (a crash loop writing raw logs) would otherwise grow the // buffer without bound until the process runs out of memory. Well above // any legitimate frame (large pull-diagnostics responses are ~1 MB). const RECV_BUFFER_CAP_BYTES = 16 * 1024 * 1024; export class LspClient { #child?: ChildProcessWithoutNullStreams; #process?: ChildProcessWithoutNullStreams; #processExit?: Promise; #buffer = Buffer.alloc(0); #nextId = 1; #pending = new Map< number, { resolve: (message: JsonRpcMessage) => void; reject: (reason: unknown) => void; timeout: NodeJS.Timeout; } >(); #publishedDiagnostics = new Map< string, { version: number; diagnostics: LspDiagnostic[] } >(); #diagnosticWaiters = new Map< string, Set<{ onPublish: (publication: { version: number; diagnostics: LspDiagnostic[]; }) => void; reject: (reason: unknown) => void; dispose: () => void; }> >(); #stderr = ""; #serverCapabilities: Record = {}; #adapter: LspServerAdapter; #command: ServerCommand; #cwd: string; #timeoutMs: number; constructor( adapter: LspServerAdapter, command: ServerCommand, cwd: string, timeoutMs: number, ) { this.#adapter = adapter; this.#command = command; this.#cwd = cwd; this.#timeoutMs = timeoutMs; } /** * Per-method budget: initialize pays the cold-start cost of the whole * workspace (jdtls/tsserver can easily exceed the per-request budget), so * it gets a triple budget; everything else stays on the standard one. */ #methodTimeoutMs(method: string) { return method === "initialize" ? this.#timeoutMs * 3 : this.#timeoutMs; } async start() { const commandPath = resolveSpawnableCommandPath( this.#command.command, this.#cwd, process.platform, commandPathValue(this.#adapter.env), ); if (!commandPath) { throw new Error( `${this.#adapter.name} LSP command not found: ${this.#command.command}. ${this.#adapter.missingCommandHint}`, ); } const spawnCommand = resolveSpawnCommand({ ...this.#command, command: commandPath, }); const child = spawn(spawnCommand.command, spawnCommand.args, { cwd: this.#cwd, env: mergeEnvironment({ ...this.#adapter.spawnEnv?.(this.#cwd), ...this.#adapter.env, }), stdio: "pipe", }); this.#child = child; this.#process = child; this.#processExit = new Promise((resolve) => { const finish = () => { child.off("exit", finish); child.off("close", finish); resolve(); }; child.once("exit", finish); child.once("close", finish); }); child.stdout.on("data", (chunk) => { try { this.#onData(chunk); } catch (error) { this.#fail( `${this.#adapter.name} LSP server sent invalid JSON-RPC data: ${formatErrorMessage(error)}.${this.#formatStderr()}`, ); } }); child.stderr.on("data", (chunk) => { if (this.#stderr.length < STDERR_CAP_BYTES) { this.#stderr += chunk.toString(); if (this.#stderr.length >= STDERR_CAP_BYTES) { this.#stderr += "\n...[stderr truncated]"; } } }); child.stdin.on("error", (error) => { this.#fail( `${this.#adapter.name} LSP stdin write failed: ${formatErrorMessage(error)}.${this.#formatStderr()}`, ); }); child.once("exit", (code, signal) => { if (this.#child === child) this.#child = undefined; if (this.#process === child) this.#process = undefined; const reason = signal ? `signal ${signal}` : `code ${code ?? "unknown"}`; this.#rejectPending( (id) => `${this.#adapter.name} LSP server exited before response ${id} (${reason}).${this.#formatStderr()}`, ); }); await new Promise((resolve, reject) => { child.once("spawn", resolve); child.once("error", (error) => { const message = `${this.#adapter.name} LSP process failed to start: ${error.message}.${this.#formatStderr()}`; this.#rejectPending(message); if (this.#child === child) this.#child = undefined; if (this.#process === child) this.#process = undefined; reject(new Error(message)); }); }); } async initialize(root: string) { const rootUri = directoryUri(root); const workspaceFolders = [ { uri: rootUri, name: path.basename(root) || "workspace" }, ]; const response = await this.request("initialize", { processId: process.pid, rootUri, workspaceFolders, initializationOptions: this.#adapter.initialization ?? {}, capabilities: { textDocument: { // This spawn-per-call client can't track dynamic registrations, so // capabilities must be advertised statically. codeAction: { dynamicRegistration: false, resolveSupport: { properties: ["edit"] }, }, diagnostic: { dynamicRegistration: false, relatedDocumentSupport: true, }, publishDiagnostics: {}, synchronization: { didSave: true }, }, workspace: { configuration: true, workspaceEdit: { documentChanges: true }, workspaceFolders: true, }, }, }); this.#serverCapabilities = ( response.result as | { capabilities?: Record } | undefined )?.capabilities ?? {}; this.notify("initialized", {}); if (this.#adapter.initialization) { this.notify("workspace/didChangeConfiguration", { settings: this.#adapter.initialization, }); } } didOpen(uri: string, text: string, languageId: string) { this.notify("textDocument/didOpen", { textDocument: { uri, languageId, version: 1, text }, }); } didClose(uri: string) { if (!this.#child) return false; this.notify("textDocument/didClose", { textDocument: { uri }, }); // The document is gone from the server's view; drop its cached // publications. Waiters (if any) keep their source of truth. const key = documentKey(uri); if (!this.#diagnosticWaiters.has(key)) this.#publishedDiagnostics.delete(key); return true; } async diagnostics(uri: string) { // Only pull if the server advertised it; otherwise use push diagnostics. if (!this.#serverCapabilities.diagnosticProvider) { return this.#waitForPublishedDiagnostics( uri, this.#adapter.pushDiagnosticsGraceMs ? { afterVersion: 0, diagnostics: [], waitMs: this.#adapter.pushDiagnosticsGraceMs, } : undefined, ); } const published = this.#publishedDiagnostics.get(documentKey(uri)); // Arbitration when the pull returns empty and a push already arrived: // a non-empty push publication predating the pull is treated as the // analysis result the provisional empty pull raced against (the // rust-analyzer pattern), so the grace window below settles with it // unless a *newer* publication arrives. An empty (or absent) earlier // publication is ignored, and only publications newer than it count. const publishedBeforePull = published?.diagnostics.length ? published.version - 1 : (published?.version ?? 0); let diagnostics: LspDiagnostic[]; try { const response = await this.request("textDocument/diagnostic", { textDocument: { uri }, }); const result = response.result as { items?: LspDiagnostic[] } | undefined; diagnostics = result?.items ?? []; } catch (error) { // A slow server is not a broken one: if the analysis already // published push diagnostics while the pull request was in flight, // settle with those instead of failing the whole lane. if (!LspRequestTimedOutError.is(error)) throw error; const timedOutPublished = this.#publishedDiagnostics.get( documentKey(uri), ); if (!timedOutPublished?.diagnostics.length) throw error; diagnostics = timedOutPublished.diagnostics; } if (diagnostics.length > 0 || !this.#adapter.pullDiagnosticsGraceMs) return diagnostics; return this.#waitForPublishedDiagnostics(uri, { afterVersion: publishedBeforePull, diagnostics, waitMs: this.#adapter.pullDiagnosticsGraceMs, }); } async codeActions( uri: string, text: string, diagnostics: LspDiagnostic[], kind: string, ) { const response = await this.request("textDocument/codeAction", { textDocument: { uri }, range: { start: { line: 0, character: 0 }, end: positionAt(text, text.length), }, context: { diagnostics, only: [kind] }, }); return (response.result as CodeAction[] | null | undefined) ?? []; } async resolveActions(actions: CodeAction[]) { // Only resolve when the server advertised resolveProvider; otherwise use the // action as-is. Any error from an advertised resolve is real and propagates. const codeActionProvider = this.#serverCapabilities.codeActionProvider; const canResolve = typeof codeActionProvider === "object" && codeActionProvider !== null && (codeActionProvider as { resolveProvider?: boolean }).resolveProvider === true; const resolvedActions: CodeAction[] = []; for (const action of actions) { if (action.edit || !canResolve) { resolvedActions.push(action); continue; } const response = await this.request("codeAction/resolve", action); resolvedActions.push( (response.result as CodeAction | undefined) ?? action, ); } return resolvedActions; } async shutdown() { const child = this.#process; const processExit = this.#processExit; if (!child || !processExit) return; if (this.#child === child) { try { await this.request("shutdown", null, SHUTDOWN_REQUEST_TIMEOUT_MS); this.notify("exit", undefined); if (await settlesWithin(processExit, PROCESS_EXIT_GRACE_MS)) return; } catch { // The process may already be gone; terminate it below if needed. } } this.close(); if (await settlesWithin(processExit, PROCESS_EXIT_GRACE_MS)) return; killProcessTree(child, "SIGKILL"); await processExit; } close() { this.#rejectPending(`${this.#adapter.name} LSP request cancelled.`); if (this.#child && !this.#child.killed) killProcessTree(this.#child); this.#child = undefined; } #rejectPending(message: string | ((id: number | "diagnostics") => string)) { for (const [id, pending] of this.#pending.entries()) { clearTimeout(pending.timeout); pending.reject( new Error(typeof message === "string" ? message : message(id)), ); } this.#pending.clear(); for (const waiters of this.#diagnosticWaiters.values()) { for (const waiter of [...waiters]) { waiter.reject( new Error( typeof message === "string" ? message : message("diagnostics"), ), ); } } this.#diagnosticWaiters.clear(); } #fail(message: string) { this.#rejectPending(message); if (this.#child && !this.#child.killed) killProcessTree(this.#child); this.#child = undefined; } private request(method: string, params: unknown, timeoutMs?: number) { const id = this.#nextId++; return new Promise((resolve, reject) => { const timeout = setTimeout(() => { this.#pending.delete(id); reject( new LspRequestTimedOutError( `${this.#adapter.name} LSP request timed out: ${method}.${this.#formatStderr()}`, ), ); }, timeoutMs ?? this.#methodTimeoutMs(method)); this.#pending.set(id, { resolve, reject, timeout }); try { this.#send({ jsonrpc: "2.0", id, method, params }); } catch (error) { clearTimeout(timeout); this.#pending.delete(id); reject(error); } }); } private notify(method: string, params: unknown) { this.#send( params === undefined ? { jsonrpc: "2.0", method } : { jsonrpc: "2.0", method, params }, ); } #send(message: JsonRpcMessage) { if (!this.#child) throw new Error(`${this.#adapter.name} LSP server is not running.`); const body = JSON.stringify(message); try { this.#child.stdin.write( `Content-Length: ${Buffer.byteLength(body)}\r\n\r\n${body}`, ); } catch (error) { const errorMessage = `${this.#adapter.name} LSP stdin write failed: ${formatErrorMessage(error)}.${this.#formatStderr()}`; this.#fail(errorMessage); throw new Error(errorMessage); } } #onData(chunk: Buffer) { this.#buffer = Buffer.concat([this.#buffer, chunk]); if (this.#buffer.length > RECV_BUFFER_CAP_BYTES) { // Unparsed remainder past any legitimate frame size (a complete // frame is admitted only after its Content-Length passes the same // cap below, so mid-frame buffering stays under it). Drop the data // before failing: a server that keeps flooding while the kill // lands must not keep growing the buffer. this.#buffer = Buffer.alloc(0); throw new Error( `${this.#adapter.name} LSP server receive buffer exceeded ${RECV_BUFFER_CAP_BYTES} bytes without a complete frame`, ); } while (true) { const separator = this.#buffer.indexOf("\r\n\r\n"); if (separator < 0) return; const header = this.#buffer.subarray(0, separator).toString("utf8"); const contentLength = /Content-Length:\s*(\d+)/i.exec(header)?.[1]; if (!contentLength) throw new Error(`Invalid LSP response header: ${header}`); const bodyStart = separator + 4; const bodyLength = Number(contentLength); if (bodyLength > RECV_BUFFER_CAP_BYTES) { throw new Error( `${this.#adapter.name} LSP frame Content-Length ${bodyLength} exceeds the ${RECV_BUFFER_CAP_BYTES} byte cap`, ); } if (this.#buffer.length < bodyStart + bodyLength) return; const rawBody = this.#buffer .subarray(bodyStart, bodyStart + bodyLength) .toString("utf8"); this.#buffer = this.#buffer.subarray(bodyStart + bodyLength); this.#handleMessage(JSON.parse(rawBody) as JsonRpcMessage); } } #handleMessage(message: JsonRpcMessage) { if (Object.hasOwn(message, "id") && !message.method) { const pending = typeof message.id === "number" ? this.#pending.get(message.id) : undefined; if (!pending) return; clearTimeout(pending.timeout); this.#pending.delete(message.id as number); if (message.error) { pending.reject( new Error( `${this.#adapter.name} LSP error: ${message.error.message}`, ), ); } else { pending.resolve(message); } return; } if (message.method === "textDocument/publishDiagnostics") { const params = message.params as | { uri?: string; diagnostics?: LspDiagnostic[] } | undefined; if (params?.uri) { const key = documentKey(params.uri); const previousVersion = this.#publishedDiagnostics.get(key)?.version ?? 0; const publication = { version: previousVersion + 1, diagnostics: params.diagnostics ?? [], }; this.#publishedDiagnostics.set(key, publication); const waiters = this.#diagnosticWaiters.get(key); if (waiters) { for (const waiter of [...waiters]) waiter.onPublish(publication); } } return; } if (Object.hasOwn(message, "id") && message.method) { this.#respondToServerRequest(message); } } #waitForPublishedDiagnostics( uri: string, fallback?: { afterVersion: number; diagnostics: LspDiagnostic[]; waitMs: number; }, ) { // See PUBLISHED_DIAGNOSTICS_SETTLE_MS. Bounded by #timeoutMs. const key = documentKey(uri); return new Promise((resolve, reject) => { let settleTimer: NodeJS.Timeout | undefined; let fallbackTimer: NodeJS.Timeout | undefined; let overallTimer: NodeJS.Timeout | undefined; let sawNonEmptyPublication = false; const afterVersion = fallback?.afterVersion ?? 0; const dispose = () => { if (settleTimer) clearTimeout(settleTimer); if (fallbackTimer) clearTimeout(fallbackTimer); if (overallTimer) clearTimeout(overallTimer); const set = this.#diagnosticWaiters.get(key); set?.delete(waiter); if (set && set.size === 0) this.#diagnosticWaiters.delete(key); }; const settleWith = (diagnostics: LspDiagnostic[]) => { dispose(); resolve(diagnostics); }; const fail = (reason: unknown) => { dispose(); reject(reason); }; const onPublish = (publication: { version: number; diagnostics: LspDiagnostic[]; }) => { if (publication.version <= afterVersion) return; if ( fallback && publication.diagnostics.length === 0 && !sawNonEmptyPublication ) return; sawNonEmptyPublication ||= publication.diagnostics.length > 0; if (fallbackTimer) clearTimeout(fallbackTimer); if (settleTimer) clearTimeout(settleTimer); settleTimer = setTimeout( () => settleWith(this.#publishedDiagnostics.get(key)?.diagnostics ?? []), this.#adapter.diagnosticsSettleMs ?? PUBLISHED_DIAGNOSTICS_SETTLE_MS, ); }; const waiter = { onPublish, reject: fail, dispose }; const set = this.#diagnosticWaiters.get(key) ?? new Set(); set.add(waiter); this.#diagnosticWaiters.set(key, set); if (fallback) { fallbackTimer = setTimeout( () => { const latest = this.#publishedDiagnostics.get(key); settleWith( latest && latest.version > afterVersion ? latest.diagnostics : fallback.diagnostics, ); }, Math.min(fallback.waitMs, this.#timeoutMs), ); } overallTimer = setTimeout(() => { const latest = this.#publishedDiagnostics.get(key); if (latest && latest.version > afterVersion) { settleWith(latest.diagnostics); } else if (fallback) { settleWith(fallback.diagnostics); } else { fail( new Error( `${this.#adapter.name} LSP did not return diagnostics for ${uri} before timeout.`, ), ); } }, this.#timeoutMs); const existing = this.#publishedDiagnostics.get(key); if (existing) onPublish(existing); }); } #respondToServerRequest(message: JsonRpcMessage) { // The server wants to edit the workspace itself. lsp_fix applies code // action edits explicitly; server-initiated edits are declined with the // protocol's honest "not applied" outcome instead of MethodNotFound. if (message.method === "workspace/applyEdit") { this.#send({ jsonrpc: "2.0", id: message.id, result: { applied: false, failureReason: "pi-lsp does not apply server-initiated workspace edits.", }, }); return; } // Progress token creation: accepting the token is harmless (the // $/progress notifications that follow are ignored), while refusing it // makes gopls/jdtls-style servers log errors on every launch. if (message.method === "window/workDoneProgress/create") { this.#send({ jsonrpc: "2.0", id: message.id, result: null }); return; } // No message actions to pick from; null is a valid "no action" answer. if (message.method === "window/showMessageRequest") { this.#send({ jsonrpc: "2.0", id: message.id, result: null }); return; } if (message.method === "workspace/configuration") { const params = message.params as | { items?: Array<{ section?: string }> } | undefined; this.#send({ jsonrpc: "2.0", id: message.id, result: (params?.items ?? []).map((item) => this.#configurationValue(item.section), ), }); return; } if (message.method === "workspace/workspaceFolders") { const rootUri = directoryUri(this.#cwd); this.#send({ jsonrpc: "2.0", id: message.id, result: [ { uri: rootUri, name: path.basename(this.#cwd) || "workspace" }, ], }); return; } if ( message.method === "client/registerCapability" || message.method === "client/unregisterCapability" ) { this.#send({ jsonrpc: "2.0", id: message.id, result: null }); return; } this.#send({ jsonrpc: "2.0", id: message.id, error: { code: -32601, message: `Method not found: ${message.method ?? "unknown"}`, }, }); } #configurationValue(section: string | undefined) { if (!section) return this.#adapter.initialization ?? {}; // Dotted sections ("intelephense.telemetry.enable") walk the nested // initialization object; an unknown section is null, the protocol's // honest "not configured", rather than a fabricated empty object. let value: unknown = this.#adapter.initialization; for (const part of section.split(".")) { if (value === null || typeof value !== "object") return null; value = (value as Record)[part]; if (value === undefined) return null; } return value; } #formatStderr() { const stderr = this.#stderr.trim(); return stderr ? `\nServer stderr:\n${stderr}` : ""; } } function formatErrorMessage(error: unknown) { return error instanceof Error ? error.message : String(error); } function settlesWithin(promise: Promise, timeoutMs: number) { return new Promise((resolve) => { const timeout = setTimeout(() => resolve(false), timeoutMs); void promise.then(() => { clearTimeout(timeout); resolve(true); }); }); }