repositories / pi-ext
pi-ext
bugabingas pi extensions
owned by admin
extensions/lsp/src/client.ts
Rawimport {
type ChildProcessWithoutNullStreams,
execFile,
spawn,
} from "node:child_process";
import { createHash, randomUUID } from "node:crypto";
import { opendir, realpath } from "node:fs/promises";
import { dirname, extname, join } from "node:path";
import { Transform } from "node:stream";
import {
ApplyWorkspaceEditRequest,
type CallHierarchyItem,
CancellationTokenSource,
ConfigurationRequest,
createProtocolConnection,
DefinitionRequest,
DidChangeTextDocumentNotification,
DidChangeWatchedFilesNotification,
DidOpenTextDocumentNotification,
ErrorCodes,
ExitNotification,
HoverRequest,
ImplementationRequest,
InitializedNotification,
InitializeRequest,
type ProtocolConnection,
Range,
ReferencesRequest,
RegistrationRequest,
ResponseError,
type ServerCapabilities,
ShutdownRequest,
StreamMessageReader,
StreamMessageWriter,
TextDocumentSyncKind,
TypeDefinitionRequest,
WorkspaceFoldersRequest,
} from "vscode-languageserver-protocol/node.js";
import type { LaunchDescriptor, Profile } from "./registry.ts";
import {
bounded,
check,
type Encoding,
LspFailure,
localPath,
snapshot,
toPosition,
uri,
within,
} from "./source.ts";
export type Operation =
| "definition"
| "references"
| "hover"
| "type_definition"
| "implementations"
| "document_symbols"
| "workspace_symbols"
| "incoming_calls"
| "outgoing_calls";
export function callItem(value: unknown): value is CallHierarchyItem {
const v = value as CallHierarchyItem | null;
return (
!!v &&
typeof v.name === "string" &&
v.name.length <= 4096 &&
Number.isInteger(v.kind) &&
v.kind >= 1 &&
v.kind <= 26 &&
typeof v.uri === "string" &&
v.uri.length <= 4096 &&
Range.is(v.range) &&
Range.is(v.selectionRange)
);
}
const hash = (text: string): string =>
createHash("sha256").update(text).digest("hex");
const MAX_TRAFFIC = 16 * 1024 * 1024;
const MAX_SNAPSHOTS = 4 * 1024 * 1024;
function pause(ms: number): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, ms));
}
export class Client {
readonly child: ChildProcessWithoutNullStreams;
readonly connection: ProtocolConnection;
readonly exited: Promise<void>;
encoding: Encoding = "utf-16";
capabilities: ServerCapabilities = {};
busy = false;
dead = false;
private ended = false;
private closing: Promise<void> | undefined;
private readonly documents = new Map<
string,
{ text: string; version: number }
>();
private readonly directories = new Set<string>();
private readonly observed = new Map<string, string>();
private readonly ready: Promise<void>;
private revision = 0;
private readonly selections = new Map<
string,
{
item: CallHierarchyItem;
file: string;
line: number;
column: number;
revision: number;
digest: string;
queryDigest: string;
expires: number;
}
>();
constructor(
readonly root: string,
readonly config: Profile,
launch: string | LaunchDescriptor,
) {
const descriptor =
typeof launch === "string"
? { command: launch, args: [], identity: launch }
: launch;
this.child = spawn(
descriptor.command,
[...descriptor.args, ...config.args],
{
cwd: root,
stdio: "pipe",
windowsHide: true,
shell: false,
detached: process.platform !== "win32",
env: {
...process.env,
GOPROXY: "off",
GOSUMDB: "off",
GOTOOLCHAIN: "local",
GOTELEMETRY: "off",
},
},
);
this.exited = new Promise((resolve) => {
this.child.once("exit", () => {
this.ended = true;
this.dead = true;
resolve();
});
this.child.once("error", () => {
if (!this.child.pid) {
this.ended = true;
resolve();
}
this.dead = true;
});
});
let bytes = 0;
const guard = new Transform({
transform: (chunk: Buffer, _encoding, callback) => {
bytes += chunk.length;
if (bytes > MAX_TRAFFIC) {
callback(new Error("LSP session traffic limit"));
return;
}
callback(null, chunk);
},
});
guard.on("error", () => {
void this.close();
});
this.child.stdout.on("error", () => {
void this.close();
});
this.child.stdin.on("error", () => {
void this.close();
});
this.child.stdout.pipe(guard);
let stderrBytes = 0;
this.child.stderr.on("data", (chunk: Buffer) => {
stderrBytes += chunk.length;
if (stderrBytes > 1024 * 1024) void this.close();
});
const reader = new StreamMessageReader(guard);
reader.partialMessageTimeout = 1000;
reader.onPartialMessage(() => {
void this.close();
});
this.connection = createProtocolConnection(
reader,
new StreamMessageWriter(this.child.stdin),
);
this.connection.onError(() => {
void this.close();
});
this.connection.onClose(() => {
void this.close();
});
this.connection.onRequest(ConfigurationRequest.type, ({ items }) => {
if (items.length > 64)
throw new ResponseError(
ErrorCodes.InvalidParams,
"Configuration request exceeds 64 items.",
);
return items.map((item) => {
if (item.scopeUri) {
try {
if (!within(root, localPath(item.scopeUri))) return null;
} catch {
return null;
}
}
return item.section
? (config.settings[item.section] ?? null)
: config.settings;
});
});
this.connection.onRequest(WorkspaceFoldersRequest.type, () => [
{ uri: uri(root), name: "workspace" },
]);
this.connection.onRequest(ApplyWorkspaceEditRequest.type, () => ({
applied: false,
failureReason: "Read-only navigation client.",
}));
// Dynamic registration is not advertised or implemented; gopls owns its filesystem watcher.
this.connection.onRequest(RegistrationRequest.type, () => {
throw new ResponseError(
ErrorCodes.MethodNotFound,
"Dynamic registration is unsupported.",
);
});
this.connection.listen();
this.ready = this.initialize();
void this.ready.catch(() => {
void this.close();
});
}
private async initialize(): Promise<void> {
const result = await this.connection.sendRequest(InitializeRequest.type, {
processId: process.pid,
rootUri: uri(this.root),
workspaceFolders: [{ uri: uri(this.root), name: "workspace" }],
capabilities: {
general: { positionEncodings: ["utf-16", "utf-8", "utf-32"] },
workspace: {
configuration: true,
workspaceFolders: true,
applyEdit: false,
symbol: {
dynamicRegistration: false,
resolveSupport: { properties: ["location.range"] },
},
},
textDocument: {
synchronization: { dynamicRegistration: false },
documentSymbol: {
dynamicRegistration: false,
hierarchicalDocumentSymbolSupport: true,
},
callHierarchy: { dynamicRegistration: false },
definition: { linkSupport: true },
typeDefinition: { dynamicRegistration: false, linkSupport: true },
implementation: { dynamicRegistration: false, linkSupport: true },
hover: { contentFormat: ["plaintext"] },
},
},
initializationOptions: this.config.initializationOptions,
});
if (this.dead)
throw new LspFailure(
"server_failure",
"Server stopped during initialization.",
);
const encoding = result.capabilities.positionEncoding ?? "utf-16";
if (!["utf-16", "utf-8", "utf-32"].includes(encoding))
throw new LspFailure(
"unsupported",
"Server selected unsupported position encoding.",
);
this.encoding = encoding as Encoding;
this.capabilities = result.capabilities;
await this.connection.sendNotification(InitializedNotification.type, {});
}
private async observe(file: string, signal: AbortSignal): Promise<void> {
const directory = dirname(file);
if (!this.directories.has(directory) && this.directories.size >= 8)
throw new LspFailure(
"resource_limit",
"Observed directory limit (8); restart Pi session.",
);
this.directories.add(directory);
const current = new Map<string, string>();
let totalBytes = 0;
for (const dir of this.directories) {
const entries = await opendir(dir);
let count = 0;
for await (const entry of entries) {
check(signal);
if (++count > 256)
throw new LspFailure(
"resource_limit",
"Directory observation exceeds 256 entries.",
);
if (
!entry.isFile() ||
!(
(this.config.extensions ?? [".go"]).includes(extname(entry.name)) ||
[
...(this.config.roots ?? []),
"go.mod",
"go.sum",
"go.work",
"go.work.sum",
"tsconfig.json",
"package.json",
"compile_commands.json",
"compile_flags.txt",
].includes(entry.name)
)
)
continue;
const path = join(dir, entry.name);
const text = await snapshot(path, signal);
totalBytes += Buffer.byteLength(text);
if (current.size >= 128 || totalBytes > MAX_SNAPSHOTS)
throw new LspFailure(
"resource_limit",
"Observed sources exceed 128 files/4 MiB.",
);
current.set(path, text);
}
}
check(signal);
const changes: { uri: string; type: 1 | 2 | 3 }[] = [];
for (const [path, text] of current)
if (this.observed.get(path) !== text)
changes.push({ uri: uri(path), type: this.observed.has(path) ? 2 : 1 });
for (const path of this.observed.keys())
if (!current.has(path)) changes.push({ uri: uri(path), type: 3 });
if (changes.length) this.revision++;
if (changes.length)
await this.connection.sendNotification(
DidChangeWatchedFilesNotification.type,
{ changes },
);
this.observed.clear();
for (const [path, text] of current) this.observed.set(path, text);
// Managed overlays must follow disk even when another file is queried.
for (const path of this.documents.keys()) {
check(signal);
const text = current.get(path);
if (text === undefined)
throw new LspFailure(
"invalid_input",
"Managed source removed; restart session before querying again.",
);
await this.sync(path, text);
}
}
private async sync(file: string, text: string): Promise<void> {
const sync = this.capabilities.textDocumentSync;
const kind = typeof sync === "number" ? sync : sync?.change;
if (
kind !== TextDocumentSyncKind.Full &&
kind !== TextDocumentSyncKind.Incremental
)
throw new LspFailure(
"unsupported",
"Server does not support document change synchronization.",
);
const previous = this.documents.get(file);
if (!previous) {
if (this.documents.size >= 32)
throw new LspFailure(
"resource_limit",
"Managed document limit (32); restart Pi session.",
);
if (typeof sync === "object" && !sync.openClose)
throw new LspFailure(
"unsupported",
"Server does not accept document open synchronization.",
);
await this.connection.sendNotification(
DidOpenTextDocumentNotification.type,
{
textDocument: {
uri: uri(file),
languageId: this.config.language,
version: 1,
text,
},
},
);
this.documents.set(file, { text, version: 1 });
} else if (previous.text !== text) {
const version = previous.version + 1;
await this.connection.sendNotification(
DidChangeTextDocumentNotification.type,
{
textDocument: { uri: uri(file), version },
contentChanges: [{ text }],
},
);
this.documents.set(file, { text, version });
}
}
async query(
operation: Operation,
file: string,
line: number,
column: number,
signal: AbortSignal,
query?: string,
selection?: string,
): Promise<unknown> {
await bounded(this.ready, signal);
check(signal);
const capability =
operation === "incoming_calls" || operation === "outgoing_calls"
? this.capabilities.callHierarchyProvider
: operation === "document_symbols"
? this.capabilities.documentSymbolProvider
: operation === "workspace_symbols"
? this.capabilities.workspaceSymbolProvider
: operation === "definition"
? this.capabilities.definitionProvider
: operation === "references"
? this.capabilities.referencesProvider
: operation === "type_definition"
? this.capabilities.typeDefinitionProvider
: operation === "implementations"
? this.capabilities.implementationProvider
: this.capabilities.hoverProvider;
if (!capability)
throw new LspFailure(
"unsupported",
`Server does not advertise ${operation}.`,
);
if (operation === "workspace_symbols") {
if (typeof query !== "string" || query.length > 256)
throw new LspFailure(
"invalid_input",
"workspace_symbols requires query (≤256 characters).",
);
await this.observe(file || join(this.root, ".lsp-workspace"), signal);
const raw = await this.request("workspace/symbol", { query }, signal);
if (raw === null) return null;
if (!Array.isArray(raw))
throw new LspFailure("server_failure", "Malformed workspace symbols.");
const provider = this.capabilities.workspaceSymbolProvider;
const items = [];
for (const item of raw.slice(0, 101)) {
check(signal);
if (
!item ||
typeof item !== "object" ||
typeof item.name !== "string" ||
!Number.isInteger(item.kind) ||
!item.location ||
typeof item.location.uri !== "string"
)
throw new LspFailure("server_failure", "Malformed workspace symbol.");
items.push(
!("range" in item.location) &&
typeof provider === "object" &&
provider.resolveProvider
? await this.request("workspaceSymbol/resolve", item, signal)
: item,
);
}
return items;
}
await this.observe(file, signal);
check(signal);
const text = await snapshot(file, signal);
check(signal);
const position =
operation === "document_symbols"
? { line: 0, character: 0 }
: toPosition(text, line, column, this.encoding);
await this.sync(file, text);
check(signal);
if (operation === "incoming_calls" || operation === "outgoing_calls")
return this.calls(
operation,
file,
line,
column,
position,
signal,
hash(text),
selection,
);
if (operation === "document_symbols")
return this.request(
"textDocument/documentSymbol",
{ textDocument: { uri: uri(file) } },
signal,
);
const cancellation = new CancellationTokenSource();
const cancel = () => cancellation.cancel();
signal.addEventListener("abort", cancel, { once: true });
try {
const params = { textDocument: { uri: uri(file) }, position };
const response =
operation === "references"
? this.connection.sendRequest(
ReferencesRequest.type,
{
...params,
context: { includeDeclaration: true },
},
cancellation.token,
)
: operation === "definition"
? this.connection.sendRequest(
DefinitionRequest.type,
params,
cancellation.token,
)
: operation === "type_definition"
? this.connection.sendRequest(
TypeDefinitionRequest.type,
params,
cancellation.token,
)
: operation === "implementations"
? this.connection.sendRequest(
ImplementationRequest.type,
params,
cancellation.token,
)
: this.connection.sendRequest(
HoverRequest.type,
params,
cancellation.token,
);
const result = await bounded<unknown>(response, signal);
check(signal);
return result;
} finally {
signal.removeEventListener("abort", cancel);
cancellation.dispose();
}
}
private async calls(
operation: Operation,
file: string,
line: number,
column: number,
position: { line: number; character: number },
signal: AbortSignal,
queryDigest: string,
selection?: string,
): Promise<unknown> {
for (const [token, entry] of this.selections)
if (entry.expires <= Date.now()) this.selections.delete(token);
let item: CallHierarchyItem;
if (selection) {
const entry = this.selections.get(selection);
let digest: string | undefined;
if (entry) {
try {
digest = hash(await snapshot(localPath(entry.item.uri), signal));
} catch {
check(signal);
}
}
if (
!entry ||
entry.file !== file ||
entry.line !== line ||
entry.column !== column ||
entry.revision !== this.revision ||
entry.queryDigest !== queryDigest ||
entry.digest !== digest
) {
this.selections.delete(selection);
throw new LspFailure(
"stale_selection",
"Selection expired or root/config/source/session changed; repeat query without selection.",
);
}
item = entry.item;
} else {
const raw = await this.request(
"textDocument/prepareCallHierarchy",
{ textDocument: { uri: uri(file) }, position },
signal,
);
if (raw === null || (Array.isArray(raw) && !raw.length))
return { phase: "prepare_no_result" };
if (!Array.isArray(raw))
throw new LspFailure(
"server_failure",
"Malformed call hierarchy preparation.",
);
if (raw.length > 32)
throw new LspFailure(
"resource_limit",
"More than 32 call targets; narrow source position.",
);
if (raw.some((v) => !callItem(v)))
throw new LspFailure(
"server_failure",
"Malformed call hierarchy preparation.",
);
if (Buffer.byteLength(JSON.stringify(raw)) > 65536)
throw new LspFailure(
"resource_limit",
"Prepared call metadata exceeds 64 KiB.",
);
if (raw.length > 1) {
for (const candidate of raw as CallHierarchyItem[])
await this.remember(localPath(candidate.uri));
await this.observe(file, signal);
const candidates = [];
for (const candidate of raw as CallHierarchyItem[]) {
if (this.selections.size >= 32)
this.selections.delete(
this.selections.keys().next().value as string,
);
const token = randomUUID();
this.selections.set(token, {
item: candidate,
file,
line,
column,
revision: this.revision,
digest: hash(await snapshot(localPath(candidate.uri), signal)),
queryDigest,
expires: Date.now() + 300000,
});
candidates.push({ item: candidate, selection: token });
}
return { phase: "ambiguous", candidates };
}
item = raw[0] as CallHierarchyItem;
}
const relationships = await this.request(
operation === "incoming_calls"
? "callHierarchy/incomingCalls"
: "callHierarchy/outgoingCalls",
{ item },
signal,
);
if (relationships !== null && !Array.isArray(relationships))
throw new LspFailure("server_failure", "Malformed call relationships.");
return { phase: "relationships", item, relationships: relationships ?? [] };
}
private async request(
method: string,
params: unknown,
signal: AbortSignal,
): Promise<unknown> {
check(signal);
const cancellation = new CancellationTokenSource();
const cancel = () => cancellation.cancel();
signal.addEventListener("abort", cancel, { once: true });
try {
const result = await bounded(
this.connection.sendRequest(method, params, cancellation.token),
signal,
);
check(signal);
return result;
} finally {
signal.removeEventListener("abort", cancel);
cancellation.dispose();
}
}
async remember(file: string): Promise<void> {
const canonical = await realpath(file);
if (within(this.root, canonical) && this.directories.size < 8)
this.directories.add(dirname(canonical));
}
close(): Promise<void> {
if (this.closing) return this.closing;
this.dead = true;
this.selections.clear();
this.closing = (async () => {
// Windows has no Node process-group kill: target the tree before graceful shutdown can remove its leader.
if (process.platform === "win32" && this.child.pid && !this.ended) {
await new Promise<void>((resolve) =>
execFile(
"taskkill",
["/pid", String(this.child.pid), "/T", "/F"],
{ timeout: 500, windowsHide: true },
() => resolve(),
),
);
}
if (!this.ended) {
try {
await Promise.race([
this.connection
.sendRequest(ShutdownRequest.type)
.catch(() => undefined),
pause(150),
]);
} catch {
/* Already closed/disposed connections can throw synchronously. Cleanup must continue. */
}
try {
await Promise.race([
this.connection.sendNotification(ExitNotification.type),
pause(50),
]);
} catch {
/* Broken pipe. */
}
}
this.connection.dispose();
this.child.stdin.destroy();
this.child.stdout.destroy();
this.child.stderr.destroy();
const kill = (signal: NodeJS.Signals) => {
try {
if (process.platform !== "win32" && this.child.pid)
process.kill(-this.child.pid, signal);
else this.child.kill(signal);
} catch {
/* Already exited. */
}
};
kill("SIGTERM");
await Promise.race([this.exited, pause(200)]);
// Kill the owned POSIX group even if its leader exited before a worker.
kill("SIGKILL");
if (process.platform === "win32" && !this.ended && this.child.pid) {
await new Promise<void>((resolve) =>
execFile(
"taskkill",
["/pid", String(this.child.pid), "/T", "/F"],
{ timeout: 500, windowsHide: true },
() => resolve(),
),
);
}
await Promise.race([this.exited, pause(500)]);
if (!this.ended)
throw new LspFailure(
"server_failure",
"Owned server exit not observed after shutdown escalation.",
);
})();
// Keep failures observable to shutdown callers, without unhandled rejection from event callbacks.
void this.closing.catch(() => undefined);
return this.closing;
}
}