@amaranthic/hernex 0.6.1 → 0.7.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +65 -0
- package/dist/engine/engineConfig.d.ts +50 -0
- package/dist/engine/engineConfig.d.ts.map +1 -1
- package/dist/engine/engineConfig.js +36 -1
- package/dist/engine/engineConfig.js.map +1 -1
- package/dist/engine/index.d.ts +1 -0
- package/dist/engine/index.d.ts.map +1 -1
- package/dist/engine/index.js +1 -0
- package/dist/engine/index.js.map +1 -1
- package/dist/engine/runTurn.d.ts +1 -1
- package/dist/engine/runTurn.d.ts.map +1 -1
- package/dist/engine/runTurn.js +7 -1
- package/dist/engine/runTurn.js.map +1 -1
- package/dist/index.d.ts +4 -3
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +2 -1
- package/dist/index.js.map +1 -1
- package/dist/tools/LspTool.d.ts +174 -0
- package/dist/tools/LspTool.d.ts.map +1 -0
- package/dist/tools/LspTool.js +195 -0
- package/dist/tools/LspTool.js.map +1 -0
- package/dist/tools/index.d.ts +2 -0
- package/dist/tools/index.d.ts.map +1 -1
- package/dist/tools/index.js +2 -0
- package/dist/tools/index.js.map +1 -1
- package/dist/tools/internal/lsp.d.ts +175 -0
- package/dist/tools/internal/lsp.d.ts.map +1 -0
- package/dist/tools/internal/lsp.js +1202 -0
- package/dist/tools/internal/lsp.js.map +1 -0
- package/dist/tools/prompts.d.ts +4 -0
- package/dist/tools/prompts.d.ts.map +1 -1
- package/dist/tools/prompts.js +23 -0
- package/dist/tools/prompts.js.map +1 -1
- package/package.json +1 -1
|
@@ -0,0 +1,1202 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @fileoverview On-demand Language Server Protocol engine for Hernex.
|
|
3
|
+
*
|
|
4
|
+
* Implements the LSP JSON-RPC wire protocol from scratch over stdio — no
|
|
5
|
+
* external vscode or jsonrpc packages. Each call to {@link runLspRequest}
|
|
6
|
+
* spawns the configured language server binary, executes exactly one
|
|
7
|
+
* operation (initialize → didOpen → request → shutdown → exit), then exits
|
|
8
|
+
* cleanly. Zero lingering processes.
|
|
9
|
+
*
|
|
10
|
+
* Wire format (per LSP spec §3.1):
|
|
11
|
+
* `Content-Length: <byteLen>\r\n\r\n<utf-8 json body>`
|
|
12
|
+
*
|
|
13
|
+
* @packageDocumentation
|
|
14
|
+
*/
|
|
15
|
+
import { execFile, spawn } from "node:child_process";
|
|
16
|
+
import { stat } from "node:fs/promises";
|
|
17
|
+
import { extname, relative } from "node:path";
|
|
18
|
+
import { pathToFileURL } from "node:url";
|
|
19
|
+
import { resolvePathWithinWorkspace } from "./pathGuard.js";
|
|
20
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
21
|
+
// Constants
|
|
22
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
23
|
+
/**
|
|
24
|
+
* Maximum file size (in bytes) accepted for `textDocument/didOpen`.
|
|
25
|
+
* Files larger than this are rejected before spawning the LSP server.
|
|
26
|
+
*/
|
|
27
|
+
const MAX_FILE_BYTES = 10 * 1024 * 1024; // 10 MB
|
|
28
|
+
/**
|
|
29
|
+
* Default per-request timeout in milliseconds.
|
|
30
|
+
*/
|
|
31
|
+
export const DEFAULT_LSP_TIMEOUT_MS = 5_000;
|
|
32
|
+
/**
|
|
33
|
+
* LSP JSON-RPC error code emitted when a request is cancelled because the
|
|
34
|
+
* document was modified while the server was processing it. Retryable.
|
|
35
|
+
*/
|
|
36
|
+
const CODE_CONTENT_MODIFIED = -32801;
|
|
37
|
+
/**
|
|
38
|
+
* Maximum number of automatic retries for `ContentModified` (-32801) errors.
|
|
39
|
+
*/
|
|
40
|
+
const MAX_RETRIES = 3;
|
|
41
|
+
/**
|
|
42
|
+
* Base delay (ms) for exponential backoff on retryable errors.
|
|
43
|
+
* Actual delays: 500 → 1000 → 2000 ms.
|
|
44
|
+
*/
|
|
45
|
+
const RETRY_BASE_DELAY_MS = 500;
|
|
46
|
+
/**
|
|
47
|
+
* Milliseconds to wait for the LSP server process to exit cleanly after
|
|
48
|
+
* sending `shutdown` + `exit` before issuing SIGKILL.
|
|
49
|
+
*/
|
|
50
|
+
const TEARDOWN_GRACE_MS = 1_500;
|
|
51
|
+
/**
|
|
52
|
+
* Timeout (ms) used specifically for the `shutdown` request during teardown.
|
|
53
|
+
* Shorter than the normal request timeout to avoid stalling on a dying server.
|
|
54
|
+
*/
|
|
55
|
+
const SHUTDOWN_TIMEOUT_MS = 2_000;
|
|
56
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
57
|
+
// LSP Symbol kind labels (LSP spec §3.16.3 — SymbolKind enum)
|
|
58
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
59
|
+
const SYMBOL_KIND_LABELS = {
|
|
60
|
+
1: "File",
|
|
61
|
+
2: "Module",
|
|
62
|
+
3: "Namespace",
|
|
63
|
+
4: "Package",
|
|
64
|
+
5: "Class",
|
|
65
|
+
6: "Method",
|
|
66
|
+
7: "Property",
|
|
67
|
+
8: "Field",
|
|
68
|
+
9: "Constructor",
|
|
69
|
+
10: "Enum",
|
|
70
|
+
11: "Interface",
|
|
71
|
+
12: "Function",
|
|
72
|
+
13: "Variable",
|
|
73
|
+
14: "Constant",
|
|
74
|
+
15: "String",
|
|
75
|
+
16: "Number",
|
|
76
|
+
17: "Boolean",
|
|
77
|
+
18: "Array",
|
|
78
|
+
19: "Object",
|
|
79
|
+
20: "Key",
|
|
80
|
+
21: "Null",
|
|
81
|
+
22: "EnumMember",
|
|
82
|
+
23: "Struct",
|
|
83
|
+
24: "Event",
|
|
84
|
+
25: "Operator",
|
|
85
|
+
26: "TypeParameter",
|
|
86
|
+
};
|
|
87
|
+
/**
|
|
88
|
+
* LSP DiagnosticSeverity values (LSP spec §3.16.1).
|
|
89
|
+
*/
|
|
90
|
+
const DIAGNOSTIC_SEVERITY_LABELS = {
|
|
91
|
+
1: "Error",
|
|
92
|
+
2: "Warning",
|
|
93
|
+
3: "Information",
|
|
94
|
+
4: "Hint",
|
|
95
|
+
};
|
|
96
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
97
|
+
// Extension → LSP languageId lookup (internal — not user-configurable)
|
|
98
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
99
|
+
/**
|
|
100
|
+
* Maps file extensions to their canonical LSP `languageId` strings.
|
|
101
|
+
* This table is internal; callers never configure it.
|
|
102
|
+
*/
|
|
103
|
+
const EXTENSION_TO_LANGUAGE_ID = {
|
|
104
|
+
".ts": "typescript",
|
|
105
|
+
".tsx": "typescriptreact",
|
|
106
|
+
".js": "javascript",
|
|
107
|
+
".jsx": "javascriptreact",
|
|
108
|
+
".mjs": "javascript",
|
|
109
|
+
".cjs": "javascript",
|
|
110
|
+
".py": "python",
|
|
111
|
+
".pyi": "python",
|
|
112
|
+
".rs": "rust",
|
|
113
|
+
".go": "go",
|
|
114
|
+
".c": "c",
|
|
115
|
+
".h": "c",
|
|
116
|
+
".cpp": "cpp",
|
|
117
|
+
".cc": "cpp",
|
|
118
|
+
".cxx": "cpp",
|
|
119
|
+
".hpp": "cpp",
|
|
120
|
+
".json": "json",
|
|
121
|
+
".jsonc": "jsonc",
|
|
122
|
+
".html": "html",
|
|
123
|
+
".htm": "html",
|
|
124
|
+
".css": "css",
|
|
125
|
+
".scss": "scss",
|
|
126
|
+
".less": "less",
|
|
127
|
+
".yaml": "yaml",
|
|
128
|
+
".yml": "yaml",
|
|
129
|
+
".sh": "shellscript",
|
|
130
|
+
".bash": "shellscript",
|
|
131
|
+
};
|
|
132
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
133
|
+
// Default LSP configurations (10 servers covering the most common languages)
|
|
134
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
135
|
+
/**
|
|
136
|
+
* Built-in LSP server configurations covering the ten most common languages.
|
|
137
|
+
*
|
|
138
|
+
* Used when {@link LspRequestOptions.config} is not provided.
|
|
139
|
+
* All binaries must be installed separately on the host system.
|
|
140
|
+
*
|
|
141
|
+
* | Key | Binary | Extensions |
|
|
142
|
+
* |---------------|-----------------------------------|-------------------------------------------|
|
|
143
|
+
* | typescript | typescript-language-server | .ts .tsx .js .jsx .mjs .cjs |
|
|
144
|
+
* | python | pyright-langserver | .py .pyi |
|
|
145
|
+
* | rust | rust-analyzer | .rs |
|
|
146
|
+
* | go | gopls | .go |
|
|
147
|
+
* | clangd | clangd | .c .cpp .cc .cxx .h .hpp |
|
|
148
|
+
* | json | vscode-json-language-server | .json .jsonc |
|
|
149
|
+
* | html | vscode-html-language-server | .html .htm |
|
|
150
|
+
* | css | vscode-css-language-server | .css .scss .less |
|
|
151
|
+
* | yaml | yaml-language-server | .yaml .yml |
|
|
152
|
+
* | shell | bash-language-server | .sh .bash |
|
|
153
|
+
*/
|
|
154
|
+
export const defaultLspConfig = {
|
|
155
|
+
typescript: {
|
|
156
|
+
command: "typescript-language-server",
|
|
157
|
+
args: ["--stdio"],
|
|
158
|
+
extensions: [".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs"],
|
|
159
|
+
},
|
|
160
|
+
python: {
|
|
161
|
+
command: "pyright-langserver",
|
|
162
|
+
args: ["--stdio"],
|
|
163
|
+
extensions: [".py", ".pyi"],
|
|
164
|
+
},
|
|
165
|
+
rust: {
|
|
166
|
+
command: "rust-analyzer",
|
|
167
|
+
extensions: [".rs"],
|
|
168
|
+
},
|
|
169
|
+
go: {
|
|
170
|
+
command: "gopls",
|
|
171
|
+
extensions: [".go"],
|
|
172
|
+
},
|
|
173
|
+
clangd: {
|
|
174
|
+
command: "clangd",
|
|
175
|
+
args: ["--background-index"],
|
|
176
|
+
extensions: [".c", ".cpp", ".cc", ".cxx", ".h", ".hpp"],
|
|
177
|
+
},
|
|
178
|
+
json: {
|
|
179
|
+
command: "vscode-json-language-server",
|
|
180
|
+
args: ["--stdio"],
|
|
181
|
+
extensions: [".json", ".jsonc"],
|
|
182
|
+
},
|
|
183
|
+
html: {
|
|
184
|
+
command: "vscode-html-language-server",
|
|
185
|
+
args: ["--stdio"],
|
|
186
|
+
extensions: [".html", ".htm"],
|
|
187
|
+
},
|
|
188
|
+
css: {
|
|
189
|
+
command: "vscode-css-language-server",
|
|
190
|
+
args: ["--stdio"],
|
|
191
|
+
extensions: [".css", ".scss", ".less"],
|
|
192
|
+
},
|
|
193
|
+
yaml: {
|
|
194
|
+
command: "yaml-language-server",
|
|
195
|
+
args: ["--stdio"],
|
|
196
|
+
extensions: [".yaml", ".yml"],
|
|
197
|
+
},
|
|
198
|
+
shell: {
|
|
199
|
+
command: "bash-language-server",
|
|
200
|
+
args: ["start"],
|
|
201
|
+
extensions: [".sh", ".bash"],
|
|
202
|
+
},
|
|
203
|
+
};
|
|
204
|
+
/**
|
|
205
|
+
* Creates a stateful LSP frame reader attached to a readable stream.
|
|
206
|
+
*
|
|
207
|
+
* Accumulates incoming `Buffer` chunks, parses `Content-Length` headers,
|
|
208
|
+
* and emits one decoded {@link JsonRpcMessage} per complete frame.
|
|
209
|
+
* Malformed JSON is swallowed and logged to `stderr` without crashing the
|
|
210
|
+
* process — the caller handles the resulting missing response via timeout.
|
|
211
|
+
*
|
|
212
|
+
* @param readable - The `stdout` stream of the spawned LSP server process.
|
|
213
|
+
* @returns A {@link FrameReader} handle for handler registration and cleanup.
|
|
214
|
+
*
|
|
215
|
+
* @internal
|
|
216
|
+
*/
|
|
217
|
+
function createFrameReader(readable) {
|
|
218
|
+
let accumulator = Buffer.alloc(0);
|
|
219
|
+
let messageHandler = null;
|
|
220
|
+
function tryDecode() {
|
|
221
|
+
// Loop so we consume multiple buffered frames in a single call.
|
|
222
|
+
while (true) {
|
|
223
|
+
// Find the header terminator \r\n\r\n
|
|
224
|
+
const separatorIndex = accumulator.indexOf("\r\n\r\n");
|
|
225
|
+
if (separatorIndex === -1) {
|
|
226
|
+
// Header not yet complete — wait for more data.
|
|
227
|
+
break;
|
|
228
|
+
}
|
|
229
|
+
const headerBlock = accumulator
|
|
230
|
+
.slice(0, separatorIndex)
|
|
231
|
+
.toString("ascii");
|
|
232
|
+
let contentLength = -1;
|
|
233
|
+
for (const line of headerBlock.split("\r\n")) {
|
|
234
|
+
// Case-insensitive per HTTP/LSP spec; most servers send exact casing.
|
|
235
|
+
const match = /^content-length:\s*(\d+)$/i.exec(line);
|
|
236
|
+
if (match !== null) {
|
|
237
|
+
const parsed = parseInt(match[1] ?? "0", 10);
|
|
238
|
+
if (!isNaN(parsed) && parsed >= 0) {
|
|
239
|
+
contentLength = parsed;
|
|
240
|
+
}
|
|
241
|
+
break;
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
if (contentLength === -1) {
|
|
245
|
+
// Protocol violation — no Content-Length in header block.
|
|
246
|
+
// Cannot recover; drain the accumulator to unblock.
|
|
247
|
+
process.stderr.write("[hernex/lsp] Frame missing Content-Length header; discarding frame.\n");
|
|
248
|
+
accumulator = Buffer.alloc(0);
|
|
249
|
+
break;
|
|
250
|
+
}
|
|
251
|
+
const bodyStart = separatorIndex + 4; // skip \r\n\r\n
|
|
252
|
+
if (accumulator.length < bodyStart + contentLength) {
|
|
253
|
+
// Body not yet fully received — wait for more data.
|
|
254
|
+
break;
|
|
255
|
+
}
|
|
256
|
+
const bodyBytes = accumulator.slice(bodyStart, bodyStart + contentLength);
|
|
257
|
+
// Advance the accumulator past this frame.
|
|
258
|
+
accumulator = accumulator.slice(bodyStart + contentLength);
|
|
259
|
+
let parsed;
|
|
260
|
+
try {
|
|
261
|
+
parsed = JSON.parse(bodyBytes.toString("utf8"));
|
|
262
|
+
}
|
|
263
|
+
catch {
|
|
264
|
+
process.stderr.write("[hernex/lsp] Failed to parse JSON frame body; skipping.\n");
|
|
265
|
+
// Continue loop — there may be more valid frames buffered.
|
|
266
|
+
continue;
|
|
267
|
+
}
|
|
268
|
+
if (messageHandler !== null &&
|
|
269
|
+
typeof parsed === "object" &&
|
|
270
|
+
parsed !== null) {
|
|
271
|
+
messageHandler(parsed);
|
|
272
|
+
}
|
|
273
|
+
}
|
|
274
|
+
}
|
|
275
|
+
const dataListener = (chunk) => {
|
|
276
|
+
accumulator = Buffer.concat([accumulator, chunk]);
|
|
277
|
+
tryDecode();
|
|
278
|
+
};
|
|
279
|
+
readable.on("data", dataListener);
|
|
280
|
+
return {
|
|
281
|
+
onMessage(handler) {
|
|
282
|
+
messageHandler = handler;
|
|
283
|
+
},
|
|
284
|
+
dispose() {
|
|
285
|
+
readable.removeListener("data", dataListener);
|
|
286
|
+
accumulator = Buffer.alloc(0);
|
|
287
|
+
messageHandler = null;
|
|
288
|
+
},
|
|
289
|
+
};
|
|
290
|
+
}
|
|
291
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
292
|
+
// Frame writer
|
|
293
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
294
|
+
/**
|
|
295
|
+
* Encodes a JSON-RPC message into an LSP wire frame and writes it to the
|
|
296
|
+
* given writable stream (the LSP server's stdin).
|
|
297
|
+
*
|
|
298
|
+
* Format: `Content-Length: <byteLen>\r\n\r\n<utf8 body>`
|
|
299
|
+
*
|
|
300
|
+
* @param writable - The `stdin` stream of the spawned LSP server process.
|
|
301
|
+
* @param msg - The JSON-RPC message to encode and send.
|
|
302
|
+
*
|
|
303
|
+
* @internal
|
|
304
|
+
*/
|
|
305
|
+
function writeFrame(writable, msg) {
|
|
306
|
+
const body = JSON.stringify(msg);
|
|
307
|
+
const byteLength = Buffer.byteLength(body, "utf8");
|
|
308
|
+
writable.write(`Content-Length: ${byteLength}\r\n\r\n${body}`, "utf8");
|
|
309
|
+
}
|
|
310
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
311
|
+
// Utilities
|
|
312
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
313
|
+
/**
|
|
314
|
+
* Returns a promise that resolves after `ms` milliseconds.
|
|
315
|
+
*
|
|
316
|
+
* @param ms - Duration to sleep in milliseconds.
|
|
317
|
+
* @internal
|
|
318
|
+
*/
|
|
319
|
+
function sleep(ms) {
|
|
320
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
321
|
+
}
|
|
322
|
+
/**
|
|
323
|
+
* Checks whether a binary name is resolvable on the system `PATH` by running
|
|
324
|
+
* `which <command>`. Returns `true` if found, `false` if not.
|
|
325
|
+
*
|
|
326
|
+
* Uses `execFile` (not `exec`) to avoid shell injection from `command`.
|
|
327
|
+
*
|
|
328
|
+
* @param command - The binary name or absolute path to check.
|
|
329
|
+
* @returns Promise resolving to `true` if the binary is accessible.
|
|
330
|
+
*
|
|
331
|
+
* @internal
|
|
332
|
+
*/
|
|
333
|
+
function isBinaryOnPath(command) {
|
|
334
|
+
return new Promise((resolve) => {
|
|
335
|
+
execFile("which", [command], (error) => {
|
|
336
|
+
resolve(error === null);
|
|
337
|
+
});
|
|
338
|
+
});
|
|
339
|
+
}
|
|
340
|
+
/**
|
|
341
|
+
* Builds a reverse lookup from each file extension to the first
|
|
342
|
+
* {@link LspServerConfig} entry in `config` that claims it.
|
|
343
|
+
*
|
|
344
|
+
* @param config - The resolved LSP config to index.
|
|
345
|
+
* @returns A `Map` from extension (e.g. `".ts"`) to the matching config entry.
|
|
346
|
+
*
|
|
347
|
+
* @internal
|
|
348
|
+
*/
|
|
349
|
+
function buildExtensionMap(config) {
|
|
350
|
+
const map = new Map();
|
|
351
|
+
for (const serverConfig of Object.values(config)) {
|
|
352
|
+
for (const ext of serverConfig.extensions) {
|
|
353
|
+
if (!map.has(ext)) {
|
|
354
|
+
map.set(ext, serverConfig);
|
|
355
|
+
}
|
|
356
|
+
}
|
|
357
|
+
}
|
|
358
|
+
return map;
|
|
359
|
+
}
|
|
360
|
+
/**
|
|
361
|
+
* Converts a file URI (`file:///abs/path`) to an absolute filesystem path.
|
|
362
|
+
* Used when converting LSP Location URIs back to display paths.
|
|
363
|
+
*
|
|
364
|
+
* @param uri - The `file://` URI to convert.
|
|
365
|
+
* @returns The decoded absolute filesystem path, or the original URI string
|
|
366
|
+
* if it is not a `file://` URI (e.g. `untitled://...`).
|
|
367
|
+
*
|
|
368
|
+
* @internal
|
|
369
|
+
*/
|
|
370
|
+
function fileUriToPath(uri) {
|
|
371
|
+
if (!uri.startsWith("file://")) {
|
|
372
|
+
return uri;
|
|
373
|
+
}
|
|
374
|
+
try {
|
|
375
|
+
return new URL(uri).pathname;
|
|
376
|
+
}
|
|
377
|
+
catch {
|
|
378
|
+
return uri;
|
|
379
|
+
}
|
|
380
|
+
}
|
|
381
|
+
/**
|
|
382
|
+
* Formats a 0-based LSP {@link LspPosition} as a human-readable 1-based
|
|
383
|
+
* `line:col` string.
|
|
384
|
+
*
|
|
385
|
+
* @param pos - The LSP position with 0-based line and character.
|
|
386
|
+
* @returns A `"<line>:<col>"` string with 1-based values.
|
|
387
|
+
*
|
|
388
|
+
* @internal
|
|
389
|
+
*/
|
|
390
|
+
function formatPosition(pos) {
|
|
391
|
+
return `${pos.line + 1}:${pos.character + 1}`;
|
|
392
|
+
}
|
|
393
|
+
/**
|
|
394
|
+
* Renders a file URI as a workspace-relative path with an optional position
|
|
395
|
+
* suffix, e.g. `src/tools/BashTool.ts:42:10`.
|
|
396
|
+
*
|
|
397
|
+
* @param uri - The `file://` URI from an LSP Location.
|
|
398
|
+
* @param workingDirectory - The workspace root used for relativisation.
|
|
399
|
+
* @param pos - Optional 0-based LSP position to append.
|
|
400
|
+
* @returns A compact relative `path[:line:col]` string.
|
|
401
|
+
*
|
|
402
|
+
* @internal
|
|
403
|
+
*/
|
|
404
|
+
function formatLocation(uri, workingDirectory, pos) {
|
|
405
|
+
const absPath = fileUriToPath(uri);
|
|
406
|
+
const rel = relative(workingDirectory, absPath) || absPath;
|
|
407
|
+
return pos !== undefined ? `${rel}:${formatPosition(pos)}` : rel;
|
|
408
|
+
}
|
|
409
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
410
|
+
// Result formatters (operation → markdown string)
|
|
411
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
412
|
+
/**
|
|
413
|
+
* Extracts plain text from LSP hover `contents`, which may be a
|
|
414
|
+
* {@link LspMarkupContent}, a {@link LspMarkedString}, or an array thereof.
|
|
415
|
+
*
|
|
416
|
+
* @param contents - The raw `contents` field from the LSP hover response.
|
|
417
|
+
* @returns A flat string suitable for markdown output.
|
|
418
|
+
*
|
|
419
|
+
* @internal
|
|
420
|
+
*/
|
|
421
|
+
function extractHoverText(contents) {
|
|
422
|
+
if (typeof contents === "string") {
|
|
423
|
+
return contents;
|
|
424
|
+
}
|
|
425
|
+
if (Array.isArray(contents)) {
|
|
426
|
+
return contents
|
|
427
|
+
.map((c) => typeof c === "string" ? c : `\`\`\`${c.language}\n${c.value}\n\`\`\``)
|
|
428
|
+
.join("\n\n");
|
|
429
|
+
}
|
|
430
|
+
// LspMarkupContent or { language, value }
|
|
431
|
+
if ("kind" in contents) {
|
|
432
|
+
return contents.value;
|
|
433
|
+
}
|
|
434
|
+
if ("language" in contents && "value" in contents) {
|
|
435
|
+
return `\`\`\`${contents.language}\n${contents.value}\n\`\`\``;
|
|
436
|
+
}
|
|
437
|
+
return String(contents);
|
|
438
|
+
}
|
|
439
|
+
/**
|
|
440
|
+
* Normalises a `textDocument/definition`, `textDocument/implementation`, or
|
|
441
|
+
* `textDocument/references` result into an array of {@link LspLocation}
|
|
442
|
+
* objects regardless of whether the server returned a single Location,
|
|
443
|
+
* an array of Locations, or an array of LocationLinks.
|
|
444
|
+
*
|
|
445
|
+
* @param raw - The raw `result` from the LSP response.
|
|
446
|
+
* @returns An array of normalised {@link LspLocation} objects.
|
|
447
|
+
*
|
|
448
|
+
* @internal
|
|
449
|
+
*/
|
|
450
|
+
function normaliseLocations(raw) {
|
|
451
|
+
if (raw === null || raw === undefined) {
|
|
452
|
+
return [];
|
|
453
|
+
}
|
|
454
|
+
// Single Location object: { uri, range }
|
|
455
|
+
if (typeof raw === "object" &&
|
|
456
|
+
!Array.isArray(raw) &&
|
|
457
|
+
"uri" in raw &&
|
|
458
|
+
"range" in raw) {
|
|
459
|
+
return [raw];
|
|
460
|
+
}
|
|
461
|
+
if (!Array.isArray(raw)) {
|
|
462
|
+
return [];
|
|
463
|
+
}
|
|
464
|
+
const locations = [];
|
|
465
|
+
for (const item of raw) {
|
|
466
|
+
if (typeof item !== "object" || item === null)
|
|
467
|
+
continue;
|
|
468
|
+
if ("uri" in item && "range" in item) {
|
|
469
|
+
// Location
|
|
470
|
+
locations.push(item);
|
|
471
|
+
}
|
|
472
|
+
else if ("targetUri" in item && "targetSelectionRange" in item) {
|
|
473
|
+
// LocationLink
|
|
474
|
+
const link = item;
|
|
475
|
+
locations.push({
|
|
476
|
+
uri: link.targetUri,
|
|
477
|
+
range: link.targetSelectionRange,
|
|
478
|
+
});
|
|
479
|
+
}
|
|
480
|
+
}
|
|
481
|
+
return locations;
|
|
482
|
+
}
|
|
483
|
+
/**
|
|
484
|
+
* Formats hover results into a compact markdown code block.
|
|
485
|
+
*
|
|
486
|
+
* @param raw - The raw `result` from `textDocument/hover`.
|
|
487
|
+
* @returns Formatted markdown string, or `"No hover information."`.
|
|
488
|
+
*
|
|
489
|
+
* @internal
|
|
490
|
+
*/
|
|
491
|
+
function formatHover(raw) {
|
|
492
|
+
if (raw === null || raw === undefined) {
|
|
493
|
+
return "No hover information.";
|
|
494
|
+
}
|
|
495
|
+
const hover = raw;
|
|
496
|
+
const text = extractHoverText(hover.contents).trim();
|
|
497
|
+
if (text.length === 0) {
|
|
498
|
+
return "No hover information.";
|
|
499
|
+
}
|
|
500
|
+
return `**Hover**\n\n${text}`;
|
|
501
|
+
}
|
|
502
|
+
/**
|
|
503
|
+
* Formats definition / implementation / references results into a markdown
|
|
504
|
+
* bullet list of `path:line:col` locations.
|
|
505
|
+
*
|
|
506
|
+
* @param raw - The raw `result` from the LSP response.
|
|
507
|
+
* @param header - Section heading (e.g. `"Definitions"`).
|
|
508
|
+
* @param workingDirectory - Workspace root for relative path rendering.
|
|
509
|
+
* @returns Formatted markdown string.
|
|
510
|
+
*
|
|
511
|
+
* @internal
|
|
512
|
+
*/
|
|
513
|
+
function formatLocations(raw, header, workingDirectory) {
|
|
514
|
+
const locations = normaliseLocations(raw);
|
|
515
|
+
if (locations.length === 0) {
|
|
516
|
+
return `No ${header.toLowerCase()}.`;
|
|
517
|
+
}
|
|
518
|
+
const lines = locations.map((loc) => `- ${formatLocation(loc.uri, workingDirectory, loc.range.start)}`);
|
|
519
|
+
return `**${header}**\n\n${lines.join("\n")}`;
|
|
520
|
+
}
|
|
521
|
+
/**
|
|
522
|
+
* Recursively renders a {@link LspDocumentSymbol} tree as an indented
|
|
523
|
+
* markdown list.
|
|
524
|
+
*
|
|
525
|
+
* @param symbols - Array of document symbols (may be nested).
|
|
526
|
+
* @param indent - Current indentation prefix string.
|
|
527
|
+
* @returns Lines of the rendered tree.
|
|
528
|
+
*
|
|
529
|
+
* @internal
|
|
530
|
+
*/
|
|
531
|
+
function renderDocumentSymbolTree(symbols, indent) {
|
|
532
|
+
const lines = [];
|
|
533
|
+
for (const sym of symbols) {
|
|
534
|
+
const kindLabel = SYMBOL_KIND_LABELS[sym.kind] ?? `Kind(${sym.kind})`;
|
|
535
|
+
const detail = sym.detail !== undefined ? ` — ${sym.detail}` : "";
|
|
536
|
+
const pos = formatPosition(sym.selectionRange.start);
|
|
537
|
+
lines.push(`${indent}- **${sym.name}** \`${kindLabel}\`${detail} ·\u202F\`${pos}\``);
|
|
538
|
+
if (sym.children !== undefined && sym.children.length > 0) {
|
|
539
|
+
lines.push(...renderDocumentSymbolTree(sym.children, `${indent} `));
|
|
540
|
+
}
|
|
541
|
+
}
|
|
542
|
+
return lines;
|
|
543
|
+
}
|
|
544
|
+
/**
|
|
545
|
+
* Formats `textDocument/documentSymbol` results into a markdown tree.
|
|
546
|
+
* The server may return {@link LspDocumentSymbol}[] (hierarchical) or
|
|
547
|
+
* {@link LspSymbolInformation}[] (flat) — both are handled.
|
|
548
|
+
*
|
|
549
|
+
* @param raw - The raw `result` from `textDocument/documentSymbol`.
|
|
550
|
+
* @param workingDirectory - Workspace root (used for flat SymbolInformation).
|
|
551
|
+
* @returns Formatted markdown string.
|
|
552
|
+
*
|
|
553
|
+
* @internal
|
|
554
|
+
*/
|
|
555
|
+
function formatDocumentSymbol(raw, workingDirectory) {
|
|
556
|
+
if (!Array.isArray(raw) || raw.length === 0) {
|
|
557
|
+
return "No symbols found.";
|
|
558
|
+
}
|
|
559
|
+
const first = raw[0];
|
|
560
|
+
if (typeof first === "object" &&
|
|
561
|
+
first !== null &&
|
|
562
|
+
"selectionRange" in first) {
|
|
563
|
+
// DocumentSymbol[] — hierarchical
|
|
564
|
+
const symbols = raw;
|
|
565
|
+
const lines = renderDocumentSymbolTree(symbols, "");
|
|
566
|
+
return `**Document Symbols**\n\n${lines.join("\n")}`;
|
|
567
|
+
}
|
|
568
|
+
// SymbolInformation[] — flat (older LSP servers)
|
|
569
|
+
const symbols = raw;
|
|
570
|
+
const lines = symbols.map((sym) => {
|
|
571
|
+
const kindLabel = SYMBOL_KIND_LABELS[sym.kind] ?? `Kind(${sym.kind})`;
|
|
572
|
+
const loc = formatLocation(sym.location.uri, workingDirectory, sym.location.range.start);
|
|
573
|
+
const container = sym.containerName !== undefined ? ` _(${sym.containerName})_` : "";
|
|
574
|
+
return `- **${sym.name}** \`${kindLabel}\`${container} · \`${loc}\``;
|
|
575
|
+
});
|
|
576
|
+
return `**Document Symbols**\n\n${lines.join("\n")}`;
|
|
577
|
+
}
|
|
578
|
+
/**
|
|
579
|
+
* Formats `workspace/symbol` results into a markdown list.
|
|
580
|
+
*
|
|
581
|
+
* @param raw - The raw `result` from `workspace/symbol`.
|
|
582
|
+
* @param workingDirectory - Workspace root for relative path rendering.
|
|
583
|
+
* @returns Formatted markdown string.
|
|
584
|
+
*
|
|
585
|
+
* @internal
|
|
586
|
+
*/
|
|
587
|
+
function formatWorkspaceSymbol(raw, workingDirectory) {
|
|
588
|
+
if (!Array.isArray(raw) || raw.length === 0) {
|
|
589
|
+
return "No workspace symbols found.";
|
|
590
|
+
}
|
|
591
|
+
const symbols = raw;
|
|
592
|
+
const lines = symbols.slice(0, 100).map((sym) => {
|
|
593
|
+
const kindLabel = SYMBOL_KIND_LABELS[sym.kind] ?? `Kind(${sym.kind})`;
|
|
594
|
+
const loc = formatLocation(sym.location.uri, workingDirectory, sym.location.range.start);
|
|
595
|
+
return `- \`${kindLabel}\` **${sym.name}** · \`${loc}\``;
|
|
596
|
+
});
|
|
597
|
+
const truncated = symbols.length > 100
|
|
598
|
+
? `\n\n_(${symbols.length - 100} more results omitted)_`
|
|
599
|
+
: "";
|
|
600
|
+
return `**Workspace Symbols**\n\n${lines.join("\n")}${truncated}`;
|
|
601
|
+
}
|
|
602
|
+
/**
|
|
603
|
+
* Formats `textDocument/publishDiagnostics` notifications into a markdown
|
|
604
|
+
* report grouped by severity.
|
|
605
|
+
*
|
|
606
|
+
* @param diagnostics - Collected diagnostics from the server notification.
|
|
607
|
+
* @param fileUri - The file URI these diagnostics belong to.
|
|
608
|
+
* @param workingDirectory - Workspace root for relative path rendering.
|
|
609
|
+
* @returns Formatted markdown string.
|
|
610
|
+
*
|
|
611
|
+
* @internal
|
|
612
|
+
*/
|
|
613
|
+
function formatDiagnostics(diagnostics, fileUri, workingDirectory) {
|
|
614
|
+
if (diagnostics.length === 0) {
|
|
615
|
+
return "No diagnostics. File is clean.";
|
|
616
|
+
}
|
|
617
|
+
const relPath = formatLocation(fileUri, workingDirectory);
|
|
618
|
+
// Group by severity (1=Error, 2=Warning, 3=Information, 4=Hint, undefined=Unknown)
|
|
619
|
+
const grouped = new Map();
|
|
620
|
+
for (const diag of diagnostics) {
|
|
621
|
+
const sev = diag.severity ?? 1;
|
|
622
|
+
let bucket = grouped.get(sev);
|
|
623
|
+
if (bucket === undefined) {
|
|
624
|
+
bucket = [];
|
|
625
|
+
grouped.set(sev, bucket);
|
|
626
|
+
}
|
|
627
|
+
bucket.push(diag);
|
|
628
|
+
}
|
|
629
|
+
const sections = [];
|
|
630
|
+
for (const [sev, items] of [...grouped.entries()].sort(([a], [b]) => a - b)) {
|
|
631
|
+
const label = DIAGNOSTIC_SEVERITY_LABELS[sev] ?? "Unknown";
|
|
632
|
+
const lines = items.map((d) => {
|
|
633
|
+
const pos = formatPosition(d.range.start);
|
|
634
|
+
const src = d.source !== undefined ? ` [${d.source}]` : "";
|
|
635
|
+
const code = d.code !== undefined ? ` (${String(d.code)})` : "";
|
|
636
|
+
return ` - \`${relPath}:${pos}\`${src}${code} — ${d.message}`;
|
|
637
|
+
});
|
|
638
|
+
sections.push(`**${label}** (${items.length})\n${lines.join("\n")}`);
|
|
639
|
+
}
|
|
640
|
+
return `**Diagnostics**\n\n${sections.join("\n\n")}`;
|
|
641
|
+
}
|
|
642
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
643
|
+
// Main exported function
|
|
644
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
645
|
+
/**
|
|
646
|
+
* Executes a single on-demand LSP operation against the appropriate language
|
|
647
|
+
* server for the given file.
|
|
648
|
+
*
|
|
649
|
+
* **Lifecycle per call:**
|
|
650
|
+
* 1. Validate inputs (path guard, file size, binary presence).
|
|
651
|
+
* 2. Spawn the LSP server with sanitized stdio.
|
|
652
|
+
* 3. Await the `'spawn'` event before writing any frames.
|
|
653
|
+
* 4. Perform the LSP handshake: `initialize` → `initialized`.
|
|
654
|
+
* 5. Send `textDocument/didOpen`.
|
|
655
|
+
* 6. Dispatch the requested operation (with retry on `-32801`).
|
|
656
|
+
* 7. Teardown: `shutdown` → `exit` → drain → SIGKILL if needed.
|
|
657
|
+
* 8. Return a `{ ok: true, markdown }` or `{ ok: false, error }` result.
|
|
658
|
+
*
|
|
659
|
+
* @param options - Request parameters; see {@link LspRequestOptions}.
|
|
660
|
+
* @returns A promise resolving to an {@link LspResult}.
|
|
661
|
+
*
|
|
662
|
+
* @example
|
|
663
|
+
* ```typescript
|
|
664
|
+
* const result = await runLspRequest({
|
|
665
|
+
* filePath: "src/index.ts",
|
|
666
|
+
* operation: "hover",
|
|
667
|
+
* line: 12,
|
|
668
|
+
* character: 8,
|
|
669
|
+
* workingDirectory: "/home/user/myproject",
|
|
670
|
+
* });
|
|
671
|
+
* if (result.ok) {
|
|
672
|
+
* console.log(result.markdown);
|
|
673
|
+
* } else {
|
|
674
|
+
* console.error(result.error);
|
|
675
|
+
* }
|
|
676
|
+
* ```
|
|
677
|
+
*/
|
|
678
|
+
export async function runLspRequest(options) {
|
|
679
|
+
const { operation, workingDirectory, query, timeoutMs = DEFAULT_LSP_TIMEOUT_MS, } = options;
|
|
680
|
+
const resolvedConfig = options.config ?? defaultLspConfig;
|
|
681
|
+
// ── Step 1: Resolve the file path (path containment guard) ────────────────
|
|
682
|
+
let resolvedFilePath;
|
|
683
|
+
try {
|
|
684
|
+
resolvedFilePath = resolvePathWithinWorkspace(options.filePath, workingDirectory);
|
|
685
|
+
}
|
|
686
|
+
catch (err) {
|
|
687
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
688
|
+
return { ok: false, error: msg };
|
|
689
|
+
}
|
|
690
|
+
// ── Step 2: Determine the file extension and find the matching LSP server ──
|
|
691
|
+
const ext = extname(resolvedFilePath).toLowerCase();
|
|
692
|
+
const extensionMap = buildExtensionMap(resolvedConfig);
|
|
693
|
+
const serverConfig = extensionMap.get(ext);
|
|
694
|
+
if (serverConfig === undefined) {
|
|
695
|
+
return {
|
|
696
|
+
ok: false,
|
|
697
|
+
error: `No LSP server configured for "${ext}" files. ` +
|
|
698
|
+
`Add a server entry with \`extensions: ["${ext}"]\` to your LspConfig, ` +
|
|
699
|
+
`or use the default config which covers .ts, .py, .rs, .go, .c, .cpp, ` +
|
|
700
|
+
`.json, .html, .css, .yaml, and .sh.`,
|
|
701
|
+
};
|
|
702
|
+
}
|
|
703
|
+
// ── Step 3: File stat (existence + size check) ────────────────────────────
|
|
704
|
+
let fileStat;
|
|
705
|
+
try {
|
|
706
|
+
fileStat = await stat(resolvedFilePath);
|
|
707
|
+
}
|
|
708
|
+
catch (err) {
|
|
709
|
+
const code = typeof err === "object" && err !== null && "code" in err
|
|
710
|
+
? err.code
|
|
711
|
+
: undefined;
|
|
712
|
+
if (code === "ENOENT") {
|
|
713
|
+
return {
|
|
714
|
+
ok: false,
|
|
715
|
+
error: `File not found: ${options.filePath}`,
|
|
716
|
+
};
|
|
717
|
+
}
|
|
718
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
719
|
+
return { ok: false, error: `Failed to stat file: ${msg}` };
|
|
720
|
+
}
|
|
721
|
+
if (!fileStat.isFile()) {
|
|
722
|
+
return {
|
|
723
|
+
ok: false,
|
|
724
|
+
error: `Path "${options.filePath}" is not a regular file.`,
|
|
725
|
+
};
|
|
726
|
+
}
|
|
727
|
+
if (fileStat.size > MAX_FILE_BYTES) {
|
|
728
|
+
const mb = (fileStat.size / (1024 * 1024)).toFixed(1);
|
|
729
|
+
return {
|
|
730
|
+
ok: false,
|
|
731
|
+
error: `File "${options.filePath}" is ${mb} MB, which exceeds the 10 MB limit for LSP analysis.`,
|
|
732
|
+
};
|
|
733
|
+
}
|
|
734
|
+
// ── Step 4: Binary presence check ─────────────────────────────────────────
|
|
735
|
+
const binaryFound = await isBinaryOnPath(serverConfig.command);
|
|
736
|
+
if (!binaryFound) {
|
|
737
|
+
return {
|
|
738
|
+
ok: false,
|
|
739
|
+
error: `LSP server binary "${serverConfig.command}" was not found on PATH. ` +
|
|
740
|
+
`Install it and ensure it is accessible before using this operation.`,
|
|
741
|
+
};
|
|
742
|
+
}
|
|
743
|
+
// ── Step 5: Build the subprocess environment ───────────────────────────────
|
|
744
|
+
// Inherit only the safe host variables (PATH, HOME, etc.) and merge in any
|
|
745
|
+
// server-specific extras. We do not forward secrets or Hernex internals.
|
|
746
|
+
const safeEnv = {};
|
|
747
|
+
const SAFE_HOST_VARS = new Set([
|
|
748
|
+
"PATH",
|
|
749
|
+
"HOME",
|
|
750
|
+
"USER",
|
|
751
|
+
"LOGNAME",
|
|
752
|
+
"SHELL",
|
|
753
|
+
"LANG",
|
|
754
|
+
"LC_ALL",
|
|
755
|
+
"LC_CTYPE",
|
|
756
|
+
"LC_MESSAGES",
|
|
757
|
+
"TMPDIR",
|
|
758
|
+
"TMP",
|
|
759
|
+
"TEMP",
|
|
760
|
+
"PWD",
|
|
761
|
+
"EDITOR",
|
|
762
|
+
"VISUAL",
|
|
763
|
+
"PAGER",
|
|
764
|
+
"NODE_PATH",
|
|
765
|
+
"NODE_ENV",
|
|
766
|
+
"XDG_RUNTIME_DIR",
|
|
767
|
+
"XDG_CONFIG_HOME",
|
|
768
|
+
"XDG_DATA_HOME",
|
|
769
|
+
]);
|
|
770
|
+
const SENSITIVE_ENV_PATTERN = /(API_KEY|TOKEN|SECRET|PASSWORD|CREDENTIAL|AUTH|HERNEX_HOME|GREG_)/i;
|
|
771
|
+
for (const [key, value] of Object.entries(process.env)) {
|
|
772
|
+
if (value === undefined)
|
|
773
|
+
continue;
|
|
774
|
+
if (SAFE_HOST_VARS.has(key) && !SENSITIVE_ENV_PATTERN.test(key)) {
|
|
775
|
+
safeEnv[key] = value;
|
|
776
|
+
}
|
|
777
|
+
}
|
|
778
|
+
if (serverConfig.env !== undefined) {
|
|
779
|
+
for (const [key, value] of Object.entries(serverConfig.env)) {
|
|
780
|
+
safeEnv[key] = value;
|
|
781
|
+
}
|
|
782
|
+
}
|
|
783
|
+
// ── Step 6: Spawn the LSP server ──────────────────────────────────────────
|
|
784
|
+
const args = serverConfig.args !== undefined ? [...serverConfig.args] : [];
|
|
785
|
+
const proc = spawn(serverConfig.command, args, {
|
|
786
|
+
stdio: ["pipe", "pipe", "pipe"],
|
|
787
|
+
env: safeEnv,
|
|
788
|
+
cwd: workingDirectory,
|
|
789
|
+
});
|
|
790
|
+
let processDead = false;
|
|
791
|
+
let processExitCode = null;
|
|
792
|
+
let processExitSignal = null;
|
|
793
|
+
proc.on("exit", (code, signal) => {
|
|
794
|
+
processDead = true;
|
|
795
|
+
processExitCode = code;
|
|
796
|
+
processExitSignal = signal;
|
|
797
|
+
});
|
|
798
|
+
// Collect stderr for diagnostics — never surface to model unless we re-throw.
|
|
799
|
+
let stderrAccum = "";
|
|
800
|
+
proc.stderr.on("data", (chunk) => {
|
|
801
|
+
stderrAccum += chunk.toString("utf8");
|
|
802
|
+
// Cap stderr buffer to 8 KB to avoid unbounded memory growth.
|
|
803
|
+
if (stderrAccum.length > 8192) {
|
|
804
|
+
stderrAccum = stderrAccum.slice(stderrAccum.length - 8192);
|
|
805
|
+
}
|
|
806
|
+
});
|
|
807
|
+
// ── Step 7: Await the 'spawn' event (guards against ENOENT at exec time) ──
|
|
808
|
+
try {
|
|
809
|
+
await new Promise((resolve, reject) => {
|
|
810
|
+
const spawnTimer = setTimeout(() => {
|
|
811
|
+
reject(new Error("LSP server process did not emit 'spawn' within 5s."));
|
|
812
|
+
}, 5_000);
|
|
813
|
+
proc.once("spawn", () => {
|
|
814
|
+
clearTimeout(spawnTimer);
|
|
815
|
+
resolve();
|
|
816
|
+
});
|
|
817
|
+
proc.once("error", (err) => {
|
|
818
|
+
clearTimeout(spawnTimer);
|
|
819
|
+
reject(err);
|
|
820
|
+
});
|
|
821
|
+
});
|
|
822
|
+
}
|
|
823
|
+
catch (spawnErr) {
|
|
824
|
+
const msg = spawnErr instanceof Error ? spawnErr.message : String(spawnErr);
|
|
825
|
+
return {
|
|
826
|
+
ok: false,
|
|
827
|
+
error: `Failed to start LSP server "${serverConfig.command}": ${msg}`,
|
|
828
|
+
};
|
|
829
|
+
}
|
|
830
|
+
// ── Step 8: Set up frame reader and pending request registry ──────────────
|
|
831
|
+
const frameReader = createFrameReader(proc.stdout);
|
|
832
|
+
// Collected notifications (for diagnostics capture)
|
|
833
|
+
const notifications = [];
|
|
834
|
+
// Pending requests: id → { resolve, reject, timer }
|
|
835
|
+
const pendingRequests = new Map();
|
|
836
|
+
let nextId = 1;
|
|
837
|
+
frameReader.onMessage((msg) => {
|
|
838
|
+
if (processDead)
|
|
839
|
+
return;
|
|
840
|
+
// Determine message type by shape.
|
|
841
|
+
if ("id" in msg && ("result" in msg || "error" in msg)) {
|
|
842
|
+
// JSON-RPC Response
|
|
843
|
+
const response = msg;
|
|
844
|
+
const pending = pendingRequests.get(response.id);
|
|
845
|
+
if (pending !== undefined) {
|
|
846
|
+
clearTimeout(pending.timer);
|
|
847
|
+
pendingRequests.delete(response.id);
|
|
848
|
+
if (response.error !== undefined) {
|
|
849
|
+
const rpcErr = new Error(`LSP error ${response.error.code}: ${response.error.message}`);
|
|
850
|
+
// Attach the code so retry logic can inspect it.
|
|
851
|
+
rpcErr.code = response.error.code;
|
|
852
|
+
pending.reject(rpcErr);
|
|
853
|
+
}
|
|
854
|
+
else {
|
|
855
|
+
pending.resolve(response.result);
|
|
856
|
+
}
|
|
857
|
+
}
|
|
858
|
+
}
|
|
859
|
+
else if ("method" in msg && !("id" in msg)) {
|
|
860
|
+
// JSON-RPC Notification
|
|
861
|
+
notifications.push(msg);
|
|
862
|
+
}
|
|
863
|
+
// Requests from the server (e.g. window/showMessage) are intentionally ignored.
|
|
864
|
+
});
|
|
865
|
+
// ── Teardown helper (always runs) ─────────────────────────────────────────
|
|
866
|
+
async function teardown() {
|
|
867
|
+
// Cancel all pending requests to unblock any awaiting callers.
|
|
868
|
+
for (const [id, pending] of pendingRequests.entries()) {
|
|
869
|
+
clearTimeout(pending.timer);
|
|
870
|
+
pending.reject(new Error("LSP session terminated during teardown."));
|
|
871
|
+
pendingRequests.delete(id);
|
|
872
|
+
}
|
|
873
|
+
if (!processDead) {
|
|
874
|
+
// Send shutdown request (best-effort, short timeout).
|
|
875
|
+
try {
|
|
876
|
+
const shutdownId = nextId++;
|
|
877
|
+
await new Promise((resolve) => {
|
|
878
|
+
const t = setTimeout(resolve, SHUTDOWN_TIMEOUT_MS);
|
|
879
|
+
const shutdownMsg = {
|
|
880
|
+
jsonrpc: "2.0",
|
|
881
|
+
id: shutdownId,
|
|
882
|
+
method: "shutdown",
|
|
883
|
+
params: null,
|
|
884
|
+
};
|
|
885
|
+
pendingRequests.set(shutdownId, {
|
|
886
|
+
resolve: () => {
|
|
887
|
+
clearTimeout(t);
|
|
888
|
+
resolve();
|
|
889
|
+
},
|
|
890
|
+
reject: () => {
|
|
891
|
+
clearTimeout(t);
|
|
892
|
+
resolve();
|
|
893
|
+
}, // ignore shutdown errors
|
|
894
|
+
timer: t,
|
|
895
|
+
});
|
|
896
|
+
writeFrame(proc.stdin, shutdownMsg);
|
|
897
|
+
});
|
|
898
|
+
}
|
|
899
|
+
catch {
|
|
900
|
+
// Ignore — server may already be exiting.
|
|
901
|
+
}
|
|
902
|
+
// Send exit notification.
|
|
903
|
+
if (!processDead) {
|
|
904
|
+
try {
|
|
905
|
+
const exitNotif = {
|
|
906
|
+
jsonrpc: "2.0",
|
|
907
|
+
method: "exit",
|
|
908
|
+
params: undefined,
|
|
909
|
+
};
|
|
910
|
+
writeFrame(proc.stdin, exitNotif);
|
|
911
|
+
proc.stdin.end();
|
|
912
|
+
}
|
|
913
|
+
catch {
|
|
914
|
+
// stdin may already be closed.
|
|
915
|
+
}
|
|
916
|
+
}
|
|
917
|
+
// Wait for the process to exit with a grace period.
|
|
918
|
+
await new Promise((resolve) => {
|
|
919
|
+
if (processDead) {
|
|
920
|
+
resolve();
|
|
921
|
+
return;
|
|
922
|
+
}
|
|
923
|
+
const graceTimer = setTimeout(() => {
|
|
924
|
+
if (!processDead) {
|
|
925
|
+
proc.kill("SIGKILL");
|
|
926
|
+
}
|
|
927
|
+
resolve();
|
|
928
|
+
}, TEARDOWN_GRACE_MS);
|
|
929
|
+
proc.once("exit", () => {
|
|
930
|
+
clearTimeout(graceTimer);
|
|
931
|
+
resolve();
|
|
932
|
+
});
|
|
933
|
+
});
|
|
934
|
+
}
|
|
935
|
+
frameReader.dispose();
|
|
936
|
+
}
|
|
937
|
+
// ── sendRequest helper ────────────────────────────────────────────────────
|
|
938
|
+
/**
|
|
939
|
+
* Sends a JSON-RPC request and returns a promise that resolves with the
|
|
940
|
+
* `result` value, or rejects with an error on timeout, server error, or
|
|
941
|
+
* process death.
|
|
942
|
+
*
|
|
943
|
+
* @param method - The JSON-RPC method name.
|
|
944
|
+
* @param params - The method parameters.
|
|
945
|
+
* @param overrideTimeoutMs - Override timeout for this specific request.
|
|
946
|
+
* @internal
|
|
947
|
+
*/
|
|
948
|
+
function sendRequest(method, params, overrideTimeoutMs) {
|
|
949
|
+
return new Promise((resolve, reject) => {
|
|
950
|
+
if (processDead) {
|
|
951
|
+
reject(new Error(`LSP server exited (code ${String(processExitCode)}, signal ${String(processExitSignal)}) before "${method}" could be sent.`));
|
|
952
|
+
return;
|
|
953
|
+
}
|
|
954
|
+
const id = nextId++;
|
|
955
|
+
const effectiveTimeout = overrideTimeoutMs ?? timeoutMs;
|
|
956
|
+
const timer = setTimeout(() => {
|
|
957
|
+
pendingRequests.delete(id);
|
|
958
|
+
reject(new Error(`LSP request "${method}" timed out after ${effectiveTimeout}ms.`));
|
|
959
|
+
}, effectiveTimeout);
|
|
960
|
+
pendingRequests.set(id, { resolve, reject, timer });
|
|
961
|
+
const request = {
|
|
962
|
+
jsonrpc: "2.0",
|
|
963
|
+
id,
|
|
964
|
+
method,
|
|
965
|
+
params,
|
|
966
|
+
};
|
|
967
|
+
try {
|
|
968
|
+
writeFrame(proc.stdin, request);
|
|
969
|
+
}
|
|
970
|
+
catch (writeErr) {
|
|
971
|
+
clearTimeout(timer);
|
|
972
|
+
pendingRequests.delete(id);
|
|
973
|
+
const msg = writeErr instanceof Error ? writeErr.message : String(writeErr);
|
|
974
|
+
reject(new Error(`Failed to write LSP frame for "${method}": ${msg}`));
|
|
975
|
+
}
|
|
976
|
+
});
|
|
977
|
+
}
|
|
978
|
+
/**
|
|
979
|
+
* Sends a JSON-RPC notification (no response expected).
|
|
980
|
+
*
|
|
981
|
+
* @param method - The notification method name.
|
|
982
|
+
* @param params - The notification parameters.
|
|
983
|
+
* @internal
|
|
984
|
+
*/
|
|
985
|
+
function sendNotification(method, params) {
|
|
986
|
+
if (processDead)
|
|
987
|
+
return;
|
|
988
|
+
const notif = {
|
|
989
|
+
jsonrpc: "2.0",
|
|
990
|
+
method,
|
|
991
|
+
params,
|
|
992
|
+
};
|
|
993
|
+
try {
|
|
994
|
+
writeFrame(proc.stdin, notif);
|
|
995
|
+
}
|
|
996
|
+
catch {
|
|
997
|
+
// stdin may be closed — nothing to do.
|
|
998
|
+
}
|
|
999
|
+
}
|
|
1000
|
+
// ── Main operation flow ───────────────────────────────────────────────────
|
|
1001
|
+
try {
|
|
1002
|
+
// ── Step 9: initialize handshake ────────────────────────────────────────
|
|
1003
|
+
const rootUri = pathToFileURL(workingDirectory).href;
|
|
1004
|
+
await sendRequest("initialize", {
|
|
1005
|
+
processId: process.pid,
|
|
1006
|
+
rootUri,
|
|
1007
|
+
capabilities: {
|
|
1008
|
+
textDocument: {
|
|
1009
|
+
hover: { contentFormat: ["plaintext", "markdown"] },
|
|
1010
|
+
definition: {},
|
|
1011
|
+
references: {},
|
|
1012
|
+
implementation: {},
|
|
1013
|
+
documentSymbol: { hierarchicalDocumentSymbolSupport: true },
|
|
1014
|
+
publishDiagnostics: {
|
|
1015
|
+
versionSupport: false,
|
|
1016
|
+
relatedInformation: false,
|
|
1017
|
+
},
|
|
1018
|
+
},
|
|
1019
|
+
workspace: {
|
|
1020
|
+
symbol: { resolveSupport: { properties: [] } },
|
|
1021
|
+
},
|
|
1022
|
+
},
|
|
1023
|
+
workspaceFolders: null,
|
|
1024
|
+
});
|
|
1025
|
+
// ── Step 10: initialized notification ───────────────────────────────────
|
|
1026
|
+
sendNotification("initialized", {});
|
|
1027
|
+
// ── Step 11: textDocument/didOpen ────────────────────────────────────────
|
|
1028
|
+
// Read file contents synchronously — we already stat'd the file above and
|
|
1029
|
+
// know it is a regular file within the size limit.
|
|
1030
|
+
const { readFileSync } = await import("node:fs");
|
|
1031
|
+
const fileText = readFileSync(resolvedFilePath, "utf8");
|
|
1032
|
+
const textDocumentUri = pathToFileURL(resolvedFilePath).href;
|
|
1033
|
+
const languageId = EXTENSION_TO_LANGUAGE_ID[ext] ?? "plaintext";
|
|
1034
|
+
sendNotification("textDocument/didOpen", {
|
|
1035
|
+
textDocument: {
|
|
1036
|
+
uri: textDocumentUri,
|
|
1037
|
+
languageId,
|
|
1038
|
+
version: 1,
|
|
1039
|
+
text: fileText,
|
|
1040
|
+
},
|
|
1041
|
+
});
|
|
1042
|
+
// ── Step 12: Dispatch the operation (with retry for -32801) ─────────────
|
|
1043
|
+
// 0-based coordinates for LSP wire protocol.
|
|
1044
|
+
const lspLine = options.line - 1;
|
|
1045
|
+
const lspCharacter = options.character - 1;
|
|
1046
|
+
const positionParams = {
|
|
1047
|
+
textDocument: { uri: textDocumentUri },
|
|
1048
|
+
position: { line: lspLine, character: lspCharacter },
|
|
1049
|
+
};
|
|
1050
|
+
let operationResult;
|
|
1051
|
+
if (operation === "diagnostics") {
|
|
1052
|
+
// ── Diagnostics: send didSave, capture publishDiagnostics ─────────────
|
|
1053
|
+
//
|
|
1054
|
+
// Some servers emit diagnostics after didOpen; others only after didSave.
|
|
1055
|
+
// We send didSave to trigger a fresh analysis pass and wait up to
|
|
1056
|
+
// `timeoutMs` for `textDocument/publishDiagnostics` with a matching URI.
|
|
1057
|
+
sendNotification("textDocument/didSave", {
|
|
1058
|
+
textDocument: { uri: textDocumentUri },
|
|
1059
|
+
});
|
|
1060
|
+
const matchingDiags = await new Promise((resolve) => {
|
|
1061
|
+
const deadline = setTimeout(() => {
|
|
1062
|
+
// Timeout — return whatever we have (even empty).
|
|
1063
|
+
resolve({ uri: textDocumentUri, diagnostics: [] });
|
|
1064
|
+
}, timeoutMs);
|
|
1065
|
+
// Check notifications already buffered before this point.
|
|
1066
|
+
const checkBuffered = () => {
|
|
1067
|
+
for (let i = notifications.length - 1; i >= 0; i--) {
|
|
1068
|
+
const n = notifications[i];
|
|
1069
|
+
if (n.method === "textDocument/publishDiagnostics" &&
|
|
1070
|
+
typeof n.params === "object" &&
|
|
1071
|
+
n.params !== null &&
|
|
1072
|
+
"uri" in n.params &&
|
|
1073
|
+
n.params.uri === textDocumentUri) {
|
|
1074
|
+
clearTimeout(deadline);
|
|
1075
|
+
resolve(n.params);
|
|
1076
|
+
return true;
|
|
1077
|
+
}
|
|
1078
|
+
}
|
|
1079
|
+
return false;
|
|
1080
|
+
};
|
|
1081
|
+
if (checkBuffered())
|
|
1082
|
+
return;
|
|
1083
|
+
// Poll newly arriving notifications by wrapping the frame handler.
|
|
1084
|
+
const originalHandler = (msg) => {
|
|
1085
|
+
if ("method" in msg &&
|
|
1086
|
+
!("id" in msg) &&
|
|
1087
|
+
msg.method === "textDocument/publishDiagnostics" &&
|
|
1088
|
+
typeof msg.params === "object" &&
|
|
1089
|
+
msg.params !== null &&
|
|
1090
|
+
"uri" in msg.params &&
|
|
1091
|
+
msg.params.uri === textDocumentUri) {
|
|
1092
|
+
clearTimeout(deadline);
|
|
1093
|
+
resolve(msg.params);
|
|
1094
|
+
}
|
|
1095
|
+
};
|
|
1096
|
+
frameReader.onMessage((msg) => {
|
|
1097
|
+
// Run the original routing (responses + generic notifications).
|
|
1098
|
+
if ("id" in msg && ("result" in msg || "error" in msg)) {
|
|
1099
|
+
const response = msg;
|
|
1100
|
+
const pending = pendingRequests.get(response.id);
|
|
1101
|
+
if (pending !== undefined) {
|
|
1102
|
+
clearTimeout(pending.timer);
|
|
1103
|
+
pendingRequests.delete(response.id);
|
|
1104
|
+
if (response.error !== undefined) {
|
|
1105
|
+
const rpcErr = new Error(`LSP error ${response.error.code}: ${response.error.message}`);
|
|
1106
|
+
rpcErr.code =
|
|
1107
|
+
response.error.code;
|
|
1108
|
+
pending.reject(rpcErr);
|
|
1109
|
+
}
|
|
1110
|
+
else {
|
|
1111
|
+
pending.resolve(response.result);
|
|
1112
|
+
}
|
|
1113
|
+
}
|
|
1114
|
+
}
|
|
1115
|
+
else if ("method" in msg && !("id" in msg)) {
|
|
1116
|
+
notifications.push(msg);
|
|
1117
|
+
originalHandler(msg);
|
|
1118
|
+
}
|
|
1119
|
+
});
|
|
1120
|
+
});
|
|
1121
|
+
operationResult = formatDiagnostics(matchingDiags.diagnostics, textDocumentUri, workingDirectory);
|
|
1122
|
+
}
|
|
1123
|
+
else {
|
|
1124
|
+
// ── All other operations: send the request with retry ──────────────────
|
|
1125
|
+
let lastError = null;
|
|
1126
|
+
for (let attempt = 0; attempt <= MAX_RETRIES; attempt++) {
|
|
1127
|
+
if (attempt > 0) {
|
|
1128
|
+
await sleep(RETRY_BASE_DELAY_MS * Math.pow(2, attempt - 1));
|
|
1129
|
+
}
|
|
1130
|
+
try {
|
|
1131
|
+
let raw;
|
|
1132
|
+
switch (operation) {
|
|
1133
|
+
case "hover":
|
|
1134
|
+
raw = await sendRequest("textDocument/hover", positionParams);
|
|
1135
|
+
operationResult = formatHover(raw);
|
|
1136
|
+
break;
|
|
1137
|
+
case "goToDefinition":
|
|
1138
|
+
raw = await sendRequest("textDocument/definition", positionParams);
|
|
1139
|
+
operationResult = formatLocations(raw, "Definitions", workingDirectory);
|
|
1140
|
+
break;
|
|
1141
|
+
case "goToImplementation":
|
|
1142
|
+
raw = await sendRequest("textDocument/implementation", positionParams);
|
|
1143
|
+
operationResult = formatLocations(raw, "Implementations", workingDirectory);
|
|
1144
|
+
break;
|
|
1145
|
+
case "findReferences":
|
|
1146
|
+
raw = await sendRequest("textDocument/references", {
|
|
1147
|
+
...positionParams,
|
|
1148
|
+
context: { includeDeclaration: true },
|
|
1149
|
+
});
|
|
1150
|
+
operationResult = formatLocations(raw, "References", workingDirectory);
|
|
1151
|
+
break;
|
|
1152
|
+
case "documentSymbol":
|
|
1153
|
+
raw = await sendRequest("textDocument/documentSymbol", {
|
|
1154
|
+
textDocument: { uri: textDocumentUri },
|
|
1155
|
+
});
|
|
1156
|
+
operationResult = formatDocumentSymbol(raw, workingDirectory);
|
|
1157
|
+
break;
|
|
1158
|
+
case "workspaceSymbol":
|
|
1159
|
+
raw = await sendRequest("workspace/symbol", {
|
|
1160
|
+
query: query ?? "",
|
|
1161
|
+
});
|
|
1162
|
+
operationResult = formatWorkspaceSymbol(raw, workingDirectory);
|
|
1163
|
+
break;
|
|
1164
|
+
}
|
|
1165
|
+
lastError = null;
|
|
1166
|
+
break; // Success — exit retry loop.
|
|
1167
|
+
}
|
|
1168
|
+
catch (err) {
|
|
1169
|
+
const isContentModified = err instanceof Error &&
|
|
1170
|
+
"code" in err &&
|
|
1171
|
+
err.code === CODE_CONTENT_MODIFIED;
|
|
1172
|
+
if (isContentModified && attempt < MAX_RETRIES) {
|
|
1173
|
+
lastError = err instanceof Error ? err : new Error(String(err));
|
|
1174
|
+
continue; // Retry.
|
|
1175
|
+
}
|
|
1176
|
+
// Non-retryable or exhausted retries — rethrow.
|
|
1177
|
+
throw err;
|
|
1178
|
+
}
|
|
1179
|
+
}
|
|
1180
|
+
if (lastError !== null) {
|
|
1181
|
+
throw lastError;
|
|
1182
|
+
}
|
|
1183
|
+
}
|
|
1184
|
+
// ── Success ───────────────────────────────────────────────────────────────
|
|
1185
|
+
const markdown = typeof operationResult === "string"
|
|
1186
|
+
? operationResult
|
|
1187
|
+
: JSON.stringify(operationResult);
|
|
1188
|
+
return { ok: true, markdown };
|
|
1189
|
+
}
|
|
1190
|
+
catch (err) {
|
|
1191
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
1192
|
+
return {
|
|
1193
|
+
ok: false,
|
|
1194
|
+
error: msg,
|
|
1195
|
+
};
|
|
1196
|
+
}
|
|
1197
|
+
finally {
|
|
1198
|
+
// ── Step 13: Teardown — always runs regardless of success or failure ─────
|
|
1199
|
+
await teardown();
|
|
1200
|
+
}
|
|
1201
|
+
}
|
|
1202
|
+
//# sourceMappingURL=lsp.js.map
|